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