Nuke USB_MATCH*, USB_ATTACH* and USB_DETACH* macros.
[dragonfly.git] / sys / dev / netif / ural / if_ural.c
1 /*      $FreeBSD: src/sys/dev/usb/if_ural.c,v 1.10.2.8 2006/07/08 07:48:43 maxim Exp $  */
2 /*      $DragonFly: src/sys/dev/netif/ural/if_ural.c,v 1.16 2007/07/01 21:24:02 hasso Exp $     */
3
4 /*-
5  * Copyright (c) 2005, 2006
6  *      Damien Bergamini <damien.bergamini@free.fr>
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 RT2500USB 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/socket.h>
34 #include <sys/sockio.h>
35 #include <sys/sysctl.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 #include <bus/usb/usbdevs.h>
53
54 #include <dev/netif/ural/if_uralreg.h>
55 #include <dev/netif/ural/if_uralvar.h>
56
57 #ifdef USB_DEBUG
58 #define DPRINTF(x)      do { if (uraldebug > 0) kprintf x; } while (0)
59 #define DPRINTFN(n, x)  do { if (uraldebug >= (n)) kprintf x; } while (0)
60 int uraldebug = 0;
61 SYSCTL_NODE(_hw_usb, OID_AUTO, ural, CTLFLAG_RW, 0, "USB ural");
62 SYSCTL_INT(_hw_usb_ural, OID_AUTO, debug, CTLFLAG_RW, &uraldebug, 0,
63     "ural debug level");
64 #else
65 #define DPRINTF(x)
66 #define DPRINTFN(n, x)
67 #endif
68
69 #define URAL_RSSI(rssi)                                 \
70         ((rssi) > (RAL_NOISE_FLOOR + RAL_RSSI_CORR) ?   \
71          ((rssi) - RAL_NOISE_FLOOR + RAL_RSSI_CORR) : 0)
72
73 /* various supported device vendors/products */
74 static const struct usb_devno ural_devs[] = {
75         { USB_VENDOR_ASUS,              USB_PRODUCT_ASUS_WL167G },
76         { USB_VENDOR_ASUS,              USB_PRODUCT_RALINK_RT2570 },
77         { USB_VENDOR_BELKIN,            USB_PRODUCT_BELKIN_F5D7050 },
78         { USB_VENDOR_CONCEPTRONIC,      USB_PRODUCT_CONCEPTRONIC_C54U },
79         { USB_VENDOR_DLINK,             USB_PRODUCT_DLINK_DWLG122 },
80         { USB_VENDOR_GIGABYTE,          USB_PRODUCT_GIGABYTE_GNWBKG },
81         { USB_VENDOR_GUILLEMOT,         USB_PRODUCT_GUILLEMOT_HWGUSB254 },
82         { USB_VENDOR_LINKSYS4,          USB_PRODUCT_LINKSYS4_WUSB54G },
83         { USB_VENDOR_LINKSYS4,          USB_PRODUCT_LINKSYS4_WUSB54GP },
84         { USB_VENDOR_LINKSYS4,          USB_PRODUCT_LINKSYS4_HU200TS },
85         { USB_VENDOR_MELCO,             USB_PRODUCT_MELCO_KG54 },
86         { USB_VENDOR_MELCO,             USB_PRODUCT_MELCO_KG54AI },
87         { USB_VENDOR_MELCO,             USB_PRODUCT_MELCO_KG54YB },
88         { USB_VENDOR_MELCO,             USB_PRODUCT_MELCO_NINWIFI },
89         { USB_VENDOR_MSI,               USB_PRODUCT_MSI_RT2570 },
90         { USB_VENDOR_MSI,               USB_PRODUCT_MSI_RT2570_2 },
91         { USB_VENDOR_MSI,               USB_PRODUCT_MSI_RT2570_3 },
92         { USB_VENDOR_NOVATECH,          USB_PRODUCT_NOVATECH_NV902W },
93         { USB_VENDOR_RALINK,            USB_PRODUCT_RALINK_RT2570 },
94         { USB_VENDOR_RALINK,            USB_PRODUCT_RALINK_RT2570_2 },
95         { USB_VENDOR_RALINK,            USB_PRODUCT_RALINK_RT2570_3 },
96         { USB_VENDOR_SPHAIRON,          USB_PRODUCT_SPHAIRON_UB801R },
97         { USB_VENDOR_SURECOM,           USB_PRODUCT_SURECOM_RT2570 },
98         { USB_VENDOR_VTECH,             USB_PRODUCT_VTECH_RT2570 },
99         { USB_VENDOR_ZINWELL,           USB_PRODUCT_ZINWELL_RT2570 }
100 };
101
102 MODULE_DEPEND(ural, wlan, 1, 1, 1);
103
104 static int              ural_alloc_tx_list(struct ural_softc *);
105 static void             ural_free_tx_list(struct ural_softc *);
106 static int              ural_alloc_rx_list(struct ural_softc *);
107 static void             ural_free_rx_list(struct ural_softc *);
108 static int              ural_media_change(struct ifnet *);
109 static void             ural_next_scan(void *);
110 static void             ural_task(void *);
111 static int              ural_newstate(struct ieee80211com *,
112                             enum ieee80211_state, int);
113 static int              ural_rxrate(struct ural_rx_desc *);
114 static void             ural_txeof(usbd_xfer_handle, usbd_private_handle,
115                             usbd_status);
116 static void             ural_rxeof(usbd_xfer_handle, usbd_private_handle,
117                             usbd_status);
118 static uint8_t          ural_plcp_signal(int);
119 static void             ural_setup_tx_desc(struct ural_softc *,
120                             struct ural_tx_desc *, uint32_t, int, int);
121 static int              ural_tx_bcn(struct ural_softc *, struct mbuf *,
122                             struct ieee80211_node *);
123 static int              ural_tx_mgt(struct ural_softc *, struct mbuf *,
124                             struct ieee80211_node *);
125 static int              ural_tx_data(struct ural_softc *, struct mbuf *,
126                             struct ieee80211_node *);
127 static void             ural_start(struct ifnet *);
128 static void             ural_watchdog(struct ifnet *);
129 static int              ural_reset(struct ifnet *);
130 static int              ural_ioctl(struct ifnet *, u_long, caddr_t,
131                             struct ucred *);
132 static void             ural_set_testmode(struct ural_softc *);
133 static void             ural_eeprom_read(struct ural_softc *, uint16_t, void *,
134                             int);
135 static uint16_t         ural_read(struct ural_softc *, uint16_t);
136 static void             ural_read_multi(struct ural_softc *, uint16_t, void *,
137                             int);
138 static void             ural_write(struct ural_softc *, uint16_t, uint16_t);
139 static void             ural_write_multi(struct ural_softc *, uint16_t, void *,
140                             int) __unused;
141 static void             ural_bbp_write(struct ural_softc *, uint8_t, uint8_t);
142 static uint8_t          ural_bbp_read(struct ural_softc *, uint8_t);
143 static void             ural_rf_write(struct ural_softc *, uint8_t, uint32_t);
144 static void             ural_set_chan(struct ural_softc *,
145                             struct ieee80211_channel *);
146 static void             ural_disable_rf_tune(struct ural_softc *);
147 static void             ural_enable_tsf_sync(struct ural_softc *);
148 static void             ural_update_slot(struct ifnet *);
149 static void             ural_set_txpreamble(struct ural_softc *);
150 static void             ural_set_basicrates(struct ural_softc *);
151 static void             ural_set_bssid(struct ural_softc *, uint8_t *);
152 static void             ural_set_macaddr(struct ural_softc *, uint8_t *);
153 static void             ural_update_promisc(struct ural_softc *);
154 static const char       *ural_get_rf(int);
155 static void             ural_read_eeprom(struct ural_softc *);
156 static int              ural_bbp_init(struct ural_softc *);
157 static void             ural_set_txantenna(struct ural_softc *, int);
158 static void             ural_set_rxantenna(struct ural_softc *, int);
159 static void             ural_init(void *);
160 static void             ural_stop(struct ural_softc *);
161 static void             ural_stats(struct ieee80211com *,
162                                    struct ieee80211_node *,
163                                    struct ieee80211_ratectl_stats *);
164 static void             ural_stats_update(usbd_xfer_handle,
165                                           usbd_private_handle, usbd_status);
166 static void             ural_stats_timeout(void *);
167 static void             ural_ratectl_change(struct ieee80211com *ic, u_int,
168                                             u_int);
169
170 /*
171  * Supported rates for 802.11a/b/g modes (in 500Kbps unit).
172  */
173 static const struct ieee80211_rateset ural_rateset_11a =
174         { 8, { 12, 18, 24, 36, 48, 72, 96, 108 } };
175
176 static const struct ieee80211_rateset ural_rateset_11b =
177         { 4, { 2, 4, 11, 22 } };
178
179 static const struct ieee80211_rateset ural_rateset_11g =
180         { 12, { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 } };
181
182 /*
183  * Default values for MAC registers; values taken from the reference driver.
184  */
185 static const struct {
186         uint16_t        reg;
187         uint16_t        val;
188 } ural_def_mac[] = {
189         { RAL_TXRX_CSR5,  0x8c8d },
190         { RAL_TXRX_CSR6,  0x8b8a },
191         { RAL_TXRX_CSR7,  0x8687 },
192         { RAL_TXRX_CSR8,  0x0085 },
193         { RAL_MAC_CSR13,  0x1111 },
194         { RAL_MAC_CSR14,  0x1e11 },
195         { RAL_TXRX_CSR21, 0xe78f },
196         { RAL_MAC_CSR9,   0xff1d },
197         { RAL_MAC_CSR11,  0x0002 },
198         { RAL_MAC_CSR22,  0x0053 },
199         { RAL_MAC_CSR15,  0x0000 },
200         { RAL_MAC_CSR8,   0x0780 },
201         { RAL_TXRX_CSR19, 0x0000 },
202         { RAL_TXRX_CSR18, 0x005a },
203         { RAL_PHY_CSR2,   0x0000 },
204         { RAL_TXRX_CSR0,  0x1ec0 },
205         { RAL_PHY_CSR4,   0x000f }
206 };
207
208 /*
209  * Default values for BBP registers; values taken from the reference driver.
210  */
211 static const struct {
212         uint8_t reg;
213         uint8_t val;
214 } ural_def_bbp[] = {
215         {  3, 0x02 },
216         {  4, 0x19 },
217         { 14, 0x1c },
218         { 15, 0x30 },
219         { 16, 0xac },
220         { 17, 0x48 },
221         { 18, 0x18 },
222         { 19, 0xff },
223         { 20, 0x1e },
224         { 21, 0x08 },
225         { 22, 0x08 },
226         { 23, 0x08 },
227         { 24, 0x80 },
228         { 25, 0x50 },
229         { 26, 0x08 },
230         { 27, 0x23 },
231         { 30, 0x10 },
232         { 31, 0x2b },
233         { 32, 0xb9 },
234         { 34, 0x12 },
235         { 35, 0x50 },
236         { 39, 0xc4 },
237         { 40, 0x02 },
238         { 41, 0x60 },
239         { 53, 0x10 },
240         { 54, 0x18 },
241         { 56, 0x08 },
242         { 57, 0x10 },
243         { 58, 0x08 },
244         { 61, 0x60 },
245         { 62, 0x10 },
246         { 75, 0xff }
247 };
248
249 /*
250  * Default values for RF register R2 indexed by channel numbers.
251  */
252 static const uint32_t ural_rf2522_r2[] = {
253         0x307f6, 0x307fb, 0x30800, 0x30805, 0x3080a, 0x3080f, 0x30814,
254         0x30819, 0x3081e, 0x30823, 0x30828, 0x3082d, 0x30832, 0x3083e
255 };
256
257 static const uint32_t ural_rf2523_r2[] = {
258         0x00327, 0x00328, 0x00329, 0x0032a, 0x0032b, 0x0032c, 0x0032d,
259         0x0032e, 0x0032f, 0x00340, 0x00341, 0x00342, 0x00343, 0x00346
260 };
261
262 static const uint32_t ural_rf2524_r2[] = {
263         0x00327, 0x00328, 0x00329, 0x0032a, 0x0032b, 0x0032c, 0x0032d,
264         0x0032e, 0x0032f, 0x00340, 0x00341, 0x00342, 0x00343, 0x00346
265 };
266
267 static const uint32_t ural_rf2525_r2[] = {
268         0x20327, 0x20328, 0x20329, 0x2032a, 0x2032b, 0x2032c, 0x2032d,
269         0x2032e, 0x2032f, 0x20340, 0x20341, 0x20342, 0x20343, 0x20346
270 };
271
272 static const uint32_t ural_rf2525_hi_r2[] = {
273         0x2032f, 0x20340, 0x20341, 0x20342, 0x20343, 0x20344, 0x20345,
274         0x20346, 0x20347, 0x20348, 0x20349, 0x2034a, 0x2034b, 0x2034e
275 };
276
277 static const uint32_t ural_rf2525e_r2[] = {
278         0x2044d, 0x2044e, 0x2044f, 0x20460, 0x20461, 0x20462, 0x20463,
279         0x20464, 0x20465, 0x20466, 0x20467, 0x20468, 0x20469, 0x2046b
280 };
281
282 static const uint32_t ural_rf2526_hi_r2[] = {
283         0x0022a, 0x0022b, 0x0022b, 0x0022c, 0x0022c, 0x0022d, 0x0022d,
284         0x0022e, 0x0022e, 0x0022f, 0x0022d, 0x00240, 0x00240, 0x00241
285 };
286
287 static const uint32_t ural_rf2526_r2[] = {
288         0x00226, 0x00227, 0x00227, 0x00228, 0x00228, 0x00229, 0x00229,
289         0x0022a, 0x0022a, 0x0022b, 0x0022b, 0x0022c, 0x0022c, 0x0022d
290 };
291
292 /*
293  * For dual-band RF, RF registers R1 and R4 also depend on channel number;
294  * values taken from the reference driver.
295  */
296 static const struct {
297         uint8_t         chan;
298         uint32_t        r1;
299         uint32_t        r2;
300         uint32_t        r4;
301 } ural_rf5222[] = {
302         {   1, 0x08808, 0x0044d, 0x00282 },
303         {   2, 0x08808, 0x0044e, 0x00282 },
304         {   3, 0x08808, 0x0044f, 0x00282 },
305         {   4, 0x08808, 0x00460, 0x00282 },
306         {   5, 0x08808, 0x00461, 0x00282 },
307         {   6, 0x08808, 0x00462, 0x00282 },
308         {   7, 0x08808, 0x00463, 0x00282 },
309         {   8, 0x08808, 0x00464, 0x00282 },
310         {   9, 0x08808, 0x00465, 0x00282 },
311         {  10, 0x08808, 0x00466, 0x00282 },
312         {  11, 0x08808, 0x00467, 0x00282 },
313         {  12, 0x08808, 0x00468, 0x00282 },
314         {  13, 0x08808, 0x00469, 0x00282 },
315         {  14, 0x08808, 0x0046b, 0x00286 },
316
317         {  36, 0x08804, 0x06225, 0x00287 },
318         {  40, 0x08804, 0x06226, 0x00287 },
319         {  44, 0x08804, 0x06227, 0x00287 },
320         {  48, 0x08804, 0x06228, 0x00287 },
321         {  52, 0x08804, 0x06229, 0x00287 },
322         {  56, 0x08804, 0x0622a, 0x00287 },
323         {  60, 0x08804, 0x0622b, 0x00287 },
324         {  64, 0x08804, 0x0622c, 0x00287 },
325
326         { 100, 0x08804, 0x02200, 0x00283 },
327         { 104, 0x08804, 0x02201, 0x00283 },
328         { 108, 0x08804, 0x02202, 0x00283 },
329         { 112, 0x08804, 0x02203, 0x00283 },
330         { 116, 0x08804, 0x02204, 0x00283 },
331         { 120, 0x08804, 0x02205, 0x00283 },
332         { 124, 0x08804, 0x02206, 0x00283 },
333         { 128, 0x08804, 0x02207, 0x00283 },
334         { 132, 0x08804, 0x02208, 0x00283 },
335         { 136, 0x08804, 0x02209, 0x00283 },
336         { 140, 0x08804, 0x0220a, 0x00283 },
337
338         { 149, 0x08808, 0x02429, 0x00281 },
339         { 153, 0x08808, 0x0242b, 0x00281 },
340         { 157, 0x08808, 0x0242d, 0x00281 },
341         { 161, 0x08808, 0x0242f, 0x00281 }
342 };
343
344 USB_DECLARE_DRIVER(ural);
345
346 static int
347 ural_match(device_t self)
348 {
349         struct usb_attach_arg *uaa = device_get_ivars(self);
350
351         if (uaa->iface != NULL)
352                 return UMATCH_NONE;
353
354         return (usb_lookup(ural_devs, uaa->vendor, uaa->product) != NULL) ?
355             UMATCH_VENDOR_PRODUCT : UMATCH_NONE;
356 }
357
358 static int
359 ural_attach(device_t self)
360 {
361         struct ural_softc *sc = device_get_softc(self);
362         struct usb_attach_arg *uaa = device_get_ivars(self);
363         struct ifnet *ifp;
364         struct ieee80211com *ic = &sc->sc_ic;
365         usb_interface_descriptor_t *id;
366         usb_endpoint_descriptor_t *ed;
367         usbd_status error;
368         char devinfo[1024];
369         int i;
370
371         sc->sc_udev = uaa->device;
372         sc->sc_tx_retries = 7;  /* TODO tunable/sysctl */
373
374         usbd_devinfo(sc->sc_udev, 0, devinfo);
375         sc->sc_dev = self;
376         device_set_desc_copy(self, devinfo);
377
378         if (usbd_set_config_no(sc->sc_udev, RAL_CONFIG_NO, 0) != 0) {
379                 kprintf("%s: could not set configuration no\n",
380                     device_get_nameunit(sc->sc_dev));
381                 return ENXIO;
382         }
383
384         /* get the first interface handle */
385         error = usbd_device2interface_handle(sc->sc_udev, RAL_IFACE_INDEX,
386             &sc->sc_iface);
387         if (error != 0) {
388                 kprintf("%s: could not get interface handle\n",
389                     device_get_nameunit(sc->sc_dev));
390                 return ENXIO;
391         }
392
393         /*
394          * Find endpoints.
395          */
396         id = usbd_get_interface_descriptor(sc->sc_iface);
397
398         sc->sc_rx_no = sc->sc_tx_no = -1;
399         for (i = 0; i < id->bNumEndpoints; i++) {
400                 ed = usbd_interface2endpoint_descriptor(sc->sc_iface, i);
401                 if (ed == NULL) {
402                         kprintf("%s: no endpoint descriptor for %d\n",
403                             device_get_nameunit(sc->sc_dev), i);
404                         return ENXIO;
405                 }
406
407                 if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
408                     UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK)
409                         sc->sc_rx_no = ed->bEndpointAddress;
410                 else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT &&
411                     UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK)
412                         sc->sc_tx_no = ed->bEndpointAddress;
413         }
414         if (sc->sc_rx_no == -1 || sc->sc_tx_no == -1) {
415                 kprintf("%s: missing endpoint\n", device_get_nameunit(sc->sc_dev));
416                 return ENXIO;
417         }
418
419         usb_init_task(&sc->sc_task, ural_task, sc);
420         callout_init(&sc->scan_ch);
421         callout_init(&sc->stats_ch);
422
423         /* retrieve RT2570 rev. no */
424         sc->asic_rev = ural_read(sc, RAL_MAC_CSR0);
425
426         /* retrieve MAC address and various other things from EEPROM */
427         ural_read_eeprom(sc);
428
429         kprintf("%s: MAC/BBP RT2570 (rev 0x%02x), RF %s\n",
430             device_get_nameunit(sc->sc_dev), sc->asic_rev, ural_get_rf(sc->rf_rev));
431
432         ifp = &ic->ic_if;
433         ifp->if_softc = sc;
434         if_initname(ifp, "ural", device_get_unit(sc->sc_dev));
435         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
436         ifp->if_init = ural_init;
437         ifp->if_ioctl = ural_ioctl;
438         ifp->if_start = ural_start;
439         ifp->if_watchdog = ural_watchdog;
440         ifq_set_maxlen(&ifp->if_snd, IFQ_MAXLEN);
441         ifq_set_ready(&ifp->if_snd);
442
443         ic->ic_ratectl.rc_st_ratectl_cap = IEEE80211_RATECTL_CAP_ONOE;
444         ic->ic_ratectl.rc_st_ratectl = IEEE80211_RATECTL_ONOE;
445         ic->ic_ratectl.rc_st_valid_stats =
446                 IEEE80211_RATECTL_STATS_PKT_NORETRY |
447                 IEEE80211_RATECTL_STATS_PKT_OK |
448                 IEEE80211_RATECTL_STATS_PKT_ERR |
449                 IEEE80211_RATECTL_STATS_RETRIES;
450         ic->ic_ratectl.rc_st_stats = ural_stats;
451         ic->ic_ratectl.rc_st_change = ural_ratectl_change;
452
453         ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
454         ic->ic_opmode = IEEE80211_M_STA; /* default to BSS mode */
455         ic->ic_state = IEEE80211_S_INIT;
456
457         /* set device capabilities */
458         ic->ic_caps =
459             IEEE80211_C_IBSS |          /* IBSS mode supported */
460             IEEE80211_C_MONITOR |       /* monitor mode supported */
461             IEEE80211_C_HOSTAP |        /* HostAp mode supported */
462             IEEE80211_C_TXPMGT |        /* tx power management */
463             IEEE80211_C_SHPREAMBLE |    /* short preamble supported */
464             IEEE80211_C_SHSLOT |        /* short slot time supported */
465             IEEE80211_C_WPA;            /* 802.11i */
466
467         if (sc->rf_rev == RAL_RF_5222) {
468                 /* set supported .11a rates */
469                 ic->ic_sup_rates[IEEE80211_MODE_11A] = ural_rateset_11a;
470
471                 /* set supported .11a channels */
472                 for (i = 36; i <= 64; i += 4) {
473                         ic->ic_channels[i].ic_freq =
474                             ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
475                         ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
476                 }
477                 for (i = 100; i <= 140; i += 4) {
478                         ic->ic_channels[i].ic_freq =
479                             ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
480                         ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
481                 }
482                 for (i = 149; i <= 161; i += 4) {
483                         ic->ic_channels[i].ic_freq =
484                             ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
485                         ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
486                 }
487         }
488
489         /* set supported .11b and .11g rates */
490         ic->ic_sup_rates[IEEE80211_MODE_11B] = ural_rateset_11b;
491         ic->ic_sup_rates[IEEE80211_MODE_11G] = ural_rateset_11g;
492
493         /* set supported .11b and .11g channels (1 through 14) */
494         for (i = 1; i <= 14; i++) {
495                 ic->ic_channels[i].ic_freq =
496                     ieee80211_ieee2mhz(i, IEEE80211_CHAN_2GHZ);
497                 ic->ic_channels[i].ic_flags =
498                     IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
499                     IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
500         }
501
502         sc->sc_sifs = IEEE80211_DUR_SIFS;       /* Default SIFS */
503
504         ieee80211_ifattach(ic);
505         ic->ic_reset = ural_reset;
506         /* enable s/w bmiss handling in sta mode */
507         ic->ic_flags_ext |= IEEE80211_FEXT_SWBMISS;
508
509         /* override state transition machine */
510         sc->sc_newstate = ic->ic_newstate;
511         ic->ic_newstate = ural_newstate;
512         ieee80211_media_init(ic, ural_media_change, ieee80211_media_status);
513
514         bpfattach_dlt(ifp, DLT_IEEE802_11_RADIO,
515             sizeof(struct ieee80211_frame) + 64, &sc->sc_drvbpf);
516
517         sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
518         sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
519         sc->sc_rxtap.wr_ihdr.it_present = htole32(RAL_RX_RADIOTAP_PRESENT);
520
521         sc->sc_txtap_len = sizeof sc->sc_txtapu;
522         sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
523         sc->sc_txtap.wt_ihdr.it_present = htole32(RAL_TX_RADIOTAP_PRESENT);
524
525         if (bootverbose)
526                 ieee80211_announce(ic);
527
528         return 0;
529 }
530
531 static int
532 ural_detach(device_t self)
533 {
534         struct ural_softc *sc = device_get_softc(self);
535         struct ieee80211com *ic = &sc->sc_ic;
536         struct ifnet *ifp = &ic->ic_if;
537 #ifdef INVARIANTS
538         int i;
539 #endif
540
541         crit_enter();
542
543         callout_stop(&sc->scan_ch);
544         callout_stop(&sc->stats_ch);
545
546         lwkt_serialize_enter(ifp->if_serializer);
547         ural_stop(sc);
548         lwkt_serialize_exit(ifp->if_serializer);
549
550         usb_rem_task(sc->sc_udev, &sc->sc_task);
551
552         bpfdetach(ifp);
553         ieee80211_ifdetach(ic);
554
555         crit_exit();
556
557         KKASSERT(sc->stats_xfer == NULL);
558         KKASSERT(sc->sc_rx_pipeh == NULL);
559         KKASSERT(sc->sc_tx_pipeh == NULL);
560
561 #ifdef INVARIANTS
562         /*
563          * Make sure TX/RX list is empty
564          */
565         for (i = 0; i < RAL_TX_LIST_COUNT; i++) {
566                 struct ural_tx_data *data = &sc->tx_data[i];
567
568                 KKASSERT(data->xfer == NULL);
569                 KKASSERT(data->ni == NULL);
570                 KKASSERT(data->m == NULL);
571         }
572         for (i = 0; i < RAL_RX_LIST_COUNT; i++) {
573                 struct ural_rx_data *data = &sc->rx_data[i];
574
575                 KKASSERT(data->xfer == NULL);
576                 KKASSERT(data->m == NULL);
577         }
578 #endif
579
580         return 0;
581 }
582
583 static int
584 ural_alloc_tx_list(struct ural_softc *sc)
585 {
586         int i;
587
588         sc->tx_queued = 0;
589
590         for (i = 0; i < RAL_TX_LIST_COUNT; i++) {
591                 struct ural_tx_data *data = &sc->tx_data[i];
592
593                 data->sc = sc;
594
595                 data->xfer = usbd_alloc_xfer(sc->sc_udev);
596                 if (data->xfer == NULL) {
597                         kprintf("%s: could not allocate tx xfer\n",
598                             device_get_nameunit(sc->sc_dev));
599                         return ENOMEM;
600                 }
601
602                 data->buf = usbd_alloc_buffer(data->xfer,
603                     RAL_TX_DESC_SIZE + MCLBYTES);
604                 if (data->buf == NULL) {
605                         kprintf("%s: could not allocate tx buffer\n",
606                             device_get_nameunit(sc->sc_dev));
607                         return ENOMEM;
608                 }
609         }
610         return 0;
611 }
612
613 static void
614 ural_free_tx_list(struct ural_softc *sc)
615 {
616         int i;
617
618         for (i = 0; i < RAL_TX_LIST_COUNT; i++) {
619                 struct ural_tx_data *data = &sc->tx_data[i];
620
621                 if (data->xfer != NULL) {
622                         usbd_free_xfer(data->xfer);
623                         data->xfer = NULL;
624                 }
625
626                 if (data->ni != NULL) {
627                         ieee80211_free_node(data->ni);
628                         data->ni = NULL;
629                 }
630                 if (data->m != NULL) {
631                         m_freem(data->m);
632                         data->m = NULL;
633                 }
634         }
635         sc->tx_queued = 0;
636 }
637
638 static int
639 ural_alloc_rx_list(struct ural_softc *sc)
640 {
641         int i;
642
643         for (i = 0; i < RAL_RX_LIST_COUNT; i++) {
644                 struct ural_rx_data *data = &sc->rx_data[i];
645
646                 data->sc = sc;
647
648                 data->xfer = usbd_alloc_xfer(sc->sc_udev);
649                 if (data->xfer == NULL) {
650                         kprintf("%s: could not allocate rx xfer\n",
651                             device_get_nameunit(sc->sc_dev));
652                         return ENOMEM;
653                 }
654
655                 if (usbd_alloc_buffer(data->xfer, MCLBYTES) == NULL) {
656                         kprintf("%s: could not allocate rx buffer\n",
657                             device_get_nameunit(sc->sc_dev));
658                         return ENOMEM;
659                 }
660
661                 data->m = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
662                 if (data->m == NULL) {
663                         kprintf("%s: could not allocate rx mbuf\n",
664                             device_get_nameunit(sc->sc_dev));
665                         return ENOMEM;
666                 }
667
668                 data->buf = mtod(data->m, uint8_t *);
669         }
670         return 0;
671 }
672
673 static void
674 ural_free_rx_list(struct ural_softc *sc)
675 {
676         int i;
677
678         for (i = 0; i < RAL_RX_LIST_COUNT; i++) {
679                 struct ural_rx_data *data = &sc->rx_data[i];
680
681                 if (data->xfer != NULL) {
682                         usbd_free_xfer(data->xfer);
683                         data->xfer = NULL;
684                 }
685
686                 if (data->m != NULL) {
687                         m_freem(data->m);
688                         data->m = NULL;
689                 }
690         }
691 }
692
693 static int
694 ural_media_change(struct ifnet *ifp)
695 {
696         struct ural_softc *sc = ifp->if_softc;
697         int error;
698
699         error = ieee80211_media_change(ifp);
700         if (error != ENETRESET)
701                 return error;
702
703         if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
704                 ural_init(sc);
705
706         return 0;
707 }
708
709 /*
710  * This function is called periodically (every 200ms) during scanning to
711  * switch from one channel to another.
712  */
713 static void
714 ural_next_scan(void *arg)
715 {
716         struct ural_softc *sc = arg;
717         struct ieee80211com *ic = &sc->sc_ic;
718         struct ifnet *ifp = &ic->ic_if;
719
720         if (sc->sc_stopped)
721                 return;
722
723         crit_enter();
724
725         if (ic->ic_state == IEEE80211_S_SCAN) {
726                 lwkt_serialize_enter(ifp->if_serializer);
727                 ieee80211_next_scan(ic);
728                 lwkt_serialize_exit(ifp->if_serializer);
729         }
730
731         crit_exit();
732 }
733
734 static void
735 ural_task(void *xarg)
736 {
737         struct ural_softc *sc = xarg;
738         struct ieee80211com *ic = &sc->sc_ic;
739         struct ifnet *ifp = &ic->ic_if;
740         enum ieee80211_state nstate;
741         struct ieee80211_node *ni;
742         struct mbuf *m;
743         int arg;
744
745         if (sc->sc_stopped)
746                 return;
747
748         crit_enter();
749
750         nstate = sc->sc_state;
751         arg = sc->sc_arg;
752
753         KASSERT(nstate != IEEE80211_S_INIT,
754                 ("->INIT state transition should not be defered\n"));
755         ural_set_chan(sc, ic->ic_curchan);
756
757         switch (sc->sc_state) {
758         case IEEE80211_S_RUN:
759                 ni = ic->ic_bss;
760
761                 if (ic->ic_opmode != IEEE80211_M_MONITOR) {
762                         ural_update_slot(&ic->ic_if);
763                         ural_set_txpreamble(sc);
764                         ural_set_basicrates(sc);
765                         ural_set_bssid(sc, ni->ni_bssid);
766                 }
767
768                 if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
769                     ic->ic_opmode == IEEE80211_M_IBSS) {
770                         lwkt_serialize_enter(ifp->if_serializer);
771                         m = ieee80211_beacon_alloc(ic, ni, &sc->sc_bo);
772                         lwkt_serialize_exit(ifp->if_serializer);
773
774                         if (m == NULL) {
775                                 kprintf("%s: could not allocate beacon\n",
776                                     device_get_nameunit(sc->sc_dev));
777                                 crit_exit();
778                                 return;
779                         }
780
781                         if (ural_tx_bcn(sc, m, ni) != 0) {
782                                 kprintf("%s: could not send beacon\n",
783                                     device_get_nameunit(sc->sc_dev));
784                                 crit_exit();
785                                 return;
786                         }
787                 }
788
789                 /* make tx led blink on tx (controlled by ASIC) */
790                 ural_write(sc, RAL_MAC_CSR20, 1);
791
792                 if (ic->ic_opmode != IEEE80211_M_MONITOR)
793                         ural_enable_tsf_sync(sc);
794
795                 /* clear statistic registers (STA_CSR0 to STA_CSR10) */
796                 ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof(sc->sta));
797
798                 callout_reset(&sc->stats_ch, 4 * hz / 5,
799                               ural_stats_timeout, sc);
800                 break;
801
802         case IEEE80211_S_SCAN:
803                 callout_reset(&sc->scan_ch, hz / 5, ural_next_scan, sc);
804                 break;
805
806         default:
807                 break;
808         }
809
810         lwkt_serialize_enter(ifp->if_serializer);
811         ieee80211_ratectl_newstate(ic, sc->sc_state);
812         sc->sc_newstate(ic, sc->sc_state, arg);
813         lwkt_serialize_exit(ifp->if_serializer);
814
815         crit_exit();
816 }
817
818 static int
819 ural_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
820 {
821         struct ifnet *ifp = &ic->ic_if;
822         struct ural_softc *sc = ifp->if_softc;
823
824         ASSERT_SERIALIZED(ifp->if_serializer);
825
826         crit_enter();
827
828         callout_stop(&sc->scan_ch);
829         callout_stop(&sc->stats_ch);
830
831         /* do it in a process context */
832         sc->sc_state = nstate;
833         sc->sc_arg = arg;
834
835         lwkt_serialize_exit(ifp->if_serializer);
836         usb_rem_task(sc->sc_udev, &sc->sc_task);
837
838         if (nstate == IEEE80211_S_INIT) {
839                 lwkt_serialize_enter(ifp->if_serializer);
840                 ieee80211_ratectl_newstate(ic, nstate);
841                 sc->sc_newstate(ic, nstate, arg);
842         } else {
843                 usb_add_task(sc->sc_udev, &sc->sc_task, USB_TASKQ_DRIVER);
844                 lwkt_serialize_enter(ifp->if_serializer);
845         }
846
847         crit_exit();
848         return 0;
849 }
850
851 /* quickly determine if a given rate is CCK or OFDM */
852 #define RAL_RATE_IS_OFDM(rate) ((rate) >= 12 && (rate) != 22)
853
854 #define RAL_ACK_SIZE    (sizeof(struct ieee80211_frame_ack) + IEEE80211_FCS_LEN)
855
856 #define RAL_RXTX_TURNAROUND     5       /* us */
857
858 /*
859  * This function is only used by the Rx radiotap code.
860  */
861 static int
862 ural_rxrate(struct ural_rx_desc *desc)
863 {
864         if (le32toh(desc->flags) & RAL_RX_OFDM) {
865                 /* reverse function of ural_plcp_signal */
866                 switch (desc->rate) {
867                 case 0xb:       return 12;
868                 case 0xf:       return 18;
869                 case 0xa:       return 24;
870                 case 0xe:       return 36;
871                 case 0x9:       return 48;
872                 case 0xd:       return 72;
873                 case 0x8:       return 96;
874                 case 0xc:       return 108;
875                 }
876         } else {
877                 if (desc->rate == 10)
878                         return 2;
879                 if (desc->rate == 20)
880                         return 4;
881                 if (desc->rate == 55)
882                         return 11;
883                 if (desc->rate == 110)
884                         return 22;
885         }
886         return 2;       /* should not get there */
887 }
888
889 static void
890 ural_txeof(usbd_xfer_handle xfer, usbd_private_handle priv, usbd_status status)
891 {
892         struct ural_tx_data *data = priv;
893         struct ural_softc *sc = data->sc;
894         struct ieee80211_node *ni;
895         struct ifnet *ifp = &sc->sc_ic.ic_if;
896
897         if (sc->sc_stopped)
898                 return;
899
900         crit_enter();
901
902         if (status != USBD_NORMAL_COMPLETION) {
903                 if (status == USBD_NOT_STARTED || status == USBD_CANCELLED) {
904                         crit_exit();
905                         return;
906                 }
907
908                 kprintf("%s: could not transmit buffer: %s\n",
909                     device_get_nameunit(sc->sc_dev), usbd_errstr(status));
910
911                 if (status == USBD_STALLED)
912                         usbd_clear_endpoint_stall_async(sc->sc_rx_pipeh);
913
914                 ifp->if_oerrors++;
915                 crit_exit();
916                 return;
917         }
918
919         m_freem(data->m);
920         data->m = NULL;
921         ni = data->ni;
922         data->ni = NULL;
923
924         sc->tx_queued--;
925         ifp->if_opackets++;
926
927         DPRINTFN(10, ("tx done\n"));
928
929         sc->sc_tx_timer = 0;
930         ifp->if_flags &= ~IFF_OACTIVE;
931
932         lwkt_serialize_enter(ifp->if_serializer);
933         ieee80211_free_node(ni);
934         ifp->if_start(ifp);
935         lwkt_serialize_exit(ifp->if_serializer);
936
937         crit_exit();
938 }
939
940 static void
941 ural_rxeof(usbd_xfer_handle xfer, usbd_private_handle priv, usbd_status status)
942 {
943         struct ural_rx_data *data = priv;
944         struct ural_softc *sc = data->sc;
945         struct ieee80211com *ic = &sc->sc_ic;
946         struct ifnet *ifp = &ic->ic_if;
947         struct ural_rx_desc *desc;
948         struct ieee80211_frame *wh;
949         struct ieee80211_node *ni;
950         struct mbuf *mnew, *m;
951         int len;
952
953         if (sc->sc_stopped)
954                 return;
955
956         crit_enter();
957
958         if (status != USBD_NORMAL_COMPLETION) {
959                 if (status == USBD_NOT_STARTED || status == USBD_CANCELLED) {
960                         crit_exit();
961                         return;
962                 }
963
964                 if (status == USBD_STALLED)
965                         usbd_clear_endpoint_stall_async(sc->sc_rx_pipeh);
966                 goto skip;
967         }
968
969         usbd_get_xfer_status(xfer, NULL, NULL, &len, NULL);
970
971         if (len < RAL_RX_DESC_SIZE + IEEE80211_MIN_LEN) {
972                 DPRINTF(("%s: xfer too short %d\n", device_get_nameunit(sc->sc_dev),
973                     len));
974                 ifp->if_ierrors++;
975                 goto skip;
976         }
977
978         /* rx descriptor is located at the end */
979         desc = (struct ural_rx_desc *)(data->buf + len - RAL_RX_DESC_SIZE);
980
981         if ((le32toh(desc->flags) & RAL_RX_PHY_ERROR) ||
982             (le32toh(desc->flags) & RAL_RX_CRC_ERROR)) {
983                 /*
984                  * This should not happen since we did not request to receive
985                  * those frames when we filled RAL_TXRX_CSR2.
986                  */
987                 DPRINTFN(5, ("PHY or CRC error\n"));
988                 ifp->if_ierrors++;
989                 goto skip;
990         }
991
992         mnew = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
993         if (mnew == NULL) {
994                 ifp->if_ierrors++;
995                 goto skip;
996         }
997
998         m = data->m;
999         data->m = NULL;
1000         data->buf = NULL;
1001
1002         lwkt_serialize_enter(ifp->if_serializer);
1003
1004         /* finalize mbuf */
1005         m->m_pkthdr.rcvif = ifp;
1006         m->m_pkthdr.len = m->m_len = (le32toh(desc->flags) >> 16) & 0xfff;
1007
1008         if (sc->sc_drvbpf != NULL) {
1009                 struct ural_rx_radiotap_header *tap = &sc->sc_rxtap;
1010
1011                 tap->wr_flags = IEEE80211_RADIOTAP_F_FCS; /* h/w leaves FCS */
1012                 tap->wr_rate = ural_rxrate(desc);
1013                 tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
1014                 tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
1015                 tap->wr_antenna = sc->rx_ant;
1016                 tap->wr_antsignal = URAL_RSSI(desc->rssi);
1017
1018                 bpf_ptap(sc->sc_drvbpf, m, tap, sc->sc_rxtap_len);
1019         }
1020
1021         /* trim CRC here so WEP can find its own CRC at the end of packet. */
1022         m_adj(m, -IEEE80211_CRC_LEN);
1023
1024         wh = mtod(m, struct ieee80211_frame *);
1025         ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
1026
1027         /* send the frame to the 802.11 layer */
1028         ieee80211_input(ic, m, ni, URAL_RSSI(desc->rssi), 0);
1029
1030         /* node is no longer needed */
1031         ieee80211_free_node(ni);
1032
1033         lwkt_serialize_exit(ifp->if_serializer);
1034
1035         data->m = mnew;
1036         data->buf = mtod(data->m, uint8_t *);
1037
1038         DPRINTFN(15, ("rx done\n"));
1039
1040 skip:   /* setup a new transfer */
1041         usbd_setup_xfer(xfer, sc->sc_rx_pipeh, data, data->buf, MCLBYTES,
1042             USBD_SHORT_XFER_OK, USBD_NO_TIMEOUT, ural_rxeof);
1043         usbd_transfer(xfer);
1044
1045         crit_exit();
1046 }
1047
1048 static uint8_t
1049 ural_plcp_signal(int rate)
1050 {
1051         switch (rate) {
1052         /* CCK rates (returned values are device-dependent) */
1053         case 2:         return 0x0;
1054         case 4:         return 0x1;
1055         case 11:        return 0x2;
1056         case 22:        return 0x3;
1057
1058         /* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
1059         case 12:        return 0xb;
1060         case 18:        return 0xf;
1061         case 24:        return 0xa;
1062         case 36:        return 0xe;
1063         case 48:        return 0x9;
1064         case 72:        return 0xd;
1065         case 96:        return 0x8;
1066         case 108:       return 0xc;
1067
1068         /* unsupported rates (should not get there) */
1069         default:        return 0xff;
1070         }
1071 }
1072
1073 static void
1074 ural_setup_tx_desc(struct ural_softc *sc, struct ural_tx_desc *desc,
1075     uint32_t flags, int len, int rate)
1076 {
1077         struct ieee80211com *ic = &sc->sc_ic;
1078         uint16_t plcp_length;
1079         int remainder;
1080
1081         desc->flags = htole32(flags);
1082         desc->flags |= htole32(RAL_TX_NEWSEQ);
1083         desc->flags |= htole32(len << 16);
1084
1085         desc->wme = htole16(RAL_AIFSN(2) | RAL_LOGCWMIN(3) | RAL_LOGCWMAX(5));
1086         desc->wme |= htole16(RAL_IVOFFSET(sizeof (struct ieee80211_frame)));
1087
1088         /* setup PLCP fields */
1089         desc->plcp_signal  = ural_plcp_signal(rate);
1090         desc->plcp_service = 4;
1091
1092         len += IEEE80211_CRC_LEN;
1093         if (RAL_RATE_IS_OFDM(rate)) {
1094                 desc->flags |= htole32(RAL_TX_OFDM);
1095
1096                 plcp_length = len & 0xfff;
1097                 desc->plcp_length_hi = plcp_length >> 6;
1098                 desc->plcp_length_lo = plcp_length & 0x3f;
1099         } else {
1100                 plcp_length = (16 * len + rate - 1) / rate;
1101                 if (rate == 22) {
1102                         remainder = (16 * len) % 22;
1103                         if (remainder != 0 && remainder < 7)
1104                                 desc->plcp_service |= RAL_PLCP_LENGEXT;
1105                 }
1106                 desc->plcp_length_hi = plcp_length >> 8;
1107                 desc->plcp_length_lo = plcp_length & 0xff;
1108
1109                 if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1110                         desc->plcp_signal |= 0x08;
1111         }
1112
1113         desc->iv = 0;
1114         desc->eiv = 0;
1115 }
1116
1117 #define RAL_TX_TIMEOUT  5000
1118
1119 static int
1120 ural_tx_bcn(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1121 {
1122         struct ural_tx_desc *desc;
1123         usbd_xfer_handle xfer;
1124         uint8_t cmd = 0;
1125         usbd_status error;
1126         uint8_t *buf;
1127         int xferlen, rate;
1128
1129         rate = IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) ? 12 : 2;
1130
1131         xfer = usbd_alloc_xfer(sc->sc_udev);
1132         if (xfer == NULL)
1133                 return ENOMEM;
1134
1135         /* xfer length needs to be a multiple of two! */
1136         xferlen = (RAL_TX_DESC_SIZE + m0->m_pkthdr.len + 1) & ~1;
1137
1138         buf = usbd_alloc_buffer(xfer, xferlen);
1139         if (buf == NULL) {
1140                 usbd_free_xfer(xfer);
1141                 return ENOMEM;
1142         }
1143
1144         usbd_setup_xfer(xfer, sc->sc_tx_pipeh, NULL, &cmd, sizeof cmd,
1145             USBD_FORCE_SHORT_XFER, RAL_TX_TIMEOUT, NULL);
1146
1147         error = usbd_sync_transfer(xfer);
1148         if (error != 0) {
1149                 usbd_free_xfer(xfer);
1150                 return error;
1151         }
1152
1153         desc = (struct ural_tx_desc *)buf;
1154
1155         m_copydata(m0, 0, m0->m_pkthdr.len, buf + RAL_TX_DESC_SIZE);
1156         ural_setup_tx_desc(sc, desc, RAL_TX_IFS_NEWBACKOFF | RAL_TX_TIMESTAMP,
1157             m0->m_pkthdr.len, rate);
1158
1159         DPRINTFN(10, ("sending beacon frame len=%u rate=%u xfer len=%u\n",
1160             m0->m_pkthdr.len, rate, xferlen));
1161
1162         usbd_setup_xfer(xfer, sc->sc_tx_pipeh, NULL, buf, xferlen,
1163             USBD_FORCE_SHORT_XFER | USBD_NO_COPY, RAL_TX_TIMEOUT, NULL);
1164
1165         error = usbd_sync_transfer(xfer);
1166         usbd_free_xfer(xfer);
1167
1168         return error;
1169 }
1170
1171 static int
1172 ural_tx_mgt(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1173 {
1174         struct ieee80211com *ic = &sc->sc_ic;
1175         struct ifnet *ifp = &ic->ic_if;
1176         struct ural_tx_desc *desc;
1177         struct ural_tx_data *data;
1178         struct ieee80211_frame *wh;
1179         uint32_t flags = 0;
1180         uint16_t dur;
1181         usbd_status error;
1182         int xferlen, rate;
1183
1184         data = &sc->tx_data[0];
1185         desc = (struct ural_tx_desc *)data->buf;
1186
1187         rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan) ? 12 : 2;
1188
1189         data->m = m0;
1190         data->ni = ni;
1191
1192         wh = mtod(m0, struct ieee80211_frame *);
1193
1194         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1195                 flags |= RAL_TX_ACK;
1196
1197                 dur = ieee80211_txtime(ni, RAL_ACK_SIZE, rate, ic->ic_flags) +
1198                       sc->sc_sifs;
1199                 *(uint16_t *)wh->i_dur = htole16(dur);
1200
1201                 /* tell hardware to add timestamp for probe responses */
1202                 if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
1203                     IEEE80211_FC0_TYPE_MGT &&
1204                     (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
1205                     IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1206                         flags |= RAL_TX_TIMESTAMP;
1207         }
1208
1209         if (sc->sc_drvbpf != NULL) {
1210                 struct ural_tx_radiotap_header *tap = &sc->sc_txtap;
1211
1212                 tap->wt_flags = 0;
1213                 tap->wt_rate = rate;
1214                 tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1215                 tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1216                 tap->wt_antenna = sc->tx_ant;
1217
1218                 bpf_ptap(sc->sc_drvbpf, m0, tap, sc->sc_txtap_len);
1219         }
1220
1221         m_copydata(m0, 0, m0->m_pkthdr.len, data->buf + RAL_TX_DESC_SIZE);
1222         ural_setup_tx_desc(sc, desc, flags, m0->m_pkthdr.len, rate);
1223
1224         /* align end on a 2-bytes boundary */
1225         xferlen = (RAL_TX_DESC_SIZE + m0->m_pkthdr.len + 1) & ~1;
1226
1227         /*
1228          * No space left in the last URB to store the extra 2 bytes, force
1229          * sending of another URB.
1230          */
1231         if ((xferlen % 64) == 0)
1232                 xferlen += 2;
1233
1234         DPRINTFN(10, ("sending mgt frame len=%u rate=%u xfer len=%u\n",
1235             m0->m_pkthdr.len, rate, xferlen));
1236
1237         lwkt_serialize_exit(ifp->if_serializer);
1238
1239         usbd_setup_xfer(data->xfer, sc->sc_tx_pipeh, data, data->buf,
1240             xferlen, USBD_FORCE_SHORT_XFER | USBD_NO_COPY, RAL_TX_TIMEOUT,
1241             ural_txeof);
1242
1243         error = usbd_transfer(data->xfer);
1244         if (error != USBD_NORMAL_COMPLETION && error != USBD_IN_PROGRESS) {
1245                 m_freem(m0);
1246                 data->m = NULL;
1247                 data->ni = NULL;
1248         } else {
1249                 sc->tx_queued++;
1250                 error = 0;
1251         }
1252
1253         lwkt_serialize_enter(ifp->if_serializer);
1254         return error;
1255 }
1256
1257 static int
1258 ural_tx_data(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1259 {
1260         struct ieee80211com *ic = &sc->sc_ic;
1261         struct ifnet *ifp = &ic->ic_if;
1262         struct ural_tx_desc *desc;
1263         struct ural_tx_data *data;
1264         struct ieee80211_frame *wh;
1265         struct ieee80211_key *k;
1266         uint32_t flags = 0;
1267         uint16_t dur;
1268         usbd_status error;
1269         int xferlen, rate, rate_idx;
1270
1271         wh = mtod(m0, struct ieee80211_frame *);
1272
1273         ieee80211_ratectl_findrate(ni, m0->m_pkthdr.len, &rate_idx, 1);
1274         rate = IEEE80211_RS_RATE(&ni->ni_rates, rate_idx);
1275
1276         if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1277                 k = ieee80211_crypto_encap(ic, ni, m0);
1278                 if (k == NULL) {
1279                         m_freem(m0);
1280                         return ENOBUFS;
1281                 }
1282
1283                 /* packet header may have moved, reset our local pointer */
1284                 wh = mtod(m0, struct ieee80211_frame *);
1285         }
1286
1287         data = &sc->tx_data[0];
1288         desc = (struct ural_tx_desc *)data->buf;
1289
1290         data->m = m0;
1291         data->ni = ni;
1292
1293         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1294                 flags |= RAL_TX_ACK;
1295                 flags |= RAL_TX_RETRY(sc->sc_tx_retries);
1296
1297                 dur = ieee80211_txtime(ni, RAL_ACK_SIZE,
1298                         ieee80211_ack_rate(ni, rate), ic->ic_flags) +
1299                         sc->sc_sifs;
1300                 *(uint16_t *)wh->i_dur = htole16(dur);
1301         }
1302
1303         if (sc->sc_drvbpf != NULL) {
1304                 struct ural_tx_radiotap_header *tap = &sc->sc_txtap;
1305
1306                 tap->wt_flags = 0;
1307                 tap->wt_rate = rate;
1308                 tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1309                 tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1310                 tap->wt_antenna = sc->tx_ant;
1311
1312                 bpf_ptap(sc->sc_drvbpf, m0, tap, sc->sc_txtap_len);
1313         }
1314
1315         m_copydata(m0, 0, m0->m_pkthdr.len, data->buf + RAL_TX_DESC_SIZE);
1316         ural_setup_tx_desc(sc, desc, flags, m0->m_pkthdr.len, rate);
1317
1318         /* align end on a 2-bytes boundary */
1319         xferlen = (RAL_TX_DESC_SIZE + m0->m_pkthdr.len + 1) & ~1;
1320
1321         /*
1322          * No space left in the last URB to store the extra 2 bytes, force
1323          * sending of another URB.
1324          */
1325         if ((xferlen % 64) == 0)
1326                 xferlen += 2;
1327
1328         DPRINTFN(10, ("sending data frame len=%u rate=%u xfer len=%u\n",
1329             m0->m_pkthdr.len, rate, xferlen));
1330
1331         lwkt_serialize_exit(ifp->if_serializer);
1332
1333         usbd_setup_xfer(data->xfer, sc->sc_tx_pipeh, data, data->buf,
1334             xferlen, USBD_FORCE_SHORT_XFER | USBD_NO_COPY, RAL_TX_TIMEOUT,
1335             ural_txeof);
1336
1337         error = usbd_transfer(data->xfer);
1338         if (error != USBD_NORMAL_COMPLETION && error != USBD_IN_PROGRESS) {
1339                 m_freem(m0);
1340                 data->m = NULL;
1341                 data->ni = NULL;
1342         } else {
1343                 sc->tx_queued++;
1344                 error = 0;
1345         }
1346
1347         lwkt_serialize_enter(ifp->if_serializer);
1348         return error;
1349 }
1350
1351 static void
1352 ural_start(struct ifnet *ifp)
1353 {
1354         struct ural_softc *sc = ifp->if_softc;
1355         struct ieee80211com *ic = &sc->sc_ic;
1356
1357         ASSERT_SERIALIZED(ifp->if_serializer);
1358
1359         if (sc->sc_stopped)
1360                 return;
1361
1362         crit_enter();
1363
1364         if ((ifp->if_flags & (IFF_OACTIVE | IFF_RUNNING)) != IFF_RUNNING) {
1365                 crit_exit();
1366                 return;
1367         }
1368
1369         for (;;) {
1370                 struct ieee80211_node *ni;
1371                 struct mbuf *m0;
1372
1373                 if (!IF_QEMPTY(&ic->ic_mgtq)) {
1374                         if (sc->tx_queued >= RAL_TX_LIST_COUNT) {
1375                                 ifp->if_flags |= IFF_OACTIVE;
1376                                 break;
1377                         }
1378                         IF_DEQUEUE(&ic->ic_mgtq, m0);
1379
1380                         ni = (struct ieee80211_node *)m0->m_pkthdr.rcvif;
1381                         m0->m_pkthdr.rcvif = NULL;
1382
1383                         if (ic->ic_rawbpf != NULL)
1384                                 bpf_mtap(ic->ic_rawbpf, m0);
1385
1386                         if (ural_tx_mgt(sc, m0, ni) != 0) {
1387                                 ieee80211_free_node(ni);
1388                                 break;
1389                         }
1390                 } else {
1391                         struct ether_header *eh;
1392
1393                         if (ic->ic_state != IEEE80211_S_RUN)
1394                                 break;
1395                         m0 = ifq_poll(&ifp->if_snd);
1396                         if (m0 == NULL)
1397                                 break;
1398                         if (sc->tx_queued >= RAL_TX_LIST_COUNT) {
1399                                 ifp->if_flags |= IFF_OACTIVE;
1400                                 break;
1401                         }
1402
1403                         ifq_dequeue(&ifp->if_snd, m0);
1404
1405                         if (m0->m_len < sizeof (struct ether_header)) {
1406                                 m0 = m_pullup(m0, sizeof (struct ether_header));
1407                                 if (m0 == NULL) {
1408                                         ifp->if_oerrors++;
1409                                         continue;
1410                                 }
1411                         }
1412
1413                         eh = mtod(m0, struct ether_header *);
1414                         ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1415                         if (ni == NULL) {
1416                                 m_freem(m0);
1417                                 continue;
1418                         }
1419                         BPF_MTAP(ifp, m0);
1420
1421                         m0 = ieee80211_encap(ic, m0, ni);
1422                         if (m0 == NULL) {
1423                                 ieee80211_free_node(ni);
1424                                 continue;
1425                         }
1426
1427                         if (ic->ic_rawbpf != NULL)
1428                                 bpf_mtap(ic->ic_rawbpf, m0);
1429
1430                         if (ural_tx_data(sc, m0, ni) != 0) {
1431                                 ieee80211_free_node(ni);
1432                                 ifp->if_oerrors++;
1433                                 break;
1434                         }
1435                 }
1436
1437                 sc->sc_tx_timer = 5;
1438                 ifp->if_timer = 1;
1439         }
1440
1441         crit_exit();
1442 }
1443
1444 static void
1445 ural_watchdog(struct ifnet *ifp)
1446 {
1447         struct ural_softc *sc = ifp->if_softc;
1448         struct ieee80211com *ic = &sc->sc_ic;
1449
1450         ASSERT_SERIALIZED(ifp->if_serializer);
1451
1452         crit_enter();
1453
1454         ifp->if_timer = 0;
1455
1456         if (sc->sc_tx_timer > 0) {
1457                 if (--sc->sc_tx_timer == 0) {
1458                         device_printf(sc->sc_dev, "device timeout\n");
1459                         /*ural_init(sc); XXX needs a process context! */
1460                         ifp->if_oerrors++;
1461
1462                         crit_exit();
1463                         return;
1464                 }
1465                 ifp->if_timer = 1;
1466         }
1467         ieee80211_watchdog(ic);
1468
1469         crit_exit();
1470 }
1471
1472 /*
1473  * This function allows for fast channel switching in monitor mode (used by
1474  * net-mgmt/kismet). In IBSS mode, we must explicitly reset the interface to
1475  * generate a new beacon frame.
1476  */
1477 static int
1478 ural_reset(struct ifnet *ifp)
1479 {
1480         struct ural_softc *sc = ifp->if_softc;
1481         struct ieee80211com *ic = &sc->sc_ic;
1482
1483         ASSERT_SERIALIZED(ifp->if_serializer);
1484
1485         if (ic->ic_opmode != IEEE80211_M_MONITOR)
1486                 return ENETRESET;
1487
1488         crit_enter();
1489
1490         lwkt_serialize_exit(ifp->if_serializer);
1491         ural_set_chan(sc, ic->ic_curchan);
1492         lwkt_serialize_enter(ifp->if_serializer);
1493
1494         crit_exit();
1495
1496         return 0;
1497 }
1498
1499 static int
1500 ural_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data, struct ucred *cr)
1501 {
1502         struct ural_softc *sc = ifp->if_softc;
1503         struct ieee80211com *ic = &sc->sc_ic;
1504         int error = 0;
1505
1506         ASSERT_SERIALIZED(ifp->if_serializer);
1507
1508         crit_enter();
1509
1510         switch (cmd) {
1511         case SIOCSIFFLAGS:
1512                 if (ifp->if_flags & IFF_UP) {
1513                         if (ifp->if_flags & IFF_RUNNING) {
1514                                 lwkt_serialize_exit(ifp->if_serializer);
1515                                 ural_update_promisc(sc);
1516                                 lwkt_serialize_enter(ifp->if_serializer);
1517                         } else {
1518                                 ural_init(sc);
1519                         }
1520                 } else {
1521                         if (ifp->if_flags & IFF_RUNNING)
1522                                 ural_stop(sc);
1523                 }
1524                 break;
1525
1526         default:
1527                 error = ieee80211_ioctl(ic, cmd, data, cr);
1528         }
1529
1530         if (error == ENETRESET) {
1531                 if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
1532                     (IFF_UP | IFF_RUNNING) &&
1533                     ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
1534                         ural_init(sc);
1535                 error = 0;
1536         }
1537
1538         crit_exit();
1539         return error;
1540 }
1541
1542 static void
1543 ural_set_testmode(struct ural_softc *sc)
1544 {
1545         usb_device_request_t req;
1546         usbd_status error;
1547
1548         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1549         req.bRequest = RAL_VENDOR_REQUEST;
1550         USETW(req.wValue, 4);
1551         USETW(req.wIndex, 1);
1552         USETW(req.wLength, 0);
1553
1554         error = usbd_do_request(sc->sc_udev, &req, NULL);
1555         if (error != 0) {
1556                 kprintf("%s: could not set test mode: %s\n",
1557                     device_get_nameunit(sc->sc_dev), usbd_errstr(error));
1558         }
1559 }
1560
1561 static void
1562 ural_eeprom_read(struct ural_softc *sc, uint16_t addr, void *buf, int len)
1563 {
1564         usb_device_request_t req;
1565         usbd_status error;
1566
1567         req.bmRequestType = UT_READ_VENDOR_DEVICE;
1568         req.bRequest = RAL_READ_EEPROM;
1569         USETW(req.wValue, 0);
1570         USETW(req.wIndex, addr);
1571         USETW(req.wLength, len);
1572
1573         error = usbd_do_request(sc->sc_udev, &req, buf);
1574         if (error != 0) {
1575                 kprintf("%s: could not read EEPROM: %s\n",
1576                     device_get_nameunit(sc->sc_dev), usbd_errstr(error));
1577         }
1578 }
1579
1580 static uint16_t
1581 ural_read(struct ural_softc *sc, uint16_t reg)
1582 {
1583         usb_device_request_t req;
1584         usbd_status error;
1585         uint16_t val;
1586
1587         req.bmRequestType = UT_READ_VENDOR_DEVICE;
1588         req.bRequest = RAL_READ_MAC;
1589         USETW(req.wValue, 0);
1590         USETW(req.wIndex, reg);
1591         USETW(req.wLength, sizeof (uint16_t));
1592
1593         error = usbd_do_request(sc->sc_udev, &req, &val);
1594         if (error != 0) {
1595                 kprintf("%s: could not read MAC register: %s\n",
1596                     device_get_nameunit(sc->sc_dev), usbd_errstr(error));
1597                 return 0;
1598         }
1599
1600         return le16toh(val);
1601 }
1602
1603 static void
1604 ural_read_multi(struct ural_softc *sc, uint16_t reg, void *buf, int len)
1605 {
1606         usb_device_request_t req;
1607         usbd_status error;
1608
1609         req.bmRequestType = UT_READ_VENDOR_DEVICE;
1610         req.bRequest = RAL_READ_MULTI_MAC;
1611         USETW(req.wValue, 0);
1612         USETW(req.wIndex, reg);
1613         USETW(req.wLength, len);
1614
1615         error = usbd_do_request(sc->sc_udev, &req, buf);
1616         if (error != 0) {
1617                 kprintf("%s: could not read MAC register: %s\n",
1618                     device_get_nameunit(sc->sc_dev), usbd_errstr(error));
1619         }
1620 }
1621
1622 static void
1623 ural_write(struct ural_softc *sc, uint16_t reg, uint16_t val)
1624 {
1625         usb_device_request_t req;
1626         usbd_status error;
1627
1628         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1629         req.bRequest = RAL_WRITE_MAC;
1630         USETW(req.wValue, val);
1631         USETW(req.wIndex, reg);
1632         USETW(req.wLength, 0);
1633
1634         error = usbd_do_request(sc->sc_udev, &req, NULL);
1635         if (error != 0) {
1636                 kprintf("%s: could not write MAC register: %s\n",
1637                     device_get_nameunit(sc->sc_dev), usbd_errstr(error));
1638         }
1639 }
1640
1641 static void
1642 ural_write_multi(struct ural_softc *sc, uint16_t reg, void *buf, int len)
1643 {
1644         usb_device_request_t req;
1645         usbd_status error;
1646
1647         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1648         req.bRequest = RAL_WRITE_MULTI_MAC;
1649         USETW(req.wValue, 0);
1650         USETW(req.wIndex, reg);
1651         USETW(req.wLength, len);
1652
1653         error = usbd_do_request(sc->sc_udev, &req, buf);
1654         if (error != 0) {
1655                 kprintf("%s: could not write MAC register: %s\n",
1656                     device_get_nameunit(sc->sc_dev), usbd_errstr(error));
1657         }
1658 }
1659
1660 static void
1661 ural_bbp_write(struct ural_softc *sc, uint8_t reg, uint8_t val)
1662 {
1663         uint16_t tmp;
1664         int ntries;
1665
1666         for (ntries = 0; ntries < 5; ntries++) {
1667                 if (!(ural_read(sc, RAL_PHY_CSR8) & RAL_BBP_BUSY))
1668                         break;
1669         }
1670         if (ntries == 5) {
1671                 kprintf("%s: could not write to BBP\n", device_get_nameunit(sc->sc_dev));
1672                 return;
1673         }
1674
1675         tmp = reg << 8 | val;
1676         ural_write(sc, RAL_PHY_CSR7, tmp);
1677 }
1678
1679 static uint8_t
1680 ural_bbp_read(struct ural_softc *sc, uint8_t reg)
1681 {
1682         uint16_t val;
1683         int ntries;
1684
1685         val = RAL_BBP_WRITE | reg << 8;
1686         ural_write(sc, RAL_PHY_CSR7, val);
1687
1688         for (ntries = 0; ntries < 5; ntries++) {
1689                 if (!(ural_read(sc, RAL_PHY_CSR8) & RAL_BBP_BUSY))
1690                         break;
1691         }
1692         if (ntries == 5) {
1693                 kprintf("%s: could not read BBP\n", device_get_nameunit(sc->sc_dev));
1694                 return 0;
1695         }
1696
1697         return ural_read(sc, RAL_PHY_CSR7) & 0xff;
1698 }
1699
1700 static void
1701 ural_rf_write(struct ural_softc *sc, uint8_t reg, uint32_t val)
1702 {
1703         uint32_t tmp;
1704         int ntries;
1705
1706         for (ntries = 0; ntries < 5; ntries++) {
1707                 if (!(ural_read(sc, RAL_PHY_CSR10) & RAL_RF_LOBUSY))
1708                         break;
1709         }
1710         if (ntries == 5) {
1711                 kprintf("%s: could not write to RF\n", device_get_nameunit(sc->sc_dev));
1712                 return;
1713         }
1714
1715         tmp = RAL_RF_BUSY | RAL_RF_20BIT | (val & 0xfffff) << 2 | (reg & 0x3);
1716         ural_write(sc, RAL_PHY_CSR9,  tmp & 0xffff);
1717         ural_write(sc, RAL_PHY_CSR10, tmp >> 16);
1718
1719         /* remember last written value in sc */
1720         sc->rf_regs[reg] = val;
1721
1722         DPRINTFN(15, ("RF R[%u] <- 0x%05x\n", reg & 0x3, val & 0xfffff));
1723 }
1724
1725 static void
1726 ural_set_chan(struct ural_softc *sc, struct ieee80211_channel *c)
1727 {
1728         struct ieee80211com *ic = &sc->sc_ic;
1729         uint8_t power, tmp;
1730         u_int i, chan;
1731
1732         chan = ieee80211_chan2ieee(ic, c);
1733         if (chan == 0 || chan == IEEE80211_CHAN_ANY)
1734                 return;
1735
1736         if (IEEE80211_IS_CHAN_2GHZ(c))
1737                 power = min(sc->txpow[chan - 1], 31);
1738         else
1739                 power = 31;
1740
1741         /* adjust txpower using ifconfig settings */
1742         power -= (100 - ic->ic_txpowlimit) / 8;
1743
1744         DPRINTFN(2, ("setting channel to %u, txpower to %u\n", chan, power));
1745
1746         switch (sc->rf_rev) {
1747         case RAL_RF_2522:
1748                 ural_rf_write(sc, RAL_RF1, 0x00814);
1749                 ural_rf_write(sc, RAL_RF2, ural_rf2522_r2[chan - 1]);
1750                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1751                 break;
1752
1753         case RAL_RF_2523:
1754                 ural_rf_write(sc, RAL_RF1, 0x08804);
1755                 ural_rf_write(sc, RAL_RF2, ural_rf2523_r2[chan - 1]);
1756                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x38044);
1757                 ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1758                 break;
1759
1760         case RAL_RF_2524:
1761                 ural_rf_write(sc, RAL_RF1, 0x0c808);
1762                 ural_rf_write(sc, RAL_RF2, ural_rf2524_r2[chan - 1]);
1763                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1764                 ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1765                 break;
1766
1767         case RAL_RF_2525:
1768                 ural_rf_write(sc, RAL_RF1, 0x08808);
1769                 ural_rf_write(sc, RAL_RF2, ural_rf2525_hi_r2[chan - 1]);
1770                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1771                 ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1772
1773                 ural_rf_write(sc, RAL_RF1, 0x08808);
1774                 ural_rf_write(sc, RAL_RF2, ural_rf2525_r2[chan - 1]);
1775                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1776                 ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1777                 break;
1778
1779         case RAL_RF_2525E:
1780                 ural_rf_write(sc, RAL_RF1, 0x08808);
1781                 ural_rf_write(sc, RAL_RF2, ural_rf2525e_r2[chan - 1]);
1782                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1783                 ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00286 : 0x00282);
1784                 break;
1785
1786         case RAL_RF_2526:
1787                 ural_rf_write(sc, RAL_RF2, ural_rf2526_hi_r2[chan - 1]);
1788                 ural_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381);
1789                 ural_rf_write(sc, RAL_RF1, 0x08804);
1790
1791                 ural_rf_write(sc, RAL_RF2, ural_rf2526_r2[chan - 1]);
1792                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1793                 ural_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381);
1794                 break;
1795
1796         /* dual-band RF */
1797         case RAL_RF_5222:
1798                 for (i = 0; ural_rf5222[i].chan != chan; i++)
1799                         ; /* EMPTY */
1800
1801                 ural_rf_write(sc, RAL_RF1, ural_rf5222[i].r1);
1802                 ural_rf_write(sc, RAL_RF2, ural_rf5222[i].r2);
1803                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1804                 ural_rf_write(sc, RAL_RF4, ural_rf5222[i].r4);
1805                 break;
1806         }
1807
1808         if (ic->ic_opmode != IEEE80211_M_MONITOR &&
1809             ic->ic_state != IEEE80211_S_SCAN) {
1810                 /* set Japan filter bit for channel 14 */
1811                 tmp = ural_bbp_read(sc, 70);
1812
1813                 tmp &= ~RAL_JAPAN_FILTER;
1814                 if (chan == 14)
1815                         tmp |= RAL_JAPAN_FILTER;
1816
1817                 ural_bbp_write(sc, 70, tmp);
1818
1819                 /* clear CRC errors */
1820                 ural_read(sc, RAL_STA_CSR0);
1821
1822                 DELAY(10000);
1823                 ural_disable_rf_tune(sc);
1824         }
1825
1826         sc->sc_sifs = IEEE80211_IS_CHAN_5GHZ(c) ? IEEE80211_DUR_OFDM_SIFS
1827                                                 : IEEE80211_DUR_SIFS;
1828 }
1829
1830 /*
1831  * Disable RF auto-tuning.
1832  */
1833 static void
1834 ural_disable_rf_tune(struct ural_softc *sc)
1835 {
1836         uint32_t tmp;
1837
1838         if (sc->rf_rev != RAL_RF_2523) {
1839                 tmp = sc->rf_regs[RAL_RF1] & ~RAL_RF1_AUTOTUNE;
1840                 ural_rf_write(sc, RAL_RF1, tmp);
1841         }
1842
1843         tmp = sc->rf_regs[RAL_RF3] & ~RAL_RF3_AUTOTUNE;
1844         ural_rf_write(sc, RAL_RF3, tmp);
1845
1846         DPRINTFN(2, ("disabling RF autotune\n"));
1847 }
1848
1849 /*
1850  * Refer to IEEE Std 802.11-1999 pp. 123 for more information on TSF
1851  * synchronization.
1852  */
1853 static void
1854 ural_enable_tsf_sync(struct ural_softc *sc)
1855 {
1856         struct ieee80211com *ic = &sc->sc_ic;
1857         uint16_t logcwmin, preload, tmp;
1858
1859         /* first, disable TSF synchronization */
1860         ural_write(sc, RAL_TXRX_CSR19, 0);
1861
1862         tmp = (16 * ic->ic_bss->ni_intval) << 4;
1863         ural_write(sc, RAL_TXRX_CSR18, tmp);
1864
1865         logcwmin = (ic->ic_opmode == IEEE80211_M_IBSS) ? 2 : 0;
1866         preload = (ic->ic_opmode == IEEE80211_M_IBSS) ? 320 : 6;
1867         tmp = logcwmin << 12 | preload;
1868         ural_write(sc, RAL_TXRX_CSR20, tmp);
1869
1870         /* finally, enable TSF synchronization */
1871         tmp = RAL_ENABLE_TSF | RAL_ENABLE_TBCN;
1872         if (ic->ic_opmode == IEEE80211_M_STA)
1873                 tmp |= RAL_ENABLE_TSF_SYNC(1);
1874         else
1875                 tmp |= RAL_ENABLE_TSF_SYNC(2) | RAL_ENABLE_BEACON_GENERATOR;
1876         ural_write(sc, RAL_TXRX_CSR19, tmp);
1877
1878         DPRINTF(("enabling TSF synchronization\n"));
1879 }
1880
1881 static void
1882 ural_update_slot(struct ifnet *ifp)
1883 {
1884         struct ural_softc *sc = ifp->if_softc;
1885         struct ieee80211com *ic = &sc->sc_ic;
1886         uint16_t slottime, sifs, eifs;
1887
1888         slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
1889
1890         /*
1891          * These settings may sound a bit inconsistent but this is what the
1892          * reference driver does.
1893          */
1894         if (ic->ic_curmode == IEEE80211_MODE_11B) {
1895                 sifs = 16 - RAL_RXTX_TURNAROUND;
1896                 eifs = 364;
1897         } else {
1898                 sifs = 10 - RAL_RXTX_TURNAROUND;
1899                 eifs = 64;
1900         }
1901
1902         ural_write(sc, RAL_MAC_CSR10, slottime);
1903         ural_write(sc, RAL_MAC_CSR11, sifs);
1904         ural_write(sc, RAL_MAC_CSR12, eifs);
1905 }
1906
1907 static void
1908 ural_set_txpreamble(struct ural_softc *sc)
1909 {
1910         uint16_t tmp;
1911
1912         tmp = ural_read(sc, RAL_TXRX_CSR10);
1913
1914         tmp &= ~RAL_SHORT_PREAMBLE;
1915         if (sc->sc_ic.ic_flags & IEEE80211_F_SHPREAMBLE)
1916                 tmp |= RAL_SHORT_PREAMBLE;
1917
1918         ural_write(sc, RAL_TXRX_CSR10, tmp);
1919 }
1920
1921 static void
1922 ural_set_basicrates(struct ural_softc *sc)
1923 {
1924         struct ieee80211com *ic = &sc->sc_ic;
1925
1926         /* update basic rate set */
1927         if (ic->ic_curmode == IEEE80211_MODE_11B) {
1928                 /* 11b basic rates: 1, 2Mbps */
1929                 ural_write(sc, RAL_TXRX_CSR11, 0x3);
1930         } else if (IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan)) {
1931                 /* 11a basic rates: 6, 12, 24Mbps */
1932                 ural_write(sc, RAL_TXRX_CSR11, 0x150);
1933         } else {
1934                 /* 11g basic rates: 1, 2, 5.5, 11, 6, 12, 24Mbps */
1935                 ural_write(sc, RAL_TXRX_CSR11, 0x15f);
1936         }
1937 }
1938
1939 static void
1940 ural_set_bssid(struct ural_softc *sc, uint8_t *bssid)
1941 {
1942         uint16_t tmp;
1943
1944         tmp = bssid[0] | bssid[1] << 8;
1945         ural_write(sc, RAL_MAC_CSR5, tmp);
1946
1947         tmp = bssid[2] | bssid[3] << 8;
1948         ural_write(sc, RAL_MAC_CSR6, tmp);
1949
1950         tmp = bssid[4] | bssid[5] << 8;
1951         ural_write(sc, RAL_MAC_CSR7, tmp);
1952
1953         DPRINTF(("setting BSSID to %6D\n", bssid, ":"));
1954 }
1955
1956 static void
1957 ural_set_macaddr(struct ural_softc *sc, uint8_t *addr)
1958 {
1959         uint16_t tmp;
1960
1961         tmp = addr[0] | addr[1] << 8;
1962         ural_write(sc, RAL_MAC_CSR2, tmp);
1963
1964         tmp = addr[2] | addr[3] << 8;
1965         ural_write(sc, RAL_MAC_CSR3, tmp);
1966
1967         tmp = addr[4] | addr[5] << 8;
1968         ural_write(sc, RAL_MAC_CSR4, tmp);
1969
1970         DPRINTF(("setting MAC address to %6D\n", addr, ":"));
1971 }
1972
1973 static void
1974 ural_update_promisc(struct ural_softc *sc)
1975 {
1976         struct ifnet *ifp = &sc->sc_ic.ic_if;
1977         uint32_t tmp;
1978
1979         tmp = ural_read(sc, RAL_TXRX_CSR2);
1980
1981         tmp &= ~RAL_DROP_NOT_TO_ME;
1982         if (!(ifp->if_flags & IFF_PROMISC))
1983                 tmp |= RAL_DROP_NOT_TO_ME;
1984
1985         ural_write(sc, RAL_TXRX_CSR2, tmp);
1986
1987         DPRINTF(("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
1988             "entering" : "leaving"));
1989 }
1990
1991 static const char *
1992 ural_get_rf(int rev)
1993 {
1994         switch (rev) {
1995         case RAL_RF_2522:       return "RT2522";
1996         case RAL_RF_2523:       return "RT2523";
1997         case RAL_RF_2524:       return "RT2524";
1998         case RAL_RF_2525:       return "RT2525";
1999         case RAL_RF_2525E:      return "RT2525e";
2000         case RAL_RF_2526:       return "RT2526";
2001         case RAL_RF_5222:       return "RT5222";
2002         default:                return "unknown";
2003         }
2004 }
2005
2006 static void
2007 ural_read_eeprom(struct ural_softc *sc)
2008 {
2009         struct ieee80211com *ic = &sc->sc_ic;
2010         uint16_t val;
2011
2012         ural_eeprom_read(sc, RAL_EEPROM_CONFIG0, &val, 2);
2013         val = le16toh(val);
2014         sc->rf_rev =   (val >> 11) & 0x7;
2015         sc->hw_radio = (val >> 10) & 0x1;
2016         sc->led_mode = (val >> 6)  & 0x7;
2017         sc->rx_ant =   (val >> 4)  & 0x3;
2018         sc->tx_ant =   (val >> 2)  & 0x3;
2019         sc->nb_ant =   val & 0x3;
2020
2021         /* read MAC address */
2022         ural_eeprom_read(sc, RAL_EEPROM_ADDRESS, ic->ic_myaddr, 6);
2023
2024         /* read default values for BBP registers */
2025         ural_eeprom_read(sc, RAL_EEPROM_BBP_BASE, sc->bbp_prom, 2 * 16);
2026
2027         /* read Tx power for all b/g channels */
2028         ural_eeprom_read(sc, RAL_EEPROM_TXPOWER, sc->txpow, 14);
2029 }
2030
2031 static int
2032 ural_bbp_init(struct ural_softc *sc)
2033 {
2034 #define N(a)    (sizeof (a) / sizeof ((a)[0]))
2035         int i, ntries;
2036
2037         /* wait for BBP to be ready */
2038         for (ntries = 0; ntries < 100; ntries++) {
2039                 if (ural_bbp_read(sc, RAL_BBP_VERSION) != 0)
2040                         break;
2041                 DELAY(1000);
2042         }
2043         if (ntries == 100) {
2044                 device_printf(sc->sc_dev, "timeout waiting for BBP\n");
2045                 return EIO;
2046         }
2047
2048         /* initialize BBP registers to default values */
2049         for (i = 0; i < N(ural_def_bbp); i++)
2050                 ural_bbp_write(sc, ural_def_bbp[i].reg, ural_def_bbp[i].val);
2051
2052 #if 0
2053         /* initialize BBP registers to values stored in EEPROM */
2054         for (i = 0; i < 16; i++) {
2055                 if (sc->bbp_prom[i].reg == 0xff)
2056                         continue;
2057                 ural_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
2058         }
2059 #endif
2060
2061         return 0;
2062 #undef N
2063 }
2064
2065 static void
2066 ural_set_txantenna(struct ural_softc *sc, int antenna)
2067 {
2068         uint16_t tmp;
2069         uint8_t tx;
2070
2071         tx = ural_bbp_read(sc, RAL_BBP_TX) & ~RAL_BBP_ANTMASK;
2072         if (antenna == 1)
2073                 tx |= RAL_BBP_ANTA;
2074         else if (antenna == 2)
2075                 tx |= RAL_BBP_ANTB;
2076         else
2077                 tx |= RAL_BBP_DIVERSITY;
2078
2079         /* need to force I/Q flip for RF 2525e, 2526 and 5222 */
2080         if (sc->rf_rev == RAL_RF_2525E || sc->rf_rev == RAL_RF_2526 ||
2081             sc->rf_rev == RAL_RF_5222)
2082                 tx |= RAL_BBP_FLIPIQ;
2083
2084         ural_bbp_write(sc, RAL_BBP_TX, tx);
2085
2086         /* update values in PHY_CSR5 and PHY_CSR6 */
2087         tmp = ural_read(sc, RAL_PHY_CSR5) & ~0x7;
2088         ural_write(sc, RAL_PHY_CSR5, tmp | (tx & 0x7));
2089
2090         tmp = ural_read(sc, RAL_PHY_CSR6) & ~0x7;
2091         ural_write(sc, RAL_PHY_CSR6, tmp | (tx & 0x7));
2092 }
2093
2094 static void
2095 ural_set_rxantenna(struct ural_softc *sc, int antenna)
2096 {
2097         uint8_t rx;
2098
2099         rx = ural_bbp_read(sc, RAL_BBP_RX) & ~RAL_BBP_ANTMASK;
2100         if (antenna == 1)
2101                 rx |= RAL_BBP_ANTA;
2102         else if (antenna == 2)
2103                 rx |= RAL_BBP_ANTB;
2104         else
2105                 rx |= RAL_BBP_DIVERSITY;
2106
2107         /* need to force no I/Q flip for RF 2525e and 2526 */
2108         if (sc->rf_rev == RAL_RF_2525E || sc->rf_rev == RAL_RF_2526)
2109                 rx &= ~RAL_BBP_FLIPIQ;
2110
2111         ural_bbp_write(sc, RAL_BBP_RX, rx);
2112 }
2113
2114 static void
2115 ural_init(void *priv)
2116 {
2117 #define N(a)    (sizeof (a) / sizeof ((a)[0]))
2118         struct ural_softc *sc = priv;
2119         struct ieee80211com *ic = &sc->sc_ic;
2120         struct ifnet *ifp = &ic->ic_if;
2121         struct ural_rx_data *data;
2122         uint16_t tmp;
2123         usbd_status usb_err;
2124         int i, ntries, error;
2125
2126         ASSERT_SERIALIZED(ifp->if_serializer);
2127
2128         crit_enter();
2129
2130         lwkt_serialize_exit(ifp->if_serializer);
2131         ural_set_testmode(sc);
2132         ural_write(sc, 0x308, 0x00f0);  /* XXX magic */
2133         lwkt_serialize_enter(ifp->if_serializer);
2134
2135         ural_stop(sc);
2136         sc->sc_stopped = 0;
2137
2138         lwkt_serialize_exit(ifp->if_serializer);
2139
2140         /* initialize MAC registers to default values */
2141         for (i = 0; i < N(ural_def_mac); i++)
2142                 ural_write(sc, ural_def_mac[i].reg, ural_def_mac[i].val);
2143
2144         /* wait for BBP and RF to wake up (this can take a long time!) */
2145         for (ntries = 0; ntries < 100; ntries++) {
2146                 tmp = ural_read(sc, RAL_MAC_CSR17);
2147                 if ((tmp & (RAL_BBP_AWAKE | RAL_RF_AWAKE)) ==
2148                     (RAL_BBP_AWAKE | RAL_RF_AWAKE))
2149                         break;
2150                 DELAY(1000);
2151         }
2152         if (ntries == 100) {
2153                 kprintf("%s: timeout waiting for BBP/RF to wakeup\n",
2154                     device_get_nameunit(sc->sc_dev));
2155                 error = ETIMEDOUT;
2156                 goto fail;
2157         }
2158
2159         /* we're ready! */
2160         ural_write(sc, RAL_MAC_CSR1, RAL_HOST_READY);
2161
2162         /* set basic rate set (will be updated later) */
2163         ural_write(sc, RAL_TXRX_CSR11, 0x15f);
2164
2165         error = ural_bbp_init(sc);
2166         if (error)
2167                 goto fail;
2168
2169         /* set default BSS channel */
2170         ural_set_chan(sc, ic->ic_curchan);
2171
2172         /* clear statistic registers (STA_CSR0 to STA_CSR10) */
2173         ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof sc->sta);
2174
2175         ural_set_txantenna(sc, sc->tx_ant);
2176         ural_set_rxantenna(sc, sc->rx_ant);
2177
2178         IEEE80211_ADDR_COPY(ic->ic_myaddr, IF_LLADDR(ifp));
2179         ural_set_macaddr(sc, ic->ic_myaddr);
2180
2181         /*
2182          * Allocate xfer for AMRR statistics requests.
2183          */
2184         sc->stats_xfer = usbd_alloc_xfer(sc->sc_udev);
2185         if (sc->stats_xfer == NULL) {
2186                 kprintf("%s: could not allocate AMRR xfer\n",
2187                     device_get_nameunit(sc->sc_dev));
2188                 error = ENOMEM;
2189                 goto fail;
2190         }
2191
2192         /*
2193          * Open Tx and Rx USB bulk pipes.
2194          */
2195         usb_err = usbd_open_pipe(sc->sc_iface, sc->sc_tx_no, USBD_EXCLUSIVE_USE,
2196             &sc->sc_tx_pipeh);
2197         if (usb_err != 0) {
2198                 kprintf("%s: could not open Tx pipe: %s\n",
2199                     device_get_nameunit(sc->sc_dev), usbd_errstr(usb_err));
2200                 error = ENOMEM;
2201                 goto fail;
2202         }
2203
2204         usb_err = usbd_open_pipe(sc->sc_iface, sc->sc_rx_no, USBD_EXCLUSIVE_USE,
2205             &sc->sc_rx_pipeh);
2206         if (usb_err != 0) {
2207                 kprintf("%s: could not open Rx pipe: %s\n",
2208                     device_get_nameunit(sc->sc_dev), usbd_errstr(usb_err));
2209                 error = ENOMEM;
2210                 goto fail;
2211         }
2212
2213         /*
2214          * Allocate Tx and Rx xfer queues.
2215          */
2216         error = ural_alloc_tx_list(sc);
2217         if (error) {
2218                 kprintf("%s: could not allocate Tx list\n",
2219                     device_get_nameunit(sc->sc_dev));
2220                 goto fail;
2221         }
2222
2223         error = ural_alloc_rx_list(sc);
2224         if (error) {
2225                 kprintf("%s: could not allocate Rx list\n",
2226                     device_get_nameunit(sc->sc_dev));
2227                 goto fail;
2228         }
2229
2230         /*
2231          * Start up the receive pipe.
2232          */
2233         for (i = 0; i < RAL_RX_LIST_COUNT; i++) {
2234                 data = &sc->rx_data[i];
2235
2236                 usbd_setup_xfer(data->xfer, sc->sc_rx_pipeh, data, data->buf,
2237                     MCLBYTES, USBD_SHORT_XFER_OK, USBD_NO_TIMEOUT, ural_rxeof);
2238                 usbd_transfer(data->xfer);
2239         }
2240
2241         /* kick Rx */
2242         tmp = RAL_DROP_PHY | RAL_DROP_CRC;
2243         if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2244                 tmp |= RAL_DROP_CTL | RAL_DROP_BAD_VERSION;
2245                 if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2246                         tmp |= RAL_DROP_TODS;
2247                 if (!(ifp->if_flags & IFF_PROMISC))
2248                         tmp |= RAL_DROP_NOT_TO_ME;
2249         }
2250         ural_write(sc, RAL_TXRX_CSR2, tmp);
2251
2252         /* clear statistic registers (STA_CSR0 to STA_CSR10) */
2253         ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof(sc->sta));
2254 fail:
2255         lwkt_serialize_enter(ifp->if_serializer);
2256         if (error) {
2257                 ural_stop(sc);
2258         } else {
2259                 ifp->if_flags &= ~IFF_OACTIVE;
2260                 ifp->if_flags |= IFF_RUNNING;
2261
2262                 if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2263                         if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
2264                                 ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
2265                 } else {
2266                         ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
2267                 }
2268         }
2269
2270         crit_exit();
2271 #undef N
2272 }
2273
2274 static void
2275 ural_stop(struct ural_softc *sc)
2276 {
2277         struct ieee80211com *ic = &sc->sc_ic;
2278         struct ifnet *ifp = &ic->ic_if;
2279
2280         ASSERT_SERIALIZED(ifp->if_serializer);
2281
2282         crit_enter();
2283
2284         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2285         sc->sc_stopped = 1;
2286
2287         ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
2288
2289         sc->sc_tx_timer = 0;
2290         ifp->if_timer = 0;
2291
2292         lwkt_serialize_exit(ifp->if_serializer);
2293
2294         /* disable Rx */
2295         ural_write(sc, RAL_TXRX_CSR2, RAL_DISABLE_RX);
2296
2297         /* reset ASIC and BBP (but won't reset MAC registers!) */
2298         ural_write(sc, RAL_MAC_CSR1, RAL_RESET_ASIC | RAL_RESET_BBP);
2299         ural_write(sc, RAL_MAC_CSR1, 0);
2300
2301         if (sc->stats_xfer != NULL) {
2302                 usbd_free_xfer(sc->stats_xfer);
2303                 sc->stats_xfer = NULL;
2304         }
2305
2306         if (sc->sc_rx_pipeh != NULL) {
2307                 usbd_abort_pipe(sc->sc_rx_pipeh);
2308                 usbd_close_pipe(sc->sc_rx_pipeh);
2309                 sc->sc_rx_pipeh = NULL;
2310         }
2311
2312         if (sc->sc_tx_pipeh != NULL) {
2313                 usbd_abort_pipe(sc->sc_tx_pipeh);
2314                 usbd_close_pipe(sc->sc_tx_pipeh);
2315                 sc->sc_tx_pipeh = NULL;
2316         }
2317
2318         lwkt_serialize_enter(ifp->if_serializer);
2319
2320         ural_free_rx_list(sc);
2321         ural_free_tx_list(sc);
2322
2323         crit_exit();
2324 }
2325
2326 static void
2327 ural_stats_timeout(void *arg)
2328 {
2329         struct ural_softc *sc = (struct ural_softc *)arg;
2330         usb_device_request_t req;
2331
2332         if (sc->sc_stopped)
2333                 return;
2334
2335         crit_enter();
2336
2337         /*
2338          * Asynchronously read statistic registers (cleared by read).
2339          */
2340         req.bmRequestType = UT_READ_VENDOR_DEVICE;
2341         req.bRequest = RAL_READ_MULTI_MAC;
2342         USETW(req.wValue, 0);
2343         USETW(req.wIndex, RAL_STA_CSR0);
2344         USETW(req.wLength, sizeof(sc->sta));
2345
2346         usbd_setup_default_xfer(sc->stats_xfer, sc->sc_udev, sc,
2347                                 USBD_DEFAULT_TIMEOUT, &req,
2348                                 sc->sta, sizeof(sc->sta), 0,
2349                                 ural_stats_update);
2350         usbd_transfer(sc->stats_xfer);
2351
2352         crit_exit();
2353 }
2354
2355 static void
2356 ural_stats_update(usbd_xfer_handle xfer, usbd_private_handle priv,
2357                   usbd_status status)
2358 {
2359         struct ural_softc *sc = (struct ural_softc *)priv;
2360         struct ifnet *ifp = &sc->sc_ic.ic_if;
2361         struct ieee80211_ratectl_stats *stats = &sc->sc_stats;
2362
2363         if (status != USBD_NORMAL_COMPLETION) {
2364                 device_printf(sc->sc_dev, "could not retrieve Tx statistics - "
2365                     "cancelling automatic rate control\n");
2366                 return;
2367         }
2368
2369         crit_enter();
2370
2371         /* count TX retry-fail as Tx errors */
2372         ifp->if_oerrors += sc->sta[RAL_TX_PKT_FAIL];
2373
2374         stats->stats_pkt_ok += sc->sta[RAL_TX_PKT_NO_RETRY] +
2375                                sc->sta[RAL_TX_PKT_ONE_RETRY] +
2376                                sc->sta[RAL_TX_PKT_MULTI_RETRY];
2377
2378         stats->stats_pkt_err += sc->sta[RAL_TX_PKT_FAIL];
2379
2380         stats->stats_pkt_noretry += sc->sta[RAL_TX_PKT_NO_RETRY];
2381
2382         stats->stats_retries += sc->sta[RAL_TX_PKT_ONE_RETRY];
2383 #if 1
2384         /*
2385          * XXX Estimated average:
2386          * Actual number of retries for each packet should belong to
2387          * [2, sc->sc_tx_retries]
2388          */
2389         stats->stats_retries += sc->sta[RAL_TX_PKT_MULTI_RETRY] *
2390                                 ((2 + sc->sc_tx_retries) / 2);
2391 #else
2392         stats->stats_retries += sc->sta[RAL_TX_PKT_MULTI_RETRY];
2393 #endif
2394         stats->stats_retries += sc->sta[RAL_TX_PKT_FAIL] * sc->sc_tx_retries;
2395
2396         callout_reset(&sc->stats_ch, 4 * hz / 5, ural_stats_timeout, sc);
2397
2398         crit_exit();
2399 }
2400
2401 static void
2402 ural_stats(struct ieee80211com *ic, struct ieee80211_node *ni __unused,
2403            struct ieee80211_ratectl_stats *stats)
2404 {
2405         struct ifnet *ifp = &ic->ic_if;
2406         struct ural_softc *sc = ifp->if_softc;
2407
2408         ASSERT_SERIALIZED(ifp->if_serializer);
2409
2410         bcopy(&sc->sc_stats, stats, sizeof(*stats));
2411         bzero(&sc->sc_stats, sizeof(sc->sc_stats));
2412 }
2413
2414 static void
2415 ural_ratectl_change(struct ieee80211com *ic, u_int orc __unused, u_int nrc)
2416 {
2417         struct ieee80211_ratectl_state *st = &ic->ic_ratectl;
2418         struct ieee80211_onoe_param *oparam;
2419
2420         if (st->rc_st_param != NULL) {
2421                 kfree(st->rc_st_param, M_DEVBUF);
2422                 st->rc_st_param = NULL;
2423         }
2424
2425         switch (nrc) {
2426         case IEEE80211_RATECTL_ONOE:
2427                 oparam = kmalloc(sizeof(*oparam), M_DEVBUF, M_INTWAIT);
2428
2429                 IEEE80211_ONOE_PARAM_SETUP(oparam);
2430                 oparam->onoe_raise = 20;
2431
2432                 st->rc_st_param = oparam;
2433                 break;
2434         case IEEE80211_RATECTL_NONE:
2435                 /* This could only happen during detaching */
2436                 break;
2437         default:
2438                 panic("unknown rate control algo %u\n", nrc);
2439         }
2440 }
2441
2442 DRIVER_MODULE(ural, uhub, ural_driver, ural_devclass, usbd_driver_load, 0);