Add support for Cisco-Linksys WUSB54GC which has a different vendor ID
[dragonfly.git] / sys / dev / netif / rum / if_rum.c
1 /*      $OpenBSD: if_rum.c,v 1.40 2006/09/18 16:20:20 damien Exp $      */
2 /*      $DragonFly: src/sys/dev/netif/rum/if_rum.c,v 1.24 2008/01/14 19:27:11 josepht Exp $     */
3
4 /*-
5  * Copyright (c) 2005, 2006 Damien Bergamini <damien.bergamini@free.fr>
6  * Copyright (c) 2006 Niall O'Higgins <niallo@openbsd.org>
7  *
8  * Permission to use, copy, modify, and distribute this software for any
9  * purpose with or without fee is hereby granted, provided that the above
10  * copyright notice and this permission notice appear in all copies.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19  */
20
21 /*-
22  * Ralink Technology RT2501USB/RT2601USB 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/rman.h>
33 #include <sys/serialize.h>
34 #include <sys/socket.h>
35 #include <sys/sockio.h>
36
37 #include <net/bpf.h>
38 #include <net/ethernet.h>
39 #include <net/if.h>
40 #include <net/if_arp.h>
41 #include <net/if_dl.h>
42 #include <net/if_media.h>
43 #include <net/ifq_var.h>
44
45 #include <netproto/802_11/ieee80211_var.h>
46 #include <netproto/802_11/ieee80211_radiotap.h>
47 #include <netproto/802_11/wlan_ratectl/onoe/ieee80211_onoe_param.h>
48
49 #include <bus/usb/usb.h>
50 #include <bus/usb/usbdi.h>
51 #include <bus/usb/usbdi_util.h>
52
53 #include "if_rumreg.h"
54 #include "if_rumvar.h"
55 #include "rum_ucode.h"
56
57 #ifdef USB_DEBUG
58 #define RUM_DEBUG
59 #endif
60
61 #ifdef RUM_DEBUG
62 #define DPRINTF(x)      do { if (rum_debug) kprintf x; } while (0)
63 #define DPRINTFN(n, x)  do { if (rum_debug >= (n)) kprintf x; } while (0)
64 int rum_debug = 0;
65 #else
66 #define DPRINTF(x)
67 #define DPRINTFN(n, x)
68 #endif
69
70 /* various supported device vendors/products */
71 static const struct usb_devno rum_devs[] = {
72         { USB_DEVICE(0x0411, 0x00d8) }, /* Melco WLI-U2-SG54HP */
73         { USB_DEVICE(0x0411, 0x00d9) }, /* Melco WLI-U2-G54HP */
74         { USB_DEVICE(0x050d, 0x705a) }, /* Belkin F5D7050A */
75         { USB_DEVICE(0x050d, 0x905b) }, /* Belkin F5D9050 ver3 */
76         { USB_DEVICE(0x06f8, 0xe010) }, /* Guillemot HWGUSB2-54-LB */
77         { USB_DEVICE(0x06f8, 0xe020) }, /* Guillemot HWGUSB2-54V2-AP */
78         { USB_DEVICE(0x0769, 0x31f3) }, /* Surecom RT2573 */
79         { USB_DEVICE(0x07b8, 0xb21b) }, /* AboCom HWU54DM */
80         { USB_DEVICE(0x07b8, 0xb21c) }, /* AboCom RT2573 */
81         { USB_DEVICE(0x07b8, 0xb21d) }, /* AboCom RT2573 */
82         { USB_DEVICE(0x07b8, 0xb21e) }, /* AboCom RT2573 */
83         { USB_DEVICE(0x07b8, 0xb21f) }, /* AboCom WUG2700 */
84         { USB_DEVICE(0x07d1, 0x3c03) }, /* D-Link DWL-G122 rev c1 */
85         { USB_DEVICE(0x07d1, 0x3c04) }, /* D-Link WUA-1340 */
86         { USB_DEVICE(0x0b05, 0x1723) }, /* Asus WL-167g */
87         { USB_DEVICE(0x0b05, 0x1724) }, /* Asus WL-167g */
88         { USB_DEVICE(0x0db0, 0x6874) }, /* MSI RT2573 */
89         { USB_DEVICE(0x0db0, 0x6877) }, /* MSI RT2573 */
90         { USB_DEVICE(0x0db0, 0xa861) }, /* MSI RT2573 */
91         { USB_DEVICE(0x0db0, 0xa874) }, /* MSI RT2573 */
92         { USB_DEVICE(0x0df6, 0x90ac) }, /* Sitecom WL-172 */
93         { USB_DEVICE(0x0df6, 0x9712) }, /* Sitecom WL-113 rev 2 */
94         { USB_DEVICE(0x0eb0, 0x9021) }, /* Nova Technology RT2573 */
95         { USB_DEVICE(0x1044, 0x8008) }, /* GIGABYTE GN-WB01GS */
96         { USB_DEVICE(0x1044, 0x800a) }, /* GIGABYTE GN-WI05GS */
97         { USB_DEVICE(0x1371, 0x9022) }, /* (really) C-Net RT2573 */
98         { USB_DEVICE(0x1371, 0x9032) }, /* (really) C-Net CWD854F */
99         { USB_DEVICE(0x13b1, 0x0020) }, /* Cisco-Linksys WUSB54GC */
100         { USB_DEVICE(0x1472, 0x0009) }, /* Huawei RT2573 */
101         { USB_DEVICE(0x148f, 0x2573) }, /* Ralink RT2573 */
102         { USB_DEVICE(0x148f, 0x2671) }, /* Ralink RT2671 */
103         { USB_DEVICE(0x148f, 0x9021) }, /* Ralink RT2573 */
104         { USB_DEVICE(0x14b2, 0x3c22) }, /* Conceptronic C54RU */
105         { USB_DEVICE(0x15a9, 0x0004) }, /* SparkLan RT2573 */
106         { USB_DEVICE(0x1631, 0xc019) }, /* Good Way Technology RT2573 */
107         { USB_DEVICE(0x1690, 0x0722) }, /* Gigaset RT2573 */
108         { USB_DEVICE(0x1737, 0x0020) }, /* Linksys WUSB54GC */
109         { USB_DEVICE(0x1737, 0x0023) }, /* Linksys WUSB54GR */
110         { USB_DEVICE(0x18c5, 0x0002) }, /* AMIT CG-WLUSB2GO */
111         { USB_DEVICE(0x18e8, 0x6196) }, /* Qcom RT2573 */
112         { USB_DEVICE(0x18e8, 0x6229) }, /* Qcom RT2573 */
113         { USB_DEVICE(0x2019, 0xab01) }, /* Planex GW-US54HP */
114         { USB_DEVICE(0x2019, 0xab50) }, /* Planex GW-US54Mini2 */
115         { USB_DEVICE(0x2019, 0xed02) }, /* Planex GW-USMM */
116 };
117
118 static int              rum_alloc_tx_list(struct rum_softc *);
119 static void             rum_free_tx_list(struct rum_softc *);
120 static int              rum_alloc_rx_list(struct rum_softc *);
121 static void             rum_free_rx_list(struct rum_softc *);
122 static int              rum_media_change(struct ifnet *);
123 static void             rum_next_scan(void *);
124 static void             rum_task(void *);
125 static int              rum_newstate(struct ieee80211com *,
126                             enum ieee80211_state, int);
127 static void             rum_txeof(usbd_xfer_handle, usbd_private_handle,
128                             usbd_status);
129 static void             rum_rxeof(usbd_xfer_handle, usbd_private_handle,
130                             usbd_status);
131 static uint8_t          rum_rxrate(struct rum_rx_desc *);
132 static uint8_t          rum_plcp_signal(int);
133 static void             rum_setup_tx_desc(struct rum_softc *,
134                             struct rum_tx_desc *, uint32_t, uint16_t, int,
135                             int);
136 static int              rum_tx_data(struct rum_softc *, struct mbuf *,
137                             struct ieee80211_node *);
138 static void             rum_start(struct ifnet *);
139 static void             rum_watchdog(struct ifnet *);
140 static int              rum_ioctl(struct ifnet *, u_long, caddr_t,
141                                   struct ucred *);
142 static void             rum_eeprom_read(struct rum_softc *, uint16_t, void *,
143                             int);
144 static uint32_t         rum_read(struct rum_softc *, uint16_t);
145 static void             rum_read_multi(struct rum_softc *, uint16_t, void *,
146                             int);
147 static void             rum_write(struct rum_softc *, uint16_t, uint32_t);
148 static void             rum_write_multi(struct rum_softc *, uint16_t, void *,
149                             size_t);
150 static void             rum_bbp_write(struct rum_softc *, uint8_t, uint8_t);
151 static uint8_t          rum_bbp_read(struct rum_softc *, uint8_t);
152 static void             rum_rf_write(struct rum_softc *, uint8_t, uint32_t);
153 static void             rum_select_antenna(struct rum_softc *);
154 static void             rum_enable_mrr(struct rum_softc *);
155 static void             rum_set_txpreamble(struct rum_softc *);
156 static void             rum_set_basicrates(struct rum_softc *);
157 static void             rum_select_band(struct rum_softc *,
158                             struct ieee80211_channel *);
159 static void             rum_set_chan(struct rum_softc *,
160                             struct ieee80211_channel *);
161 static void             rum_enable_tsf_sync(struct rum_softc *);
162 static void             rum_update_slot(struct rum_softc *);
163 static void             rum_set_bssid(struct rum_softc *, const uint8_t *);
164 static void             rum_set_macaddr(struct rum_softc *, const uint8_t *);
165 static void             rum_update_promisc(struct rum_softc *);
166 static const char       *rum_get_rf(int);
167 static void             rum_read_eeprom(struct rum_softc *);
168 static int              rum_bbp_init(struct rum_softc *);
169 static void             rum_init(void *);
170 static void             rum_stop(struct rum_softc *);
171 static int              rum_load_microcode(struct rum_softc *, const uint8_t *,
172                             size_t);
173 static int              rum_prepare_beacon(struct rum_softc *);
174
175 static void             rum_stats_timeout(void *);
176 static void             rum_stats_update(usbd_xfer_handle, usbd_private_handle,
177                                          usbd_status);
178 static void             rum_stats(struct ieee80211com *,
179                                   struct ieee80211_node *,
180                                   struct ieee80211_ratectl_stats *);
181 static void             rum_ratectl_change(struct ieee80211com *ic, u_int,
182                                            u_int);
183 static int              rum_get_rssi(struct rum_softc *, uint8_t);
184
185 /*
186  * Supported rates for 802.11a/b/g modes (in 500Kbps unit).
187  */
188 static const struct ieee80211_rateset rum_rateset_11a =
189         { 8, { 12, 18, 24, 36, 48, 72, 96, 108 } };
190
191 static const struct ieee80211_rateset rum_rateset_11b =
192         { 4, { 2, 4, 11, 22 } };
193
194 static const struct ieee80211_rateset rum_rateset_11g =
195         { 12, { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 } };
196
197 static const struct {
198         uint32_t        reg;
199         uint32_t        val;
200 } rum_def_mac[] = {
201         RT2573_DEF_MAC
202 };
203
204 static const struct {
205         uint8_t reg;
206         uint8_t val;
207 } rum_def_bbp[] = {
208         RT2573_DEF_BBP
209 };
210
211 static const struct rfprog {
212         uint8_t         chan;
213         uint32_t        r1, r2, r3, r4;
214 }  rum_rf5226[] = {
215         RT2573_RF5226
216 }, rum_rf5225[] = {
217         RT2573_RF5225
218 };
219
220 static device_probe_t rum_match;
221 static device_attach_t rum_attach;
222 static device_detach_t rum_detach;
223
224 static devclass_t rum_devclass;
225
226 static kobj_method_t rum_methods[] = {
227         DEVMETHOD(device_probe, rum_match),
228         DEVMETHOD(device_attach, rum_attach),
229         DEVMETHOD(device_detach, rum_detach),
230         {0,0}
231 };
232
233 static driver_t rum_driver = {
234         "rum",
235         rum_methods,
236         sizeof(struct rum_softc)
237 };
238
239 MODULE_DEPEND(rum, usb, 1, 1, 1);
240 DRIVER_MODULE(rum, uhub, rum_driver, rum_devclass, usbd_driver_load, 0);
241
242 static int
243 rum_match(device_t self)
244 {
245         struct usb_attach_arg *uaa = device_get_ivars(self);
246
247         if (uaa->iface != NULL)
248                 return UMATCH_NONE;
249
250         return (usb_lookup(rum_devs, uaa->vendor, uaa->product) != NULL) ?
251             UMATCH_VENDOR_PRODUCT : UMATCH_NONE;
252 }
253
254 static int
255 rum_attach(device_t self)
256 {
257         struct rum_softc *sc = device_get_softc(self);
258         struct usb_attach_arg *uaa = device_get_ivars(self);
259         struct ieee80211com *ic = &sc->sc_ic;
260         struct ifnet *ifp = &ic->ic_if;
261         usb_interface_descriptor_t *id;
262         usb_endpoint_descriptor_t *ed;
263         usbd_status error;
264         int i, ntries;
265         uint32_t tmp;
266
267         sc->sc_udev = uaa->device;
268         sc->sc_dev = self;
269
270         if (usbd_set_config_no(sc->sc_udev, RT2573_CONFIG_NO, 0) != 0) {
271                 kprintf("%s: could not set configuration no\n",
272                     device_get_nameunit(sc->sc_dev));
273                 return ENXIO;
274         }
275
276         /* get the first interface handle */
277         error = usbd_device2interface_handle(sc->sc_udev, RT2573_IFACE_INDEX,
278             &sc->sc_iface);
279         if (error != 0) {
280                 kprintf("%s: could not get interface handle\n",
281                     device_get_nameunit(sc->sc_dev));
282                 return ENXIO;
283         }
284
285         /*
286          * Find endpoints.
287          */
288         id = usbd_get_interface_descriptor(sc->sc_iface);
289
290         sc->sc_rx_no = sc->sc_tx_no = -1;
291         for (i = 0; i < id->bNumEndpoints; i++) {
292                 ed = usbd_interface2endpoint_descriptor(sc->sc_iface, i);
293                 if (ed == NULL) {
294                         kprintf("%s: no endpoint descriptor for iface %d\n",
295                             device_get_nameunit(sc->sc_dev), i);
296                         return ENXIO;
297                 }
298
299                 if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
300                     UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK)
301                         sc->sc_rx_no = ed->bEndpointAddress;
302                 else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT &&
303                     UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK)
304                         sc->sc_tx_no = ed->bEndpointAddress;
305         }
306         if (sc->sc_rx_no == -1 || sc->sc_tx_no == -1) {
307                 kprintf("%s: missing endpoint\n", device_get_nameunit(sc->sc_dev));
308                 return ENXIO;
309         }
310
311         usb_init_task(&sc->sc_task, rum_task, sc);
312
313         callout_init(&sc->scan_ch);
314         callout_init(&sc->stats_ch);
315
316         /* retrieve RT2573 rev. no */
317         for (ntries = 0; ntries < 1000; ntries++) {
318                 if ((tmp = rum_read(sc, RT2573_MAC_CSR0)) != 0)
319                         break;
320                 DELAY(1000);
321         }
322         if (ntries == 1000) {
323                 kprintf("%s: timeout waiting for chip to settle\n",
324                     device_get_nameunit(sc->sc_dev));
325                 return ENXIO;
326         }
327
328         /* retrieve MAC address and various other things from EEPROM */
329         rum_read_eeprom(sc);
330
331         kprintf("%s: MAC/BBP RT%04x (rev 0x%05x), RF %s, address %6D\n",
332             device_get_nameunit(sc->sc_dev), sc->macbbp_rev, tmp,
333             rum_get_rf(sc->rf_rev), ic->ic_myaddr, ":");
334
335         error = rum_load_microcode(sc, rt2573, sizeof(rt2573));
336         if (error != 0) {
337                 device_printf(self, "can't load microcode\n");
338                 return ENXIO;
339         }
340
341         ic->ic_phytype = IEEE80211_T_OFDM;      /* not only, but not used */
342         ic->ic_opmode = IEEE80211_M_STA;        /* default to BSS mode */
343         ic->ic_state = IEEE80211_S_INIT;
344
345         /* set device capabilities */
346         ic->ic_caps =
347             IEEE80211_C_IBSS |          /* IBSS mode supported */
348             IEEE80211_C_MONITOR |       /* monitor mode supported */
349             IEEE80211_C_HOSTAP |        /* HostAp mode supported */
350             IEEE80211_C_TXPMGT |        /* tx power management */
351             IEEE80211_C_SHPREAMBLE |    /* short preamble supported */
352             IEEE80211_C_SHSLOT |        /* short slot time supported */
353             IEEE80211_C_WPA;            /* WPA 1+2 */
354
355         if (sc->rf_rev == RT2573_RF_5225 || sc->rf_rev == RT2573_RF_5226) {
356                 /* set supported .11a rates */
357                 ic->ic_sup_rates[IEEE80211_MODE_11A] = rum_rateset_11a;
358
359                 /* set supported .11a channels */
360                 for (i = 34; i <= 46; i += 4) {
361                         ic->ic_channels[i].ic_freq =
362                             ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
363                         ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
364                 }
365                 for (i = 36; i <= 64; i += 4) {
366                         ic->ic_channels[i].ic_freq =
367                             ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
368                         ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
369                 }
370                 for (i = 100; i <= 140; i += 4) {
371                         ic->ic_channels[i].ic_freq =
372                             ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
373                         ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
374                 }
375                 for (i = 149; i <= 165; i += 4) {
376                         ic->ic_channels[i].ic_freq =
377                             ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
378                         ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
379                 }
380         }
381
382         /* set supported .11b and .11g rates */
383         ic->ic_sup_rates[IEEE80211_MODE_11B] = rum_rateset_11b;
384         ic->ic_sup_rates[IEEE80211_MODE_11G] = rum_rateset_11g;
385
386         /* set supported .11b and .11g channels (1 through 14) */
387         for (i = 1; i <= 14; i++) {
388                 ic->ic_channels[i].ic_freq =
389                     ieee80211_ieee2mhz(i, IEEE80211_CHAN_2GHZ);
390                 ic->ic_channels[i].ic_flags =
391                     IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
392                     IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
393         }
394
395         sc->sc_sifs = IEEE80211_DUR_SIFS;       /* Default SIFS */
396
397         if_initname(ifp, device_get_name(self), device_get_unit(self));
398         ifp->if_softc = sc;
399         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
400         ifp->if_init = rum_init;
401         ifp->if_ioctl = rum_ioctl;
402         ifp->if_start = rum_start;
403         ifp->if_watchdog = rum_watchdog;
404         ifq_set_maxlen(&ifp->if_snd, IFQ_MAXLEN);
405         ifq_set_ready(&ifp->if_snd);
406
407         ic->ic_ratectl.rc_st_ratectl_cap = IEEE80211_RATECTL_CAP_ONOE;
408         ic->ic_ratectl.rc_st_ratectl = IEEE80211_RATECTL_ONOE;
409         ic->ic_ratectl.rc_st_valid_stats =
410                 IEEE80211_RATECTL_STATS_PKT_NORETRY |
411                 IEEE80211_RATECTL_STATS_PKT_OK |
412                 IEEE80211_RATECTL_STATS_PKT_ERR |
413                 IEEE80211_RATECTL_STATS_RETRIES;
414         ic->ic_ratectl.rc_st_stats = rum_stats;
415         ic->ic_ratectl.rc_st_change = rum_ratectl_change;
416
417         ieee80211_ifattach(ic);
418
419         /* Enable software beacon missing handling. */
420         ic->ic_flags_ext |= IEEE80211_FEXT_SWBMISS;
421
422         /* override state transition machine */
423         sc->sc_newstate = ic->ic_newstate;
424         ic->ic_newstate = rum_newstate;
425         ieee80211_media_init(ic, rum_media_change, ieee80211_media_status);
426
427         bpfattach_dlt(ifp, DLT_IEEE802_11_RADIO,
428             sizeof(struct ieee80211_frame) + IEEE80211_RADIOTAP_HDRLEN,
429             &sc->sc_drvbpf);
430
431         sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
432         sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
433         sc->sc_rxtap.wr_ihdr.it_present = htole32(RT2573_RX_RADIOTAP_PRESENT);
434
435         sc->sc_txtap_len = sizeof sc->sc_txtapu;
436         sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
437         sc->sc_txtap.wt_ihdr.it_present = htole32(RT2573_TX_RADIOTAP_PRESENT);
438
439         if (bootverbose)
440                 ieee80211_announce(ic);
441
442         return 0;
443 }
444
445 static int
446 rum_detach(device_t self)
447 {
448         struct rum_softc *sc = device_get_softc(self);
449         struct ifnet *ifp = &sc->sc_ic.ic_if;
450 #ifdef INVARIANTS
451         int i;
452 #endif
453
454         crit_enter();
455
456         callout_stop(&sc->scan_ch);
457         callout_stop(&sc->stats_ch);
458
459         lwkt_serialize_enter(ifp->if_serializer);
460         rum_stop(sc);
461         lwkt_serialize_exit(ifp->if_serializer);
462
463         usb_rem_task(sc->sc_udev, &sc->sc_task);
464
465         bpfdetach(ifp);
466         ieee80211_ifdetach(&sc->sc_ic); /* free all nodes */
467
468         crit_exit();
469
470         KKASSERT(sc->stats_xfer == NULL);
471         KKASSERT(sc->sc_rx_pipeh == NULL);
472         KKASSERT(sc->sc_tx_pipeh == NULL);
473
474 #ifdef INVARIANTS
475         /*
476          * Make sure TX/RX list is empty
477          */
478         for (i = 0; i < RT2573_TX_LIST_COUNT; i++) {
479                 struct rum_tx_data *data = &sc->tx_data[i];
480
481                 KKASSERT(data->xfer == NULL);
482                 KKASSERT(data->ni == NULL);
483                 KKASSERT(data->m == NULL);
484         }
485         for (i = 0; i < RT2573_RX_LIST_COUNT; i++) {
486                 struct rum_rx_data *data = &sc->rx_data[i];
487
488                 KKASSERT(data->xfer == NULL);
489                 KKASSERT(data->m == NULL);
490         }
491 #endif
492         return 0;
493 }
494
495 static int
496 rum_alloc_tx_list(struct rum_softc *sc)
497 {
498         int i;
499
500         sc->tx_queued = 0;
501         for (i = 0; i < RT2573_TX_LIST_COUNT; i++) {
502                 struct rum_tx_data *data = &sc->tx_data[i];
503
504                 data->sc = sc;
505
506                 data->xfer = usbd_alloc_xfer(sc->sc_udev);
507                 if (data->xfer == NULL) {
508                         kprintf("%s: could not allocate tx xfer\n",
509                             device_get_nameunit(sc->sc_dev));
510                         return ENOMEM;
511                 }
512
513                 data->buf = usbd_alloc_buffer(data->xfer,
514                     RT2573_TX_DESC_SIZE + IEEE80211_MAX_LEN);
515                 if (data->buf == NULL) {
516                         kprintf("%s: could not allocate tx buffer\n",
517                             device_get_nameunit(sc->sc_dev));
518                         return ENOMEM;
519                 }
520
521                 /* clean Tx descriptor */
522                 bzero(data->buf, RT2573_TX_DESC_SIZE);
523         }
524         return 0;
525 }
526
527 static void
528 rum_free_tx_list(struct rum_softc *sc)
529 {
530         int i;
531
532         for (i = 0; i < RT2573_TX_LIST_COUNT; i++) {
533                 struct rum_tx_data *data = &sc->tx_data[i];
534
535                 if (data->xfer != NULL) {
536                         usbd_free_xfer(data->xfer);
537                         data->xfer = NULL;
538                 }
539                 if (data->ni != NULL) {
540                         ieee80211_free_node(data->ni);
541                         data->ni = NULL;
542                 }
543                 if (data->m != NULL) {
544                         m_freem(data->m);
545                         data->m = NULL;
546                 }
547         }
548         sc->tx_queued = 0;
549 }
550
551 static int
552 rum_alloc_rx_list(struct rum_softc *sc)
553 {
554         int i;
555
556         for (i = 0; i < RT2573_RX_LIST_COUNT; i++) {
557                 struct rum_rx_data *data = &sc->rx_data[i];
558
559                 data->sc = sc;
560
561                 data->xfer = usbd_alloc_xfer(sc->sc_udev);
562                 if (data->xfer == NULL) {
563                         kprintf("%s: could not allocate rx xfer\n",
564                             device_get_nameunit(sc->sc_dev));
565                         return ENOMEM;
566                 }
567
568                 if (usbd_alloc_buffer(data->xfer, MCLBYTES) == NULL) {
569                         kprintf("%s: could not allocate rx buffer\n",
570                             device_get_nameunit(sc->sc_dev));
571                         return ENOMEM;
572                 }
573
574                 data->m = m_getcl(MB_WAIT, MT_DATA, M_PKTHDR);
575
576                 data->buf = mtod(data->m, uint8_t *);
577                 bzero(data->buf, sizeof(struct rum_rx_desc));
578         }
579         return 0;
580 }
581
582 static void
583 rum_free_rx_list(struct rum_softc *sc)
584 {
585         int i;
586
587         for (i = 0; i < RT2573_RX_LIST_COUNT; i++) {
588                 struct rum_rx_data *data = &sc->rx_data[i];
589
590                 if (data->xfer != NULL) {
591                         usbd_free_xfer(data->xfer);
592                         data->xfer = NULL;
593                 }
594                 if (data->m != NULL) {
595                         m_freem(data->m);
596                         data->m = NULL;
597                 }
598         }
599 }
600
601 static int
602 rum_media_change(struct ifnet *ifp)
603 {
604         int error;
605
606         error = ieee80211_media_change(ifp);
607         if (error != ENETRESET)
608                 return error;
609
610         if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
611                 rum_init(ifp->if_softc);
612
613         return 0;
614 }
615
616 /*
617  * This function is called periodically (every 200ms) during scanning to
618  * switch from one channel to another.
619  */
620 static void
621 rum_next_scan(void *arg)
622 {
623         struct rum_softc *sc = arg;
624         struct ieee80211com *ic = &sc->sc_ic;
625         struct ifnet *ifp = &ic->ic_if;
626
627         if (sc->sc_stopped)
628                 return;
629
630         crit_enter();
631
632         if (ic->ic_state == IEEE80211_S_SCAN) {
633                 lwkt_serialize_enter(ifp->if_serializer);
634                 ieee80211_next_scan(ic);
635                 lwkt_serialize_exit(ifp->if_serializer);
636         }
637
638         crit_exit();
639 }
640
641 static void
642 rum_task(void *xarg)
643 {
644         struct rum_softc *sc = xarg;
645         struct ieee80211com *ic = &sc->sc_ic;
646         struct ifnet *ifp = &ic->ic_if;
647         enum ieee80211_state nstate;
648         struct ieee80211_node *ni;
649         int arg;
650
651         if (sc->sc_stopped)
652                 return;
653
654         crit_enter();
655
656         nstate = sc->sc_state;
657         arg = sc->sc_arg;
658
659         KASSERT(nstate != IEEE80211_S_INIT,
660                 ("->INIT state transition should not be defered\n"));
661         rum_set_chan(sc, ic->ic_curchan);
662
663         switch (nstate) {
664         case IEEE80211_S_RUN:
665                 ni = ic->ic_bss;
666
667                 if (ic->ic_opmode != IEEE80211_M_MONITOR) {
668                         rum_update_slot(sc);
669                         rum_enable_mrr(sc);
670                         rum_set_txpreamble(sc);
671                         rum_set_basicrates(sc);
672                         rum_set_bssid(sc, ni->ni_bssid);
673                 }
674
675                 if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
676                     ic->ic_opmode == IEEE80211_M_IBSS)
677                         rum_prepare_beacon(sc);
678
679                 if (ic->ic_opmode != IEEE80211_M_MONITOR)
680                         rum_enable_tsf_sync(sc);
681
682                 /* clear statistic registers (STA_CSR0 to STA_CSR5) */
683                 rum_read_multi(sc, RT2573_STA_CSR0, sc->sta, sizeof(sc->sta));
684                 callout_reset(&sc->stats_ch, 4 * hz / 5, rum_stats_timeout, sc);
685                 break;
686
687         case IEEE80211_S_SCAN:
688                 callout_reset(&sc->scan_ch, hz / 5, rum_next_scan, sc);
689                 break;
690
691         default:
692                 break;
693         }
694
695         lwkt_serialize_enter(ifp->if_serializer);
696         ieee80211_ratectl_newstate(ic, nstate);
697         sc->sc_newstate(ic, nstate, arg);
698         lwkt_serialize_exit(ifp->if_serializer);
699
700         crit_exit();
701 }
702
703 static int
704 rum_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
705 {
706         struct rum_softc *sc = ic->ic_if.if_softc;
707         struct ifnet *ifp = &ic->ic_if;
708
709         crit_enter();
710
711         ASSERT_SERIALIZED(ifp->if_serializer);
712
713         callout_stop(&sc->scan_ch);
714         callout_stop(&sc->stats_ch);
715
716         /* do it in a process context */
717         sc->sc_state = nstate;
718         sc->sc_arg = arg;
719
720         lwkt_serialize_exit(ifp->if_serializer);
721         usb_rem_task(sc->sc_udev, &sc->sc_task);
722
723         if (nstate == IEEE80211_S_INIT) {
724                 lwkt_serialize_enter(ifp->if_serializer);
725                 ieee80211_ratectl_newstate(ic, nstate);
726                 sc->sc_newstate(ic, nstate, arg);
727         } else {
728                 usb_add_task(sc->sc_udev, &sc->sc_task, USB_TASKQ_DRIVER);
729                 lwkt_serialize_enter(ifp->if_serializer);
730         }
731
732         crit_exit();
733         return 0;
734 }
735
736 /* quickly determine if a given rate is CCK or OFDM */
737 #define RUM_RATE_IS_OFDM(rate)  ((rate) >= 12 && (rate) != 22)
738
739 #define RUM_ACK_SIZE    (sizeof(struct ieee80211_frame_ack) + IEEE80211_CRC_LEN)
740
741 static void
742 rum_txeof(usbd_xfer_handle xfer, usbd_private_handle priv, usbd_status status)
743 {
744         struct rum_tx_data *data = priv;
745         struct rum_softc *sc = data->sc;
746         struct ieee80211com *ic = &sc->sc_ic;
747         struct ifnet *ifp = &ic->ic_if;
748         struct ieee80211_node *ni;
749
750         if (sc->sc_stopped)
751                 return;
752
753         crit_enter();
754
755         if (status != USBD_NORMAL_COMPLETION) {
756                 if (status == USBD_NOT_STARTED || status == USBD_CANCELLED) {
757                         crit_exit();
758                         return;
759                 }
760
761                 kprintf("%s: could not transmit buffer: %s\n",
762                     device_get_nameunit(sc->sc_dev), usbd_errstr(status));
763
764                 if (status == USBD_STALLED)
765                         usbd_clear_endpoint_stall_async(sc->sc_tx_pipeh);
766
767                 ifp->if_oerrors++;
768                 crit_exit();
769                 return;
770         }
771
772         m_freem(data->m);
773         data->m = NULL;
774         ni = data->ni;
775         data->ni = NULL;
776
777         bzero(data->buf, sizeof(struct rum_tx_data));
778         sc->tx_queued--;
779         ifp->if_opackets++;     /* XXX may fail too */
780
781         DPRINTFN(10, ("tx done\n"));
782
783         sc->sc_tx_timer = 0;
784         ifp->if_flags &= ~IFF_OACTIVE;
785
786         lwkt_serialize_enter(ifp->if_serializer);
787         ieee80211_free_node(ni);
788         ifp->if_start(ifp);
789         lwkt_serialize_exit(ifp->if_serializer);
790
791         crit_exit();
792 }
793
794 static void
795 rum_rxeof(usbd_xfer_handle xfer, usbd_private_handle priv, usbd_status status)
796 {
797         struct rum_rx_data *data = priv;
798         struct rum_softc *sc = data->sc;
799         struct ieee80211com *ic = &sc->sc_ic;
800         struct ifnet *ifp = &ic->ic_if;
801         struct rum_rx_desc *desc;
802         struct ieee80211_frame_min *wh;
803         struct ieee80211_node *ni;
804         struct mbuf *mnew, *m;
805         int len, rssi;
806
807         if (sc->sc_stopped)
808                 return;
809
810         crit_enter();
811
812         if (status != USBD_NORMAL_COMPLETION) {
813                 if (status == USBD_NOT_STARTED || status == USBD_CANCELLED) {
814                         crit_exit();
815                         return;
816                 }
817
818                 if (status == USBD_STALLED)
819                         usbd_clear_endpoint_stall_async(sc->sc_rx_pipeh);
820                 goto skip;
821         }
822
823         usbd_get_xfer_status(xfer, NULL, NULL, &len, NULL);
824
825         if (len < RT2573_RX_DESC_SIZE + sizeof(struct ieee80211_frame_min)) {
826                 DPRINTF(("%s: xfer too short %d\n", device_get_nameunit(sc->sc_dev),
827                     len));
828                 ifp->if_ierrors++;
829                 goto skip;
830         }
831
832         desc = (struct rum_rx_desc *)data->buf;
833
834         if (le32toh(desc->flags) & RT2573_RX_CRC_ERROR) {
835                 /*
836                  * This should not happen since we did not request to receive
837                  * those frames when we filled RT2573_TXRX_CSR0.
838                  */
839                 DPRINTFN(5, ("CRC error\n"));
840                 ifp->if_ierrors++;
841                 goto skip;
842         }
843
844         mnew = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
845         if (mnew == NULL) {
846                 kprintf("%s: could not allocate rx mbuf\n",
847                     device_get_nameunit(sc->sc_dev));
848                 ifp->if_ierrors++;
849                 goto skip;
850         }
851
852         m = data->m;
853         data->m = NULL;
854         data->buf = NULL;
855
856         lwkt_serialize_enter(ifp->if_serializer);
857
858         /* finalize mbuf */
859         m->m_pkthdr.rcvif = ifp;
860         m->m_data = (caddr_t)(desc + 1);
861         m->m_pkthdr.len = m->m_len = (le32toh(desc->flags) >> 16) & 0xfff;
862
863         rssi = rum_get_rssi(sc, desc->rssi);
864
865         wh = mtod(m, struct ieee80211_frame_min *);
866         ni = ieee80211_find_rxnode(ic, wh);
867
868         /* Error happened during RSSI conversion. */
869         if (rssi < 0)
870                 rssi = ni->ni_rssi;
871
872         if (sc->sc_drvbpf != NULL) {
873                 struct rum_rx_radiotap_header *tap = &sc->sc_rxtap;
874
875                 tap->wr_flags = 0;
876                 tap->wr_rate = rum_rxrate(desc);
877                 tap->wr_chan_freq = htole16(ic->ic_bss->ni_chan->ic_freq);
878                 tap->wr_chan_flags = htole16(ic->ic_bss->ni_chan->ic_flags);
879                 tap->wr_antenna = sc->rx_ant;
880                 tap->wr_antsignal = rssi;
881
882                 bpf_ptap(sc->sc_drvbpf, m, tap, sc->sc_rxtap_len);
883         }
884
885         /* send the frame to the 802.11 layer */
886         ieee80211_input(ic, m, ni, rssi, 0);
887
888         /* node is no longer needed */
889         ieee80211_free_node(ni);
890
891         if ((ifp->if_flags & IFF_OACTIVE) == 0)
892                 ifp->if_start(ifp);
893
894         lwkt_serialize_exit(ifp->if_serializer);
895
896         data->m = mnew;
897         data->buf = mtod(data->m, uint8_t *);
898
899         DPRINTFN(15, ("rx done\n"));
900
901 skip:   /* setup a new transfer */
902         bzero(data->buf, sizeof(struct rum_rx_desc));
903         usbd_setup_xfer(xfer, sc->sc_rx_pipeh, data, data->buf, MCLBYTES,
904             USBD_SHORT_XFER_OK, USBD_NO_TIMEOUT, rum_rxeof);
905         usbd_transfer(xfer);
906
907         crit_exit();
908 }
909
910 /*
911  * This function is only used by the Rx radiotap code. It returns the rate at
912  * which a given frame was received.
913  */
914 static uint8_t
915 rum_rxrate(struct rum_rx_desc *desc)
916 {
917         if (le32toh(desc->flags) & RT2573_RX_OFDM) {
918                 /* reverse function of rum_plcp_signal */
919                 switch (desc->rate) {
920                 case 0xb:       return 12;
921                 case 0xf:       return 18;
922                 case 0xa:       return 24;
923                 case 0xe:       return 36;
924                 case 0x9:       return 48;
925                 case 0xd:       return 72;
926                 case 0x8:       return 96;
927                 case 0xc:       return 108;
928                 }
929         } else {
930                 if (desc->rate == 10)
931                         return 2;
932                 if (desc->rate == 20)
933                         return 4;
934                 if (desc->rate == 55)
935                         return 11;
936                 if (desc->rate == 110)
937                         return 22;
938         }
939         return 2;       /* should not get there */
940 }
941
942 static uint8_t
943 rum_plcp_signal(int rate)
944 {
945         switch (rate) {
946         /* CCK rates (returned values are device-dependent) */
947         case 2:         return 0x0;
948         case 4:         return 0x1;
949         case 11:        return 0x2;
950         case 22:        return 0x3;
951
952         /* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
953         case 12:        return 0xb;
954         case 18:        return 0xf;
955         case 24:        return 0xa;
956         case 36:        return 0xe;
957         case 48:        return 0x9;
958         case 72:        return 0xd;
959         case 96:        return 0x8;
960         case 108:       return 0xc;
961
962         /* unsupported rates (should not get there) */
963         default:        return 0xff;
964         }
965 }
966
967 static void
968 rum_setup_tx_desc(struct rum_softc *sc, struct rum_tx_desc *desc,
969     uint32_t flags, uint16_t xflags, int len, int rate)
970 {
971         struct ieee80211com *ic = &sc->sc_ic;
972         uint16_t plcp_length;
973         int remainder;
974
975         desc->flags = htole32(flags);
976         desc->flags |= htole32(len << 16);
977
978         desc->xflags = htole16(xflags);
979
980         desc->wme = htole16(
981             RT2573_QID(0) |
982             RT2573_AIFSN(2) |
983             RT2573_LOGCWMIN(4) |
984             RT2573_LOGCWMAX(10));
985
986         /* setup PLCP fields */
987         desc->plcp_signal  = rum_plcp_signal(rate);
988         desc->plcp_service = 4;
989
990         len += IEEE80211_CRC_LEN;
991         if (RUM_RATE_IS_OFDM(rate)) {
992                 desc->flags |= htole32(RT2573_TX_OFDM);
993
994                 plcp_length = len & 0xfff;
995                 desc->plcp_length_hi = plcp_length >> 6;
996                 desc->plcp_length_lo = plcp_length & 0x3f;
997         } else {
998                 plcp_length = (16 * len + rate - 1) / rate;
999                 if (rate == 22) {
1000                         remainder = (16 * len) % 22;
1001                         if (remainder != 0 && remainder < 7)
1002                                 desc->plcp_service |= RT2573_PLCP_LENGEXT;
1003                 }
1004                 desc->plcp_length_hi = plcp_length >> 8;
1005                 desc->plcp_length_lo = plcp_length & 0xff;
1006
1007                 if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1008                         desc->plcp_signal |= 0x08;
1009         }
1010         desc->flags |= htole32(RT2573_TX_VALID);
1011 }
1012
1013 #define RUM_TX_TIMEOUT  5000
1014
1015 static int
1016 rum_tx_data(struct rum_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1017 {
1018         struct ieee80211com *ic = &sc->sc_ic;
1019         struct ifnet *ifp = &ic->ic_if;
1020         struct rum_tx_desc *desc;
1021         struct rum_tx_data *data;
1022         struct ieee80211_frame *wh;
1023         uint32_t flags = 0;
1024         uint16_t dur;
1025         usbd_status error;
1026         int xferlen, rate, rateidx;
1027
1028         wh = mtod(m0, struct ieee80211_frame *);
1029
1030         if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1031                 if (ieee80211_crypto_encap(ic, ni, m0) == NULL) {
1032                         m_freem(m0);
1033                         return ENOBUFS;
1034                 }
1035
1036                 /* packet header may have moved, reset our local pointer */
1037                 wh = mtod(m0, struct ieee80211_frame *);
1038         }
1039
1040         /* pickup a rate */
1041         if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
1042             IEEE80211_FC0_TYPE_MGT) {
1043                 /* mgmt frames are sent at the lowest available bit-rate */
1044                 rateidx = 0;
1045         } else {
1046                 ieee80211_ratectl_findrate(ni, m0->m_pkthdr.len, &rateidx, 1);
1047         }
1048         rate = IEEE80211_RS_RATE(&ni->ni_rates, rateidx);
1049
1050         data = &sc->tx_data[0];
1051         desc = (struct rum_tx_desc *)data->buf;
1052
1053         data->m = m0;
1054         data->ni = ni;
1055
1056         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1057                 flags |= RT2573_TX_ACK;
1058
1059                 dur = ieee80211_txtime(ni, RUM_ACK_SIZE,
1060                         ieee80211_ack_rate(ni, rate), ic->ic_flags) +
1061                         sc->sc_sifs;
1062                 *(uint16_t *)wh->i_dur = htole16(dur);
1063
1064                 /* tell hardware to set timestamp in probe responses */
1065                 if ((wh->i_fc[0] &
1066                     (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
1067                     (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP))
1068                         flags |= RT2573_TX_TIMESTAMP;
1069         }
1070
1071         if (sc->sc_drvbpf != NULL) {
1072                 struct rum_tx_radiotap_header *tap = &sc->sc_txtap;
1073
1074                 tap->wt_flags = 0;
1075                 tap->wt_rate = rate;
1076                 tap->wt_chan_freq = htole16(ic->ic_bss->ni_chan->ic_freq);
1077                 tap->wt_chan_flags = htole16(ic->ic_bss->ni_chan->ic_flags);
1078                 tap->wt_antenna = sc->tx_ant;
1079
1080                 bpf_ptap(sc->sc_drvbpf, m0, tap, sc->sc_txtap_len);
1081         }
1082
1083         m_copydata(m0, 0, m0->m_pkthdr.len, data->buf + RT2573_TX_DESC_SIZE);
1084         rum_setup_tx_desc(sc, desc, flags, 0, m0->m_pkthdr.len, rate);
1085
1086         /* Align end on a 4-bytes boundary */
1087         xferlen = roundup(RT2573_TX_DESC_SIZE + m0->m_pkthdr.len, 4);
1088
1089         /*
1090          * No space left in the last URB to store the extra 4 bytes, force
1091          * sending of another URB.
1092          */
1093         if ((xferlen % 64) == 0)
1094                 xferlen += 4;
1095
1096         DPRINTFN(10, ("sending frame len=%u rate=%u xfer len=%u\n",
1097             m0->m_pkthdr.len + RT2573_TX_DESC_SIZE, rate, xferlen));
1098
1099         lwkt_serialize_exit(ifp->if_serializer);
1100
1101         usbd_setup_xfer(data->xfer, sc->sc_tx_pipeh, data, data->buf, xferlen,
1102             USBD_FORCE_SHORT_XFER | USBD_NO_COPY, RUM_TX_TIMEOUT, rum_txeof);
1103
1104         error = usbd_transfer(data->xfer);
1105         if (error != USBD_NORMAL_COMPLETION && error != USBD_IN_PROGRESS) {
1106                 m_freem(m0);
1107                 data->m = NULL;
1108                 data->ni = NULL;
1109         } else {
1110                 sc->tx_queued++;
1111                 error = 0;
1112         }
1113
1114         lwkt_serialize_enter(ifp->if_serializer);
1115         return error;
1116 }
1117
1118 static void
1119 rum_start(struct ifnet *ifp)
1120 {
1121         struct rum_softc *sc = ifp->if_softc;
1122         struct ieee80211com *ic = &sc->sc_ic;
1123
1124         ASSERT_SERIALIZED(ifp->if_serializer);
1125
1126         if (sc->sc_stopped)
1127                 return;
1128
1129         crit_enter();
1130
1131         if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING) {
1132                 crit_exit();
1133                 return;
1134         }
1135
1136         for (;;) {
1137                 struct ieee80211_node *ni;
1138                 struct mbuf *m0;
1139
1140                 if (!IF_QEMPTY(&ic->ic_mgtq)) {
1141                         if (sc->tx_queued >= RT2573_TX_LIST_COUNT) {
1142                                 ifp->if_flags |= IFF_OACTIVE;
1143                                 break;
1144                         }
1145                         IF_DEQUEUE(&ic->ic_mgtq, m0);
1146
1147                         ni = (struct ieee80211_node *)m0->m_pkthdr.rcvif;
1148                         m0->m_pkthdr.rcvif = NULL;
1149
1150                         BPF_MTAP(ifp, m0);
1151
1152                         if (rum_tx_data(sc, m0, ni) != 0) {
1153                                 ieee80211_free_node(ni);
1154                                 break;
1155                         }
1156                 } else {
1157                         struct ether_header *eh;
1158
1159                         if (ic->ic_state != IEEE80211_S_RUN)
1160                                 break;
1161
1162                         m0 = ifq_poll(&ifp->if_snd);
1163                         if (m0 == NULL)
1164                                 break;
1165                         if (sc->tx_queued >= RT2573_TX_LIST_COUNT) {
1166                                 ifp->if_flags |= IFF_OACTIVE;
1167                                 break;
1168                         }
1169                         ifq_dequeue(&ifp->if_snd, m0);
1170
1171                         if (m0->m_len < sizeof(struct ether_header)) {
1172                                 m0 = m_pullup(m0, sizeof(struct ether_header));
1173                                 if (m0 == NULL) {
1174                                         ifp->if_oerrors++;
1175                                         continue;
1176                                 }
1177                         }
1178                         eh = mtod(m0, struct ether_header *);
1179
1180                         ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1181                         if (ni == NULL) {
1182                                 m_freem(m0);
1183                                 continue;
1184                         }
1185
1186                         BPF_MTAP(ifp, m0);
1187
1188                         m0 = ieee80211_encap(ic, m0, ni);
1189                         if (m0 == NULL) {
1190                                 ieee80211_free_node(ni);
1191                                 continue;
1192                         }
1193
1194                         if (ic->ic_rawbpf != NULL)
1195                                 bpf_mtap(ic->ic_rawbpf, m0);
1196
1197                         if (rum_tx_data(sc, m0, ni) != 0) {
1198                                 ieee80211_free_node(ni);
1199                                 ifp->if_oerrors++;
1200                                 break;
1201                         }
1202                 }
1203
1204                 sc->sc_tx_timer = 5;
1205                 ifp->if_timer = 1;
1206         }
1207
1208         crit_exit();
1209 }
1210
1211 static void
1212 rum_watchdog(struct ifnet *ifp)
1213 {
1214         struct rum_softc *sc = ifp->if_softc;
1215
1216         ASSERT_SERIALIZED(ifp->if_serializer);
1217
1218         crit_enter();
1219
1220         ifp->if_timer = 0;
1221
1222         if (sc->sc_tx_timer > 0) {
1223                 if (--sc->sc_tx_timer == 0) {
1224                         kprintf("%s: device timeout\n", device_get_nameunit(sc->sc_dev));
1225                         /*rum_init(sc); XXX needs a process context! */
1226                         ifp->if_oerrors++;
1227
1228                         crit_exit();
1229                         return;
1230                 }
1231                 ifp->if_timer = 1;
1232         }
1233
1234         ieee80211_watchdog(&sc->sc_ic);
1235
1236         crit_exit();
1237 }
1238
1239 static int
1240 rum_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data, struct ucred *cr)
1241 {
1242         struct rum_softc *sc = ifp->if_softc;
1243         struct ieee80211com *ic = &sc->sc_ic;
1244         int error = 0;
1245
1246         ASSERT_SERIALIZED(ifp->if_serializer);
1247
1248         crit_enter();
1249
1250         switch (cmd) {
1251         case SIOCSIFFLAGS:
1252                 if (ifp->if_flags & IFF_UP) {
1253                         if (ifp->if_flags & IFF_RUNNING) {
1254                                 lwkt_serialize_exit(ifp->if_serializer);
1255                                 rum_update_promisc(sc);
1256                                 lwkt_serialize_enter(ifp->if_serializer);
1257                         } else {
1258                                 rum_init(sc);
1259                         }
1260                 } else {
1261                         if (ifp->if_flags & IFF_RUNNING)
1262                                 rum_stop(sc);
1263                 }
1264                 break;
1265         default:
1266                 error = ieee80211_ioctl(ic, cmd, data, cr);
1267                 break;
1268         }
1269
1270         if (error == ENETRESET) {
1271                 struct ieee80211req *ireq = (struct ieee80211req *)data;
1272
1273                 if (cmd == SIOCS80211 &&
1274                     ireq->i_type == IEEE80211_IOC_CHANNEL &&
1275                     ic->ic_opmode == IEEE80211_M_MONITOR) {
1276                         /*
1277                          * This allows for fast channel switching in monitor
1278                          * mode (used by kismet). In IBSS mode, we must
1279                          * explicitly reset the interface to generate a new
1280                          * beacon frame.
1281                          */
1282                         lwkt_serialize_exit(ifp->if_serializer);
1283                         rum_set_chan(sc, ic->ic_ibss_chan);
1284                         lwkt_serialize_enter(ifp->if_serializer);
1285                 } else if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
1286                            (IFF_UP | IFF_RUNNING)) {
1287                         rum_init(sc);
1288                 }
1289                 error = 0;
1290         }
1291
1292         crit_exit();
1293         return error;
1294 }
1295
1296 static void
1297 rum_eeprom_read(struct rum_softc *sc, uint16_t addr, void *buf, int len)
1298 {
1299         usb_device_request_t req;
1300         usbd_status error;
1301
1302         req.bmRequestType = UT_READ_VENDOR_DEVICE;
1303         req.bRequest = RT2573_READ_EEPROM;
1304         USETW(req.wValue, 0);
1305         USETW(req.wIndex, addr);
1306         USETW(req.wLength, len);
1307
1308         error = usbd_do_request(sc->sc_udev, &req, buf);
1309         if (error != 0) {
1310                 kprintf("%s: could not read EEPROM: %s\n",
1311                     device_get_nameunit(sc->sc_dev), usbd_errstr(error));
1312         }
1313 }
1314
1315 static uint32_t
1316 rum_read(struct rum_softc *sc, uint16_t reg)
1317 {
1318         uint32_t val;
1319
1320         rum_read_multi(sc, reg, &val, sizeof val);
1321
1322         return le32toh(val);
1323 }
1324
1325 static void
1326 rum_read_multi(struct rum_softc *sc, uint16_t reg, void *buf, int len)
1327 {
1328         usb_device_request_t req;
1329         usbd_status error;
1330
1331         req.bmRequestType = UT_READ_VENDOR_DEVICE;
1332         req.bRequest = RT2573_READ_MULTI_MAC;
1333         USETW(req.wValue, 0);
1334         USETW(req.wIndex, reg);
1335         USETW(req.wLength, len);
1336
1337         error = usbd_do_request(sc->sc_udev, &req, buf);
1338         if (error != 0) {
1339                 kprintf("%s: could not multi read MAC register: %s\n",
1340                     device_get_nameunit(sc->sc_dev), usbd_errstr(error));
1341         }
1342 }
1343
1344 static void
1345 rum_write(struct rum_softc *sc, uint16_t reg, uint32_t val)
1346 {
1347         uint32_t tmp = htole32(val);
1348
1349         rum_write_multi(sc, reg, &tmp, sizeof tmp);
1350 }
1351
1352 static void
1353 rum_write_multi(struct rum_softc *sc, uint16_t reg, void *buf, size_t len)
1354 {
1355         usb_device_request_t req;
1356         usbd_status error;
1357
1358         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1359         req.bRequest = RT2573_WRITE_MULTI_MAC;
1360         USETW(req.wValue, 0);
1361         USETW(req.wIndex, reg);
1362         USETW(req.wLength, len);
1363
1364         error = usbd_do_request(sc->sc_udev, &req, buf);
1365         if (error != 0) {
1366                 kprintf("%s: could not multi write MAC register: %s\n",
1367                     device_get_nameunit(sc->sc_dev), usbd_errstr(error));
1368         }
1369 }
1370
1371 static void
1372 rum_bbp_write(struct rum_softc *sc, uint8_t reg, uint8_t val)
1373 {
1374         uint32_t tmp;
1375         int ntries;
1376
1377         for (ntries = 0; ntries < 5; ntries++) {
1378                 if (!(rum_read(sc, RT2573_PHY_CSR3) & RT2573_BBP_BUSY))
1379                         break;
1380         }
1381         if (ntries == 5) {
1382                 kprintf("%s: could not write to BBP\n", device_get_nameunit(sc->sc_dev));
1383                 return;
1384         }
1385
1386         tmp = RT2573_BBP_BUSY | (reg & 0x7f) << 8 | val;
1387         rum_write(sc, RT2573_PHY_CSR3, tmp);
1388 }
1389
1390 static uint8_t
1391 rum_bbp_read(struct rum_softc *sc, uint8_t reg)
1392 {
1393         uint32_t val;
1394         int ntries;
1395
1396         for (ntries = 0; ntries < 5; ntries++) {
1397                 if (!(rum_read(sc, RT2573_PHY_CSR3) & RT2573_BBP_BUSY))
1398                         break;
1399         }
1400         if (ntries == 5) {
1401                 kprintf("%s: could not read BBP\n", device_get_nameunit(sc->sc_dev));
1402                 return 0;
1403         }
1404
1405         val = RT2573_BBP_BUSY | RT2573_BBP_READ | reg << 8;
1406         rum_write(sc, RT2573_PHY_CSR3, val);
1407
1408         for (ntries = 0; ntries < 100; ntries++) {
1409                 val = rum_read(sc, RT2573_PHY_CSR3);
1410                 if (!(val & RT2573_BBP_BUSY))
1411                         return val & 0xff;
1412                 DELAY(1);
1413         }
1414
1415         kprintf("%s: could not read BBP\n", device_get_nameunit(sc->sc_dev));
1416         return 0;
1417 }
1418
1419 static void
1420 rum_rf_write(struct rum_softc *sc, uint8_t reg, uint32_t val)
1421 {
1422         uint32_t tmp;
1423         int ntries;
1424
1425         for (ntries = 0; ntries < 5; ntries++) {
1426                 if (!(rum_read(sc, RT2573_PHY_CSR4) & RT2573_RF_BUSY))
1427                         break;
1428         }
1429         if (ntries == 5) {
1430                 kprintf("%s: could not write to RF\n", device_get_nameunit(sc->sc_dev));
1431                 return;
1432         }
1433
1434         tmp = RT2573_RF_BUSY | RT2573_RF_20BIT | (val & 0xfffff) << 2 |
1435             (reg & 3);
1436         rum_write(sc, RT2573_PHY_CSR4, tmp);
1437
1438         /* remember last written value in sc */
1439         sc->rf_regs[reg] = val;
1440
1441         DPRINTFN(15, ("RF R[%u] <- 0x%05x\n", reg & 3, val & 0xfffff));
1442 }
1443
1444 static void
1445 rum_select_antenna(struct rum_softc *sc)
1446 {
1447         uint8_t bbp4, bbp77;
1448         uint32_t tmp;
1449
1450         bbp4  = rum_bbp_read(sc, 4);
1451         bbp77 = rum_bbp_read(sc, 77);
1452
1453         /* TBD */
1454
1455         /* make sure Rx is disabled before switching antenna */
1456         tmp = rum_read(sc, RT2573_TXRX_CSR0);
1457         rum_write(sc, RT2573_TXRX_CSR0, tmp | RT2573_DISABLE_RX);
1458
1459         rum_bbp_write(sc,  4, bbp4);
1460         rum_bbp_write(sc, 77, bbp77);
1461
1462         rum_write(sc, RT2573_TXRX_CSR0, tmp);
1463 }
1464
1465 /*
1466  * Enable multi-rate retries for frames sent at OFDM rates.
1467  * In 802.11b/g mode, allow fallback to CCK rates.
1468  */
1469 static void
1470 rum_enable_mrr(struct rum_softc *sc)
1471 {
1472         struct ieee80211com *ic = &sc->sc_ic;
1473         uint32_t tmp;
1474
1475         tmp = rum_read(sc, RT2573_TXRX_CSR4);
1476
1477         tmp &= ~RT2573_MRR_CCK_FALLBACK;
1478         if (!IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan))
1479                 tmp |= RT2573_MRR_CCK_FALLBACK;
1480         tmp |= RT2573_MRR_ENABLED;
1481
1482         rum_write(sc, RT2573_TXRX_CSR4, tmp);
1483 }
1484
1485 static void
1486 rum_set_txpreamble(struct rum_softc *sc)
1487 {
1488         uint32_t tmp;
1489
1490         tmp = rum_read(sc, RT2573_TXRX_CSR4);
1491
1492         tmp &= ~RT2573_SHORT_PREAMBLE;
1493         if (sc->sc_ic.ic_flags & IEEE80211_F_SHPREAMBLE)
1494                 tmp |= RT2573_SHORT_PREAMBLE;
1495
1496         rum_write(sc, RT2573_TXRX_CSR4, tmp);
1497 }
1498
1499 static void
1500 rum_set_basicrates(struct rum_softc *sc)
1501 {
1502         struct ieee80211com *ic = &sc->sc_ic;
1503
1504         /* update basic rate set */
1505         if (ic->ic_curmode == IEEE80211_MODE_11B) {
1506                 /* 11b basic rates: 1, 2Mbps */
1507                 rum_write(sc, RT2573_TXRX_CSR5, 0x3);
1508         } else if (IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan)) {
1509                 /* 11a basic rates: 6, 12, 24Mbps */
1510                 rum_write(sc, RT2573_TXRX_CSR5, 0x150);
1511         } else {
1512                 /* 11g basic rates: 1, 2, 5.5, 11, 6, 12, 24Mbps */
1513                 rum_write(sc, RT2573_TXRX_CSR5, 0x15f);
1514         }
1515 }
1516
1517 /*
1518  * Reprogram MAC/BBP to switch to a new band.  Values taken from the reference
1519  * driver.
1520  */
1521 static void
1522 rum_select_band(struct rum_softc *sc, struct ieee80211_channel *c)
1523 {
1524         uint8_t bbp17, bbp35, bbp96, bbp97, bbp98, bbp104;
1525         uint32_t tmp;
1526
1527         /* update all BBP registers that depend on the band */
1528         bbp17 = 0x20; bbp96 = 0x48; bbp104 = 0x2c;
1529         bbp35 = 0x50; bbp97 = 0x48; bbp98  = 0x48;
1530         if (IEEE80211_IS_CHAN_5GHZ(c)) {
1531                 bbp17 += 0x08; bbp96 += 0x10; bbp104 += 0x0c;
1532                 bbp35 += 0x10; bbp97 += 0x10; bbp98  += 0x10;
1533         }
1534         if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
1535             (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
1536                 bbp17 += 0x10; bbp96 += 0x10; bbp104 += 0x10;
1537         }
1538
1539         sc->bbp17 = bbp17;
1540         rum_bbp_write(sc,  17, bbp17);
1541         rum_bbp_write(sc,  96, bbp96);
1542         rum_bbp_write(sc, 104, bbp104);
1543
1544         if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
1545             (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
1546                 rum_bbp_write(sc, 75, 0x80);
1547                 rum_bbp_write(sc, 86, 0x80);
1548                 rum_bbp_write(sc, 88, 0x80);
1549         }
1550
1551         rum_bbp_write(sc, 35, bbp35);
1552         rum_bbp_write(sc, 97, bbp97);
1553         rum_bbp_write(sc, 98, bbp98);
1554
1555         tmp = rum_read(sc, RT2573_PHY_CSR0);
1556         tmp &= ~(RT2573_PA_PE_2GHZ | RT2573_PA_PE_5GHZ);
1557         if (IEEE80211_IS_CHAN_2GHZ(c))
1558                 tmp |= RT2573_PA_PE_2GHZ;
1559         else
1560                 tmp |= RT2573_PA_PE_5GHZ;
1561         rum_write(sc, RT2573_PHY_CSR0, tmp);
1562 }
1563
1564 static void
1565 rum_set_chan(struct rum_softc *sc, struct ieee80211_channel *c)
1566 {
1567         struct ieee80211com *ic = &sc->sc_ic;
1568         const struct rfprog *rfprog;
1569         uint8_t bbp3, bbp94 = RT2573_BBPR94_DEFAULT;
1570         int8_t power;
1571         u_int i, chan;
1572
1573         chan = ieee80211_chan2ieee(ic, c);
1574         if (chan == 0 || chan == IEEE80211_CHAN_ANY)
1575                 return;
1576
1577         /* select the appropriate RF settings based on what EEPROM says */
1578         rfprog = (sc->rf_rev == RT2573_RF_5225 ||
1579                   sc->rf_rev == RT2573_RF_2527) ? rum_rf5225 : rum_rf5226;
1580
1581         /* find the settings for this channel (we know it exists) */
1582         for (i = 0; rfprog[i].chan != chan; i++)
1583                 ;       /* EMPTY */
1584
1585         power = sc->txpow[i];
1586         if (power < 0) {
1587                 bbp94 += power;
1588                 power = 0;
1589         } else if (power > 31) {
1590                 bbp94 += power - 31;
1591                 power = 31;
1592         }
1593
1594         /*
1595          * If we are switching from the 2GHz band to the 5GHz band or
1596          * vice-versa, BBP registers need to be reprogrammed.
1597          */
1598         if (c->ic_flags != sc->sc_curchan->ic_flags) {
1599                 rum_select_band(sc, c);
1600                 rum_select_antenna(sc);
1601         }
1602         sc->sc_curchan = c;
1603
1604         rum_rf_write(sc, RT2573_RF1, rfprog[i].r1);
1605         rum_rf_write(sc, RT2573_RF2, rfprog[i].r2);
1606         rum_rf_write(sc, RT2573_RF3, rfprog[i].r3 | power << 7);
1607         rum_rf_write(sc, RT2573_RF4, rfprog[i].r4 | sc->rffreq << 10);
1608
1609         rum_rf_write(sc, RT2573_RF1, rfprog[i].r1);
1610         rum_rf_write(sc, RT2573_RF2, rfprog[i].r2);
1611         rum_rf_write(sc, RT2573_RF3, rfprog[i].r3 | power << 7 | 1);
1612         rum_rf_write(sc, RT2573_RF4, rfprog[i].r4 | sc->rffreq << 10);
1613
1614         rum_rf_write(sc, RT2573_RF1, rfprog[i].r1);
1615         rum_rf_write(sc, RT2573_RF2, rfprog[i].r2);
1616         rum_rf_write(sc, RT2573_RF3, rfprog[i].r3 | power << 7);
1617         rum_rf_write(sc, RT2573_RF4, rfprog[i].r4 | sc->rffreq << 10);
1618
1619         DELAY(10);
1620
1621         /* enable smart mode for MIMO-capable RFs */
1622         bbp3 = rum_bbp_read(sc, 3);
1623
1624         if (sc->rf_rev == RT2573_RF_5225 || sc->rf_rev == RT2573_RF_2527)
1625                 bbp3 &= ~RT2573_SMART_MODE;
1626         else
1627                 bbp3 |= RT2573_SMART_MODE;
1628
1629         rum_bbp_write(sc, 3, bbp3);
1630
1631         if (bbp94 != RT2573_BBPR94_DEFAULT)
1632                 rum_bbp_write(sc, 94, bbp94);
1633
1634         sc->sc_sifs = IEEE80211_IS_CHAN_5GHZ(c) ? IEEE80211_DUR_OFDM_SIFS
1635                                                 : IEEE80211_DUR_SIFS;
1636 }
1637
1638 /*
1639  * Enable TSF synchronization and tell h/w to start sending beacons for IBSS
1640  * and HostAP operating modes.
1641  */
1642 static void
1643 rum_enable_tsf_sync(struct rum_softc *sc)
1644 {
1645         struct ieee80211com *ic = &sc->sc_ic;
1646         uint32_t tmp;
1647
1648         if (ic->ic_opmode != IEEE80211_M_STA) {
1649                 /*
1650                  * Change default 16ms TBTT adjustment to 8ms.
1651                  * Must be done before enabling beacon generation.
1652                  */
1653                 rum_write(sc, RT2573_TXRX_CSR10, 1 << 12 | 8);
1654         }
1655
1656         tmp = rum_read(sc, RT2573_TXRX_CSR9) & 0xff000000;
1657
1658         /* set beacon interval (in 1/16ms unit) */
1659         tmp |= ic->ic_bss->ni_intval * 16;
1660
1661         tmp |= RT2573_TSF_TICKING | RT2573_ENABLE_TBTT;
1662         if (ic->ic_opmode == IEEE80211_M_STA)
1663                 tmp |= RT2573_TSF_MODE(1);
1664         else
1665                 tmp |= RT2573_TSF_MODE(2) | RT2573_GENERATE_BEACON;
1666
1667         rum_write(sc, RT2573_TXRX_CSR9, tmp);
1668 }
1669
1670 static void
1671 rum_update_slot(struct rum_softc *sc)
1672 {
1673         struct ieee80211com *ic = &sc->sc_ic;
1674         uint8_t slottime;
1675         uint32_t tmp;
1676
1677         slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
1678
1679         tmp = rum_read(sc, RT2573_MAC_CSR9);
1680         tmp = (tmp & ~0xff) | slottime;
1681         rum_write(sc, RT2573_MAC_CSR9, tmp);
1682
1683         DPRINTF(("setting slot time to %uus\n", slottime));
1684 }
1685
1686 static void
1687 rum_set_bssid(struct rum_softc *sc, const uint8_t *bssid)
1688 {
1689         uint32_t tmp;
1690
1691         tmp = bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24;
1692         rum_write(sc, RT2573_MAC_CSR4, tmp);
1693
1694         tmp = bssid[4] | bssid[5] << 8 | RT2573_ONE_BSSID << 16;
1695         rum_write(sc, RT2573_MAC_CSR5, tmp);
1696 }
1697
1698 static void
1699 rum_set_macaddr(struct rum_softc *sc, const uint8_t *addr)
1700 {
1701         uint32_t tmp;
1702
1703         tmp = addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24;
1704         rum_write(sc, RT2573_MAC_CSR2, tmp);
1705
1706         tmp = addr[4] | addr[5] << 8 | 0xff << 16;
1707         rum_write(sc, RT2573_MAC_CSR3, tmp);
1708 }
1709
1710 static void
1711 rum_update_promisc(struct rum_softc *sc)
1712 {
1713         struct ifnet *ifp = &sc->sc_ic.ic_if;
1714         uint32_t tmp;
1715
1716         tmp = rum_read(sc, RT2573_TXRX_CSR0);
1717
1718         tmp &= ~RT2573_DROP_NOT_TO_ME;
1719         if (!(ifp->if_flags & IFF_PROMISC))
1720                 tmp |= RT2573_DROP_NOT_TO_ME;
1721
1722         rum_write(sc, RT2573_TXRX_CSR0, tmp);
1723
1724         DPRINTF(("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
1725             "entering" : "leaving"));
1726 }
1727
1728 static const char *
1729 rum_get_rf(int rev)
1730 {
1731         switch (rev) {
1732         case RT2573_RF_2527:    return "RT2527 (MIMO XR)";
1733         case RT2573_RF_2528:    return "RT2528";
1734         case RT2573_RF_5225:    return "RT5225 (MIMO XR)";
1735         case RT2573_RF_5226:    return "RT5226";
1736         default:                return "unknown";
1737         }
1738 }
1739
1740 static void
1741 rum_read_eeprom(struct rum_softc *sc)
1742 {
1743         struct ieee80211com *ic = &sc->sc_ic;
1744         uint16_t val;
1745 #ifdef RUM_DEBUG
1746         int i;
1747 #endif
1748
1749         /* read MAC/BBP type */
1750         rum_eeprom_read(sc, RT2573_EEPROM_MACBBP, &val, 2);
1751         sc->macbbp_rev = le16toh(val);
1752
1753         /* read MAC address */
1754         rum_eeprom_read(sc, RT2573_EEPROM_ADDRESS, ic->ic_myaddr, 6);
1755
1756         rum_eeprom_read(sc, RT2573_EEPROM_ANTENNA, &val, 2);
1757         val = le16toh(val);
1758         sc->rf_rev =   (val >> 11) & 0x1f;
1759         sc->hw_radio = (val >> 10) & 0x1;
1760         sc->rx_ant =   (val >> 4)  & 0x3;
1761         sc->tx_ant =   (val >> 2)  & 0x3;
1762         sc->nb_ant =   val & 0x3;
1763
1764         DPRINTF(("RF revision=%d\n", sc->rf_rev));
1765
1766         rum_eeprom_read(sc, RT2573_EEPROM_CONFIG2, &val, 2);
1767         val = le16toh(val);
1768         sc->ext_5ghz_lna = (val >> 6) & 0x1;
1769         sc->ext_2ghz_lna = (val >> 4) & 0x1;
1770
1771         DPRINTF(("External 2GHz LNA=%d\nExternal 5GHz LNA=%d\n",
1772             sc->ext_2ghz_lna, sc->ext_5ghz_lna));
1773
1774         rum_eeprom_read(sc, RT2573_EEPROM_RSSI_2GHZ_OFFSET, &val, 2);
1775         val = le16toh(val);
1776         if ((val & 0xff) != 0xff)
1777                 sc->rssi_2ghz_corr = (int8_t)(val & 0xff);      /* signed */
1778
1779         /* Only [-10, 10] is valid */
1780         if (sc->rssi_2ghz_corr < -10 || sc->rssi_2ghz_corr > 10)
1781                 sc->rssi_2ghz_corr = 0;
1782
1783         rum_eeprom_read(sc, RT2573_EEPROM_RSSI_5GHZ_OFFSET, &val, 2);
1784         val = le16toh(val);
1785         if ((val & 0xff) != 0xff)
1786                 sc->rssi_5ghz_corr = (int8_t)(val & 0xff);      /* signed */
1787
1788         /* Only [-10, 10] is valid */
1789         if (sc->rssi_5ghz_corr < -10 || sc->rssi_5ghz_corr > 10)
1790                 sc->rssi_5ghz_corr = 0;
1791
1792         if (sc->ext_2ghz_lna)
1793                 sc->rssi_2ghz_corr -= 14;
1794         if (sc->ext_5ghz_lna)
1795                 sc->rssi_5ghz_corr -= 14;
1796
1797         DPRINTF(("RSSI 2GHz corr=%d\nRSSI 5GHz corr=%d\n",
1798             sc->rssi_2ghz_corr, sc->rssi_5ghz_corr));
1799
1800         rum_eeprom_read(sc, RT2573_EEPROM_FREQ_OFFSET, &val, 2);
1801         val = le16toh(val);
1802         if ((val & 0xff) != 0xff)
1803                 sc->rffreq = val & 0xff;
1804
1805         DPRINTF(("RF freq=%d\n", sc->rffreq));
1806
1807         /* read Tx power for all a/b/g channels */
1808         rum_eeprom_read(sc, RT2573_EEPROM_TXPOWER, sc->txpow, 14);
1809         /* XXX default Tx power for 802.11a channels */
1810         memset(sc->txpow + 14, 24, sizeof (sc->txpow) - 14);
1811 #ifdef RUM_DEBUG
1812         for (i = 0; i < 14; i++)
1813                 DPRINTF(("Channel=%d Tx power=%d\n", i + 1,  sc->txpow[i]));
1814 #endif
1815
1816         /* read default values for BBP registers */
1817         rum_eeprom_read(sc, RT2573_EEPROM_BBP_BASE, sc->bbp_prom, 2 * 16);
1818 #ifdef RUM_DEBUG
1819         for (i = 0; i < 14; i++) {
1820                 if (sc->bbp_prom[i].reg == 0 || sc->bbp_prom[i].reg == 0xff)
1821                         continue;
1822                 DPRINTF(("BBP R%d=%02x\n", sc->bbp_prom[i].reg,
1823                     sc->bbp_prom[i].val));
1824         }
1825 #endif
1826 }
1827
1828 static int
1829 rum_bbp_init(struct rum_softc *sc)
1830 {
1831 #define N(a)    (sizeof (a) / sizeof ((a)[0]))
1832         int i, ntries;
1833         uint8_t val;
1834
1835         /* wait for BBP to be ready */
1836         for (ntries = 0; ntries < 100; ntries++) {
1837                 val = rum_bbp_read(sc, 0);
1838                 if (val != 0 && val != 0xff)
1839                         break;
1840                 DELAY(1000);
1841         }
1842         if (ntries == 100) {
1843                 kprintf("%s: timeout waiting for BBP\n",
1844                     device_get_nameunit(sc->sc_dev));
1845                 return EIO;
1846         }
1847
1848         /* initialize BBP registers to default values */
1849         for (i = 0; i < N(rum_def_bbp); i++)
1850                 rum_bbp_write(sc, rum_def_bbp[i].reg, rum_def_bbp[i].val);
1851
1852         /* write vendor-specific BBP values (from EEPROM) */
1853         for (i = 0; i < 16; i++) {
1854                 if (sc->bbp_prom[i].reg == 0 || sc->bbp_prom[i].reg == 0xff)
1855                         continue;
1856                 rum_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
1857         }
1858
1859         return 0;
1860 #undef N
1861 }
1862
1863 static void
1864 rum_init(void *xsc)
1865 {
1866 #define N(a)    (sizeof(a) / sizeof((a)[0]))
1867         struct rum_softc *sc = xsc;
1868         struct ieee80211com *ic = &sc->sc_ic;
1869         struct ifnet *ifp = &ic->ic_if;
1870         struct rum_rx_data *data;
1871         uint32_t tmp;
1872         usbd_status usb_err;
1873         int i, ntries, error;
1874
1875         ASSERT_SERIALIZED(ifp->if_serializer);
1876
1877         crit_enter();
1878
1879         rum_stop(sc);
1880         sc->sc_stopped = 0;
1881
1882         lwkt_serialize_exit(ifp->if_serializer);
1883
1884         /* initialize MAC registers to default values */
1885         for (i = 0; i < N(rum_def_mac); i++)
1886                 rum_write(sc, rum_def_mac[i].reg, rum_def_mac[i].val);
1887
1888         /* set host ready */
1889         rum_write(sc, RT2573_MAC_CSR1, 3);
1890         rum_write(sc, RT2573_MAC_CSR1, 0);
1891
1892         /* wait for BBP/RF to wakeup */
1893         for (ntries = 0; ntries < 1000; ntries++) {
1894                 if (rum_read(sc, RT2573_MAC_CSR12) & 8)
1895                         break;
1896                 rum_write(sc, RT2573_MAC_CSR12, 4);     /* force wakeup */
1897                 DELAY(1000);
1898         }
1899         if (ntries == 1000) {
1900                 kprintf("%s: timeout waiting for BBP/RF to wakeup\n",
1901                         device_get_nameunit(sc->sc_dev));
1902                 error = ETIMEDOUT;
1903                 goto fail;
1904         }
1905
1906         error = rum_bbp_init(sc);
1907         if (error)
1908                 goto fail;
1909
1910         /* select default channel */
1911         sc->sc_curchan = ic->ic_curchan = ic->ic_ibss_chan;
1912
1913         rum_select_band(sc, sc->sc_curchan);
1914         rum_select_antenna(sc);
1915         rum_set_chan(sc, sc->sc_curchan);
1916
1917         /* clear STA registers */
1918         rum_read_multi(sc, RT2573_STA_CSR0, sc->sta, sizeof sc->sta);
1919
1920         IEEE80211_ADDR_COPY(ic->ic_myaddr, IF_LLADDR(ifp));
1921         rum_set_macaddr(sc, ic->ic_myaddr);
1922
1923         /* initialize ASIC */
1924         rum_write(sc, RT2573_MAC_CSR1, 4);
1925
1926         /*
1927          * Allocate xfer for AMRR statistics requests.
1928          */
1929         sc->stats_xfer = usbd_alloc_xfer(sc->sc_udev);
1930         if (sc->stats_xfer == NULL) {
1931                 kprintf("%s: could not allocate AMRR xfer\n",
1932                         device_get_nameunit(sc->sc_dev));
1933                 error = ENOMEM;
1934                 goto fail;
1935         }
1936
1937         /*
1938          * Open Tx and Rx USB bulk pipes.
1939          */
1940         usb_err = usbd_open_pipe(sc->sc_iface, sc->sc_tx_no, USBD_EXCLUSIVE_USE,
1941                                  &sc->sc_tx_pipeh);
1942         if (usb_err != USBD_NORMAL_COMPLETION) {
1943                 kprintf("%s: could not open Tx pipe: %s\n",
1944                         device_get_nameunit(sc->sc_dev), usbd_errstr(usb_err));
1945                 error = EIO;
1946                 goto fail;
1947         }
1948
1949         usb_err = usbd_open_pipe(sc->sc_iface, sc->sc_rx_no, USBD_EXCLUSIVE_USE,
1950                                  &sc->sc_rx_pipeh);
1951         if (usb_err != USBD_NORMAL_COMPLETION) {
1952                 kprintf("%s: could not open Rx pipe: %s\n",
1953                     device_get_nameunit(sc->sc_dev), usbd_errstr(usb_err));
1954                 error = EIO;
1955                 goto fail;
1956         }
1957
1958         /*
1959          * Allocate Tx and Rx xfer queues.
1960          */
1961         error = rum_alloc_tx_list(sc);
1962         if (error) {
1963                 kprintf("%s: could not allocate Tx list\n",
1964                         device_get_nameunit(sc->sc_dev));
1965                 goto fail;
1966         }
1967
1968         error = rum_alloc_rx_list(sc);
1969         if (error) {
1970                 kprintf("%s: could not allocate Rx list\n",
1971                         device_get_nameunit(sc->sc_dev));
1972                 goto fail;
1973         }
1974
1975         /*
1976          * Start up the receive pipe.
1977          */
1978         for (i = 0; i < RT2573_RX_LIST_COUNT; i++) {
1979                 data = &sc->rx_data[i];
1980
1981                 usbd_setup_xfer(data->xfer, sc->sc_rx_pipeh, data, data->buf,
1982                     MCLBYTES, USBD_SHORT_XFER_OK, USBD_NO_TIMEOUT, rum_rxeof);
1983                 usbd_transfer(data->xfer);
1984         }
1985
1986         /* update Rx filter */
1987         tmp = rum_read(sc, RT2573_TXRX_CSR0) & 0xffff;
1988
1989         tmp |= RT2573_DROP_PHY_ERROR | RT2573_DROP_CRC_ERROR;
1990         if (ic->ic_opmode != IEEE80211_M_MONITOR) {
1991                 tmp |= RT2573_DROP_CTL | RT2573_DROP_VER_ERROR |
1992                        RT2573_DROP_ACKCTS;
1993                 if (ic->ic_opmode != IEEE80211_M_HOSTAP)
1994                         tmp |= RT2573_DROP_TODS;
1995                 if (!(ifp->if_flags & IFF_PROMISC))
1996                         tmp |= RT2573_DROP_NOT_TO_ME;
1997         }
1998         rum_write(sc, RT2573_TXRX_CSR0, tmp);
1999 fail:
2000         lwkt_serialize_enter(ifp->if_serializer);
2001
2002         if (error) {
2003                 rum_stop(sc);
2004         } else {
2005                 ifp->if_flags &= ~IFF_OACTIVE;
2006                 ifp->if_flags |= IFF_RUNNING;
2007
2008                 if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2009                         if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
2010                                 ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
2011                 } else {
2012                         ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
2013                 }
2014         }
2015
2016         crit_exit();
2017 #undef N
2018 }
2019
2020 static void
2021 rum_stop(struct rum_softc *sc)
2022 {
2023         struct ieee80211com *ic = &sc->sc_ic;
2024         struct ifnet *ifp = &ic->ic_if;
2025         uint32_t tmp;
2026
2027         ASSERT_SERIALIZED(ifp->if_serializer);
2028
2029         crit_enter();
2030
2031         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2032         sc->sc_stopped = 1;
2033
2034         ieee80211_new_state(ic, IEEE80211_S_INIT, -1);  /* free all nodes */
2035
2036         sc->sc_tx_timer = 0;
2037         ifp->if_timer = 0;
2038
2039         lwkt_serialize_exit(ifp->if_serializer);
2040
2041         /* disable Rx */
2042         tmp = rum_read(sc, RT2573_TXRX_CSR0);
2043         rum_write(sc, RT2573_TXRX_CSR0, tmp | RT2573_DISABLE_RX);
2044
2045         /* reset ASIC */
2046         rum_write(sc, RT2573_MAC_CSR1, 3);
2047         rum_write(sc, RT2573_MAC_CSR1, 0);
2048
2049         if (sc->stats_xfer != NULL) {
2050                 usbd_free_xfer(sc->stats_xfer);
2051                 sc->stats_xfer = NULL;
2052         }
2053
2054         if (sc->sc_rx_pipeh != NULL) {
2055                 usbd_abort_pipe(sc->sc_rx_pipeh);
2056                 usbd_close_pipe(sc->sc_rx_pipeh);
2057                 sc->sc_rx_pipeh = NULL;
2058         }
2059
2060         if (sc->sc_tx_pipeh != NULL) {
2061                 usbd_abort_pipe(sc->sc_tx_pipeh);
2062                 usbd_close_pipe(sc->sc_tx_pipeh);
2063                 sc->sc_tx_pipeh = NULL;
2064         }
2065
2066         lwkt_serialize_enter(ifp->if_serializer);
2067
2068         rum_free_rx_list(sc);
2069         rum_free_tx_list(sc);
2070
2071         crit_exit();
2072 }
2073
2074 static int
2075 rum_load_microcode(struct rum_softc *sc, const uint8_t *ucode, size_t size)
2076 {
2077         usb_device_request_t req;
2078         uint16_t reg = RT2573_MCU_CODE_BASE;
2079         usbd_status error;
2080
2081         /* copy firmware image into NIC */
2082         for (; size >= 4; reg += 4, ucode += 4, size -= 4)
2083                 rum_write(sc, reg, UGETDW(ucode));
2084
2085         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
2086         req.bRequest = RT2573_MCU_CNTL;
2087         USETW(req.wValue, RT2573_MCU_RUN);
2088         USETW(req.wIndex, 0);
2089         USETW(req.wLength, 0);
2090
2091         error = usbd_do_request(sc->sc_udev, &req, NULL);
2092         if (error != 0) {
2093                 kprintf("%s: could not run firmware: %s\n",
2094                     device_get_nameunit(sc->sc_dev), usbd_errstr(error));
2095         }
2096         return error;
2097 }
2098
2099 static int
2100 rum_prepare_beacon(struct rum_softc *sc)
2101 {
2102         struct ieee80211com *ic = &sc->sc_ic;
2103         struct ifnet *ifp = &ic->ic_if;
2104         struct ieee80211_beacon_offsets bo;
2105         struct rum_tx_desc desc;
2106         struct mbuf *m0;
2107         int rate;
2108
2109         lwkt_serialize_enter(ifp->if_serializer);
2110         m0 = ieee80211_beacon_alloc(ic, ic->ic_bss, &bo);
2111         lwkt_serialize_exit(ifp->if_serializer);
2112
2113         if (m0 == NULL) {
2114                 if_printf(&ic->ic_if, "could not allocate beacon frame\n");
2115                 return ENOBUFS;
2116         }
2117
2118         /* send beacons at the lowest available rate */
2119         rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan) ? 12 : 2;
2120
2121         rum_setup_tx_desc(sc, &desc, RT2573_TX_TIMESTAMP, RT2573_TX_HWSEQ,
2122             m0->m_pkthdr.len, rate);
2123
2124         /* copy the first 24 bytes of Tx descriptor into NIC memory */
2125         rum_write_multi(sc, RT2573_HW_BEACON_BASE0, (uint8_t *)&desc, 24);
2126
2127         /* copy beacon header and payload into NIC memory */
2128         rum_write_multi(sc, RT2573_HW_BEACON_BASE0 + 24, mtod(m0, uint8_t *),
2129             m0->m_pkthdr.len);
2130
2131         m_freem(m0);
2132
2133         return 0;
2134 }
2135
2136 static void
2137 rum_stats_timeout(void *arg)
2138 {
2139         struct rum_softc *sc = arg;
2140         usb_device_request_t req;
2141
2142         if (sc->sc_stopped)
2143                 return;
2144
2145         crit_enter();
2146
2147         /*
2148          * Asynchronously read statistic registers (cleared by read).
2149          */
2150         req.bmRequestType = UT_READ_VENDOR_DEVICE;
2151         req.bRequest = RT2573_READ_MULTI_MAC;
2152         USETW(req.wValue, 0);
2153         USETW(req.wIndex, RT2573_STA_CSR0);
2154         USETW(req.wLength, sizeof(sc->sta));
2155
2156         usbd_setup_default_xfer(sc->stats_xfer, sc->sc_udev, sc,
2157                                 USBD_DEFAULT_TIMEOUT, &req,
2158                                 sc->sta, sizeof(sc->sta), 0,
2159                                 rum_stats_update);
2160         usbd_transfer(sc->stats_xfer);
2161
2162         crit_exit();
2163 }
2164
2165 static void
2166 rum_stats_update(usbd_xfer_handle xfer, usbd_private_handle priv,
2167                  usbd_status status)
2168 {
2169         struct rum_softc *sc = (struct rum_softc *)priv;
2170         struct ifnet *ifp = &sc->sc_ic.ic_if;
2171         struct ieee80211_ratectl_stats *stats = &sc->sc_stats;
2172
2173         if (status != USBD_NORMAL_COMPLETION) {
2174                 kprintf("%s: could not retrieve Tx statistics - cancelling "
2175                     "automatic rate control\n", device_get_nameunit(sc->sc_dev));
2176                 return;
2177         }
2178
2179         crit_enter();
2180
2181         /* count TX retry-fail as Tx errors */
2182         ifp->if_oerrors += RUM_TX_PKT_FAIL(sc);
2183
2184         stats->stats_pkt_noretry += RUM_TX_PKT_NO_RETRY(sc);
2185         stats->stats_pkt_ok += RUM_TX_PKT_NO_RETRY(sc) +
2186                                RUM_TX_PKT_ONE_RETRY(sc) +
2187                                RUM_TX_PKT_MULTI_RETRY(sc);
2188         stats->stats_pkt_err += RUM_TX_PKT_FAIL(sc);
2189
2190         stats->stats_retries += RUM_TX_PKT_ONE_RETRY(sc);
2191 #if 1
2192         /*
2193          * XXX Estimated average:
2194          * Actual number of retries for each packet should belong to
2195          * [2, RUM_TX_SHORT_RETRY_MAX]
2196          */
2197         stats->stats_retries += RUM_TX_PKT_MULTI_RETRY(sc) *
2198                                 ((2 + RUM_TX_SHORT_RETRY_MAX) / 2);
2199 #else
2200         stats->stats_retries += RUM_TX_PKT_MULTI_RETRY(sc);
2201 #endif
2202         stats->stats_retries += RUM_TX_PKT_FAIL(sc) * RUM_TX_SHORT_RETRY_MAX;
2203
2204         callout_reset(&sc->stats_ch, 4 * hz / 5, rum_stats_timeout, sc);
2205
2206         crit_exit();
2207 }
2208
2209 static void
2210 rum_stats(struct ieee80211com *ic, struct ieee80211_node *ni __unused,
2211           struct ieee80211_ratectl_stats *stats)
2212 {
2213         struct ifnet *ifp = &ic->ic_if;
2214         struct rum_softc *sc = ifp->if_softc;
2215
2216         ASSERT_SERIALIZED(ifp->if_serializer);
2217
2218         bcopy(&sc->sc_stats, stats, sizeof(*stats));
2219         bzero(&sc->sc_stats, sizeof(sc->sc_stats));
2220 }
2221
2222 static void
2223 rum_ratectl_change(struct ieee80211com *ic, u_int orc __unused, u_int nrc)
2224 {
2225         struct ieee80211_ratectl_state *st = &ic->ic_ratectl;
2226         struct ieee80211_onoe_param *oparam;
2227
2228         if (st->rc_st_param != NULL) {
2229                 kfree(st->rc_st_param, M_DEVBUF);
2230                 st->rc_st_param = NULL;
2231         }
2232
2233         switch (nrc) {
2234         case IEEE80211_RATECTL_ONOE:
2235                 oparam = kmalloc(sizeof(*oparam), M_DEVBUF, M_INTWAIT);
2236
2237                 IEEE80211_ONOE_PARAM_SETUP(oparam);
2238                 oparam->onoe_raise = 15;
2239
2240                 st->rc_st_param = oparam;
2241                 break;
2242         case IEEE80211_RATECTL_NONE:
2243                 /* This could only happen during detaching */
2244                 break;
2245         default:
2246                 panic("unknown rate control algo %u\n", nrc);
2247         }
2248 }
2249
2250 static int
2251 rum_get_rssi(struct rum_softc *sc, uint8_t raw)
2252 {
2253         int lna, agc, rssi;
2254
2255         lna = (raw >> 5) & 0x3;
2256         agc = raw & 0x1f;
2257
2258         if (lna == 0) {
2259                 /*
2260                  * No RSSI mapping
2261                  *
2262                  * NB: Since RSSI is relative to noise floor, -1 is
2263                  *     adequate for caller to know error happened.
2264                  */
2265                 return -1;
2266         }
2267
2268         rssi = (2 * agc) - RT2573_NOISE_FLOOR;
2269
2270         if (IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan)) {
2271                 rssi += sc->rssi_2ghz_corr;
2272
2273                 if (lna == 1)
2274                         rssi -= 64;
2275                 else if (lna == 2)
2276                         rssi -= 74;
2277                 else if (lna == 3)
2278                         rssi -= 90;
2279         } else {
2280                 rssi += sc->rssi_5ghz_corr;
2281
2282                 if (!sc->ext_5ghz_lna && lna != 1)
2283                         rssi += 4;
2284
2285                 if (lna == 1)
2286                         rssi -= 64;
2287                 else if (lna == 2)
2288                         rssi -= 86;
2289                 else if (lna == 3)
2290                         rssi -= 100;
2291         }
2292         return rssi;
2293 }