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