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