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