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