- Don't set hardware slot time according to "short slot time" capability
[dragonfly.git] / sys / dev / netif / ral / rt2560.c
1 /*
2  * Copyright (c) 2005, 2006
3  *      Damien Bergamini <damien.bergamini@free.fr>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  *
17  * $FreeBSD: src/sys/dev/ral/rt2560.c,v 1.3 2006/03/21 21:15:43 damien Exp $
18  * $DragonFly: src/sys/dev/netif/ral/rt2560.c,v 1.23 2008/01/19 10:08:52 sephe Exp $
19  */
20
21 /*
22  * Ralink Technology RT2560 chipset driver
23  * http://www.ralinktech.com/
24  */
25
26 #include <sys/param.h>
27 #include <sys/bus.h>
28 #include <sys/endian.h>
29 #include <sys/kernel.h>
30 #include <sys/malloc.h>
31 #include <sys/mbuf.h>
32 #include <sys/module.h>
33 #include <sys/rman.h>
34 #include <sys/socket.h>
35 #include <sys/sockio.h>
36 #include <sys/sysctl.h>
37 #include <sys/serialize.h>
38
39 #include <net/bpf.h>
40 #include <net/if.h>
41 #include <net/if_arp.h>
42 #include <net/ethernet.h>
43 #include <net/if_dl.h>
44 #include <net/if_media.h>
45 #include <net/ifq_var.h>
46
47 #include <netproto/802_11/ieee80211_var.h>
48 #include <netproto/802_11/ieee80211_radiotap.h>
49 #include <netproto/802_11/wlan_ratectl/onoe/ieee80211_onoe_param.h>
50 #include <netproto/802_11/wlan_ratectl/sample/ieee80211_sample_param.h>
51
52 #include <dev/netif/ral/rt2560reg.h>
53 #include <dev/netif/ral/rt2560var.h>
54
55 #define RT2560_RSSI(sc, rssi)                                   \
56         ((rssi) > (RT2560_NOISE_FLOOR + (sc)->rssi_corr) ?      \
57          ((rssi) - RT2560_NOISE_FLOOR - (sc)->rssi_corr) : 0)
58
59 #ifdef RAL_DEBUG
60 #define DPRINTF(x)      do { if (ral_debug > 0) kprintf x; } while (0)
61 #define DPRINTFN(n, x)  do { if (ral_debug >= (n)) kprintf x; } while (0)
62 extern int ral_debug;
63 #else
64 #define DPRINTF(x)
65 #define DPRINTFN(n, x)
66 #endif
67
68 static void             rt2560_dma_map_addr(void *, bus_dma_segment_t *, int,
69                             int);
70 static void             rt2560_dma_map_mbuf(void *, bus_dma_segment_t *, int,
71                                             bus_size_t, int);
72 static int              rt2560_alloc_tx_ring(struct rt2560_softc *,
73                             struct rt2560_tx_ring *, int);
74 static void             rt2560_reset_tx_ring(struct rt2560_softc *,
75                             struct rt2560_tx_ring *);
76 static void             rt2560_free_tx_ring(struct rt2560_softc *,
77                             struct rt2560_tx_ring *);
78 static int              rt2560_alloc_rx_ring(struct rt2560_softc *,
79                             struct rt2560_rx_ring *, int);
80 static void             rt2560_reset_rx_ring(struct rt2560_softc *,
81                             struct rt2560_rx_ring *);
82 static void             rt2560_free_rx_ring(struct rt2560_softc *,
83                             struct rt2560_rx_ring *);
84 static int              rt2560_media_change(struct ifnet *);
85 static void             rt2560_next_scan(void *);
86 static int              rt2560_newstate(struct ieee80211com *,
87                             enum ieee80211_state, int);
88 static uint16_t         rt2560_eeprom_read(struct rt2560_softc *, uint8_t);
89 static void             rt2560_encryption_intr(struct rt2560_softc *);
90 static void             rt2560_tx_intr(struct rt2560_softc *);
91 static void             rt2560_prio_intr(struct rt2560_softc *);
92 static void             rt2560_decryption_intr(struct rt2560_softc *);
93 static void             rt2560_rx_intr(struct rt2560_softc *);
94 static void             rt2560_beacon_expire(struct rt2560_softc *);
95 static void             rt2560_wakeup_expire(struct rt2560_softc *);
96 static uint8_t          rt2560_rxrate(struct rt2560_rx_desc *);
97 static uint8_t          rt2560_plcp_signal(int);
98 static void             rt2560_setup_tx_desc(struct rt2560_softc *,
99                             struct rt2560_tx_desc *, uint32_t, int, int, int,
100                             bus_addr_t);
101 static int              rt2560_tx_bcn(struct rt2560_softc *, struct mbuf *,
102                             struct ieee80211_node *);
103 static int              rt2560_tx_mgt(struct rt2560_softc *, struct mbuf *,
104                             struct ieee80211_node *);
105 static struct           mbuf *rt2560_get_rts(struct rt2560_softc *,
106                             struct ieee80211_frame *, uint16_t);
107 static int              rt2560_tx_data(struct rt2560_softc *, struct mbuf *,
108                             struct ieee80211_node *);
109 static void             rt2560_start(struct ifnet *);
110 static void             rt2560_watchdog(struct ifnet *);
111 static int              rt2560_reset(struct ifnet *);
112 static int              rt2560_ioctl(struct ifnet *, u_long, caddr_t,
113                                      struct ucred *);
114 static void             rt2560_bbp_write(struct rt2560_softc *, uint8_t,
115                             uint8_t);
116 static uint8_t          rt2560_bbp_read(struct rt2560_softc *, uint8_t);
117 static void             rt2560_rf_write(struct rt2560_softc *, uint8_t,
118                             uint32_t);
119 static void             rt2560_set_chan(struct rt2560_softc *,
120                             struct ieee80211_channel *);
121 static void             rt2560_enable_tsf_sync(struct rt2560_softc *);
122 static void             rt2560_update_plcp(struct rt2560_softc *);
123 static void             rt2560_update_slot(struct ifnet *);
124 static void             rt2560_set_basicrates(struct rt2560_softc *);
125 static void             rt2560_update_led(struct rt2560_softc *, int, int);
126 static void             rt2560_set_bssid(struct rt2560_softc *, uint8_t *);
127 static void             rt2560_set_macaddr(struct rt2560_softc *, uint8_t *);
128 static void             rt2560_get_macaddr(struct rt2560_softc *, uint8_t *);
129 static void             rt2560_update_promisc(struct rt2560_softc *);
130 static const char       *rt2560_get_rf(int);
131 static void             rt2560_read_config(struct rt2560_softc *);
132 static int              rt2560_bbp_init(struct rt2560_softc *);
133 static void             rt2560_set_txantenna(struct rt2560_softc *, int);
134 static void             rt2560_set_rxantenna(struct rt2560_softc *, int);
135 static void             rt2560_init(void *);
136 static void             rt2560_stop(void *);
137 static void             rt2560_intr(void *);
138 static void             *rt2560_ratectl_attach(struct ieee80211com *, u_int);
139
140 /*
141  * Supported rates for 802.11a/b/g modes (in 500Kbps unit).
142  */
143 static const struct ieee80211_rateset rt2560_rateset_11a =
144         { 8, { 12, 18, 24, 36, 48, 72, 96, 108 } };
145
146 static const struct ieee80211_rateset rt2560_rateset_11b =
147         { 4, { 2, 4, 11, 22 } };
148
149 static const struct ieee80211_rateset rt2560_rateset_11g =
150         { 12, { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 } };
151
152 static const struct {
153         uint32_t        reg;
154         uint32_t        val;
155 } rt2560_def_mac[] = {
156         RT2560_DEF_MAC
157 };
158
159 static const struct {
160         uint8_t reg;
161         uint8_t val;
162 } rt2560_def_bbp[] = {
163         RT2560_DEF_BBP
164 };
165
166 static const uint32_t rt2560_rf2522_r2[]    = RT2560_RF2522_R2;
167 static const uint32_t rt2560_rf2523_r2[]    = RT2560_RF2523_R2;
168 static const uint32_t rt2560_rf2524_r2[]    = RT2560_RF2524_R2;
169 static const uint32_t rt2560_rf2525_r2[]    = RT2560_RF2525_R2;
170 static const uint32_t rt2560_rf2525_hi_r2[] = RT2560_RF2525_HI_R2;
171 static const uint32_t rt2560_rf2525e_r2[]   = RT2560_RF2525E_R2;
172 static const uint32_t rt2560_rf2526_r2[]    = RT2560_RF2526_R2;
173 static const uint32_t rt2560_rf2526_hi_r2[] = RT2560_RF2526_HI_R2;
174
175 static const struct {
176         uint8_t         chan;
177         uint32_t        r1, r2, r4;
178 } rt2560_rf5222[] = {
179         RT2560_RF5222
180 };
181
182 int
183 rt2560_attach(device_t dev, int id)
184 {
185         struct rt2560_softc *sc = device_get_softc(dev);
186         struct ieee80211com *ic = &sc->sc_ic;
187         struct ifnet *ifp = &ic->ic_if;
188         int error, i;
189
190         callout_init(&sc->scan_ch);
191
192         sc->sc_irq_rid = 0;
193         sc->sc_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->sc_irq_rid,
194                                             RF_ACTIVE | RF_SHAREABLE);
195         if (sc->sc_irq == NULL) {
196                 device_printf(dev, "could not allocate interrupt resource\n");
197                 return ENXIO;
198         }
199
200         /* retrieve RT2560 rev. no */
201         sc->asic_rev = RAL_READ(sc, RT2560_CSR0);
202
203         /* retrieve MAC address */
204         rt2560_get_macaddr(sc, ic->ic_myaddr);
205
206         /* retrieve RF rev. no and various other things from EEPROM */
207         rt2560_read_config(sc);
208
209         device_printf(dev, "MAC/BBP RT2560 (rev 0x%02x), RF %s\n",
210             sc->asic_rev, rt2560_get_rf(sc->rf_rev));
211
212         /*
213          * Allocate Tx and Rx rings.
214          */
215         error = rt2560_alloc_tx_ring(sc, &sc->txq, RT2560_TX_RING_COUNT);
216         if (error != 0) {
217                 device_printf(sc->sc_dev, "could not allocate Tx ring\n");
218                 goto fail;
219         }
220
221         error = rt2560_alloc_tx_ring(sc, &sc->atimq, RT2560_ATIM_RING_COUNT);
222         if (error != 0) {
223                 device_printf(sc->sc_dev, "could not allocate ATIM ring\n");
224                 goto fail;
225         }
226
227         error = rt2560_alloc_tx_ring(sc, &sc->prioq, RT2560_PRIO_RING_COUNT);
228         if (error != 0) {
229                 device_printf(sc->sc_dev, "could not allocate Prio ring\n");
230                 goto fail;
231         }
232
233         error = rt2560_alloc_tx_ring(sc, &sc->bcnq, RT2560_BEACON_RING_COUNT);
234         if (error != 0) {
235                 device_printf(sc->sc_dev, "could not allocate Beacon ring\n");
236                 goto fail;
237         }
238
239         error = rt2560_alloc_rx_ring(sc, &sc->rxq, RT2560_RX_RING_COUNT);
240         if (error != 0) {
241                 device_printf(sc->sc_dev, "could not allocate Rx ring\n");
242                 goto fail;
243         }
244
245         sysctl_ctx_init(&sc->sysctl_ctx);
246         sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
247                                           SYSCTL_STATIC_CHILDREN(_hw),
248                                           OID_AUTO,
249                                           device_get_nameunit(dev),
250                                           CTLFLAG_RD, 0, "");
251         if (sc->sysctl_tree == NULL) {
252                 device_printf(dev, "could not add sysctl node\n");
253                 error = ENXIO;
254                 goto fail;
255         }
256
257         ifp->if_softc = sc;
258         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
259         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
260         ifp->if_init = rt2560_init;
261         ifp->if_ioctl = rt2560_ioctl;
262         ifp->if_start = rt2560_start;
263         ifp->if_watchdog = rt2560_watchdog;
264         ifq_set_maxlen(&ifp->if_snd, IFQ_MAXLEN);
265         ifq_set_ready(&ifp->if_snd);
266
267         ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
268         ic->ic_opmode = IEEE80211_M_STA; /* default to BSS mode */
269         ic->ic_state = IEEE80211_S_INIT;
270
271         IEEE80211_ONOE_PARAM_SETUP(&sc->sc_onoe_param);
272         IEEE80211_SAMPLE_PARAM_SETUP(&sc->sc_sample_param);
273         ic->ic_ratectl.rc_st_ratectl_cap = IEEE80211_RATECTL_CAP_ONOE |
274                                            IEEE80211_RATECTL_CAP_SAMPLE;
275         ic->ic_ratectl.rc_st_ratectl = IEEE80211_RATECTL_SAMPLE;
276         ic->ic_ratectl.rc_st_attach = rt2560_ratectl_attach;
277
278         /* set device capabilities */
279         ic->ic_caps =
280             IEEE80211_C_IBSS |          /* IBSS mode supported */
281             IEEE80211_C_MONITOR |       /* monitor mode supported */
282             IEEE80211_C_HOSTAP |        /* HostAp mode supported */
283             IEEE80211_C_TXPMGT |        /* tx power management */
284             IEEE80211_C_SHPREAMBLE |    /* short preamble supported */
285             IEEE80211_C_SHSLOT |        /* short slot time supported */
286             IEEE80211_C_WEP |           /* WEP */
287             IEEE80211_C_WPA;            /* 802.11i */
288
289         if (sc->rf_rev == RT2560_RF_5222) {
290                 /* set supported .11a rates */
291                 ic->ic_sup_rates[IEEE80211_MODE_11A] = rt2560_rateset_11a;
292
293                 /* set supported .11a channels */
294                 for (i = 36; i <= 64; i += 4) {
295                         ic->ic_channels[i].ic_freq =
296                             ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
297                         ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
298                 }
299                 for (i = 100; i <= 140; i += 4) {
300                         ic->ic_channels[i].ic_freq =
301                             ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
302                         ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
303                 }
304                 for (i = 149; i <= 161; i += 4) {
305                         ic->ic_channels[i].ic_freq =
306                             ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
307                         ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
308                 }
309         }
310
311         /* set supported .11b and .11g rates */
312         ic->ic_sup_rates[IEEE80211_MODE_11B] = rt2560_rateset_11b;
313         ic->ic_sup_rates[IEEE80211_MODE_11G] = rt2560_rateset_11g;
314
315         /* set supported .11b and .11g channels (1 through 14) */
316         for (i = 1; i <= 14; i++) {
317                 ic->ic_channels[i].ic_freq =
318                     ieee80211_ieee2mhz(i, IEEE80211_CHAN_2GHZ);
319                 ic->ic_channels[i].ic_flags =
320                     IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
321                     IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
322         }
323
324         sc->sc_sifs = IEEE80211_DUR_SIFS;       /* Default SIFS */
325
326         ieee80211_ifattach(ic);
327         ic->ic_updateslot = rt2560_update_slot;
328         ic->ic_reset = rt2560_reset;
329         /* enable s/w bmiss handling in sta mode */
330         ic->ic_flags_ext |= IEEE80211_FEXT_SWBMISS;
331
332         /* override state transition machine */
333         sc->sc_newstate = ic->ic_newstate;
334         ic->ic_newstate = rt2560_newstate;
335         ieee80211_media_init(ic, rt2560_media_change, ieee80211_media_status);
336
337         bpfattach_dlt(ifp, DLT_IEEE802_11_RADIO,
338             sizeof (struct ieee80211_frame) + 64, &sc->sc_drvbpf);
339
340         sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
341         sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
342         sc->sc_rxtap.wr_ihdr.it_present = htole32(RT2560_RX_RADIOTAP_PRESENT);
343
344         sc->sc_txtap_len = sizeof sc->sc_txtapu;
345         sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
346         sc->sc_txtap.wt_ihdr.it_present = htole32(RT2560_TX_RADIOTAP_PRESENT);
347
348         /*
349          * Add a few sysctl knobs.
350          */
351         sc->dwelltime = 200;
352
353         SYSCTL_ADD_INT(&sc->sysctl_ctx,
354             SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO,
355             "txantenna", CTLFLAG_RW, &sc->tx_ant, 0, "tx antenna (0=auto)");
356
357         SYSCTL_ADD_INT(&sc->sysctl_ctx,
358             SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO,
359             "rxantenna", CTLFLAG_RW, &sc->rx_ant, 0, "rx antenna (0=auto)");
360
361         SYSCTL_ADD_INT(&sc->sysctl_ctx,
362             SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO, "dwell",
363             CTLFLAG_RW, &sc->dwelltime, 0,
364             "channel dwell time (ms) for AP/station scanning");
365
366         error = bus_setup_intr(dev, sc->sc_irq, INTR_MPSAFE, rt2560_intr,
367                                sc, &sc->sc_ih, ifp->if_serializer);
368         if (error != 0) {
369                 device_printf(dev, "could not set up interrupt\n");
370                 bpfdetach(ifp);
371                 ieee80211_ifdetach(ic);
372                 goto fail;
373         }
374
375         if (bootverbose)
376                 ieee80211_announce(ic);
377         return 0;
378 fail:
379         rt2560_detach(sc);
380         return error;
381 }
382
383 int
384 rt2560_detach(void *xsc)
385 {
386         struct rt2560_softc *sc = xsc;
387         struct ieee80211com *ic = &sc->sc_ic;
388         struct ifnet *ifp = ic->ic_ifp;
389
390         if (device_is_attached(sc->sc_dev)) {
391                 lwkt_serialize_enter(ifp->if_serializer);
392
393                 callout_stop(&sc->scan_ch);
394
395                 rt2560_stop(sc);
396                 bus_teardown_intr(sc->sc_dev, sc->sc_irq, sc->sc_ih);
397
398                 lwkt_serialize_exit(ifp->if_serializer);
399
400                 bpfdetach(ifp);
401                 ieee80211_ifdetach(ic);
402         }
403
404         rt2560_free_tx_ring(sc, &sc->txq);
405         rt2560_free_tx_ring(sc, &sc->atimq);
406         rt2560_free_tx_ring(sc, &sc->prioq);
407         rt2560_free_tx_ring(sc, &sc->bcnq);
408         rt2560_free_rx_ring(sc, &sc->rxq);
409
410         if (sc->sc_irq != NULL) {
411                 bus_release_resource(sc->sc_dev, SYS_RES_IRQ, sc->sc_irq_rid,
412                                      sc->sc_irq);
413         }
414
415         if (sc->sysctl_tree != NULL)
416                 sysctl_ctx_free(&sc->sysctl_ctx);
417
418         return 0;
419 }
420
421 void
422 rt2560_shutdown(void *xsc)
423 {
424         struct rt2560_softc *sc = xsc;
425         struct ifnet *ifp = &sc->sc_ic.ic_if;
426
427         lwkt_serialize_enter(ifp->if_serializer);
428         rt2560_stop(sc);
429         lwkt_serialize_exit(ifp->if_serializer);
430 }
431
432 void
433 rt2560_suspend(void *xsc)
434 {
435         struct rt2560_softc *sc = xsc;
436         struct ifnet *ifp = &sc->sc_ic.ic_if;
437
438         lwkt_serialize_enter(ifp->if_serializer);
439         rt2560_stop(sc);
440         lwkt_serialize_exit(ifp->if_serializer);
441 }
442
443 void
444 rt2560_resume(void *xsc)
445 {
446         struct rt2560_softc *sc = xsc;
447         struct ifnet *ifp = sc->sc_ic.ic_ifp;
448
449         lwkt_serialize_enter(ifp->if_serializer);
450         if (ifp->if_flags & IFF_UP) {
451                 ifp->if_init(ifp->if_softc);
452                 if (ifp->if_flags & IFF_RUNNING)
453                         ifp->if_start(ifp);
454         }
455         lwkt_serialize_exit(ifp->if_serializer);
456 }
457
458 static void
459 rt2560_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
460 {
461         if (error != 0)
462                 return;
463
464         KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
465
466         *(bus_addr_t *)arg = segs[0].ds_addr;
467 }
468
469 static int
470 rt2560_alloc_tx_ring(struct rt2560_softc *sc, struct rt2560_tx_ring *ring,
471     int count)
472 {
473         int i, error;
474
475         ring->count = count;
476         ring->queued = 0;
477         ring->cur = ring->next = 0;
478         ring->cur_encrypt = ring->next_encrypt = 0;
479
480         error = bus_dma_tag_create(NULL, 4, 0, BUS_SPACE_MAXADDR_32BIT,
481             BUS_SPACE_MAXADDR, NULL, NULL, count * RT2560_TX_DESC_SIZE, 1,
482             count * RT2560_TX_DESC_SIZE, 0, &ring->desc_dmat);
483         if (error != 0) {
484                 device_printf(sc->sc_dev, "could not create desc DMA tag\n");
485                 goto fail;
486         }
487
488         error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
489             BUS_DMA_WAITOK | BUS_DMA_ZERO, &ring->desc_map);
490         if (error != 0) {
491                 device_printf(sc->sc_dev, "could not allocate DMA memory\n");
492                 goto fail;
493         }
494
495         error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
496                                 count * RT2560_TX_DESC_SIZE,
497                                 rt2560_dma_map_addr, &ring->physaddr, 0);
498         if (error != 0) {
499                 device_printf(sc->sc_dev, "could not load desc DMA map\n");
500
501                 bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
502                 ring->desc = NULL;
503                 goto fail;
504         }
505
506         ring->data = kmalloc(count * sizeof (struct rt2560_tx_data), M_DEVBUF,
507             M_WAITOK | M_ZERO);
508
509         error = bus_dma_tag_create(NULL, 1, 0, BUS_SPACE_MAXADDR_32BIT,
510             BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, RT2560_MAX_SCATTER,
511             MCLBYTES, 0, &ring->data_dmat);
512         if (error != 0) {
513                 device_printf(sc->sc_dev, "could not create data DMA tag\n");
514                 goto fail;
515         }
516
517         for (i = 0; i < count; i++) {
518                 error = bus_dmamap_create(ring->data_dmat, 0,
519                     &ring->data[i].map);
520                 if (error != 0) {
521                         device_printf(sc->sc_dev, "could not create DMA map\n");
522                         goto fail;
523                 }
524         }
525         return 0;
526
527 fail:   rt2560_free_tx_ring(sc, ring);
528         return error;
529 }
530
531 static void
532 rt2560_reset_tx_ring(struct rt2560_softc *sc, struct rt2560_tx_ring *ring)
533 {
534         struct rt2560_tx_desc *desc;
535         struct rt2560_tx_data *data;
536         int i;
537
538         for (i = 0; i < ring->count; i++) {
539                 desc = &ring->desc[i];
540                 data = &ring->data[i];
541
542                 if (data->m != NULL) {
543                         bus_dmamap_sync(ring->data_dmat, data->map,
544                             BUS_DMASYNC_POSTWRITE);
545                         bus_dmamap_unload(ring->data_dmat, data->map);
546                         m_freem(data->m);
547                         data->m = NULL;
548                 }
549
550                 if (data->ni != NULL) {
551                         ieee80211_free_node(data->ni);
552                         data->ni = NULL;
553                 }
554
555                 desc->flags = 0;
556         }
557
558         bus_dmamap_sync(ring->desc_dmat, ring->desc_map, BUS_DMASYNC_PREWRITE);
559
560         ring->queued = 0;
561         ring->cur = ring->next = 0;
562         ring->cur_encrypt = ring->next_encrypt = 0;
563 }
564
565 static void
566 rt2560_free_tx_ring(struct rt2560_softc *sc, struct rt2560_tx_ring *ring)
567 {
568         struct rt2560_tx_data *data;
569         int i;
570
571         if (ring->desc != NULL) {
572                 bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
573                     BUS_DMASYNC_POSTWRITE);
574                 bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
575                 bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
576                 ring->desc = NULL;
577         }
578
579         if (ring->desc_dmat != NULL) {
580                 bus_dma_tag_destroy(ring->desc_dmat);
581                 ring->desc_dmat = NULL;
582         }
583
584         if (ring->data != NULL) {
585                 for (i = 0; i < ring->count; i++) {
586                         data = &ring->data[i];
587
588                         if (data->m != NULL) {
589                                 bus_dmamap_sync(ring->data_dmat, data->map,
590                                     BUS_DMASYNC_POSTWRITE);
591                                 bus_dmamap_unload(ring->data_dmat, data->map);
592                                 m_freem(data->m);
593                                 data->m = NULL;
594                         }
595
596                         if (data->ni != NULL) {
597                                 ieee80211_free_node(data->ni);
598                                 data->ni = NULL;
599                         }
600
601                         if (data->map != NULL) {
602                                 bus_dmamap_destroy(ring->data_dmat, data->map);
603                                 data->map = NULL;
604                         }
605                 }
606
607                 kfree(ring->data, M_DEVBUF);
608                 ring->data = NULL;
609         }
610
611         if (ring->data_dmat != NULL) {
612                 bus_dma_tag_destroy(ring->data_dmat);
613                 ring->data_dmat = NULL;
614         }
615 }
616
617 static int
618 rt2560_alloc_rx_ring(struct rt2560_softc *sc, struct rt2560_rx_ring *ring,
619     int count)
620 {
621         struct rt2560_rx_desc *desc;
622         struct rt2560_rx_data *data;
623         bus_addr_t physaddr;
624         int i, error;
625
626         ring->count = count;
627         ring->cur = ring->next = 0;
628         ring->cur_decrypt = 0;
629
630         error = bus_dma_tag_create(NULL, 4, 0, BUS_SPACE_MAXADDR_32BIT,
631             BUS_SPACE_MAXADDR, NULL, NULL, count * RT2560_RX_DESC_SIZE, 1,
632             count * RT2560_RX_DESC_SIZE, 0, &ring->desc_dmat);
633         if (error != 0) {
634                 device_printf(sc->sc_dev, "could not create desc DMA tag\n");
635                 goto fail;
636         }
637
638         error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
639             BUS_DMA_WAITOK | BUS_DMA_ZERO, &ring->desc_map);
640         if (error != 0) {
641                 device_printf(sc->sc_dev, "could not allocate DMA memory\n");
642                 goto fail;
643         }
644
645         error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
646                                 count * RT2560_RX_DESC_SIZE,
647                                 rt2560_dma_map_addr, &ring->physaddr, 0);
648         if (error != 0) {
649                 device_printf(sc->sc_dev, "could not load desc DMA map\n");
650
651                 bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
652                 ring->desc = NULL;
653                 goto fail;
654         }
655
656         ring->data = kmalloc(count * sizeof (struct rt2560_rx_data), M_DEVBUF,
657             M_WAITOK | M_ZERO);
658
659         /*
660          * Pre-allocate Rx buffers and populate Rx ring.
661          */
662         error = bus_dma_tag_create(NULL, 1, 0, BUS_SPACE_MAXADDR_32BIT,
663             BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, 1, MCLBYTES, 0,
664             &ring->data_dmat);
665         if (error != 0) {
666                 device_printf(sc->sc_dev, "could not create data DMA tag\n");
667                 goto fail;
668         }
669
670         for (i = 0; i < count; i++) {
671                 desc = &sc->rxq.desc[i];
672                 data = &sc->rxq.data[i];
673
674                 error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
675                 if (error != 0) {
676                         device_printf(sc->sc_dev, "could not create DMA map\n");
677                         goto fail;
678                 }
679
680                 data->m = m_getcl(MB_WAIT, MT_DATA, M_PKTHDR);
681                 if (data->m == NULL) {
682                         device_printf(sc->sc_dev,
683                             "could not allocate rx mbuf\n");
684                         error = ENOMEM;
685                         goto fail;
686                 }
687
688                 error = bus_dmamap_load(ring->data_dmat, data->map,
689                     mtod(data->m, void *), MCLBYTES, rt2560_dma_map_addr,
690                     &physaddr, 0);
691                 if (error != 0) {
692                         device_printf(sc->sc_dev,
693                             "could not load rx buf DMA map");
694
695                         m_freem(data->m);
696                         data->m = NULL;
697                         goto fail;
698                 }
699
700                 desc->flags = htole32(RT2560_RX_BUSY);
701                 desc->physaddr = htole32(physaddr);
702         }
703
704         bus_dmamap_sync(ring->desc_dmat, ring->desc_map, BUS_DMASYNC_PREWRITE);
705
706         return 0;
707
708 fail:   rt2560_free_rx_ring(sc, ring);
709         return error;
710 }
711
712 static void
713 rt2560_reset_rx_ring(struct rt2560_softc *sc, struct rt2560_rx_ring *ring)
714 {
715         int i;
716
717         for (i = 0; i < ring->count; i++) {
718                 ring->desc[i].flags = htole32(RT2560_RX_BUSY);
719                 ring->data[i].drop = 0;
720         }
721
722         bus_dmamap_sync(ring->desc_dmat, ring->desc_map, BUS_DMASYNC_PREWRITE);
723
724         ring->cur = ring->next = 0;
725         ring->cur_decrypt = 0;
726 }
727
728 static void
729 rt2560_free_rx_ring(struct rt2560_softc *sc, struct rt2560_rx_ring *ring)
730 {
731         struct rt2560_rx_data *data;
732
733         if (ring->desc != NULL) {
734                 bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
735                     BUS_DMASYNC_POSTWRITE);
736                 bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
737                 bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
738                 ring->desc = NULL;
739         }
740
741         if (ring->desc_dmat != NULL) {
742                 bus_dma_tag_destroy(ring->desc_dmat);
743                 ring->desc_dmat = NULL;
744         }
745
746         if (ring->data != NULL) {
747                 int i;
748
749                 for (i = 0; i < ring->count; i++) {
750                         data = &ring->data[i];
751
752                         if (data->m != NULL) {
753                                 bus_dmamap_sync(ring->data_dmat, data->map,
754                                     BUS_DMASYNC_POSTREAD);
755                                 bus_dmamap_unload(ring->data_dmat, data->map);
756                                 m_freem(data->m);
757                                 data->m = NULL;
758                         }
759
760                         if (data->map != NULL) {
761                                 bus_dmamap_destroy(ring->data_dmat, data->map);
762                                 data->map = NULL;
763                         }
764                 }
765
766                 kfree(ring->data, M_DEVBUF);
767                 ring->data = NULL;
768         }
769
770         if (ring->data_dmat != NULL) {
771                 bus_dma_tag_destroy(ring->data_dmat);
772                 ring->data_dmat = NULL;
773         }
774 }
775
776 static int
777 rt2560_media_change(struct ifnet *ifp)
778 {
779         struct rt2560_softc *sc = ifp->if_softc;
780         int error;
781
782         error = ieee80211_media_change(ifp);
783         if (error != ENETRESET)
784                 return error;
785
786         if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
787                 rt2560_init(sc);
788         return 0;
789 }
790
791 /*
792  * This function is called periodically (every 200ms) during scanning to
793  * switch from one channel to another.
794  */
795 static void
796 rt2560_next_scan(void *arg)
797 {
798         struct rt2560_softc *sc = arg;
799         struct ieee80211com *ic = &sc->sc_ic;
800         struct ifnet *ifp = ic->ic_ifp;
801
802         lwkt_serialize_enter(ifp->if_serializer);
803         if (ic->ic_state == IEEE80211_S_SCAN)
804                 ieee80211_next_scan(ic);
805         lwkt_serialize_exit(ifp->if_serializer);
806 }
807
808 static int
809 rt2560_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
810 {
811         struct rt2560_softc *sc = ic->ic_ifp->if_softc;
812         enum ieee80211_state ostate;
813         struct ieee80211_node *ni;
814         struct mbuf *m;
815         int error = 0;
816
817         ostate = ic->ic_state;
818         callout_stop(&sc->scan_ch);
819         ieee80211_ratectl_newstate(ic, nstate);
820
821         switch (nstate) {
822         case IEEE80211_S_INIT:
823                 if (ostate == IEEE80211_S_RUN) {
824                         /* abort TSF synchronization */
825                         RAL_WRITE(sc, RT2560_CSR14, 0);
826
827                         /* turn association led off */
828                         rt2560_update_led(sc, 0, 0);
829                 }
830                 break;
831
832         case IEEE80211_S_SCAN:
833                 rt2560_set_chan(sc, ic->ic_curchan);
834                 callout_reset(&sc->scan_ch, (sc->dwelltime * hz) / 1000,
835                     rt2560_next_scan, sc);
836                 break;
837
838         case IEEE80211_S_AUTH:
839                 rt2560_set_chan(sc, ic->ic_curchan);
840                 break;
841
842         case IEEE80211_S_ASSOC:
843                 rt2560_set_chan(sc, ic->ic_curchan);
844                 break;
845
846         case IEEE80211_S_RUN:
847                 rt2560_set_chan(sc, ic->ic_curchan);
848
849                 ni = ic->ic_bss;
850
851                 if (ic->ic_opmode != IEEE80211_M_MONITOR) {
852                         rt2560_update_plcp(sc);
853                         rt2560_set_basicrates(sc);
854                         rt2560_set_bssid(sc, ni->ni_bssid);
855                 }
856
857                 if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
858                     ic->ic_opmode == IEEE80211_M_IBSS) {
859                         m = ieee80211_beacon_alloc(ic, ni, &sc->sc_bo);
860                         if (m == NULL) {
861                                 device_printf(sc->sc_dev,
862                                     "could not allocate beacon\n");
863                                 error = ENOBUFS;
864                                 break;
865                         }
866
867                         ieee80211_ref_node(ni);
868                         error = rt2560_tx_bcn(sc, m, ni);
869                         if (error != 0)
870                                 break;
871                 }
872
873                 /* turn assocation led on */
874                 rt2560_update_led(sc, 1, 0);
875
876                 if (ic->ic_opmode != IEEE80211_M_MONITOR)
877                         rt2560_enable_tsf_sync(sc);
878                 break;
879         }
880
881         return (error != 0) ? error : sc->sc_newstate(ic, nstate, arg);
882 }
883
884 /*
885  * Read 16 bits at address 'addr' from the serial EEPROM (either 93C46 or
886  * 93C66).
887  */
888 static uint16_t
889 rt2560_eeprom_read(struct rt2560_softc *sc, uint8_t addr)
890 {
891         uint32_t tmp;
892         uint16_t val;
893         int n;
894
895         /* clock C once before the first command */
896         RT2560_EEPROM_CTL(sc, 0);
897
898         RT2560_EEPROM_CTL(sc, RT2560_S);
899         RT2560_EEPROM_CTL(sc, RT2560_S | RT2560_C);
900         RT2560_EEPROM_CTL(sc, RT2560_S);
901
902         /* write start bit (1) */
903         RT2560_EEPROM_CTL(sc, RT2560_S | RT2560_D);
904         RT2560_EEPROM_CTL(sc, RT2560_S | RT2560_D | RT2560_C);
905
906         /* write READ opcode (10) */
907         RT2560_EEPROM_CTL(sc, RT2560_S | RT2560_D);
908         RT2560_EEPROM_CTL(sc, RT2560_S | RT2560_D | RT2560_C);
909         RT2560_EEPROM_CTL(sc, RT2560_S);
910         RT2560_EEPROM_CTL(sc, RT2560_S | RT2560_C);
911
912         /* write address (A5-A0 or A7-A0) */
913         n = (RAL_READ(sc, RT2560_CSR21) & RT2560_93C46) ? 5 : 7;
914         for (; n >= 0; n--) {
915                 RT2560_EEPROM_CTL(sc, RT2560_S |
916                     (((addr >> n) & 1) << RT2560_SHIFT_D));
917                 RT2560_EEPROM_CTL(sc, RT2560_S |
918                     (((addr >> n) & 1) << RT2560_SHIFT_D) | RT2560_C);
919         }
920
921         RT2560_EEPROM_CTL(sc, RT2560_S);
922
923         /* read data Q15-Q0 */
924         val = 0;
925         for (n = 15; n >= 0; n--) {
926                 RT2560_EEPROM_CTL(sc, RT2560_S | RT2560_C);
927                 tmp = RAL_READ(sc, RT2560_CSR21);
928                 val |= ((tmp & RT2560_Q) >> RT2560_SHIFT_Q) << n;
929                 RT2560_EEPROM_CTL(sc, RT2560_S);
930         }
931
932         RT2560_EEPROM_CTL(sc, 0);
933
934         /* clear Chip Select and clock C */
935         RT2560_EEPROM_CTL(sc, RT2560_S);
936         RT2560_EEPROM_CTL(sc, 0);
937         RT2560_EEPROM_CTL(sc, RT2560_C);
938
939         return val;
940 }
941
942 /*
943  * Some frames were processed by the hardware cipher engine and are ready for
944  * transmission.
945  */
946 static void
947 rt2560_encryption_intr(struct rt2560_softc *sc)
948 {
949         struct rt2560_tx_desc *desc;
950         int hw;
951
952         /* retrieve last descriptor index processed by cipher engine */
953         hw = RAL_READ(sc, RT2560_SECCSR1) - sc->txq.physaddr;
954         hw /= RT2560_TX_DESC_SIZE;
955
956         bus_dmamap_sync(sc->txq.desc_dmat, sc->txq.desc_map,
957             BUS_DMASYNC_POSTREAD);
958
959         for (; sc->txq.next_encrypt != hw;) {
960                 desc = &sc->txq.desc[sc->txq.next_encrypt];
961
962                 if ((le32toh(desc->flags) & RT2560_TX_BUSY) ||
963                     (le32toh(desc->flags) & RT2560_TX_CIPHER_BUSY))
964                         break;
965
966                 /* for TKIP, swap eiv field to fix a bug in ASIC */
967                 if ((le32toh(desc->flags) & RT2560_TX_CIPHER_MASK) ==
968                     RT2560_TX_CIPHER_TKIP)
969                         desc->eiv = bswap32(desc->eiv);
970
971                 /* mark the frame ready for transmission */
972                 desc->flags |= htole32(RT2560_TX_VALID);
973                 desc->flags |= htole32(RT2560_TX_BUSY);
974
975                 DPRINTFN(15, ("encryption done idx=%u\n",
976                     sc->txq.next_encrypt));
977
978                 sc->txq.next_encrypt =
979                     (sc->txq.next_encrypt + 1) % RT2560_TX_RING_COUNT;
980         }
981
982         bus_dmamap_sync(sc->txq.desc_dmat, sc->txq.desc_map,
983             BUS_DMASYNC_PREWRITE);
984
985         /* kick Tx */
986         RAL_WRITE(sc, RT2560_TXCSR0, RT2560_KICK_TX);
987 }
988
989 static void
990 rt2560_tx_intr(struct rt2560_softc *sc)
991 {
992         struct ieee80211com *ic = &sc->sc_ic;
993         struct ifnet *ifp = ic->ic_ifp;
994
995         bus_dmamap_sync(sc->txq.desc_dmat, sc->txq.desc_map,
996             BUS_DMASYNC_POSTREAD);
997
998         for (;;) {
999                 struct rt2560_tx_desc *desc;
1000                 struct rt2560_tx_data *data;
1001                 struct ieee80211_node *ni;
1002                 int rateidx, data_retries, failed;
1003                 struct mbuf *m;
1004                 uint32_t flags;
1005
1006                 desc = &sc->txq.desc[sc->txq.next];
1007                 data = &sc->txq.data[sc->txq.next];
1008
1009                 flags = le32toh(desc->flags);
1010
1011                 if ((flags & RT2560_TX_BUSY) ||
1012                     (flags & RT2560_TX_CIPHER_BUSY) ||
1013                     !(flags & RT2560_TX_VALID))
1014                         break;
1015
1016                 rateidx = data->rateidx;
1017                 ni = data->ni;
1018                 m = data->m;
1019
1020                 data->ni = NULL;
1021                 data->m = NULL;
1022
1023                 failed = 0;
1024                 switch (flags & RT2560_TX_RESULT_MASK) {
1025                 case RT2560_TX_SUCCESS:
1026                         DPRINTFN(10, ("data frame sent successfully\n"));
1027                         ifp->if_opackets++;
1028                         data_retries = 0;
1029                         break;
1030
1031                 case RT2560_TX_SUCCESS_RETRY:
1032                         data_retries = (flags >> 5) & 0x7;
1033                         DPRINTFN(9, ("data frame sent after %u retries\n",
1034                                  data_retries));
1035                         ifp->if_opackets++;
1036                         break;
1037
1038                 case RT2560_TX_FAIL_RETRY:
1039                         DPRINTFN(9, ("sending data frame failed (too much "
1040                             "retries)\n"));
1041                         ifp->if_oerrors++;
1042                         data_retries = 7;
1043                         failed = 1;
1044                         break;
1045
1046                 case RT2560_TX_FAIL_INVALID:
1047                 case RT2560_TX_FAIL_OTHER:
1048                 default:
1049                         data_retries = 7;
1050                         failed = 1;
1051                         device_printf(sc->sc_dev, "sending data frame failed "
1052                             "0x%08x\n", flags);
1053                         ifp->if_oerrors++;
1054                         break;
1055                 }
1056
1057                 bus_dmamap_sync(sc->txq.data_dmat, data->map,
1058                     BUS_DMASYNC_POSTWRITE);
1059                 bus_dmamap_unload(sc->txq.data_dmat, data->map);
1060
1061                 if (rateidx >= 0) {
1062                         struct ieee80211_ratectl_res res;
1063
1064                         res.rc_res_tries = data_retries + 1;
1065                         res.rc_res_rateidx = rateidx;
1066                         ieee80211_ratectl_tx_complete(ni, m->m_pkthdr.len,
1067                                 &res, 1, data_retries, 0, failed);
1068                 }
1069
1070                 m_freem(m);
1071                 ieee80211_free_node(ni);
1072
1073                 /* descriptor is no longer valid */
1074                 desc->flags &= ~htole32(RT2560_TX_VALID);
1075
1076                 DPRINTFN(15, ("tx done idx=%u\n", sc->txq.next));
1077
1078                 sc->txq.queued--;
1079                 sc->txq.next = (sc->txq.next + 1) % RT2560_TX_RING_COUNT;
1080         }
1081
1082         bus_dmamap_sync(sc->txq.desc_dmat, sc->txq.desc_map,
1083             BUS_DMASYNC_PREWRITE);
1084
1085         sc->sc_tx_timer = 0;
1086         ifp->if_flags &= ~IFF_OACTIVE;
1087         rt2560_start(ifp);
1088 }
1089
1090 static void
1091 rt2560_prio_intr(struct rt2560_softc *sc)
1092 {
1093         struct ieee80211com *ic = &sc->sc_ic;
1094         struct ifnet *ifp = ic->ic_ifp;
1095         struct rt2560_tx_desc *desc;
1096         struct rt2560_tx_data *data;
1097
1098         bus_dmamap_sync(sc->prioq.desc_dmat, sc->prioq.desc_map,
1099             BUS_DMASYNC_POSTREAD);
1100
1101         for (;;) {
1102                 desc = &sc->prioq.desc[sc->prioq.next];
1103                 data = &sc->prioq.data[sc->prioq.next];
1104
1105                 if ((le32toh(desc->flags) & RT2560_TX_BUSY) ||
1106                     !(le32toh(desc->flags) & RT2560_TX_VALID))
1107                         break;
1108
1109                 switch (le32toh(desc->flags) & RT2560_TX_RESULT_MASK) {
1110                 case RT2560_TX_SUCCESS:
1111                         DPRINTFN(10, ("mgt frame sent successfully\n"));
1112                         break;
1113
1114                 case RT2560_TX_SUCCESS_RETRY:
1115                         DPRINTFN(9, ("mgt frame sent after %u retries\n",
1116                             (le32toh(desc->flags) >> 5) & 0x7));
1117                         break;
1118
1119                 case RT2560_TX_FAIL_RETRY:
1120                         DPRINTFN(9, ("sending mgt frame failed (too much "
1121                             "retries)\n"));
1122                         break;
1123
1124                 case RT2560_TX_FAIL_INVALID:
1125                 case RT2560_TX_FAIL_OTHER:
1126                 default:
1127                         device_printf(sc->sc_dev, "sending mgt frame failed "
1128                             "0x%08x\n", le32toh(desc->flags));
1129                 }
1130
1131                 bus_dmamap_sync(sc->prioq.data_dmat, data->map,
1132                     BUS_DMASYNC_POSTWRITE);
1133                 bus_dmamap_unload(sc->prioq.data_dmat, data->map);
1134                 m_freem(data->m);
1135                 data->m = NULL;
1136
1137                 KASSERT(data->ni == NULL, ("mgmt node is not empty\n"));
1138
1139                 /* descriptor is no longer valid */
1140                 desc->flags &= ~htole32(RT2560_TX_VALID);
1141
1142                 DPRINTFN(15, ("prio done idx=%u\n", sc->prioq.next));
1143
1144                 sc->prioq.queued--;
1145                 sc->prioq.next = (sc->prioq.next + 1) % RT2560_PRIO_RING_COUNT;
1146         }
1147
1148         bus_dmamap_sync(sc->prioq.desc_dmat, sc->prioq.desc_map,
1149             BUS_DMASYNC_PREWRITE);
1150
1151         sc->sc_tx_timer = 0;
1152         ifp->if_flags &= ~IFF_OACTIVE;
1153         rt2560_start(ifp);
1154 }
1155
1156 /*
1157  * Some frames were processed by the hardware cipher engine and are ready for
1158  * transmission to the IEEE802.11 layer.
1159  */
1160 static void
1161 rt2560_decryption_intr(struct rt2560_softc *sc)
1162 {
1163         struct ieee80211com *ic = &sc->sc_ic;
1164         struct ifnet *ifp = ic->ic_ifp;
1165         struct rt2560_rx_desc *desc;
1166         struct rt2560_rx_data *data;
1167         bus_addr_t physaddr;
1168         struct ieee80211_frame *wh;
1169         struct ieee80211_node *ni;
1170         struct mbuf *mnew, *m;
1171         int hw, error;
1172
1173         /* retrieve last decriptor index processed by cipher engine */
1174         hw = RAL_READ(sc, RT2560_SECCSR0) - sc->rxq.physaddr;
1175         hw /= RT2560_RX_DESC_SIZE;
1176
1177         bus_dmamap_sync(sc->rxq.desc_dmat, sc->rxq.desc_map,
1178             BUS_DMASYNC_POSTREAD);
1179
1180         for (; sc->rxq.cur_decrypt != hw;) {
1181                 desc = &sc->rxq.desc[sc->rxq.cur_decrypt];
1182                 data = &sc->rxq.data[sc->rxq.cur_decrypt];
1183
1184                 if ((le32toh(desc->flags) & RT2560_RX_BUSY) ||
1185                     (le32toh(desc->flags) & RT2560_RX_CIPHER_BUSY))
1186                         break;
1187
1188                 if (data->drop) {
1189                         ifp->if_ierrors++;
1190                         goto skip;
1191                 }
1192
1193                 if ((le32toh(desc->flags) & RT2560_RX_CIPHER_MASK) != 0 &&
1194                     (le32toh(desc->flags) & RT2560_RX_ICV_ERROR)) {
1195                         ifp->if_ierrors++;
1196                         goto skip;
1197                 }
1198
1199                 /*
1200                  * Try to allocate a new mbuf for this ring element and load it
1201                  * before processing the current mbuf. If the ring element
1202                  * cannot be loaded, drop the received packet and reuse the old
1203                  * mbuf. In the unlikely case that the old mbuf can't be
1204                  * reloaded either, explicitly panic.
1205                  */
1206                 mnew = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
1207                 if (mnew == NULL) {
1208                         ifp->if_ierrors++;
1209                         goto skip;
1210                 }
1211
1212                 bus_dmamap_sync(sc->rxq.data_dmat, data->map,
1213                     BUS_DMASYNC_POSTREAD);
1214                 bus_dmamap_unload(sc->rxq.data_dmat, data->map);
1215
1216                 error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1217                     mtod(mnew, void *), MCLBYTES, rt2560_dma_map_addr,
1218                     &physaddr, 0);
1219                 if (error != 0) {
1220                         m_freem(mnew);
1221
1222                         /* try to reload the old mbuf */
1223                         error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1224                             mtod(data->m, void *), MCLBYTES,
1225                             rt2560_dma_map_addr, &physaddr, 0);
1226                         if (error != 0) {
1227                                 /* very unlikely that it will fail... */
1228                                 panic("%s: could not load old rx mbuf",
1229                                     device_get_name(sc->sc_dev));
1230                         }
1231                         ifp->if_ierrors++;
1232                         goto skip;
1233                 }
1234
1235                 /*
1236                  * New mbuf successfully loaded, update Rx ring and continue
1237                  * processing.
1238                  */
1239                 m = data->m;
1240                 data->m = mnew;
1241                 desc->physaddr = htole32(physaddr);
1242
1243                 /* finalize mbuf */
1244                 m->m_pkthdr.rcvif = ifp;
1245                 m->m_pkthdr.len = m->m_len =
1246                     (le32toh(desc->flags) >> 16) & 0xfff;
1247
1248                 if (sc->sc_drvbpf != NULL) {
1249                         struct rt2560_rx_radiotap_header *tap = &sc->sc_rxtap;
1250                         uint32_t tsf_lo, tsf_hi;
1251
1252                         /* get timestamp (low and high 32 bits) */
1253                         tsf_hi = RAL_READ(sc, RT2560_CSR17);
1254                         tsf_lo = RAL_READ(sc, RT2560_CSR16);
1255
1256                         tap->wr_tsf =
1257                             htole64(((uint64_t)tsf_hi << 32) | tsf_lo);
1258                         tap->wr_flags = 0;
1259                         tap->wr_rate = rt2560_rxrate(desc);
1260                         tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
1261                         tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
1262                         tap->wr_antenna = sc->rx_ant;
1263                         tap->wr_antsignal = RT2560_RSSI(sc, desc->rssi);
1264
1265                         bpf_ptap(sc->sc_drvbpf, m, tap, sc->sc_rxtap_len);
1266                 }
1267
1268                 wh = mtod(m, struct ieee80211_frame *);
1269                 ni = ieee80211_find_rxnode(ic,
1270                     (struct ieee80211_frame_min *)wh);
1271
1272                 /* send the frame to the 802.11 layer */
1273                 ieee80211_input(ic, m, ni, RT2560_RSSI(sc, desc->rssi), 0);
1274
1275                 /* node is no longer needed */
1276                 ieee80211_free_node(ni);
1277
1278 skip:           desc->flags = htole32(RT2560_RX_BUSY);
1279
1280                 DPRINTFN(15, ("decryption done idx=%u\n", sc->rxq.cur_decrypt));
1281
1282                 sc->rxq.cur_decrypt =
1283                     (sc->rxq.cur_decrypt + 1) % RT2560_RX_RING_COUNT;
1284         }
1285
1286         bus_dmamap_sync(sc->rxq.desc_dmat, sc->rxq.desc_map,
1287             BUS_DMASYNC_PREWRITE);
1288 }
1289
1290 /*
1291  * Some frames were received. Pass them to the hardware cipher engine before
1292  * sending them to the 802.11 layer.
1293  */
1294 static void
1295 rt2560_rx_intr(struct rt2560_softc *sc)
1296 {
1297         struct rt2560_rx_desc *desc;
1298         struct rt2560_rx_data *data;
1299
1300         bus_dmamap_sync(sc->rxq.desc_dmat, sc->rxq.desc_map,
1301             BUS_DMASYNC_POSTREAD);
1302
1303         for (;;) {
1304                 desc = &sc->rxq.desc[sc->rxq.cur];
1305                 data = &sc->rxq.data[sc->rxq.cur];
1306
1307                 if ((le32toh(desc->flags) & RT2560_RX_BUSY) ||
1308                     (le32toh(desc->flags) & RT2560_RX_CIPHER_BUSY))
1309                         break;
1310
1311                 data->drop = 0;
1312
1313                 if ((le32toh(desc->flags) & RT2560_RX_PHY_ERROR) ||
1314                     (le32toh(desc->flags) & RT2560_RX_CRC_ERROR)) {
1315                         /*
1316                          * This should not happen since we did not request
1317                          * to receive those frames when we filled RXCSR0.
1318                          */
1319                         DPRINTFN(5, ("PHY or CRC error flags 0x%08x\n",
1320                             le32toh(desc->flags)));
1321                         data->drop = 1;
1322                 }
1323
1324                 if (((le32toh(desc->flags) >> 16) & 0xfff) > MCLBYTES) {
1325                         DPRINTFN(5, ("bad length\n"));
1326                         data->drop = 1;
1327                 }
1328
1329                 /* mark the frame for decryption */
1330                 desc->flags |= htole32(RT2560_RX_CIPHER_BUSY);
1331
1332                 DPRINTFN(15, ("rx done idx=%u\n", sc->rxq.cur));
1333
1334                 sc->rxq.cur = (sc->rxq.cur + 1) % RT2560_RX_RING_COUNT;
1335         }
1336
1337         bus_dmamap_sync(sc->rxq.desc_dmat, sc->rxq.desc_map,
1338             BUS_DMASYNC_PREWRITE);
1339
1340         /* kick decrypt */
1341         RAL_WRITE(sc, RT2560_SECCSR0, RT2560_KICK_DECRYPT);
1342 }
1343
1344 /*
1345  * This function is called periodically in IBSS mode when a new beacon must be
1346  * sent out.
1347  */
1348 static void
1349 rt2560_beacon_expire(struct rt2560_softc *sc)
1350 {
1351         struct ieee80211com *ic = &sc->sc_ic;
1352         struct rt2560_tx_data *data;
1353
1354         if (ic->ic_opmode != IEEE80211_M_IBSS &&
1355             ic->ic_opmode != IEEE80211_M_HOSTAP)
1356                 return;
1357
1358         data = &sc->bcnq.data[sc->bcnq.next];
1359
1360         bus_dmamap_sync(sc->bcnq.data_dmat, data->map, BUS_DMASYNC_POSTWRITE);
1361         bus_dmamap_unload(sc->bcnq.data_dmat, data->map);
1362
1363         ieee80211_beacon_update(ic, data->ni, &sc->sc_bo, data->m, 1);
1364
1365         if (ic->ic_rawbpf != NULL)
1366                 bpf_mtap(ic->ic_rawbpf, data->m);
1367
1368         rt2560_tx_bcn(sc, data->m, data->ni);
1369
1370         DPRINTFN(15, ("beacon expired\n"));
1371
1372         sc->bcnq.next = (sc->bcnq.next + 1) % RT2560_BEACON_RING_COUNT;
1373 }
1374
1375 /* ARGSUSED */
1376 static void
1377 rt2560_wakeup_expire(struct rt2560_softc *sc)
1378 {
1379         DPRINTFN(2, ("wakeup expired\n"));
1380 }
1381
1382 static void
1383 rt2560_intr(void *arg)
1384 {
1385         struct rt2560_softc *sc = arg;
1386         struct ifnet *ifp = &sc->sc_ic.ic_if;
1387         uint32_t r;
1388
1389         /* disable interrupts */
1390         RAL_WRITE(sc, RT2560_CSR8, 0xffffffff);
1391
1392         /* don't re-enable interrupts if we're shutting down */
1393         if (!(ifp->if_flags & IFF_RUNNING))
1394                 return;
1395
1396         r = RAL_READ(sc, RT2560_CSR7);
1397         RAL_WRITE(sc, RT2560_CSR7, r);
1398
1399         if (r & RT2560_BEACON_EXPIRE)
1400                 rt2560_beacon_expire(sc);
1401
1402         if (r & RT2560_WAKEUP_EXPIRE)
1403                 rt2560_wakeup_expire(sc);
1404
1405         if (r & RT2560_PRIO_DONE)
1406                 rt2560_prio_intr(sc);
1407
1408         if (r & (RT2560_RX_DONE | RT2560_TX_DONE | RT2560_ENCRYPTION_DONE)) {
1409                 int i;
1410
1411                 for (i = 0; i < 2; ++i) {
1412                         rt2560_tx_intr(sc);
1413                         rt2560_encryption_intr(sc);
1414                 }
1415         }
1416
1417         if (r & (RT2560_DECRYPTION_DONE | RT2560_RX_DONE)) {
1418                 int i;
1419
1420                 for (i = 0; i < 2; ++i) {
1421                         rt2560_decryption_intr(sc);
1422                         rt2560_rx_intr(sc);
1423                 }
1424         }
1425
1426         /* re-enable interrupts */
1427         RAL_WRITE(sc, RT2560_CSR8, RT2560_INTR_MASK);
1428 }
1429
1430 /* quickly determine if a given rate is CCK or OFDM */
1431 #define RAL_RATE_IS_OFDM(rate) ((rate) >= 12 && (rate) != 22)
1432
1433 #define RAL_ACK_SIZE    (sizeof(struct ieee80211_frame_ack) + IEEE80211_CRC_LEN)
1434 #define RAL_CTS_SIZE    (sizeof(struct ieee80211_frame_cts) + IEEE80211_CRC_LEN)
1435
1436 #define RT2560_TXRX_TURNAROUND  10      /* us */
1437
1438 /*
1439  * This function is only used by the Rx radiotap code.
1440  */
1441 static uint8_t
1442 rt2560_rxrate(struct rt2560_rx_desc *desc)
1443 {
1444         if (le32toh(desc->flags) & RT2560_RX_OFDM) {
1445                 /* reverse function of rt2560_plcp_signal */
1446                 switch (desc->rate) {
1447                 case 0xb:       return 12;
1448                 case 0xf:       return 18;
1449                 case 0xa:       return 24;
1450                 case 0xe:       return 36;
1451                 case 0x9:       return 48;
1452                 case 0xd:       return 72;
1453                 case 0x8:       return 96;
1454                 case 0xc:       return 108;
1455                 }
1456         } else {
1457                 if (desc->rate == 10)
1458                         return 2;
1459                 if (desc->rate == 20)
1460                         return 4;
1461                 if (desc->rate == 55)
1462                         return 11;
1463                 if (desc->rate == 110)
1464                         return 22;
1465         }
1466         return 2;       /* should not get there */
1467 }
1468
1469 static uint8_t
1470 rt2560_plcp_signal(int rate)
1471 {
1472         switch (rate) {
1473         /* CCK rates (returned values are device-dependent) */
1474         case 2:         return 0x0;
1475         case 4:         return 0x1;
1476         case 11:        return 0x2;
1477         case 22:        return 0x3;
1478
1479         /* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
1480         case 12:        return 0xb;
1481         case 18:        return 0xf;
1482         case 24:        return 0xa;
1483         case 36:        return 0xe;
1484         case 48:        return 0x9;
1485         case 72:        return 0xd;
1486         case 96:        return 0x8;
1487         case 108:       return 0xc;
1488
1489         /* unsupported rates (should not get there) */
1490         default:        return 0xff;
1491         }
1492 }
1493
1494 static void
1495 rt2560_setup_tx_desc(struct rt2560_softc *sc, struct rt2560_tx_desc *desc,
1496     uint32_t flags, int len, int rate, int encrypt, bus_addr_t physaddr)
1497 {
1498         struct ieee80211com *ic = &sc->sc_ic;
1499         uint16_t plcp_length;
1500         int remainder;
1501
1502         desc->flags = htole32(flags);
1503         desc->flags |= htole32(len << 16);
1504         if (!encrypt)
1505                 desc->flags |= htole32(RT2560_TX_VALID);
1506
1507         desc->physaddr = htole32(physaddr);
1508         desc->wme = htole16(
1509             RT2560_AIFSN(2) |
1510             RT2560_LOGCWMIN(3) |
1511             RT2560_LOGCWMAX(8));
1512
1513         /* setup PLCP fields */
1514         desc->plcp_signal  = rt2560_plcp_signal(rate);
1515         desc->plcp_service = 4;
1516
1517         len += IEEE80211_CRC_LEN;
1518         if (RAL_RATE_IS_OFDM(rate)) {
1519                 desc->flags |= htole32(RT2560_TX_OFDM);
1520
1521                 plcp_length = len & 0xfff;
1522                 desc->plcp_length_hi = plcp_length >> 6;
1523                 desc->plcp_length_lo = plcp_length & 0x3f;
1524         } else {
1525                 plcp_length = (16 * len + rate - 1) / rate;
1526                 if (rate == 22) {
1527                         remainder = (16 * len) % 22;
1528                         if (remainder != 0 && remainder < 7)
1529                                 desc->plcp_service |= RT2560_PLCP_LENGEXT;
1530                 }
1531                 desc->plcp_length_hi = plcp_length >> 8;
1532                 desc->plcp_length_lo = plcp_length & 0xff;
1533
1534                 if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1535                         desc->plcp_signal |= 0x08;
1536         }
1537
1538         desc->flags |= encrypt ? htole32(RT2560_TX_CIPHER_BUSY)
1539                                : htole32(RT2560_TX_BUSY);
1540 }
1541
1542 static int
1543 rt2560_tx_bcn(struct rt2560_softc *sc, struct mbuf *m0,
1544     struct ieee80211_node *ni)
1545 {
1546         struct ieee80211com *ic = &sc->sc_ic;
1547         struct rt2560_tx_desc *desc;
1548         struct rt2560_tx_data *data;
1549         bus_addr_t paddr;
1550         int rate, error;
1551
1552         desc = &sc->bcnq.desc[sc->bcnq.cur];
1553         data = &sc->bcnq.data[sc->bcnq.cur];
1554
1555         rate = IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) ? 12 : 2;
1556
1557         error = bus_dmamap_load_mbuf(sc->bcnq.data_dmat, data->map, m0,
1558                                      rt2560_dma_map_mbuf, &paddr,
1559                                      BUS_DMA_NOWAIT);
1560         if (error != 0) {
1561                 device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1562                     error);
1563                 m_freem(m0);
1564                 return error;
1565         }
1566
1567         if (sc->sc_drvbpf != NULL) {
1568                 struct rt2560_tx_radiotap_header *tap = &sc->sc_txtap;
1569
1570                 tap->wt_flags = 0;
1571                 tap->wt_rate = rate;
1572                 tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1573                 tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1574                 tap->wt_antenna = sc->tx_ant;
1575
1576                 bpf_ptap(sc->sc_drvbpf, m0, tap, sc->sc_txtap_len);
1577         }
1578
1579         data->m = m0;
1580         data->ni = ni;
1581
1582         rt2560_setup_tx_desc(sc, desc, RT2560_TX_IFS_NEWBACKOFF |
1583             RT2560_TX_TIMESTAMP, m0->m_pkthdr.len, rate, 0, paddr);
1584
1585         DPRINTFN(10, ("sending beacon frame len=%u idx=%u rate=%u\n",
1586             m0->m_pkthdr.len, sc->bcnq.cur, rate));
1587
1588         bus_dmamap_sync(sc->bcnq.data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1589         bus_dmamap_sync(sc->bcnq.desc_dmat, sc->bcnq.desc_map,
1590             BUS_DMASYNC_PREWRITE);
1591
1592         sc->bcnq.cur = (sc->bcnq.cur + 1) % RT2560_BEACON_RING_COUNT;
1593
1594         return 0;
1595 }
1596
1597 static int
1598 rt2560_tx_mgt(struct rt2560_softc *sc, struct mbuf *m0,
1599     struct ieee80211_node *ni)
1600 {
1601         struct ieee80211com *ic = &sc->sc_ic;
1602         struct rt2560_tx_desc *desc;
1603         struct rt2560_tx_data *data;
1604         struct ieee80211_frame *wh;
1605         bus_addr_t paddr;
1606         uint16_t dur;
1607         uint32_t flags = 0;
1608         int rate, error;
1609
1610         desc = &sc->prioq.desc[sc->prioq.cur];
1611         data = &sc->prioq.data[sc->prioq.cur];
1612
1613         rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan) ? 12 : 2;
1614
1615         error = bus_dmamap_load_mbuf(sc->prioq.data_dmat, data->map, m0,
1616                                      rt2560_dma_map_mbuf, &paddr, 0);
1617         if (error != 0) {
1618                 device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1619                     error);
1620                 ieee80211_free_node(ni);
1621                 m_freem(m0);
1622                 return error;
1623         }
1624
1625         if (sc->sc_drvbpf != NULL) {
1626                 struct rt2560_tx_radiotap_header *tap = &sc->sc_txtap;
1627
1628                 tap->wt_flags = 0;
1629                 tap->wt_rate = rate;
1630                 tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1631                 tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1632                 tap->wt_antenna = sc->tx_ant;
1633
1634                 bpf_ptap(sc->sc_drvbpf, m0, tap, sc->sc_txtap_len);
1635         }
1636
1637         data->m = m0;
1638         data->ni = NULL;
1639
1640         wh = mtod(m0, struct ieee80211_frame *);
1641
1642         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1643                 flags |= RT2560_TX_ACK;
1644
1645                 dur = ieee80211_txtime(ni, RAL_ACK_SIZE, rate, ic->ic_flags) +
1646                       sc->sc_sifs;
1647                 *(uint16_t *)wh->i_dur = htole16(dur);
1648
1649                 /* tell hardware to add timestamp for probe responses */
1650                 if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
1651                     IEEE80211_FC0_TYPE_MGT &&
1652                     (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
1653                     IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1654                         flags |= RT2560_TX_TIMESTAMP;
1655         }
1656
1657         rt2560_setup_tx_desc(sc, desc, flags, m0->m_pkthdr.len, rate, 0, paddr);
1658
1659         bus_dmamap_sync(sc->prioq.data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1660         bus_dmamap_sync(sc->prioq.desc_dmat, sc->prioq.desc_map,
1661             BUS_DMASYNC_PREWRITE);
1662
1663         DPRINTFN(10, ("sending mgt frame len=%u idx=%u rate=%u\n",
1664             m0->m_pkthdr.len, sc->prioq.cur, rate));
1665
1666         /* kick prio */
1667         sc->prioq.queued++;
1668         sc->prioq.cur = (sc->prioq.cur + 1) % RT2560_PRIO_RING_COUNT;
1669         RAL_WRITE(sc, RT2560_TXCSR0, RT2560_KICK_PRIO);
1670
1671         ieee80211_free_node(ni);
1672
1673         return 0;
1674 }
1675
1676 /*
1677  * Build a RTS control frame.
1678  */
1679 static struct mbuf *
1680 rt2560_get_rts(struct rt2560_softc *sc, struct ieee80211_frame *wh,
1681     uint16_t dur)
1682 {
1683         struct ieee80211_frame_rts *rts;
1684         struct mbuf *m;
1685
1686         MGETHDR(m, MB_DONTWAIT, MT_DATA);
1687         if (m == NULL) {
1688                 sc->sc_ic.ic_stats.is_tx_nobuf++;
1689                 device_printf(sc->sc_dev, "could not allocate RTS frame\n");
1690                 return NULL;
1691         }
1692
1693         rts = mtod(m, struct ieee80211_frame_rts *);
1694
1695         rts->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_CTL |
1696             IEEE80211_FC0_SUBTYPE_RTS;
1697         rts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1698         *(uint16_t *)rts->i_dur = htole16(dur);
1699         IEEE80211_ADDR_COPY(rts->i_ra, wh->i_addr1);
1700         IEEE80211_ADDR_COPY(rts->i_ta, wh->i_addr2);
1701
1702         m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame_rts);
1703
1704         return m;
1705 }
1706
1707 static int
1708 rt2560_tx_data(struct rt2560_softc *sc, struct mbuf *m0,
1709     struct ieee80211_node *ni)
1710 {
1711         struct ieee80211com *ic = &sc->sc_ic;
1712         struct rt2560_tx_desc *desc;
1713         struct rt2560_tx_data *data;
1714         struct ieee80211_frame *wh;
1715         struct ieee80211_key *k;
1716         struct mbuf *mnew;
1717         bus_addr_t paddr;
1718         uint16_t dur;
1719         uint32_t flags = 0;
1720         int rate, error, ackrate, rateidx;
1721
1722         wh = mtod(m0, struct ieee80211_frame *);
1723         if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1724                 k = ieee80211_crypto_encap(ic, ni, m0);
1725                 if (k == NULL) {
1726                         m_freem(m0);
1727                         return ENOBUFS;
1728                 }
1729
1730                 /* packet header may have moved, reset our local pointer */
1731                 wh = mtod(m0, struct ieee80211_frame *);
1732         }
1733
1734         ieee80211_ratectl_findrate(ni, m0->m_pkthdr.len, &rateidx, 1);
1735         rate = IEEE80211_RS_RATE(&ni->ni_rates, rateidx);
1736
1737         ackrate = ieee80211_ack_rate(ni, rate);
1738
1739         /*
1740          * IEEE Std 802.11-1999, pp 82: "A STA shall use an RTS/CTS exchange
1741          * for directed frames only when the length of the MPDU is greater
1742          * than the length threshold indicated by [...]" ic_rtsthreshold.
1743          */
1744         if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
1745             m0->m_pkthdr.len > ic->ic_rtsthreshold) {
1746                 struct mbuf *m;
1747                 uint16_t dur;
1748                 int rtsrate;
1749
1750                 rtsrate = IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan) ? 12 : 2;
1751                 dur = ieee80211_txtime(ni, m0->m_pkthdr.len + IEEE80211_CRC_LEN,
1752                                        rate, ic->ic_flags) +
1753                       ieee80211_txtime(ni, RAL_CTS_SIZE, rtsrate, ic->ic_flags)+
1754                       ieee80211_txtime(ni, RAL_ACK_SIZE, ackrate, ic->ic_flags)+
1755                       3 * sc->sc_sifs;
1756
1757                 m = rt2560_get_rts(sc, wh, dur);
1758
1759                 desc = &sc->txq.desc[sc->txq.cur_encrypt];
1760                 data = &sc->txq.data[sc->txq.cur_encrypt];
1761
1762                 error = bus_dmamap_load_mbuf(sc->txq.data_dmat, data->map,
1763                                              m, rt2560_dma_map_mbuf, &paddr, 0);
1764                 if (error != 0) {
1765                         device_printf(sc->sc_dev,
1766                             "could not map mbuf (error %d)\n", error);
1767                         m_freem(m);
1768                         m_freem(m0);
1769                         return error;
1770                 }
1771
1772                 /* avoid multiple free() of the same node for each fragment */
1773                 ieee80211_ref_node(ni);
1774
1775                 data->m = m;
1776                 data->ni = ni;
1777                 data->rateidx = -1;     /* don't count RTS */
1778
1779                 rt2560_setup_tx_desc(sc, desc, RT2560_TX_ACK |
1780                     RT2560_TX_MORE_FRAG, m->m_pkthdr.len, rtsrate, 1, paddr);
1781
1782                 bus_dmamap_sync(sc->txq.data_dmat, data->map,
1783                     BUS_DMASYNC_PREWRITE);
1784
1785                 sc->txq.queued++;
1786                 sc->txq.cur_encrypt =
1787                     (sc->txq.cur_encrypt + 1) % RT2560_TX_RING_COUNT;
1788
1789                 /*
1790                  * IEEE Std 802.11-1999: when an RTS/CTS exchange is used, the
1791                  * asynchronous data frame shall be transmitted after the CTS
1792                  * frame and a SIFS period.
1793                  */
1794                 flags |= RT2560_TX_LONG_RETRY | RT2560_TX_IFS_SIFS;
1795         }
1796
1797         data = &sc->txq.data[sc->txq.cur_encrypt];
1798         desc = &sc->txq.desc[sc->txq.cur_encrypt];
1799
1800         error = bus_dmamap_load_mbuf(sc->txq.data_dmat, data->map, m0,
1801                                      rt2560_dma_map_mbuf, &paddr, 0);
1802         if (error != 0 && error != EFBIG) {
1803                 device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1804                     error);
1805                 m_freem(m0);
1806                 return error;
1807         }
1808         if (error != 0) {
1809                 mnew = m_defrag(m0, MB_DONTWAIT);
1810                 if (mnew == NULL) {
1811                         device_printf(sc->sc_dev,
1812                             "could not defragment mbuf\n");
1813                         m_freem(m0);
1814                         return ENOBUFS;
1815                 }
1816                 m0 = mnew;
1817
1818                 error = bus_dmamap_load_mbuf(sc->txq.data_dmat, data->map,
1819                                              m0, rt2560_dma_map_mbuf, &paddr,
1820                                              0);
1821                 if (error != 0) {
1822                         device_printf(sc->sc_dev,
1823                             "could not map mbuf (error %d)\n", error);
1824                         m_freem(m0);
1825                         return error;
1826                 }
1827
1828                 /* packet header may have moved, reset our local pointer */
1829                 wh = mtod(m0, struct ieee80211_frame *);
1830         }
1831
1832         if (sc->sc_drvbpf != NULL) {
1833                 struct rt2560_tx_radiotap_header *tap = &sc->sc_txtap;
1834
1835                 tap->wt_flags = 0;
1836                 tap->wt_rate = rate;
1837                 tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1838                 tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1839                 tap->wt_antenna = sc->tx_ant;
1840
1841                 bpf_ptap(sc->sc_drvbpf, m0, tap, sc->sc_txtap_len);
1842         }
1843
1844         data->m = m0;
1845         data->ni = ni;
1846         data->rateidx = rateidx;
1847
1848         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1849                 flags |= RT2560_TX_ACK;
1850                 dur = ieee80211_txtime(ni, RAL_ACK_SIZE, ackrate, ic->ic_flags)+
1851                       sc->sc_sifs;
1852                 *(uint16_t *)wh->i_dur = htole16(dur);
1853         }
1854
1855         rt2560_setup_tx_desc(sc, desc, flags, m0->m_pkthdr.len, rate, 1, paddr);
1856
1857         bus_dmamap_sync(sc->txq.data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1858         bus_dmamap_sync(sc->txq.desc_dmat, sc->txq.desc_map,
1859             BUS_DMASYNC_PREWRITE);
1860
1861         DPRINTFN(10, ("sending data frame len=%u idx=%u rate=%u\n",
1862             m0->m_pkthdr.len, sc->txq.cur_encrypt, rate));
1863
1864         /* kick encrypt */
1865         sc->txq.queued++;
1866         sc->txq.cur_encrypt = (sc->txq.cur_encrypt + 1) % RT2560_TX_RING_COUNT;
1867         RAL_WRITE(sc, RT2560_SECCSR1, RT2560_KICK_ENCRYPT);
1868
1869         return 0;
1870 }
1871
1872 static void
1873 rt2560_start(struct ifnet *ifp)
1874 {
1875         struct rt2560_softc *sc = ifp->if_softc;
1876         struct ieee80211com *ic = &sc->sc_ic;
1877         struct mbuf *m0;
1878         struct ether_header *eh;
1879         struct ieee80211_node *ni;
1880
1881         /* prevent management frames from being sent if we're not ready */
1882         if (!(ifp->if_flags & IFF_RUNNING))
1883                 return;
1884
1885         for (;;) {
1886                 IF_POLL(&ic->ic_mgtq, m0);
1887                 if (m0 != NULL) {
1888                         if (sc->prioq.queued >= RT2560_PRIO_RING_COUNT) {
1889                                 ifp->if_flags |= IFF_OACTIVE;
1890                                 break;
1891                         }
1892                         IF_DEQUEUE(&ic->ic_mgtq, m0);
1893
1894                         ni = (struct ieee80211_node *)m0->m_pkthdr.rcvif;
1895                         m0->m_pkthdr.rcvif = NULL;
1896
1897                         if (ic->ic_rawbpf != NULL)
1898                                 bpf_mtap(ic->ic_rawbpf, m0);
1899
1900                         if (rt2560_tx_mgt(sc, m0, ni) != 0)
1901                                 break;
1902
1903                 } else {
1904                         if (ic->ic_state != IEEE80211_S_RUN)
1905                                 break;
1906                         m0 = ifq_poll(&ifp->if_snd);
1907                         if (m0 == NULL)
1908                                 break;
1909                         if (sc->txq.queued >= RT2560_TX_RING_COUNT - 1) {
1910                                 ifp->if_flags |= IFF_OACTIVE;
1911                                 break;
1912                         }
1913                         m0 = ifq_dequeue(&ifp->if_snd, m0);
1914
1915                         if (m0->m_len < sizeof (struct ether_header) &&
1916                             !(m0 = m_pullup(m0, sizeof (struct ether_header))))
1917                                 continue;
1918
1919                         eh = mtod(m0, struct ether_header *);
1920                         ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1921                         if (ni == NULL) {
1922                                 m_freem(m0);
1923                                 continue;
1924                         }
1925                         BPF_MTAP(ifp, m0);
1926
1927                         m0 = ieee80211_encap(ic, m0, ni);
1928                         if (m0 == NULL) {
1929                                 ieee80211_free_node(ni);
1930                                 continue;
1931                         }
1932
1933                         if (ic->ic_rawbpf != NULL)
1934                                 bpf_mtap(ic->ic_rawbpf, m0);
1935
1936                         if (rt2560_tx_data(sc, m0, ni) != 0) {
1937                                 ieee80211_free_node(ni);
1938                                 ifp->if_oerrors++;
1939                                 break;
1940                         }
1941                 }
1942
1943                 sc->sc_tx_timer = 5;
1944                 ifp->if_timer = 1;
1945         }
1946 }
1947
1948 static void
1949 rt2560_watchdog(struct ifnet *ifp)
1950 {
1951         struct rt2560_softc *sc = ifp->if_softc;
1952         struct ieee80211com *ic = &sc->sc_ic;
1953
1954         ifp->if_timer = 0;
1955
1956         if (sc->sc_tx_timer > 0) {
1957                 if (--sc->sc_tx_timer == 0) {
1958                         device_printf(sc->sc_dev, "device timeout\n");
1959                         rt2560_init(sc);
1960                         ifp->if_oerrors++;
1961                         return;
1962                 }
1963                 ifp->if_timer = 1;
1964         }
1965
1966         ieee80211_watchdog(ic);
1967 }
1968
1969 /*
1970  * This function allows for fast channel switching in monitor mode (used by
1971  * net-mgmt/kismet). In IBSS mode, we must explicitly reset the interface to
1972  * generate a new beacon frame.
1973  */
1974 static int
1975 rt2560_reset(struct ifnet *ifp)
1976 {
1977         struct rt2560_softc *sc = ifp->if_softc;
1978         struct ieee80211com *ic = &sc->sc_ic;
1979
1980         if (ic->ic_opmode != IEEE80211_M_MONITOR)
1981                 return ENETRESET;
1982
1983         rt2560_set_chan(sc, ic->ic_curchan);
1984
1985         return 0;
1986 }
1987
1988 static int
1989 rt2560_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data, struct ucred *cr)
1990 {
1991         struct rt2560_softc *sc = ifp->if_softc;
1992         struct ieee80211com *ic = &sc->sc_ic;
1993         int error = 0;
1994
1995         switch (cmd) {
1996         case SIOCSIFFLAGS:
1997                 if (ifp->if_flags & IFF_UP) {
1998                         if (ifp->if_flags & IFF_RUNNING)
1999                                 rt2560_update_promisc(sc);
2000                         else
2001                                 rt2560_init(sc);
2002                 } else {
2003                         if (ifp->if_flags & IFF_RUNNING)
2004                                 rt2560_stop(sc);
2005                 }
2006                 break;
2007
2008         default:
2009                 error = ieee80211_ioctl(ic, cmd, data, cr);
2010         }
2011
2012         if (error == ENETRESET) {
2013                 if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
2014                     (IFF_UP | IFF_RUNNING) &&
2015                     (ic->ic_roaming != IEEE80211_ROAMING_MANUAL))
2016                         rt2560_init(sc);
2017                 error = 0;
2018         }
2019
2020         return error;
2021 }
2022
2023 static void
2024 rt2560_bbp_write(struct rt2560_softc *sc, uint8_t reg, uint8_t val)
2025 {
2026         uint32_t tmp;
2027         int ntries;
2028
2029         for (ntries = 0; ntries < 100; ntries++) {
2030                 if (!(RAL_READ(sc, RT2560_BBPCSR) & RT2560_BBP_BUSY))
2031                         break;
2032                 DELAY(1);
2033         }
2034         if (ntries == 100) {
2035                 device_printf(sc->sc_dev, "could not write to BBP\n");
2036                 return;
2037         }
2038
2039         tmp = RT2560_BBP_WRITE | RT2560_BBP_BUSY | reg << 8 | val;
2040         RAL_WRITE(sc, RT2560_BBPCSR, tmp);
2041
2042         DPRINTFN(15, ("BBP R%u <- 0x%02x\n", reg, val));
2043 }
2044
2045 static uint8_t
2046 rt2560_bbp_read(struct rt2560_softc *sc, uint8_t reg)
2047 {
2048         uint32_t val;
2049         int ntries;
2050
2051         for (ntries = 0; ntries < 100; ntries++) {
2052                 if (!(RAL_READ(sc, RT2560_BBPCSR) & RT2560_BBP_BUSY))
2053                         break;
2054                 DELAY(1);
2055         }
2056         if (ntries == 100) {
2057                 device_printf(sc->sc_dev, "could not read from BBP\n");
2058                 return 0;
2059         }
2060
2061         val = RT2560_BBP_BUSY | reg << 8;
2062         RAL_WRITE(sc, RT2560_BBPCSR, val);
2063
2064         for (ntries = 0; ntries < 100; ntries++) {
2065                 val = RAL_READ(sc, RT2560_BBPCSR);
2066                 if (!(val & RT2560_BBP_BUSY))
2067                         return val & 0xff;
2068                 DELAY(1);
2069         }
2070
2071         device_printf(sc->sc_dev, "could not read from BBP\n");
2072         return 0;
2073 }
2074
2075 static void
2076 rt2560_rf_write(struct rt2560_softc *sc, uint8_t reg, uint32_t val)
2077 {
2078         uint32_t tmp;
2079         int ntries;
2080
2081         for (ntries = 0; ntries < 100; ntries++) {
2082                 if (!(RAL_READ(sc, RT2560_RFCSR) & RT2560_RF_BUSY))
2083                         break;
2084                 DELAY(1);
2085         }
2086         if (ntries == 100) {
2087                 device_printf(sc->sc_dev, "could not write to RF\n");
2088                 return;
2089         }
2090
2091         tmp = RT2560_RF_BUSY | RT2560_RF_20BIT | (val & 0xfffff) << 2 |
2092             (reg & 0x3);
2093         RAL_WRITE(sc, RT2560_RFCSR, tmp);
2094
2095         /* remember last written value in sc */
2096         sc->rf_regs[reg] = val;
2097
2098         DPRINTFN(15, ("RF R[%u] <- 0x%05x\n", reg & 0x3, val & 0xfffff));
2099 }
2100
2101 static void
2102 rt2560_set_chan(struct rt2560_softc *sc, struct ieee80211_channel *c)
2103 {
2104         struct ieee80211com *ic = &sc->sc_ic;
2105         uint8_t power, tmp;
2106         u_int i, chan;
2107
2108         chan = ieee80211_chan2ieee(ic, c);
2109         if (chan == 0 || chan == IEEE80211_CHAN_ANY)
2110                 return;
2111
2112         if (IEEE80211_IS_CHAN_2GHZ(c))
2113                 power = min(sc->txpow[chan - 1], 31);
2114         else
2115                 power = 31;
2116
2117         /* adjust txpower using ifconfig settings */
2118         power -= (100 - ic->ic_txpowlimit) / 8;
2119
2120         DPRINTFN(2, ("setting channel to %u, txpower to %u\n", chan, power));
2121
2122         switch (sc->rf_rev) {
2123         case RT2560_RF_2522:
2124                 rt2560_rf_write(sc, RAL_RF1, 0x00814);
2125                 rt2560_rf_write(sc, RAL_RF2, rt2560_rf2522_r2[chan - 1]);
2126                 rt2560_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
2127                 break;
2128
2129         case RT2560_RF_2523:
2130                 rt2560_rf_write(sc, RAL_RF1, 0x08804);
2131                 rt2560_rf_write(sc, RAL_RF2, rt2560_rf2523_r2[chan - 1]);
2132                 rt2560_rf_write(sc, RAL_RF3, power << 7 | 0x38044);
2133                 rt2560_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
2134                 break;
2135
2136         case RT2560_RF_2524:
2137                 rt2560_rf_write(sc, RAL_RF1, 0x0c808);
2138                 rt2560_rf_write(sc, RAL_RF2, rt2560_rf2524_r2[chan - 1]);
2139                 rt2560_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
2140                 rt2560_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
2141                 break;
2142
2143         case RT2560_RF_2525:
2144                 rt2560_rf_write(sc, RAL_RF1, 0x08808);
2145                 rt2560_rf_write(sc, RAL_RF2, rt2560_rf2525_hi_r2[chan - 1]);
2146                 rt2560_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
2147                 rt2560_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
2148
2149                 rt2560_rf_write(sc, RAL_RF1, 0x08808);
2150                 rt2560_rf_write(sc, RAL_RF2, rt2560_rf2525_r2[chan - 1]);
2151                 rt2560_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
2152                 rt2560_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
2153                 break;
2154
2155         case RT2560_RF_2525E:
2156                 rt2560_rf_write(sc, RAL_RF1, 0x08808);
2157                 rt2560_rf_write(sc, RAL_RF2, rt2560_rf2525e_r2[chan - 1]);
2158                 rt2560_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
2159                 rt2560_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00286 : 0x00282);
2160                 break;
2161
2162         case RT2560_RF_2526:
2163                 rt2560_rf_write(sc, RAL_RF2, rt2560_rf2526_hi_r2[chan - 1]);
2164                 rt2560_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381);
2165                 rt2560_rf_write(sc, RAL_RF1, 0x08804);
2166
2167                 rt2560_rf_write(sc, RAL_RF2, rt2560_rf2526_r2[chan - 1]);
2168                 rt2560_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
2169                 rt2560_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381);
2170                 break;
2171
2172         /* dual-band RF */
2173         case RT2560_RF_5222:
2174                 for (i = 0; rt2560_rf5222[i].chan != chan; i++);
2175
2176                 rt2560_rf_write(sc, RAL_RF1, rt2560_rf5222[i].r1);
2177                 rt2560_rf_write(sc, RAL_RF2, rt2560_rf5222[i].r2);
2178                 rt2560_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
2179                 rt2560_rf_write(sc, RAL_RF4, rt2560_rf5222[i].r4);
2180                 break;
2181         }
2182
2183         if (ic->ic_state != IEEE80211_S_SCAN) {
2184                 /* set Japan filter bit for channel 14 */
2185                 tmp = rt2560_bbp_read(sc, 70);
2186
2187                 tmp &= ~RT2560_JAPAN_FILTER;
2188                 if (chan == 14)
2189                         tmp |= RT2560_JAPAN_FILTER;
2190
2191                 rt2560_bbp_write(sc, 70, tmp);
2192
2193                 /* clear CRC errors */
2194                 RAL_READ(sc, RT2560_CNT0);
2195         }
2196
2197         sc->sc_sifs = IEEE80211_IS_CHAN_5GHZ(c) ? IEEE80211_DUR_OFDM_SIFS
2198                                                 : IEEE80211_DUR_SIFS;
2199 }
2200
2201 /*
2202  * Refer to IEEE Std 802.11-1999 pp. 123 for more information on TSF
2203  * synchronization.
2204  */
2205 static void
2206 rt2560_enable_tsf_sync(struct rt2560_softc *sc)
2207 {
2208         struct ieee80211com *ic = &sc->sc_ic;
2209         uint16_t logcwmin, preload;
2210         uint32_t tmp;
2211
2212         /* first, disable TSF synchronization */
2213         RAL_WRITE(sc, RT2560_CSR14, 0);
2214
2215         tmp = 16 * ic->ic_bss->ni_intval;
2216         RAL_WRITE(sc, RT2560_CSR12, tmp);
2217
2218         RAL_WRITE(sc, RT2560_CSR13, 0);
2219
2220         logcwmin = 5;
2221         preload = (ic->ic_opmode == IEEE80211_M_STA) ? 384 : 1024;
2222         tmp = logcwmin << 16 | preload;
2223         RAL_WRITE(sc, RT2560_BCNOCSR, tmp);
2224
2225         /* finally, enable TSF synchronization */
2226         tmp = RT2560_ENABLE_TSF | RT2560_ENABLE_TBCN;
2227         if (ic->ic_opmode == IEEE80211_M_STA)
2228                 tmp |= RT2560_ENABLE_TSF_SYNC(1);
2229         else
2230                 tmp |= RT2560_ENABLE_TSF_SYNC(2) |
2231                        RT2560_ENABLE_BEACON_GENERATOR;
2232         RAL_WRITE(sc, RT2560_CSR14, tmp);
2233
2234         DPRINTF(("enabling TSF synchronization\n"));
2235 }
2236
2237 static void
2238 rt2560_update_plcp(struct rt2560_softc *sc)
2239 {
2240         struct ieee80211com *ic = &sc->sc_ic;
2241
2242         /* no short preamble for 1Mbps */
2243         RAL_WRITE(sc, RT2560_PLCP1MCSR, 0x00700400);
2244
2245         if (!(ic->ic_flags & IEEE80211_F_SHPREAMBLE)) {
2246                 /* values taken from the reference driver */
2247                 RAL_WRITE(sc, RT2560_PLCP2MCSR,   0x00380401);
2248                 RAL_WRITE(sc, RT2560_PLCP5p5MCSR, 0x00150402);
2249                 RAL_WRITE(sc, RT2560_PLCP11MCSR,  0x000b8403);
2250         } else {
2251                 /* same values as above or'ed 0x8 */
2252                 RAL_WRITE(sc, RT2560_PLCP2MCSR,   0x00380409);
2253                 RAL_WRITE(sc, RT2560_PLCP5p5MCSR, 0x0015040a);
2254                 RAL_WRITE(sc, RT2560_PLCP11MCSR,  0x000b840b);
2255         }
2256
2257         DPRINTF(("updating PLCP for %s preamble\n",
2258             (ic->ic_flags & IEEE80211_F_SHPREAMBLE) ? "short" : "long"));
2259 }
2260
2261 /*
2262  * This function can be called by ieee80211_set_shortslottime(). Refer to
2263  * IEEE Std 802.11-1999 pp. 85 to know how these values are computed.
2264  */
2265 static void
2266 rt2560_update_slot(struct ifnet *ifp)
2267 {
2268         struct rt2560_softc *sc = ifp->if_softc;
2269         struct ieee80211com *ic = &sc->sc_ic;
2270         uint8_t slottime;
2271         uint16_t tx_sifs, tx_pifs, tx_difs, eifs;
2272         uint32_t tmp;
2273
2274 #ifdef foo
2275         slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
2276 #else
2277         /*
2278          * Setting slot time according to "short slot time" capability
2279          * in beacon/probe_resp seems to cause problem to acknowledge
2280          * certain AP's data frames transimitted at CCK/DS rates: the
2281          * problematic AP keeps retransmitting data frames, probably
2282          * because MAC level acks are not received by hardware.
2283          * So we cheat a little bit here by claiming we are capable of
2284          * "short slot time" but setting hardware slot time to the normal
2285          * slot time.  ral(4) does not seem to have trouble to receive
2286          * frames transmitted using short slot time even if hardware
2287          * slot time is set to normal slot time.  If we didn't use this
2288          * trick, we would have to claim that short slot time is not
2289          * supported; this would give relative poor TX performance
2290          * (-1Mb~-2Mb lower) and the _whole_ BSS would stop using short
2291          * slot time.
2292          */
2293         slottime = (ic->ic_curmode == IEEE80211_MODE_11A) ? 9 : 20;
2294 #endif
2295
2296         /* update the MAC slot boundaries */
2297         tx_sifs = sc->sc_sifs - RT2560_TXRX_TURNAROUND;
2298         tx_pifs = tx_sifs + slottime;
2299         tx_difs = tx_sifs + 2 * slottime;
2300         eifs = (ic->ic_curmode == IEEE80211_MODE_11B) ? 364 : 60;
2301
2302         tmp = RAL_READ(sc, RT2560_CSR11);
2303         tmp = (tmp & ~0x1f00) | slottime << 8;
2304         RAL_WRITE(sc, RT2560_CSR11, tmp);
2305
2306         tmp = tx_pifs << 16 | tx_sifs;
2307         RAL_WRITE(sc, RT2560_CSR18, tmp);
2308
2309         tmp = eifs << 16 | tx_difs;
2310         RAL_WRITE(sc, RT2560_CSR19, tmp);
2311
2312         DPRINTF(("setting slottime to %uus\n", slottime));
2313 }
2314
2315 static void
2316 rt2560_set_basicrates(struct rt2560_softc *sc)
2317 {
2318         struct ieee80211com *ic = &sc->sc_ic;
2319
2320         /* update basic rate set */
2321         if (ic->ic_curmode == IEEE80211_MODE_11B) {
2322                 /* 11b basic rates: 1, 2Mbps */
2323                 RAL_WRITE(sc, RT2560_ARSP_PLCP_1, 0x3);
2324         } else if (IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan)) {
2325                 /* 11a basic rates: 6, 12, 24Mbps */
2326                 RAL_WRITE(sc, RT2560_ARSP_PLCP_1, 0x150);
2327         } else {
2328                 /* 11g basic rates: 1, 2, 5.5, 11, 6, 12, 24Mbps */
2329                 RAL_WRITE(sc, RT2560_ARSP_PLCP_1, 0x15f);
2330         }
2331 }
2332
2333 static void
2334 rt2560_update_led(struct rt2560_softc *sc, int led1, int led2)
2335 {
2336         uint32_t tmp;
2337
2338         /* set ON period to 70ms and OFF period to 30ms */
2339         tmp = led1 << 16 | led2 << 17 | 70 << 8 | 30;
2340         RAL_WRITE(sc, RT2560_LEDCSR, tmp);
2341 }
2342
2343 static void
2344 rt2560_set_bssid(struct rt2560_softc *sc, uint8_t *bssid)
2345 {
2346         uint32_t tmp;
2347
2348         tmp = bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24;
2349         RAL_WRITE(sc, RT2560_CSR5, tmp);
2350
2351         tmp = bssid[4] | bssid[5] << 8;
2352         RAL_WRITE(sc, RT2560_CSR6, tmp);
2353
2354         DPRINTF(("setting BSSID to %6D\n", bssid, ":"));
2355 }
2356
2357 static void
2358 rt2560_set_macaddr(struct rt2560_softc *sc, uint8_t *addr)
2359 {
2360         uint32_t tmp;
2361
2362         tmp = addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24;
2363         RAL_WRITE(sc, RT2560_CSR3, tmp);
2364
2365         tmp = addr[4] | addr[5] << 8;
2366         RAL_WRITE(sc, RT2560_CSR4, tmp);
2367
2368         DPRINTF(("setting MAC address to %6D\n", addr, ":"));
2369 }
2370
2371 static void
2372 rt2560_get_macaddr(struct rt2560_softc *sc, uint8_t *addr)
2373 {
2374         uint32_t tmp;
2375
2376         tmp = RAL_READ(sc, RT2560_CSR3);
2377         addr[0] = tmp & 0xff;
2378         addr[1] = (tmp >>  8) & 0xff;
2379         addr[2] = (tmp >> 16) & 0xff;
2380         addr[3] = (tmp >> 24);
2381
2382         tmp = RAL_READ(sc, RT2560_CSR4);
2383         addr[4] = tmp & 0xff;
2384         addr[5] = (tmp >> 8) & 0xff;
2385 }
2386
2387 static void
2388 rt2560_update_promisc(struct rt2560_softc *sc)
2389 {
2390         struct ifnet *ifp = sc->sc_ic.ic_ifp;
2391         uint32_t tmp;
2392
2393         tmp = RAL_READ(sc, RT2560_RXCSR0);
2394
2395         tmp &= ~RT2560_DROP_NOT_TO_ME;
2396         if (!(ifp->if_flags & IFF_PROMISC))
2397                 tmp |= RT2560_DROP_NOT_TO_ME;
2398
2399         RAL_WRITE(sc, RT2560_RXCSR0, tmp);
2400
2401         DPRINTF(("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
2402             "entering" : "leaving"));
2403 }
2404
2405 static const char *
2406 rt2560_get_rf(int rev)
2407 {
2408         switch (rev) {
2409         case RT2560_RF_2522:    return "RT2522";
2410         case RT2560_RF_2523:    return "RT2523";
2411         case RT2560_RF_2524:    return "RT2524";
2412         case RT2560_RF_2525:    return "RT2525";
2413         case RT2560_RF_2525E:   return "RT2525e";
2414         case RT2560_RF_2526:    return "RT2526";
2415         case RT2560_RF_5222:    return "RT5222";
2416         default:                return "unknown";
2417         }
2418 }
2419
2420 static void
2421 rt2560_read_config(struct rt2560_softc *sc)
2422 {
2423         uint16_t val;
2424         int i;
2425
2426         val = rt2560_eeprom_read(sc, RT2560_EEPROM_CONFIG0);
2427         sc->rf_rev =   (val >> 11) & 0x7;
2428         sc->hw_radio = (val >> 10) & 0x1;
2429         sc->led_mode = (val >> 6)  & 0x7;
2430         sc->rx_ant =   (val >> 4)  & 0x3;
2431         sc->tx_ant =   (val >> 2)  & 0x3;
2432         sc->nb_ant =   val & 0x3;
2433
2434         /* read default values for BBP registers */
2435         for (i = 0; i < 16; i++) {
2436                 val = rt2560_eeprom_read(sc, RT2560_EEPROM_BBP_BASE + i);
2437                 if (val == 0xffff || val == 0)
2438                         continue;
2439                 sc->bbp_prom[i].reg = val >> 8;
2440                 sc->bbp_prom[i].val = val & 0xff;
2441                 DPRINTF(("rom bbp reg:%u val:%#x\n",
2442                          sc->bbp_prom[i].reg, sc->bbp_prom[i].val));
2443         }
2444
2445         /* read Tx power for all b/g channels */
2446         for (i = 0; i < 14 / 2; i++) {
2447                 val = rt2560_eeprom_read(sc, RT2560_EEPROM_TXPOWER + i);
2448                 sc->txpow[i * 2] = val & 0xff;
2449                 sc->txpow[i * 2 + 1] = val >> 8;
2450         }
2451         for (i = 0; i < 14; ++i) {
2452                 if (sc->txpow[i] > 32)
2453                         sc->txpow[i] = 24;
2454                 DPRINTF(("tx power chan %d: %u\n", i + 1, sc->txpow[i]));
2455         }
2456
2457         val = rt2560_eeprom_read(sc, RT2560_EEPROM_CALIBRATE);
2458         if ((val & 0xff) == 0xff)
2459                 sc->rssi_corr = RT2560_DEFAULT_RSSI_CORR;
2460         else
2461                 sc->rssi_corr = val & 0xff;
2462         DPRINTF(("rssi correction %d, calibrate 0x%02x\n",
2463                  sc->rssi_corr, val));
2464
2465         val = rt2560_eeprom_read(sc, RT2560_EEPROM_CONFIG1);
2466         if (val == 0xffff)
2467                 val = 0;
2468         if ((val & 0x2) == 0) {
2469                 DPRINTF(("capable of RX sensitivity calibration\n"));
2470                 sc->sc_flags |= RT2560_FLAG_RXSNS;
2471         }
2472 }
2473
2474 static int
2475 rt2560_bbp_init(struct rt2560_softc *sc)
2476 {
2477 #define N(a)    (sizeof (a) / sizeof ((a)[0]))
2478         int i, ntries;
2479
2480         /* wait for BBP to be ready */
2481         for (ntries = 0; ntries < 100; ntries++) {
2482                 if (rt2560_bbp_read(sc, RT2560_BBP_VERSION) != 0)
2483                         break;
2484                 DELAY(1);
2485         }
2486         if (ntries == 100) {
2487                 device_printf(sc->sc_dev, "timeout waiting for BBP\n");
2488                 return EIO;
2489         }
2490
2491         /* initialize BBP registers to default values */
2492         for (i = 0; i < N(rt2560_def_bbp); i++) {
2493                 rt2560_bbp_write(sc, rt2560_def_bbp[i].reg,
2494                     rt2560_def_bbp[i].val);
2495         }
2496
2497 #if 0
2498         /* initialize BBP registers to values stored in EEPROM */
2499         for (i = 0; i < 16; i++) {
2500                 if (sc->bbp_prom[i].reg == 0xff)
2501                         continue;
2502                 rt2560_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
2503         }
2504 #endif
2505
2506         return 0;
2507 #undef N
2508 }
2509
2510 static void
2511 rt2560_set_txantenna(struct rt2560_softc *sc, int antenna)
2512 {
2513         uint32_t tmp;
2514         uint8_t tx;
2515
2516         tx = rt2560_bbp_read(sc, RT2560_BBP_TX) & ~RT2560_BBP_ANTMASK;
2517         if (antenna == 1)
2518                 tx |= RT2560_BBP_ANTA;
2519         else if (antenna == 2)
2520                 tx |= RT2560_BBP_ANTB;
2521         else
2522                 tx |= RT2560_BBP_DIVERSITY;
2523
2524         /* need to force I/Q flip for RF 2525e and 5222 */
2525         if (sc->rf_rev == RT2560_RF_2525E || sc->rf_rev == RT2560_RF_5222)
2526                 tx |= RT2560_BBP_FLIPIQ;
2527
2528         rt2560_bbp_write(sc, RT2560_BBP_TX, tx);
2529
2530         /* update values for CCK and OFDM in BBPCSR1 */
2531         tmp = RAL_READ(sc, RT2560_BBPCSR1) & ~0x00070007;
2532         tmp |= (tx & 0x7) << 16 | (tx & 0x7);
2533         RAL_WRITE(sc, RT2560_BBPCSR1, tmp);
2534 }
2535
2536 static void
2537 rt2560_set_rxantenna(struct rt2560_softc *sc, int antenna)
2538 {
2539         uint8_t rx;
2540
2541         rx = rt2560_bbp_read(sc, RT2560_BBP_RX) & ~RT2560_BBP_ANTMASK;
2542         if (antenna == 1)
2543                 rx |= RT2560_BBP_ANTA;
2544         else if (antenna == 2)
2545                 rx |= RT2560_BBP_ANTB;
2546         else
2547                 rx |= RT2560_BBP_DIVERSITY;
2548
2549         /* need to force no I/Q flip for RF 2525e */
2550         if (sc->rf_rev == RT2560_RF_2525E)
2551                 rx &= ~RT2560_BBP_FLIPIQ;
2552
2553         rt2560_bbp_write(sc, RT2560_BBP_RX, rx);
2554 }
2555
2556 static void
2557 rt2560_init(void *priv)
2558 {
2559 #define N(a)    (sizeof (a) / sizeof ((a)[0]))
2560         struct rt2560_softc *sc = priv;
2561         struct ieee80211com *ic = &sc->sc_ic;
2562         struct ifnet *ifp = ic->ic_ifp;
2563         uint32_t tmp;
2564         int i;
2565
2566         rt2560_stop(sc);
2567
2568         /* setup tx rings */
2569         tmp = RT2560_PRIO_RING_COUNT << 24 |
2570               RT2560_ATIM_RING_COUNT << 16 |
2571               RT2560_TX_RING_COUNT   <<  8 |
2572               RT2560_TX_DESC_SIZE;
2573
2574         /* rings must be initialized in this exact order */
2575         RAL_WRITE(sc, RT2560_TXCSR2, tmp);
2576         RAL_WRITE(sc, RT2560_TXCSR3, sc->txq.physaddr);
2577         RAL_WRITE(sc, RT2560_TXCSR5, sc->prioq.physaddr);
2578         RAL_WRITE(sc, RT2560_TXCSR4, sc->atimq.physaddr);
2579         RAL_WRITE(sc, RT2560_TXCSR6, sc->bcnq.physaddr);
2580
2581         /* setup rx ring */
2582         tmp = RT2560_RX_RING_COUNT << 8 | RT2560_RX_DESC_SIZE;
2583
2584         RAL_WRITE(sc, RT2560_RXCSR1, tmp);
2585         RAL_WRITE(sc, RT2560_RXCSR2, sc->rxq.physaddr);
2586
2587         /* initialize MAC registers to default values */
2588         for (i = 0; i < N(rt2560_def_mac); i++)
2589                 RAL_WRITE(sc, rt2560_def_mac[i].reg, rt2560_def_mac[i].val);
2590
2591         IEEE80211_ADDR_COPY(ic->ic_myaddr, IF_LLADDR(ifp));
2592         rt2560_set_macaddr(sc, ic->ic_myaddr);
2593
2594         /* set basic rate set (will be updated later) */
2595         RAL_WRITE(sc, RT2560_ARSP_PLCP_1, 0x153);
2596
2597         rt2560_update_slot(ifp);
2598         rt2560_update_plcp(sc);
2599         rt2560_update_led(sc, 0, 0);
2600
2601         RAL_WRITE(sc, RT2560_CSR1, RT2560_RESET_ASIC);
2602         RAL_WRITE(sc, RT2560_CSR1, RT2560_HOST_READY);
2603
2604         if (rt2560_bbp_init(sc) != 0) {
2605                 rt2560_stop(sc);
2606                 return;
2607         }
2608
2609         rt2560_set_txantenna(sc, sc->tx_ant);
2610         rt2560_set_rxantenna(sc, sc->rx_ant);
2611
2612         /* set default BSS channel */
2613         rt2560_set_chan(sc, ic->ic_curchan);
2614
2615         /* kick Rx */
2616         tmp = RT2560_DROP_PHY_ERROR | RT2560_DROP_CRC_ERROR;
2617         if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2618                 tmp |= RT2560_DROP_CTL | RT2560_DROP_VERSION_ERROR;
2619                 if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2620                         tmp |= RT2560_DROP_TODS;
2621                 if (!(ifp->if_flags & IFF_PROMISC))
2622                         tmp |= RT2560_DROP_NOT_TO_ME;
2623         }
2624         RAL_WRITE(sc, RT2560_RXCSR0, tmp);
2625
2626         /* clear old FCS and Rx FIFO errors */
2627         RAL_READ(sc, RT2560_CNT0);
2628         RAL_READ(sc, RT2560_CNT4);
2629
2630         /* clear any pending interrupts */
2631         RAL_WRITE(sc, RT2560_CSR7, 0xffffffff);
2632
2633         /* enable interrupts */
2634         RAL_WRITE(sc, RT2560_CSR8, RT2560_INTR_MASK);
2635
2636         ifp->if_flags &= ~IFF_OACTIVE;
2637         ifp->if_flags |= IFF_RUNNING;
2638
2639         /* XXX */
2640         if (ic->ic_flags & IEEE80211_F_PRIVACY) {
2641                 int i;
2642
2643                 ic->ic_flags &= ~IEEE80211_F_DROPUNENC;
2644                 for (i = 0; i < IEEE80211_WEP_NKID; ++i) {
2645                         struct ieee80211_key *wk = &ic->ic_nw_keys[i];
2646
2647                         if (wk->wk_keylen == 0)
2648                                 continue;
2649                         if (wk->wk_flags & IEEE80211_KEY_XMIT)
2650                                 wk->wk_flags |= IEEE80211_KEY_SWCRYPT;
2651                 }
2652         }
2653
2654         if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2655                 if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
2656                         ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
2657         } else
2658                 ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
2659 #undef N
2660 }
2661
2662 void
2663 rt2560_stop(void *priv)
2664 {
2665         struct rt2560_softc *sc = priv;
2666         struct ieee80211com *ic = &sc->sc_ic;
2667         struct ifnet *ifp = ic->ic_ifp;
2668
2669         ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
2670
2671         sc->sc_tx_timer = 0;
2672         ifp->if_timer = 0;
2673         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2674
2675         /* abort Tx */
2676         RAL_WRITE(sc, RT2560_TXCSR0, RT2560_ABORT_TX);
2677
2678         /* disable Rx */
2679         RAL_WRITE(sc, RT2560_RXCSR0, RT2560_DISABLE_RX);
2680
2681         /* reset ASIC (imply reset BBP) */
2682         RAL_WRITE(sc, RT2560_CSR1, RT2560_RESET_ASIC);
2683         RAL_WRITE(sc, RT2560_CSR1, 0);
2684
2685         /* disable interrupts */
2686         RAL_WRITE(sc, RT2560_CSR8, 0xffffffff);
2687
2688         /* reset Tx and Rx rings */
2689         rt2560_reset_tx_ring(sc, &sc->txq);
2690         rt2560_reset_tx_ring(sc, &sc->atimq);
2691         rt2560_reset_tx_ring(sc, &sc->prioq);
2692         rt2560_reset_tx_ring(sc, &sc->bcnq);
2693         rt2560_reset_rx_ring(sc, &sc->rxq);
2694 }
2695
2696 static void
2697 rt2560_dma_map_mbuf(void *arg, bus_dma_segment_t *seg, int nseg,
2698                     bus_size_t map_size __unused, int error)
2699 {
2700         if (error)
2701                 return;
2702
2703         KASSERT(nseg == 1, ("too many dma segments\n"));
2704         *((bus_addr_t *)arg) = seg->ds_addr;
2705 }
2706
2707 static void *
2708 rt2560_ratectl_attach(struct ieee80211com *ic, u_int rc)
2709 {
2710         struct rt2560_softc *sc = ic->ic_if.if_softc;
2711
2712         switch (rc) {
2713         case IEEE80211_RATECTL_SAMPLE:
2714                 return &sc->sc_sample_param;
2715         case IEEE80211_RATECTL_ONOE:
2716                 return &sc->sc_onoe_param;
2717         case IEEE80211_RATECTL_NONE:
2718                 /* This could only happen during detaching */
2719                 return NULL;
2720         default:
2721                 panic("unknown rate control algo %u\n", rc);
2722                 return NULL;
2723         }
2724 }