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