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