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