xref: /freebsd/sys/dev/usb/wlan/if_ural.c (revision 1834282de6b9f6fd30291bfe1cc9c3ecf5547c40)
1 /*	$FreeBSD$	*/
2 
3 /*-
4  * Copyright (c) 2005, 2006
5  *	Damien Bergamini <damien.bergamini@free.fr>
6  *
7  * Copyright (c) 2006, 2008
8  *	Hans Petter Selasky <hselasky@FreeBSD.org>
9  *
10  * Permission to use, copy, modify, and distribute this software for any
11  * purpose with or without fee is hereby granted, provided that the above
12  * copyright notice and this permission notice appear in all copies.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
15  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
16  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
17  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
18  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
19  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
20  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21  */
22 
23 #include <sys/cdefs.h>
24 __FBSDID("$FreeBSD$");
25 
26 /*-
27  * Ralink Technology RT2500USB chipset driver
28  * http://www.ralinktech.com/
29  */
30 
31 #include <sys/param.h>
32 #include <sys/sockio.h>
33 #include <sys/sysctl.h>
34 #include <sys/lock.h>
35 #include <sys/mutex.h>
36 #include <sys/mbuf.h>
37 #include <sys/kernel.h>
38 #include <sys/socket.h>
39 #include <sys/systm.h>
40 #include <sys/malloc.h>
41 #include <sys/module.h>
42 #include <sys/bus.h>
43 #include <sys/endian.h>
44 #include <sys/kdb.h>
45 
46 #include <machine/bus.h>
47 #include <machine/resource.h>
48 #include <sys/rman.h>
49 
50 #include <net/bpf.h>
51 #include <net/if.h>
52 #include <net/if_var.h>
53 #include <net/if_arp.h>
54 #include <net/ethernet.h>
55 #include <net/if_dl.h>
56 #include <net/if_media.h>
57 #include <net/if_types.h>
58 
59 #ifdef INET
60 #include <netinet/in.h>
61 #include <netinet/in_systm.h>
62 #include <netinet/in_var.h>
63 #include <netinet/if_ether.h>
64 #include <netinet/ip.h>
65 #endif
66 
67 #include <net80211/ieee80211_var.h>
68 #include <net80211/ieee80211_regdomain.h>
69 #include <net80211/ieee80211_radiotap.h>
70 #include <net80211/ieee80211_ratectl.h>
71 
72 #include <dev/usb/usb.h>
73 #include <dev/usb/usbdi.h>
74 #include "usbdevs.h"
75 
76 #define	USB_DEBUG_VAR ural_debug
77 #include <dev/usb/usb_debug.h>
78 
79 #include <dev/usb/wlan/if_uralreg.h>
80 #include <dev/usb/wlan/if_uralvar.h>
81 
82 #ifdef USB_DEBUG
83 static int ural_debug = 0;
84 
85 static SYSCTL_NODE(_hw_usb, OID_AUTO, ural, CTLFLAG_RW, 0, "USB ural");
86 SYSCTL_INT(_hw_usb_ural, OID_AUTO, debug, CTLFLAG_RWTUN, &ural_debug, 0,
87     "Debug level");
88 #endif
89 
90 #define URAL_RSSI(rssi)					\
91 	((rssi) > (RAL_NOISE_FLOOR + RAL_RSSI_CORR) ?	\
92 	 ((rssi) - (RAL_NOISE_FLOOR + RAL_RSSI_CORR)) : 0)
93 
94 /* various supported device vendors/products */
95 static const STRUCT_USB_HOST_ID ural_devs[] = {
96 #define	URAL_DEV(v,p)  { USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##p) }
97 	URAL_DEV(ASUS, WL167G),
98 	URAL_DEV(ASUS, RT2570),
99 	URAL_DEV(BELKIN, F5D7050),
100 	URAL_DEV(BELKIN, F5D7051),
101 	URAL_DEV(CISCOLINKSYS, HU200TS),
102 	URAL_DEV(CISCOLINKSYS, WUSB54G),
103 	URAL_DEV(CISCOLINKSYS, WUSB54GP),
104 	URAL_DEV(CONCEPTRONIC2, C54RU),
105 	URAL_DEV(DLINK, DWLG122),
106 	URAL_DEV(GIGABYTE, GN54G),
107 	URAL_DEV(GIGABYTE, GNWBKG),
108 	URAL_DEV(GUILLEMOT, HWGUSB254),
109 	URAL_DEV(MELCO, KG54),
110 	URAL_DEV(MELCO, KG54AI),
111 	URAL_DEV(MELCO, KG54YB),
112 	URAL_DEV(MELCO, NINWIFI),
113 	URAL_DEV(MSI, RT2570),
114 	URAL_DEV(MSI, RT2570_2),
115 	URAL_DEV(MSI, RT2570_3),
116 	URAL_DEV(NOVATECH, NV902),
117 	URAL_DEV(RALINK, RT2570),
118 	URAL_DEV(RALINK, RT2570_2),
119 	URAL_DEV(RALINK, RT2570_3),
120 	URAL_DEV(SIEMENS2, WL54G),
121 	URAL_DEV(SMC, 2862WG),
122 	URAL_DEV(SPHAIRON, UB801R),
123 	URAL_DEV(SURECOM, RT2570),
124 	URAL_DEV(VTECH, RT2570),
125 	URAL_DEV(ZINWELL, RT2570),
126 #undef URAL_DEV
127 };
128 
129 static usb_callback_t ural_bulk_read_callback;
130 static usb_callback_t ural_bulk_write_callback;
131 
132 static usb_error_t	ural_do_request(struct ural_softc *sc,
133 			    struct usb_device_request *req, void *data);
134 static struct ieee80211vap *ural_vap_create(struct ieee80211com *,
135 			    const char [IFNAMSIZ], int, enum ieee80211_opmode,
136 			    int, const uint8_t [IEEE80211_ADDR_LEN],
137 			    const uint8_t [IEEE80211_ADDR_LEN]);
138 static void		ural_vap_delete(struct ieee80211vap *);
139 static void		ural_tx_free(struct ural_tx_data *, int);
140 static void		ural_setup_tx_list(struct ural_softc *);
141 static void		ural_unsetup_tx_list(struct ural_softc *);
142 static int		ural_newstate(struct ieee80211vap *,
143 			    enum ieee80211_state, int);
144 static void		ural_setup_tx_desc(struct ural_softc *,
145 			    struct ural_tx_desc *, uint32_t, int, int);
146 static int		ural_tx_bcn(struct ural_softc *, struct mbuf *,
147 			    struct ieee80211_node *);
148 static int		ural_tx_mgt(struct ural_softc *, struct mbuf *,
149 			    struct ieee80211_node *);
150 static int		ural_tx_data(struct ural_softc *, struct mbuf *,
151 			    struct ieee80211_node *);
152 static int		ural_transmit(struct ieee80211com *, struct mbuf *);
153 static void		ural_start(struct ural_softc *);
154 static void		ural_parent(struct ieee80211com *);
155 static void		ural_set_testmode(struct ural_softc *);
156 static void		ural_eeprom_read(struct ural_softc *, uint16_t, void *,
157 			    int);
158 static uint16_t		ural_read(struct ural_softc *, uint16_t);
159 static void		ural_read_multi(struct ural_softc *, uint16_t, void *,
160 			    int);
161 static void		ural_write(struct ural_softc *, uint16_t, uint16_t);
162 static void		ural_write_multi(struct ural_softc *, uint16_t, void *,
163 			    int) __unused;
164 static void		ural_bbp_write(struct ural_softc *, uint8_t, uint8_t);
165 static uint8_t		ural_bbp_read(struct ural_softc *, uint8_t);
166 static void		ural_rf_write(struct ural_softc *, uint8_t, uint32_t);
167 static void		ural_scan_start(struct ieee80211com *);
168 static void		ural_scan_end(struct ieee80211com *);
169 static void		ural_getradiocaps(struct ieee80211com *, int, int *,
170 			    struct ieee80211_channel[]);
171 static void		ural_set_channel(struct ieee80211com *);
172 static void		ural_set_chan(struct ural_softc *,
173 			    struct ieee80211_channel *);
174 static void		ural_disable_rf_tune(struct ural_softc *);
175 static void		ural_enable_tsf_sync(struct ural_softc *);
176 static void 		ural_enable_tsf(struct ural_softc *);
177 static void		ural_update_slot(struct ural_softc *);
178 static void		ural_set_txpreamble(struct ural_softc *);
179 static void		ural_set_basicrates(struct ural_softc *,
180 			    const struct ieee80211_channel *);
181 static void		ural_set_bssid(struct ural_softc *, const uint8_t *);
182 static void		ural_set_macaddr(struct ural_softc *, const uint8_t *);
183 static void		ural_update_promisc(struct ieee80211com *);
184 static void		ural_setpromisc(struct ural_softc *);
185 static const char	*ural_get_rf(int);
186 static void		ural_read_eeprom(struct ural_softc *);
187 static int		ural_bbp_init(struct ural_softc *);
188 static void		ural_set_txantenna(struct ural_softc *, int);
189 static void		ural_set_rxantenna(struct ural_softc *, int);
190 static void		ural_init(struct ural_softc *);
191 static void		ural_stop(struct ural_softc *);
192 static int		ural_raw_xmit(struct ieee80211_node *, struct mbuf *,
193 			    const struct ieee80211_bpf_params *);
194 static void		ural_ratectl_start(struct ural_softc *,
195 			    struct ieee80211_node *);
196 static void		ural_ratectl_timeout(void *);
197 static void		ural_ratectl_task(void *, int);
198 static int		ural_pause(struct ural_softc *sc, int timeout);
199 
200 /*
201  * Default values for MAC registers; values taken from the reference driver.
202  */
203 static const struct {
204 	uint16_t	reg;
205 	uint16_t	val;
206 } ural_def_mac[] = {
207 	{ RAL_TXRX_CSR5,  0x8c8d },
208 	{ RAL_TXRX_CSR6,  0x8b8a },
209 	{ RAL_TXRX_CSR7,  0x8687 },
210 	{ RAL_TXRX_CSR8,  0x0085 },
211 	{ RAL_MAC_CSR13,  0x1111 },
212 	{ RAL_MAC_CSR14,  0x1e11 },
213 	{ RAL_TXRX_CSR21, 0xe78f },
214 	{ RAL_MAC_CSR9,   0xff1d },
215 	{ RAL_MAC_CSR11,  0x0002 },
216 	{ RAL_MAC_CSR22,  0x0053 },
217 	{ RAL_MAC_CSR15,  0x0000 },
218 	{ RAL_MAC_CSR8,   RAL_FRAME_SIZE },
219 	{ RAL_TXRX_CSR19, 0x0000 },
220 	{ RAL_TXRX_CSR18, 0x005a },
221 	{ RAL_PHY_CSR2,   0x0000 },
222 	{ RAL_TXRX_CSR0,  0x1ec0 },
223 	{ RAL_PHY_CSR4,   0x000f }
224 };
225 
226 /*
227  * Default values for BBP registers; values taken from the reference driver.
228  */
229 static const struct {
230 	uint8_t	reg;
231 	uint8_t	val;
232 } ural_def_bbp[] = {
233 	{  3, 0x02 },
234 	{  4, 0x19 },
235 	{ 14, 0x1c },
236 	{ 15, 0x30 },
237 	{ 16, 0xac },
238 	{ 17, 0x48 },
239 	{ 18, 0x18 },
240 	{ 19, 0xff },
241 	{ 20, 0x1e },
242 	{ 21, 0x08 },
243 	{ 22, 0x08 },
244 	{ 23, 0x08 },
245 	{ 24, 0x80 },
246 	{ 25, 0x50 },
247 	{ 26, 0x08 },
248 	{ 27, 0x23 },
249 	{ 30, 0x10 },
250 	{ 31, 0x2b },
251 	{ 32, 0xb9 },
252 	{ 34, 0x12 },
253 	{ 35, 0x50 },
254 	{ 39, 0xc4 },
255 	{ 40, 0x02 },
256 	{ 41, 0x60 },
257 	{ 53, 0x10 },
258 	{ 54, 0x18 },
259 	{ 56, 0x08 },
260 	{ 57, 0x10 },
261 	{ 58, 0x08 },
262 	{ 61, 0x60 },
263 	{ 62, 0x10 },
264 	{ 75, 0xff }
265 };
266 
267 /*
268  * Default values for RF register R2 indexed by channel numbers.
269  */
270 static const uint32_t ural_rf2522_r2[] = {
271 	0x307f6, 0x307fb, 0x30800, 0x30805, 0x3080a, 0x3080f, 0x30814,
272 	0x30819, 0x3081e, 0x30823, 0x30828, 0x3082d, 0x30832, 0x3083e
273 };
274 
275 static const uint32_t ural_rf2523_r2[] = {
276 	0x00327, 0x00328, 0x00329, 0x0032a, 0x0032b, 0x0032c, 0x0032d,
277 	0x0032e, 0x0032f, 0x00340, 0x00341, 0x00342, 0x00343, 0x00346
278 };
279 
280 static const uint32_t ural_rf2524_r2[] = {
281 	0x00327, 0x00328, 0x00329, 0x0032a, 0x0032b, 0x0032c, 0x0032d,
282 	0x0032e, 0x0032f, 0x00340, 0x00341, 0x00342, 0x00343, 0x00346
283 };
284 
285 static const uint32_t ural_rf2525_r2[] = {
286 	0x20327, 0x20328, 0x20329, 0x2032a, 0x2032b, 0x2032c, 0x2032d,
287 	0x2032e, 0x2032f, 0x20340, 0x20341, 0x20342, 0x20343, 0x20346
288 };
289 
290 static const uint32_t ural_rf2525_hi_r2[] = {
291 	0x2032f, 0x20340, 0x20341, 0x20342, 0x20343, 0x20344, 0x20345,
292 	0x20346, 0x20347, 0x20348, 0x20349, 0x2034a, 0x2034b, 0x2034e
293 };
294 
295 static const uint32_t ural_rf2525e_r2[] = {
296 	0x2044d, 0x2044e, 0x2044f, 0x20460, 0x20461, 0x20462, 0x20463,
297 	0x20464, 0x20465, 0x20466, 0x20467, 0x20468, 0x20469, 0x2046b
298 };
299 
300 static const uint32_t ural_rf2526_hi_r2[] = {
301 	0x0022a, 0x0022b, 0x0022b, 0x0022c, 0x0022c, 0x0022d, 0x0022d,
302 	0x0022e, 0x0022e, 0x0022f, 0x0022d, 0x00240, 0x00240, 0x00241
303 };
304 
305 static const uint32_t ural_rf2526_r2[] = {
306 	0x00226, 0x00227, 0x00227, 0x00228, 0x00228, 0x00229, 0x00229,
307 	0x0022a, 0x0022a, 0x0022b, 0x0022b, 0x0022c, 0x0022c, 0x0022d
308 };
309 
310 /*
311  * For dual-band RF, RF registers R1 and R4 also depend on channel number;
312  * values taken from the reference driver.
313  */
314 static const struct {
315 	uint8_t		chan;
316 	uint32_t	r1;
317 	uint32_t	r2;
318 	uint32_t	r4;
319 } ural_rf5222[] = {
320 	{   1, 0x08808, 0x0044d, 0x00282 },
321 	{   2, 0x08808, 0x0044e, 0x00282 },
322 	{   3, 0x08808, 0x0044f, 0x00282 },
323 	{   4, 0x08808, 0x00460, 0x00282 },
324 	{   5, 0x08808, 0x00461, 0x00282 },
325 	{   6, 0x08808, 0x00462, 0x00282 },
326 	{   7, 0x08808, 0x00463, 0x00282 },
327 	{   8, 0x08808, 0x00464, 0x00282 },
328 	{   9, 0x08808, 0x00465, 0x00282 },
329 	{  10, 0x08808, 0x00466, 0x00282 },
330 	{  11, 0x08808, 0x00467, 0x00282 },
331 	{  12, 0x08808, 0x00468, 0x00282 },
332 	{  13, 0x08808, 0x00469, 0x00282 },
333 	{  14, 0x08808, 0x0046b, 0x00286 },
334 
335 	{  36, 0x08804, 0x06225, 0x00287 },
336 	{  40, 0x08804, 0x06226, 0x00287 },
337 	{  44, 0x08804, 0x06227, 0x00287 },
338 	{  48, 0x08804, 0x06228, 0x00287 },
339 	{  52, 0x08804, 0x06229, 0x00287 },
340 	{  56, 0x08804, 0x0622a, 0x00287 },
341 	{  60, 0x08804, 0x0622b, 0x00287 },
342 	{  64, 0x08804, 0x0622c, 0x00287 },
343 
344 	{ 100, 0x08804, 0x02200, 0x00283 },
345 	{ 104, 0x08804, 0x02201, 0x00283 },
346 	{ 108, 0x08804, 0x02202, 0x00283 },
347 	{ 112, 0x08804, 0x02203, 0x00283 },
348 	{ 116, 0x08804, 0x02204, 0x00283 },
349 	{ 120, 0x08804, 0x02205, 0x00283 },
350 	{ 124, 0x08804, 0x02206, 0x00283 },
351 	{ 128, 0x08804, 0x02207, 0x00283 },
352 	{ 132, 0x08804, 0x02208, 0x00283 },
353 	{ 136, 0x08804, 0x02209, 0x00283 },
354 	{ 140, 0x08804, 0x0220a, 0x00283 },
355 
356 	{ 149, 0x08808, 0x02429, 0x00281 },
357 	{ 153, 0x08808, 0x0242b, 0x00281 },
358 	{ 157, 0x08808, 0x0242d, 0x00281 },
359 	{ 161, 0x08808, 0x0242f, 0x00281 }
360 };
361 
362 static const uint8_t ural_chan_2ghz[] =
363 	{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
364 
365 static const uint8_t ural_chan_5ghz[] =
366 	{ 36, 40, 44, 48, 52, 56, 60, 64,
367 	  100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140,
368 	  149, 153, 157, 161 };
369 
370 static const struct usb_config ural_config[URAL_N_TRANSFER] = {
371 	[URAL_BULK_WR] = {
372 		.type = UE_BULK,
373 		.endpoint = UE_ADDR_ANY,
374 		.direction = UE_DIR_OUT,
375 		.bufsize = (RAL_FRAME_SIZE + RAL_TX_DESC_SIZE + 4),
376 		.flags = {.pipe_bof = 1,.force_short_xfer = 1,},
377 		.callback = ural_bulk_write_callback,
378 		.timeout = 5000,	/* ms */
379 	},
380 	[URAL_BULK_RD] = {
381 		.type = UE_BULK,
382 		.endpoint = UE_ADDR_ANY,
383 		.direction = UE_DIR_IN,
384 		.bufsize = (RAL_FRAME_SIZE + RAL_RX_DESC_SIZE),
385 		.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
386 		.callback = ural_bulk_read_callback,
387 	},
388 };
389 
390 static device_probe_t ural_match;
391 static device_attach_t ural_attach;
392 static device_detach_t ural_detach;
393 
394 static device_method_t ural_methods[] = {
395 	/* Device interface */
396 	DEVMETHOD(device_probe,		ural_match),
397 	DEVMETHOD(device_attach,	ural_attach),
398 	DEVMETHOD(device_detach,	ural_detach),
399 	DEVMETHOD_END
400 };
401 
402 static driver_t ural_driver = {
403 	.name = "ural",
404 	.methods = ural_methods,
405 	.size = sizeof(struct ural_softc),
406 };
407 
408 static devclass_t ural_devclass;
409 
410 DRIVER_MODULE(ural, uhub, ural_driver, ural_devclass, NULL, 0);
411 MODULE_DEPEND(ural, usb, 1, 1, 1);
412 MODULE_DEPEND(ural, wlan, 1, 1, 1);
413 MODULE_VERSION(ural, 1);
414 USB_PNP_HOST_INFO(ural_devs);
415 
416 static int
417 ural_match(device_t self)
418 {
419 	struct usb_attach_arg *uaa = device_get_ivars(self);
420 
421 	if (uaa->usb_mode != USB_MODE_HOST)
422 		return (ENXIO);
423 	if (uaa->info.bConfigIndex != 0)
424 		return (ENXIO);
425 	if (uaa->info.bIfaceIndex != RAL_IFACE_INDEX)
426 		return (ENXIO);
427 
428 	return (usbd_lookup_id_by_uaa(ural_devs, sizeof(ural_devs), uaa));
429 }
430 
431 static int
432 ural_attach(device_t self)
433 {
434 	struct usb_attach_arg *uaa = device_get_ivars(self);
435 	struct ural_softc *sc = device_get_softc(self);
436 	struct ieee80211com *ic = &sc->sc_ic;
437 	uint8_t iface_index;
438 	int error;
439 
440 	device_set_usb_desc(self);
441 	sc->sc_udev = uaa->device;
442 	sc->sc_dev = self;
443 
444 	mtx_init(&sc->sc_mtx, device_get_nameunit(self),
445 	    MTX_NETWORK_LOCK, MTX_DEF);
446 	mbufq_init(&sc->sc_snd, ifqmaxlen);
447 
448 	iface_index = RAL_IFACE_INDEX;
449 	error = usbd_transfer_setup(uaa->device,
450 	    &iface_index, sc->sc_xfer, ural_config,
451 	    URAL_N_TRANSFER, sc, &sc->sc_mtx);
452 	if (error) {
453 		device_printf(self, "could not allocate USB transfers, "
454 		    "err=%s\n", usbd_errstr(error));
455 		goto detach;
456 	}
457 
458 	RAL_LOCK(sc);
459 	/* retrieve RT2570 rev. no */
460 	sc->asic_rev = ural_read(sc, RAL_MAC_CSR0);
461 
462 	/* retrieve MAC address and various other things from EEPROM */
463 	ural_read_eeprom(sc);
464 	RAL_UNLOCK(sc);
465 
466 	device_printf(self, "MAC/BBP RT2570 (rev 0x%02x), RF %s\n",
467 	    sc->asic_rev, ural_get_rf(sc->rf_rev));
468 
469 	ic->ic_softc = sc;
470 	ic->ic_name = device_get_nameunit(self);
471 	ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
472 
473 	/* set device capabilities */
474 	ic->ic_caps =
475 	      IEEE80211_C_STA		/* station mode supported */
476 	    | IEEE80211_C_IBSS		/* IBSS mode supported */
477 	    | IEEE80211_C_MONITOR	/* monitor mode supported */
478 	    | IEEE80211_C_HOSTAP	/* HostAp mode supported */
479 	    | IEEE80211_C_TXPMGT	/* tx power management */
480 	    | IEEE80211_C_SHPREAMBLE	/* short preamble supported */
481 	    | IEEE80211_C_SHSLOT	/* short slot time supported */
482 	    | IEEE80211_C_BGSCAN	/* bg scanning supported */
483 	    | IEEE80211_C_WPA		/* 802.11i */
484 	    ;
485 
486 	ural_getradiocaps(ic, IEEE80211_CHAN_MAX, &ic->ic_nchans,
487 	    ic->ic_channels);
488 
489 	ieee80211_ifattach(ic);
490 	ic->ic_update_promisc = ural_update_promisc;
491 	ic->ic_raw_xmit = ural_raw_xmit;
492 	ic->ic_scan_start = ural_scan_start;
493 	ic->ic_scan_end = ural_scan_end;
494 	ic->ic_getradiocaps = ural_getradiocaps;
495 	ic->ic_set_channel = ural_set_channel;
496 	ic->ic_parent = ural_parent;
497 	ic->ic_transmit = ural_transmit;
498 	ic->ic_vap_create = ural_vap_create;
499 	ic->ic_vap_delete = ural_vap_delete;
500 
501 	ieee80211_radiotap_attach(ic,
502 	    &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
503 		RAL_TX_RADIOTAP_PRESENT,
504 	    &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
505 		RAL_RX_RADIOTAP_PRESENT);
506 
507 	if (bootverbose)
508 		ieee80211_announce(ic);
509 
510 	return (0);
511 
512 detach:
513 	ural_detach(self);
514 	return (ENXIO);			/* failure */
515 }
516 
517 static int
518 ural_detach(device_t self)
519 {
520 	struct ural_softc *sc = device_get_softc(self);
521 	struct ieee80211com *ic = &sc->sc_ic;
522 
523 	/* prevent further ioctls */
524 	RAL_LOCK(sc);
525 	sc->sc_detached = 1;
526 	RAL_UNLOCK(sc);
527 
528 	/* stop all USB transfers */
529 	usbd_transfer_unsetup(sc->sc_xfer, URAL_N_TRANSFER);
530 
531 	/* free TX list, if any */
532 	RAL_LOCK(sc);
533 	ural_unsetup_tx_list(sc);
534 	RAL_UNLOCK(sc);
535 
536 	if (ic->ic_softc == sc)
537 		ieee80211_ifdetach(ic);
538 	mbufq_drain(&sc->sc_snd);
539 	mtx_destroy(&sc->sc_mtx);
540 
541 	return (0);
542 }
543 
544 static usb_error_t
545 ural_do_request(struct ural_softc *sc,
546     struct usb_device_request *req, void *data)
547 {
548 	usb_error_t err;
549 	int ntries = 10;
550 
551 	while (ntries--) {
552 		err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx,
553 		    req, data, 0, NULL, 250 /* ms */);
554 		if (err == 0)
555 			break;
556 
557 		DPRINTFN(1, "Control request failed, %s (retrying)\n",
558 		    usbd_errstr(err));
559 		if (ural_pause(sc, hz / 100))
560 			break;
561 	}
562 	return (err);
563 }
564 
565 static struct ieee80211vap *
566 ural_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
567     enum ieee80211_opmode opmode, int flags,
568     const uint8_t bssid[IEEE80211_ADDR_LEN],
569     const uint8_t mac[IEEE80211_ADDR_LEN])
570 {
571 	struct ural_softc *sc = ic->ic_softc;
572 	struct ural_vap *uvp;
573 	struct ieee80211vap *vap;
574 
575 	if (!TAILQ_EMPTY(&ic->ic_vaps))		/* only one at a time */
576 		return NULL;
577 	uvp = malloc(sizeof(struct ural_vap), M_80211_VAP, M_WAITOK | M_ZERO);
578 	vap = &uvp->vap;
579 	/* enable s/w bmiss handling for sta mode */
580 
581 	if (ieee80211_vap_setup(ic, vap, name, unit, opmode,
582 	    flags | IEEE80211_CLONE_NOBEACONS, bssid) != 0) {
583 		/* out of memory */
584 		free(uvp, M_80211_VAP);
585 		return (NULL);
586 	}
587 
588 	/* override state transition machine */
589 	uvp->newstate = vap->iv_newstate;
590 	vap->iv_newstate = ural_newstate;
591 
592 	usb_callout_init_mtx(&uvp->ratectl_ch, &sc->sc_mtx, 0);
593 	TASK_INIT(&uvp->ratectl_task, 0, ural_ratectl_task, uvp);
594 	ieee80211_ratectl_init(vap);
595 	ieee80211_ratectl_setinterval(vap, 1000 /* 1 sec */);
596 
597 	/* complete setup */
598 	ieee80211_vap_attach(vap, ieee80211_media_change,
599 	    ieee80211_media_status, mac);
600 	ic->ic_opmode = opmode;
601 	return vap;
602 }
603 
604 static void
605 ural_vap_delete(struct ieee80211vap *vap)
606 {
607 	struct ural_vap *uvp = URAL_VAP(vap);
608 	struct ieee80211com *ic = vap->iv_ic;
609 
610 	usb_callout_drain(&uvp->ratectl_ch);
611 	ieee80211_draintask(ic, &uvp->ratectl_task);
612 	ieee80211_ratectl_deinit(vap);
613 	ieee80211_vap_detach(vap);
614 	free(uvp, M_80211_VAP);
615 }
616 
617 static void
618 ural_tx_free(struct ural_tx_data *data, int txerr)
619 {
620 	struct ural_softc *sc = data->sc;
621 
622 	if (data->m != NULL) {
623 		ieee80211_tx_complete(data->ni, data->m, txerr);
624 		data->m = NULL;
625 		data->ni = NULL;
626 	}
627 	STAILQ_INSERT_TAIL(&sc->tx_free, data, next);
628 	sc->tx_nfree++;
629 }
630 
631 static void
632 ural_setup_tx_list(struct ural_softc *sc)
633 {
634 	struct ural_tx_data *data;
635 	int i;
636 
637 	sc->tx_nfree = 0;
638 	STAILQ_INIT(&sc->tx_q);
639 	STAILQ_INIT(&sc->tx_free);
640 
641 	for (i = 0; i < RAL_TX_LIST_COUNT; i++) {
642 		data = &sc->tx_data[i];
643 
644 		data->sc = sc;
645 		STAILQ_INSERT_TAIL(&sc->tx_free, data, next);
646 		sc->tx_nfree++;
647 	}
648 }
649 
650 static void
651 ural_unsetup_tx_list(struct ural_softc *sc)
652 {
653 	struct ural_tx_data *data;
654 	int i;
655 
656 	/* make sure any subsequent use of the queues will fail */
657 	sc->tx_nfree = 0;
658 	STAILQ_INIT(&sc->tx_q);
659 	STAILQ_INIT(&sc->tx_free);
660 
661 	/* free up all node references and mbufs */
662 	for (i = 0; i < RAL_TX_LIST_COUNT; i++) {
663 		data = &sc->tx_data[i];
664 
665 		if (data->m != NULL) {
666 			m_freem(data->m);
667 			data->m = NULL;
668 		}
669 		if (data->ni != NULL) {
670 			ieee80211_free_node(data->ni);
671 			data->ni = NULL;
672 		}
673 	}
674 }
675 
676 static int
677 ural_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
678 {
679 	struct ural_vap *uvp = URAL_VAP(vap);
680 	struct ieee80211com *ic = vap->iv_ic;
681 	struct ural_softc *sc = ic->ic_softc;
682 	const struct ieee80211_txparam *tp;
683 	struct ieee80211_node *ni;
684 	struct mbuf *m;
685 
686 	DPRINTF("%s -> %s\n",
687 		ieee80211_state_name[vap->iv_state],
688 		ieee80211_state_name[nstate]);
689 
690 	IEEE80211_UNLOCK(ic);
691 	RAL_LOCK(sc);
692 	usb_callout_stop(&uvp->ratectl_ch);
693 
694 	switch (nstate) {
695 	case IEEE80211_S_INIT:
696 		if (vap->iv_state == IEEE80211_S_RUN) {
697 			/* abort TSF synchronization */
698 			ural_write(sc, RAL_TXRX_CSR19, 0);
699 
700 			/* force tx led to stop blinking */
701 			ural_write(sc, RAL_MAC_CSR20, 0);
702 		}
703 		break;
704 
705 	case IEEE80211_S_RUN:
706 		ni = ieee80211_ref_node(vap->iv_bss);
707 
708 		if (vap->iv_opmode != IEEE80211_M_MONITOR) {
709 			if (ic->ic_bsschan == IEEE80211_CHAN_ANYC)
710 				goto fail;
711 
712 			ural_update_slot(sc);
713 			ural_set_txpreamble(sc);
714 			ural_set_basicrates(sc, ic->ic_bsschan);
715 			IEEE80211_ADDR_COPY(sc->sc_bssid, ni->ni_bssid);
716 			ural_set_bssid(sc, sc->sc_bssid);
717 		}
718 
719 		if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
720 		    vap->iv_opmode == IEEE80211_M_IBSS) {
721 			m = ieee80211_beacon_alloc(ni);
722 			if (m == NULL) {
723 				device_printf(sc->sc_dev,
724 				    "could not allocate beacon\n");
725 				goto fail;
726 			}
727 			ieee80211_ref_node(ni);
728 			if (ural_tx_bcn(sc, m, ni) != 0) {
729 				device_printf(sc->sc_dev,
730 				    "could not send beacon\n");
731 				goto fail;
732 			}
733 		}
734 
735 		/* make tx led blink on tx (controlled by ASIC) */
736 		ural_write(sc, RAL_MAC_CSR20, 1);
737 
738 		if (vap->iv_opmode != IEEE80211_M_MONITOR)
739 			ural_enable_tsf_sync(sc);
740 		else
741 			ural_enable_tsf(sc);
742 
743 		/* enable automatic rate adaptation */
744 		/* XXX should use ic_bsschan but not valid until after newstate call below */
745 		tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
746 		if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
747 			ural_ratectl_start(sc, ni);
748 		ieee80211_free_node(ni);
749 		break;
750 
751 	default:
752 		break;
753 	}
754 	RAL_UNLOCK(sc);
755 	IEEE80211_LOCK(ic);
756 	return (uvp->newstate(vap, nstate, arg));
757 
758 fail:
759 	RAL_UNLOCK(sc);
760 	IEEE80211_LOCK(ic);
761 	ieee80211_free_node(ni);
762 	return (-1);
763 }
764 
765 
766 static void
767 ural_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
768 {
769 	struct ural_softc *sc = usbd_xfer_softc(xfer);
770 	struct ieee80211vap *vap;
771 	struct ural_tx_data *data;
772 	struct mbuf *m;
773 	struct usb_page_cache *pc;
774 	int len;
775 
776 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
777 
778 	switch (USB_GET_STATE(xfer)) {
779 	case USB_ST_TRANSFERRED:
780 		DPRINTFN(11, "transfer complete, %d bytes\n", len);
781 
782 		/* free resources */
783 		data = usbd_xfer_get_priv(xfer);
784 		ural_tx_free(data, 0);
785 		usbd_xfer_set_priv(xfer, NULL);
786 
787 		/* FALLTHROUGH */
788 	case USB_ST_SETUP:
789 tr_setup:
790 		data = STAILQ_FIRST(&sc->tx_q);
791 		if (data) {
792 			STAILQ_REMOVE_HEAD(&sc->tx_q, next);
793 			m = data->m;
794 
795 			if (m->m_pkthdr.len > (int)(RAL_FRAME_SIZE + RAL_TX_DESC_SIZE)) {
796 				DPRINTFN(0, "data overflow, %u bytes\n",
797 				    m->m_pkthdr.len);
798 				m->m_pkthdr.len = (RAL_FRAME_SIZE + RAL_TX_DESC_SIZE);
799 			}
800 			pc = usbd_xfer_get_frame(xfer, 0);
801 			usbd_copy_in(pc, 0, &data->desc, RAL_TX_DESC_SIZE);
802 			usbd_m_copy_in(pc, RAL_TX_DESC_SIZE, m, 0,
803 			    m->m_pkthdr.len);
804 
805 			vap = data->ni->ni_vap;
806 			if (ieee80211_radiotap_active_vap(vap)) {
807 				struct ural_tx_radiotap_header *tap = &sc->sc_txtap;
808 
809 				tap->wt_flags = 0;
810 				tap->wt_rate = data->rate;
811 				tap->wt_antenna = sc->tx_ant;
812 
813 				ieee80211_radiotap_tx(vap, m);
814 			}
815 
816 			/* xfer length needs to be a multiple of two! */
817 			len = (RAL_TX_DESC_SIZE + m->m_pkthdr.len + 1) & ~1;
818 			if ((len % 64) == 0)
819 				len += 2;
820 
821 			DPRINTFN(11, "sending frame len=%u xferlen=%u\n",
822 			    m->m_pkthdr.len, len);
823 
824 			usbd_xfer_set_frame_len(xfer, 0, len);
825 			usbd_xfer_set_priv(xfer, data);
826 
827 			usbd_transfer_submit(xfer);
828 		}
829 		ural_start(sc);
830 		break;
831 
832 	default:			/* Error */
833 		DPRINTFN(11, "transfer error, %s\n",
834 		    usbd_errstr(error));
835 
836 		data = usbd_xfer_get_priv(xfer);
837 		if (data != NULL) {
838 			ural_tx_free(data, error);
839 			usbd_xfer_set_priv(xfer, NULL);
840 		}
841 
842 		if (error == USB_ERR_STALLED) {
843 			/* try to clear stall first */
844 			usbd_xfer_set_stall(xfer);
845 			goto tr_setup;
846 		}
847 		if (error == USB_ERR_TIMEOUT)
848 			device_printf(sc->sc_dev, "device timeout\n");
849 		break;
850 	}
851 }
852 
853 static void
854 ural_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
855 {
856 	struct ural_softc *sc = usbd_xfer_softc(xfer);
857 	struct ieee80211com *ic = &sc->sc_ic;
858 	struct ieee80211_node *ni;
859 	struct mbuf *m = NULL;
860 	struct usb_page_cache *pc;
861 	uint32_t flags;
862 	int8_t rssi = 0, nf = 0;
863 	int len;
864 
865 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
866 
867 	switch (USB_GET_STATE(xfer)) {
868 	case USB_ST_TRANSFERRED:
869 
870 		DPRINTFN(15, "rx done, actlen=%d\n", len);
871 
872 		if (len < (int)(RAL_RX_DESC_SIZE + IEEE80211_MIN_LEN)) {
873 			DPRINTF("%s: xfer too short %d\n",
874 			    device_get_nameunit(sc->sc_dev), len);
875 			counter_u64_add(ic->ic_ierrors, 1);
876 			goto tr_setup;
877 		}
878 
879 		len -= RAL_RX_DESC_SIZE;
880 		/* rx descriptor is located at the end */
881 		pc = usbd_xfer_get_frame(xfer, 0);
882 		usbd_copy_out(pc, len, &sc->sc_rx_desc, RAL_RX_DESC_SIZE);
883 
884 		rssi = URAL_RSSI(sc->sc_rx_desc.rssi);
885 		nf = RAL_NOISE_FLOOR;
886 		flags = le32toh(sc->sc_rx_desc.flags);
887 		if (flags & (RAL_RX_PHY_ERROR | RAL_RX_CRC_ERROR)) {
888 			/*
889 		         * This should not happen since we did not
890 		         * request to receive those frames when we
891 		         * filled RAL_TXRX_CSR2:
892 		         */
893 			DPRINTFN(5, "PHY or CRC error\n");
894 			counter_u64_add(ic->ic_ierrors, 1);
895 			goto tr_setup;
896 		}
897 
898 		m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
899 		if (m == NULL) {
900 			DPRINTF("could not allocate mbuf\n");
901 			counter_u64_add(ic->ic_ierrors, 1);
902 			goto tr_setup;
903 		}
904 		usbd_copy_out(pc, 0, mtod(m, uint8_t *), len);
905 
906 		/* finalize mbuf */
907 		m->m_pkthdr.len = m->m_len = (flags >> 16) & 0xfff;
908 
909 		if (ieee80211_radiotap_active(ic)) {
910 			struct ural_rx_radiotap_header *tap = &sc->sc_rxtap;
911 
912 			/* XXX set once */
913 			tap->wr_flags = 0;
914 			tap->wr_rate = ieee80211_plcp2rate(sc->sc_rx_desc.rate,
915 			    (flags & RAL_RX_OFDM) ?
916 			    IEEE80211_T_OFDM : IEEE80211_T_CCK);
917 			tap->wr_antenna = sc->rx_ant;
918 			tap->wr_antsignal = nf + rssi;
919 			tap->wr_antnoise = nf;
920 		}
921 		/* Strip trailing 802.11 MAC FCS. */
922 		m_adj(m, -IEEE80211_CRC_LEN);
923 
924 		/* FALLTHROUGH */
925 	case USB_ST_SETUP:
926 tr_setup:
927 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
928 		usbd_transfer_submit(xfer);
929 
930 		/*
931 		 * At the end of a USB callback it is always safe to unlock
932 		 * the private mutex of a device! That is why we do the
933 		 * "ieee80211_input" here, and not some lines up!
934 		 */
935 		RAL_UNLOCK(sc);
936 		if (m) {
937 			ni = ieee80211_find_rxnode(ic,
938 			    mtod(m, struct ieee80211_frame_min *));
939 			if (ni != NULL) {
940 				(void) ieee80211_input(ni, m, rssi, nf);
941 				ieee80211_free_node(ni);
942 			} else
943 				(void) ieee80211_input_all(ic, m, rssi, nf);
944 		}
945 		RAL_LOCK(sc);
946 		ural_start(sc);
947 		return;
948 
949 	default:			/* Error */
950 		if (error != USB_ERR_CANCELLED) {
951 			/* try to clear stall first */
952 			usbd_xfer_set_stall(xfer);
953 			goto tr_setup;
954 		}
955 		return;
956 	}
957 }
958 
959 static uint8_t
960 ural_plcp_signal(int rate)
961 {
962 	switch (rate) {
963 	/* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
964 	case 12:	return 0xb;
965 	case 18:	return 0xf;
966 	case 24:	return 0xa;
967 	case 36:	return 0xe;
968 	case 48:	return 0x9;
969 	case 72:	return 0xd;
970 	case 96:	return 0x8;
971 	case 108:	return 0xc;
972 
973 	/* CCK rates (NB: not IEEE std, device-specific) */
974 	case 2:		return 0x0;
975 	case 4:		return 0x1;
976 	case 11:	return 0x2;
977 	case 22:	return 0x3;
978 	}
979 	return 0xff;		/* XXX unsupported/unknown rate */
980 }
981 
982 static void
983 ural_setup_tx_desc(struct ural_softc *sc, struct ural_tx_desc *desc,
984     uint32_t flags, int len, int rate)
985 {
986 	struct ieee80211com *ic = &sc->sc_ic;
987 	uint16_t plcp_length;
988 	int remainder;
989 
990 	desc->flags = htole32(flags);
991 	desc->flags |= htole32(RAL_TX_NEWSEQ);
992 	desc->flags |= htole32(len << 16);
993 
994 	desc->wme = htole16(RAL_AIFSN(2) | RAL_LOGCWMIN(3) | RAL_LOGCWMAX(5));
995 	desc->wme |= htole16(RAL_IVOFFSET(sizeof (struct ieee80211_frame)));
996 
997 	/* setup PLCP fields */
998 	desc->plcp_signal  = ural_plcp_signal(rate);
999 	desc->plcp_service = 4;
1000 
1001 	len += IEEE80211_CRC_LEN;
1002 	if (ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM) {
1003 		desc->flags |= htole32(RAL_TX_OFDM);
1004 
1005 		plcp_length = len & 0xfff;
1006 		desc->plcp_length_hi = plcp_length >> 6;
1007 		desc->plcp_length_lo = plcp_length & 0x3f;
1008 	} else {
1009 		if (rate == 0)
1010 			rate = 2;	/* avoid division by zero */
1011 		plcp_length = howmany(16 * len, rate);
1012 		if (rate == 22) {
1013 			remainder = (16 * len) % 22;
1014 			if (remainder != 0 && remainder < 7)
1015 				desc->plcp_service |= RAL_PLCP_LENGEXT;
1016 		}
1017 		desc->plcp_length_hi = plcp_length >> 8;
1018 		desc->plcp_length_lo = plcp_length & 0xff;
1019 
1020 		if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1021 			desc->plcp_signal |= 0x08;
1022 	}
1023 
1024 	desc->iv = 0;
1025 	desc->eiv = 0;
1026 }
1027 
1028 #define RAL_TX_TIMEOUT	5000
1029 
1030 static int
1031 ural_tx_bcn(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1032 {
1033 	struct ieee80211vap *vap = ni->ni_vap;
1034 	struct ieee80211com *ic = ni->ni_ic;
1035 	const struct ieee80211_txparam *tp;
1036 	struct ural_tx_data *data;
1037 
1038 	if (sc->tx_nfree == 0) {
1039 		m_freem(m0);
1040 		ieee80211_free_node(ni);
1041 		return (EIO);
1042 	}
1043 	if (ic->ic_bsschan == IEEE80211_CHAN_ANYC) {
1044 		m_freem(m0);
1045 		ieee80211_free_node(ni);
1046 		return (ENXIO);
1047 	}
1048 	data = STAILQ_FIRST(&sc->tx_free);
1049 	STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1050 	sc->tx_nfree--;
1051 	tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_bsschan)];
1052 
1053 	data->m = m0;
1054 	data->ni = ni;
1055 	data->rate = tp->mgmtrate;
1056 
1057 	ural_setup_tx_desc(sc, &data->desc,
1058 	    RAL_TX_IFS_NEWBACKOFF | RAL_TX_TIMESTAMP, m0->m_pkthdr.len,
1059 	    tp->mgmtrate);
1060 
1061 	DPRINTFN(10, "sending beacon frame len=%u rate=%u\n",
1062 	    m0->m_pkthdr.len, tp->mgmtrate);
1063 
1064 	STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1065 	usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1066 
1067 	return (0);
1068 }
1069 
1070 static int
1071 ural_tx_mgt(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1072 {
1073 	struct ieee80211vap *vap = ni->ni_vap;
1074 	struct ieee80211com *ic = ni->ni_ic;
1075 	const struct ieee80211_txparam *tp;
1076 	struct ural_tx_data *data;
1077 	struct ieee80211_frame *wh;
1078 	struct ieee80211_key *k;
1079 	uint32_t flags;
1080 	uint16_t dur;
1081 
1082 	RAL_LOCK_ASSERT(sc, MA_OWNED);
1083 
1084 	data = STAILQ_FIRST(&sc->tx_free);
1085 	STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1086 	sc->tx_nfree--;
1087 
1088 	tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
1089 
1090 	wh = mtod(m0, struct ieee80211_frame *);
1091 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1092 		k = ieee80211_crypto_encap(ni, m0);
1093 		if (k == NULL) {
1094 			m_freem(m0);
1095 			return ENOBUFS;
1096 		}
1097 		wh = mtod(m0, struct ieee80211_frame *);
1098 	}
1099 
1100 	data->m = m0;
1101 	data->ni = ni;
1102 	data->rate = tp->mgmtrate;
1103 
1104 	flags = 0;
1105 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1106 		flags |= RAL_TX_ACK;
1107 
1108 		dur = ieee80211_ack_duration(ic->ic_rt, tp->mgmtrate,
1109 		    ic->ic_flags & IEEE80211_F_SHPREAMBLE);
1110 		USETW(wh->i_dur, dur);
1111 
1112 		/* tell hardware to add timestamp for probe responses */
1113 		if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
1114 		    IEEE80211_FC0_TYPE_MGT &&
1115 		    (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
1116 		    IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1117 			flags |= RAL_TX_TIMESTAMP;
1118 	}
1119 
1120 	ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, tp->mgmtrate);
1121 
1122 	DPRINTFN(10, "sending mgt frame len=%u rate=%u\n",
1123 	    m0->m_pkthdr.len, tp->mgmtrate);
1124 
1125 	STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1126 	usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1127 
1128 	return 0;
1129 }
1130 
1131 static int
1132 ural_sendprot(struct ural_softc *sc,
1133     const struct mbuf *m, struct ieee80211_node *ni, int prot, int rate)
1134 {
1135 	struct ieee80211com *ic = ni->ni_ic;
1136 	const struct ieee80211_frame *wh;
1137 	struct ural_tx_data *data;
1138 	struct mbuf *mprot;
1139 	int protrate, ackrate, pktlen, flags, isshort;
1140 	uint16_t dur;
1141 
1142 	KASSERT(prot == IEEE80211_PROT_RTSCTS || prot == IEEE80211_PROT_CTSONLY,
1143 	    ("protection %d", prot));
1144 
1145 	wh = mtod(m, const struct ieee80211_frame *);
1146 	pktlen = m->m_pkthdr.len + IEEE80211_CRC_LEN;
1147 
1148 	protrate = ieee80211_ctl_rate(ic->ic_rt, rate);
1149 	ackrate = ieee80211_ack_rate(ic->ic_rt, rate);
1150 
1151 	isshort = (ic->ic_flags & IEEE80211_F_SHPREAMBLE) != 0;
1152 	dur = ieee80211_compute_duration(ic->ic_rt, pktlen, rate, isshort)
1153 	    + ieee80211_ack_duration(ic->ic_rt, rate, isshort);
1154 	flags = RAL_TX_RETRY(7);
1155 	if (prot == IEEE80211_PROT_RTSCTS) {
1156 		/* NB: CTS is the same size as an ACK */
1157 		dur += ieee80211_ack_duration(ic->ic_rt, rate, isshort);
1158 		flags |= RAL_TX_ACK;
1159 		mprot = ieee80211_alloc_rts(ic, wh->i_addr1, wh->i_addr2, dur);
1160 	} else {
1161 		mprot = ieee80211_alloc_cts(ic, ni->ni_vap->iv_myaddr, dur);
1162 	}
1163 	if (mprot == NULL) {
1164 		/* XXX stat + msg */
1165 		return ENOBUFS;
1166 	}
1167 	data = STAILQ_FIRST(&sc->tx_free);
1168 	STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1169 	sc->tx_nfree--;
1170 
1171 	data->m = mprot;
1172 	data->ni = ieee80211_ref_node(ni);
1173 	data->rate = protrate;
1174 	ural_setup_tx_desc(sc, &data->desc, flags, mprot->m_pkthdr.len, protrate);
1175 
1176 	STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1177 	usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1178 
1179 	return 0;
1180 }
1181 
1182 static int
1183 ural_tx_raw(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni,
1184     const struct ieee80211_bpf_params *params)
1185 {
1186 	struct ieee80211com *ic = ni->ni_ic;
1187 	struct ural_tx_data *data;
1188 	uint32_t flags;
1189 	int error;
1190 	int rate;
1191 
1192 	RAL_LOCK_ASSERT(sc, MA_OWNED);
1193 	KASSERT(params != NULL, ("no raw xmit params"));
1194 
1195 	rate = params->ibp_rate0;
1196 	if (!ieee80211_isratevalid(ic->ic_rt, rate)) {
1197 		m_freem(m0);
1198 		return EINVAL;
1199 	}
1200 	flags = 0;
1201 	if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
1202 		flags |= RAL_TX_ACK;
1203 	if (params->ibp_flags & (IEEE80211_BPF_RTS|IEEE80211_BPF_CTS)) {
1204 		error = ural_sendprot(sc, m0, ni,
1205 		    params->ibp_flags & IEEE80211_BPF_RTS ?
1206 			 IEEE80211_PROT_RTSCTS : IEEE80211_PROT_CTSONLY,
1207 		    rate);
1208 		if (error || sc->tx_nfree == 0) {
1209 			m_freem(m0);
1210 			return ENOBUFS;
1211 		}
1212 		flags |= RAL_TX_IFS_SIFS;
1213 	}
1214 
1215 	data = STAILQ_FIRST(&sc->tx_free);
1216 	STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1217 	sc->tx_nfree--;
1218 
1219 	data->m = m0;
1220 	data->ni = ni;
1221 	data->rate = rate;
1222 
1223 	/* XXX need to setup descriptor ourself */
1224 	ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, rate);
1225 
1226 	DPRINTFN(10, "sending raw frame len=%u rate=%u\n",
1227 	    m0->m_pkthdr.len, rate);
1228 
1229 	STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1230 	usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1231 
1232 	return 0;
1233 }
1234 
1235 static int
1236 ural_tx_data(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1237 {
1238 	struct ieee80211vap *vap = ni->ni_vap;
1239 	struct ieee80211com *ic = ni->ni_ic;
1240 	struct ural_tx_data *data;
1241 	struct ieee80211_frame *wh;
1242 	const struct ieee80211_txparam *tp;
1243 	struct ieee80211_key *k;
1244 	uint32_t flags = 0;
1245 	uint16_t dur;
1246 	int error, rate;
1247 
1248 	RAL_LOCK_ASSERT(sc, MA_OWNED);
1249 
1250 	wh = mtod(m0, struct ieee80211_frame *);
1251 
1252 	tp = &vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)];
1253 	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
1254 		rate = tp->mcastrate;
1255 	else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
1256 		rate = tp->ucastrate;
1257 	else {
1258 		(void) ieee80211_ratectl_rate(ni, NULL, 0);
1259 		rate = ni->ni_txrate;
1260 	}
1261 
1262 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1263 		k = ieee80211_crypto_encap(ni, m0);
1264 		if (k == NULL) {
1265 			m_freem(m0);
1266 			return ENOBUFS;
1267 		}
1268 		/* packet header may have moved, reset our local pointer */
1269 		wh = mtod(m0, struct ieee80211_frame *);
1270 	}
1271 
1272 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1273 		int prot = IEEE80211_PROT_NONE;
1274 		if (m0->m_pkthdr.len + IEEE80211_CRC_LEN > vap->iv_rtsthreshold)
1275 			prot = IEEE80211_PROT_RTSCTS;
1276 		else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
1277 		    ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM)
1278 			prot = ic->ic_protmode;
1279 		if (prot != IEEE80211_PROT_NONE) {
1280 			error = ural_sendprot(sc, m0, ni, prot, rate);
1281 			if (error || sc->tx_nfree == 0) {
1282 				m_freem(m0);
1283 				return ENOBUFS;
1284 			}
1285 			flags |= RAL_TX_IFS_SIFS;
1286 		}
1287 	}
1288 
1289 	data = STAILQ_FIRST(&sc->tx_free);
1290 	STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1291 	sc->tx_nfree--;
1292 
1293 	data->m = m0;
1294 	data->ni = ni;
1295 	data->rate = rate;
1296 
1297 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1298 		flags |= RAL_TX_ACK;
1299 		flags |= RAL_TX_RETRY(7);
1300 
1301 		dur = ieee80211_ack_duration(ic->ic_rt, rate,
1302 		    ic->ic_flags & IEEE80211_F_SHPREAMBLE);
1303 		USETW(wh->i_dur, dur);
1304 	}
1305 
1306 	ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, rate);
1307 
1308 	DPRINTFN(10, "sending data frame len=%u rate=%u\n",
1309 	    m0->m_pkthdr.len, rate);
1310 
1311 	STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1312 	usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1313 
1314 	return 0;
1315 }
1316 
1317 static int
1318 ural_transmit(struct ieee80211com *ic, struct mbuf *m)
1319 {
1320 	struct ural_softc *sc = ic->ic_softc;
1321 	int error;
1322 
1323 	RAL_LOCK(sc);
1324 	if (!sc->sc_running) {
1325 		RAL_UNLOCK(sc);
1326 		return (ENXIO);
1327 	}
1328 	error = mbufq_enqueue(&sc->sc_snd, m);
1329 	if (error) {
1330 		RAL_UNLOCK(sc);
1331 		return (error);
1332 	}
1333 	ural_start(sc);
1334 	RAL_UNLOCK(sc);
1335 
1336 	return (0);
1337 }
1338 
1339 static void
1340 ural_start(struct ural_softc *sc)
1341 {
1342 	struct ieee80211_node *ni;
1343 	struct mbuf *m;
1344 
1345 	RAL_LOCK_ASSERT(sc, MA_OWNED);
1346 
1347 	if (sc->sc_running == 0)
1348 		return;
1349 
1350 	while (sc->tx_nfree >= RAL_TX_MINFREE &&
1351 	    (m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
1352 		ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1353 		if (ural_tx_data(sc, m, ni) != 0) {
1354 			if_inc_counter(ni->ni_vap->iv_ifp,
1355 			     IFCOUNTER_OERRORS, 1);
1356 			ieee80211_free_node(ni);
1357 			break;
1358 		}
1359 	}
1360 }
1361 
1362 static void
1363 ural_parent(struct ieee80211com *ic)
1364 {
1365 	struct ural_softc *sc = ic->ic_softc;
1366 	int startall = 0;
1367 
1368 	RAL_LOCK(sc);
1369 	if (sc->sc_detached) {
1370 		RAL_UNLOCK(sc);
1371 		return;
1372 	}
1373 	if (ic->ic_nrunning > 0) {
1374 		if (sc->sc_running == 0) {
1375 			ural_init(sc);
1376 			startall = 1;
1377 		} else
1378 			ural_setpromisc(sc);
1379 	} else if (sc->sc_running)
1380 		ural_stop(sc);
1381 	RAL_UNLOCK(sc);
1382 	if (startall)
1383 		ieee80211_start_all(ic);
1384 }
1385 
1386 static void
1387 ural_set_testmode(struct ural_softc *sc)
1388 {
1389 	struct usb_device_request req;
1390 	usb_error_t error;
1391 
1392 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1393 	req.bRequest = RAL_VENDOR_REQUEST;
1394 	USETW(req.wValue, 4);
1395 	USETW(req.wIndex, 1);
1396 	USETW(req.wLength, 0);
1397 
1398 	error = ural_do_request(sc, &req, NULL);
1399 	if (error != 0) {
1400 		device_printf(sc->sc_dev, "could not set test mode: %s\n",
1401 		    usbd_errstr(error));
1402 	}
1403 }
1404 
1405 static void
1406 ural_eeprom_read(struct ural_softc *sc, uint16_t addr, void *buf, int len)
1407 {
1408 	struct usb_device_request req;
1409 	usb_error_t error;
1410 
1411 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1412 	req.bRequest = RAL_READ_EEPROM;
1413 	USETW(req.wValue, 0);
1414 	USETW(req.wIndex, addr);
1415 	USETW(req.wLength, len);
1416 
1417 	error = ural_do_request(sc, &req, buf);
1418 	if (error != 0) {
1419 		device_printf(sc->sc_dev, "could not read EEPROM: %s\n",
1420 		    usbd_errstr(error));
1421 	}
1422 }
1423 
1424 static uint16_t
1425 ural_read(struct ural_softc *sc, uint16_t reg)
1426 {
1427 	struct usb_device_request req;
1428 	usb_error_t error;
1429 	uint16_t val;
1430 
1431 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1432 	req.bRequest = RAL_READ_MAC;
1433 	USETW(req.wValue, 0);
1434 	USETW(req.wIndex, reg);
1435 	USETW(req.wLength, sizeof (uint16_t));
1436 
1437 	error = ural_do_request(sc, &req, &val);
1438 	if (error != 0) {
1439 		device_printf(sc->sc_dev, "could not read MAC register: %s\n",
1440 		    usbd_errstr(error));
1441 		return 0;
1442 	}
1443 
1444 	return le16toh(val);
1445 }
1446 
1447 static void
1448 ural_read_multi(struct ural_softc *sc, uint16_t reg, void *buf, int len)
1449 {
1450 	struct usb_device_request req;
1451 	usb_error_t error;
1452 
1453 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1454 	req.bRequest = RAL_READ_MULTI_MAC;
1455 	USETW(req.wValue, 0);
1456 	USETW(req.wIndex, reg);
1457 	USETW(req.wLength, len);
1458 
1459 	error = ural_do_request(sc, &req, buf);
1460 	if (error != 0) {
1461 		device_printf(sc->sc_dev, "could not read MAC register: %s\n",
1462 		    usbd_errstr(error));
1463 	}
1464 }
1465 
1466 static void
1467 ural_write(struct ural_softc *sc, uint16_t reg, uint16_t val)
1468 {
1469 	struct usb_device_request req;
1470 	usb_error_t error;
1471 
1472 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1473 	req.bRequest = RAL_WRITE_MAC;
1474 	USETW(req.wValue, val);
1475 	USETW(req.wIndex, reg);
1476 	USETW(req.wLength, 0);
1477 
1478 	error = ural_do_request(sc, &req, NULL);
1479 	if (error != 0) {
1480 		device_printf(sc->sc_dev, "could not write MAC register: %s\n",
1481 		    usbd_errstr(error));
1482 	}
1483 }
1484 
1485 static void
1486 ural_write_multi(struct ural_softc *sc, uint16_t reg, void *buf, int len)
1487 {
1488 	struct usb_device_request req;
1489 	usb_error_t error;
1490 
1491 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1492 	req.bRequest = RAL_WRITE_MULTI_MAC;
1493 	USETW(req.wValue, 0);
1494 	USETW(req.wIndex, reg);
1495 	USETW(req.wLength, len);
1496 
1497 	error = ural_do_request(sc, &req, buf);
1498 	if (error != 0) {
1499 		device_printf(sc->sc_dev, "could not write MAC register: %s\n",
1500 		    usbd_errstr(error));
1501 	}
1502 }
1503 
1504 static void
1505 ural_bbp_write(struct ural_softc *sc, uint8_t reg, uint8_t val)
1506 {
1507 	uint16_t tmp;
1508 	int ntries;
1509 
1510 	for (ntries = 0; ntries < 100; ntries++) {
1511 		if (!(ural_read(sc, RAL_PHY_CSR8) & RAL_BBP_BUSY))
1512 			break;
1513 		if (ural_pause(sc, hz / 100))
1514 			break;
1515 	}
1516 	if (ntries == 100) {
1517 		device_printf(sc->sc_dev, "could not write to BBP\n");
1518 		return;
1519 	}
1520 
1521 	tmp = reg << 8 | val;
1522 	ural_write(sc, RAL_PHY_CSR7, tmp);
1523 }
1524 
1525 static uint8_t
1526 ural_bbp_read(struct ural_softc *sc, uint8_t reg)
1527 {
1528 	uint16_t val;
1529 	int ntries;
1530 
1531 	val = RAL_BBP_WRITE | reg << 8;
1532 	ural_write(sc, RAL_PHY_CSR7, val);
1533 
1534 	for (ntries = 0; ntries < 100; ntries++) {
1535 		if (!(ural_read(sc, RAL_PHY_CSR8) & RAL_BBP_BUSY))
1536 			break;
1537 		if (ural_pause(sc, hz / 100))
1538 			break;
1539 	}
1540 	if (ntries == 100) {
1541 		device_printf(sc->sc_dev, "could not read BBP\n");
1542 		return 0;
1543 	}
1544 
1545 	return ural_read(sc, RAL_PHY_CSR7) & 0xff;
1546 }
1547 
1548 static void
1549 ural_rf_write(struct ural_softc *sc, uint8_t reg, uint32_t val)
1550 {
1551 	uint32_t tmp;
1552 	int ntries;
1553 
1554 	for (ntries = 0; ntries < 100; ntries++) {
1555 		if (!(ural_read(sc, RAL_PHY_CSR10) & RAL_RF_LOBUSY))
1556 			break;
1557 		if (ural_pause(sc, hz / 100))
1558 			break;
1559 	}
1560 	if (ntries == 100) {
1561 		device_printf(sc->sc_dev, "could not write to RF\n");
1562 		return;
1563 	}
1564 
1565 	tmp = RAL_RF_BUSY | RAL_RF_20BIT | (val & 0xfffff) << 2 | (reg & 0x3);
1566 	ural_write(sc, RAL_PHY_CSR9,  tmp & 0xffff);
1567 	ural_write(sc, RAL_PHY_CSR10, tmp >> 16);
1568 
1569 	/* remember last written value in sc */
1570 	sc->rf_regs[reg] = val;
1571 
1572 	DPRINTFN(15, "RF R[%u] <- 0x%05x\n", reg & 0x3, val & 0xfffff);
1573 }
1574 
1575 static void
1576 ural_scan_start(struct ieee80211com *ic)
1577 {
1578 	struct ural_softc *sc = ic->ic_softc;
1579 
1580 	RAL_LOCK(sc);
1581 	ural_write(sc, RAL_TXRX_CSR19, 0);
1582 	ural_set_bssid(sc, ieee80211broadcastaddr);
1583 	RAL_UNLOCK(sc);
1584 }
1585 
1586 static void
1587 ural_scan_end(struct ieee80211com *ic)
1588 {
1589 	struct ural_softc *sc = ic->ic_softc;
1590 
1591 	RAL_LOCK(sc);
1592 	ural_enable_tsf_sync(sc);
1593 	ural_set_bssid(sc, sc->sc_bssid);
1594 	RAL_UNLOCK(sc);
1595 
1596 }
1597 
1598 static void
1599 ural_getradiocaps(struct ieee80211com *ic,
1600     int maxchans, int *nchans, struct ieee80211_channel chans[])
1601 {
1602 	struct ural_softc *sc = ic->ic_softc;
1603 	uint8_t bands[IEEE80211_MODE_BYTES];
1604 
1605 	memset(bands, 0, sizeof(bands));
1606 	setbit(bands, IEEE80211_MODE_11B);
1607 	setbit(bands, IEEE80211_MODE_11G);
1608 	ieee80211_add_channel_list_2ghz(chans, maxchans, nchans,
1609 	    ural_chan_2ghz, nitems(ural_chan_2ghz), bands, 0);
1610 
1611 	if (sc->rf_rev == RAL_RF_5222) {
1612 		setbit(bands, IEEE80211_MODE_11A);
1613 		ieee80211_add_channel_list_5ghz(chans, maxchans, nchans,
1614 		    ural_chan_5ghz, nitems(ural_chan_5ghz), bands, 0);
1615 	}
1616 }
1617 
1618 static void
1619 ural_set_channel(struct ieee80211com *ic)
1620 {
1621 	struct ural_softc *sc = ic->ic_softc;
1622 
1623 	RAL_LOCK(sc);
1624 	ural_set_chan(sc, ic->ic_curchan);
1625 	RAL_UNLOCK(sc);
1626 }
1627 
1628 static void
1629 ural_set_chan(struct ural_softc *sc, struct ieee80211_channel *c)
1630 {
1631 	struct ieee80211com *ic = &sc->sc_ic;
1632 	uint8_t power, tmp;
1633 	int i, chan;
1634 
1635 	chan = ieee80211_chan2ieee(ic, c);
1636 	if (chan == 0 || chan == IEEE80211_CHAN_ANY)
1637 		return;
1638 
1639 	if (IEEE80211_IS_CHAN_2GHZ(c))
1640 		power = min(sc->txpow[chan - 1], 31);
1641 	else
1642 		power = 31;
1643 
1644 	/* adjust txpower using ifconfig settings */
1645 	power -= (100 - ic->ic_txpowlimit) / 8;
1646 
1647 	DPRINTFN(2, "setting channel to %u, txpower to %u\n", chan, power);
1648 
1649 	switch (sc->rf_rev) {
1650 	case RAL_RF_2522:
1651 		ural_rf_write(sc, RAL_RF1, 0x00814);
1652 		ural_rf_write(sc, RAL_RF2, ural_rf2522_r2[chan - 1]);
1653 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1654 		break;
1655 
1656 	case RAL_RF_2523:
1657 		ural_rf_write(sc, RAL_RF1, 0x08804);
1658 		ural_rf_write(sc, RAL_RF2, ural_rf2523_r2[chan - 1]);
1659 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x38044);
1660 		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1661 		break;
1662 
1663 	case RAL_RF_2524:
1664 		ural_rf_write(sc, RAL_RF1, 0x0c808);
1665 		ural_rf_write(sc, RAL_RF2, ural_rf2524_r2[chan - 1]);
1666 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1667 		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1668 		break;
1669 
1670 	case RAL_RF_2525:
1671 		ural_rf_write(sc, RAL_RF1, 0x08808);
1672 		ural_rf_write(sc, RAL_RF2, ural_rf2525_hi_r2[chan - 1]);
1673 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1674 		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1675 
1676 		ural_rf_write(sc, RAL_RF1, 0x08808);
1677 		ural_rf_write(sc, RAL_RF2, ural_rf2525_r2[chan - 1]);
1678 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1679 		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1680 		break;
1681 
1682 	case RAL_RF_2525E:
1683 		ural_rf_write(sc, RAL_RF1, 0x08808);
1684 		ural_rf_write(sc, RAL_RF2, ural_rf2525e_r2[chan - 1]);
1685 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1686 		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00286 : 0x00282);
1687 		break;
1688 
1689 	case RAL_RF_2526:
1690 		ural_rf_write(sc, RAL_RF2, ural_rf2526_hi_r2[chan - 1]);
1691 		ural_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381);
1692 		ural_rf_write(sc, RAL_RF1, 0x08804);
1693 
1694 		ural_rf_write(sc, RAL_RF2, ural_rf2526_r2[chan - 1]);
1695 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1696 		ural_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381);
1697 		break;
1698 
1699 	/* dual-band RF */
1700 	case RAL_RF_5222:
1701 		for (i = 0; ural_rf5222[i].chan != chan; i++);
1702 
1703 		ural_rf_write(sc, RAL_RF1, ural_rf5222[i].r1);
1704 		ural_rf_write(sc, RAL_RF2, ural_rf5222[i].r2);
1705 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1706 		ural_rf_write(sc, RAL_RF4, ural_rf5222[i].r4);
1707 		break;
1708 	}
1709 
1710 	if (ic->ic_opmode != IEEE80211_M_MONITOR &&
1711 	    (ic->ic_flags & IEEE80211_F_SCAN) == 0) {
1712 		/* set Japan filter bit for channel 14 */
1713 		tmp = ural_bbp_read(sc, 70);
1714 
1715 		tmp &= ~RAL_JAPAN_FILTER;
1716 		if (chan == 14)
1717 			tmp |= RAL_JAPAN_FILTER;
1718 
1719 		ural_bbp_write(sc, 70, tmp);
1720 
1721 		/* clear CRC errors */
1722 		ural_read(sc, RAL_STA_CSR0);
1723 
1724 		ural_pause(sc, hz / 100);
1725 		ural_disable_rf_tune(sc);
1726 	}
1727 
1728 	/* XXX doesn't belong here */
1729 	/* update basic rate set */
1730 	ural_set_basicrates(sc, c);
1731 
1732 	/* give the hardware some time to do the switchover */
1733 	ural_pause(sc, hz / 100);
1734 }
1735 
1736 /*
1737  * Disable RF auto-tuning.
1738  */
1739 static void
1740 ural_disable_rf_tune(struct ural_softc *sc)
1741 {
1742 	uint32_t tmp;
1743 
1744 	if (sc->rf_rev != RAL_RF_2523) {
1745 		tmp = sc->rf_regs[RAL_RF1] & ~RAL_RF1_AUTOTUNE;
1746 		ural_rf_write(sc, RAL_RF1, tmp);
1747 	}
1748 
1749 	tmp = sc->rf_regs[RAL_RF3] & ~RAL_RF3_AUTOTUNE;
1750 	ural_rf_write(sc, RAL_RF3, tmp);
1751 
1752 	DPRINTFN(2, "disabling RF autotune\n");
1753 }
1754 
1755 /*
1756  * Refer to IEEE Std 802.11-1999 pp. 123 for more information on TSF
1757  * synchronization.
1758  */
1759 static void
1760 ural_enable_tsf_sync(struct ural_softc *sc)
1761 {
1762 	struct ieee80211com *ic = &sc->sc_ic;
1763 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1764 	uint16_t logcwmin, preload, tmp;
1765 
1766 	/* first, disable TSF synchronization */
1767 	ural_write(sc, RAL_TXRX_CSR19, 0);
1768 
1769 	tmp = (16 * vap->iv_bss->ni_intval) << 4;
1770 	ural_write(sc, RAL_TXRX_CSR18, tmp);
1771 
1772 	logcwmin = (ic->ic_opmode == IEEE80211_M_IBSS) ? 2 : 0;
1773 	preload = (ic->ic_opmode == IEEE80211_M_IBSS) ? 320 : 6;
1774 	tmp = logcwmin << 12 | preload;
1775 	ural_write(sc, RAL_TXRX_CSR20, tmp);
1776 
1777 	/* finally, enable TSF synchronization */
1778 	tmp = RAL_ENABLE_TSF | RAL_ENABLE_TBCN;
1779 	if (ic->ic_opmode == IEEE80211_M_STA)
1780 		tmp |= RAL_ENABLE_TSF_SYNC(1);
1781 	else
1782 		tmp |= RAL_ENABLE_TSF_SYNC(2) | RAL_ENABLE_BEACON_GENERATOR;
1783 	ural_write(sc, RAL_TXRX_CSR19, tmp);
1784 
1785 	DPRINTF("enabling TSF synchronization\n");
1786 }
1787 
1788 static void
1789 ural_enable_tsf(struct ural_softc *sc)
1790 {
1791 	/* first, disable TSF synchronization */
1792 	ural_write(sc, RAL_TXRX_CSR19, 0);
1793 	ural_write(sc, RAL_TXRX_CSR19, RAL_ENABLE_TSF | RAL_ENABLE_TSF_SYNC(2));
1794 }
1795 
1796 #define RAL_RXTX_TURNAROUND	5	/* us */
1797 static void
1798 ural_update_slot(struct ural_softc *sc)
1799 {
1800 	struct ieee80211com *ic = &sc->sc_ic;
1801 	uint16_t slottime, sifs, eifs;
1802 
1803 	slottime = IEEE80211_GET_SLOTTIME(ic);
1804 
1805 	/*
1806 	 * These settings may sound a bit inconsistent but this is what the
1807 	 * reference driver does.
1808 	 */
1809 	if (ic->ic_curmode == IEEE80211_MODE_11B) {
1810 		sifs = 16 - RAL_RXTX_TURNAROUND;
1811 		eifs = 364;
1812 	} else {
1813 		sifs = 10 - RAL_RXTX_TURNAROUND;
1814 		eifs = 64;
1815 	}
1816 
1817 	ural_write(sc, RAL_MAC_CSR10, slottime);
1818 	ural_write(sc, RAL_MAC_CSR11, sifs);
1819 	ural_write(sc, RAL_MAC_CSR12, eifs);
1820 }
1821 
1822 static void
1823 ural_set_txpreamble(struct ural_softc *sc)
1824 {
1825 	struct ieee80211com *ic = &sc->sc_ic;
1826 	uint16_t tmp;
1827 
1828 	tmp = ural_read(sc, RAL_TXRX_CSR10);
1829 
1830 	tmp &= ~RAL_SHORT_PREAMBLE;
1831 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
1832 		tmp |= RAL_SHORT_PREAMBLE;
1833 
1834 	ural_write(sc, RAL_TXRX_CSR10, tmp);
1835 }
1836 
1837 static void
1838 ural_set_basicrates(struct ural_softc *sc, const struct ieee80211_channel *c)
1839 {
1840 	/* XXX wrong, take from rate set */
1841 	/* update basic rate set */
1842 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
1843 		/* 11a basic rates: 6, 12, 24Mbps */
1844 		ural_write(sc, RAL_TXRX_CSR11, 0x150);
1845 	} else if (IEEE80211_IS_CHAN_ANYG(c)) {
1846 		/* 11g basic rates: 1, 2, 5.5, 11, 6, 12, 24Mbps */
1847 		ural_write(sc, RAL_TXRX_CSR11, 0x15f);
1848 	} else {
1849 		/* 11b basic rates: 1, 2Mbps */
1850 		ural_write(sc, RAL_TXRX_CSR11, 0x3);
1851 	}
1852 }
1853 
1854 static void
1855 ural_set_bssid(struct ural_softc *sc, const uint8_t *bssid)
1856 {
1857 	uint16_t tmp;
1858 
1859 	tmp = bssid[0] | bssid[1] << 8;
1860 	ural_write(sc, RAL_MAC_CSR5, tmp);
1861 
1862 	tmp = bssid[2] | bssid[3] << 8;
1863 	ural_write(sc, RAL_MAC_CSR6, tmp);
1864 
1865 	tmp = bssid[4] | bssid[5] << 8;
1866 	ural_write(sc, RAL_MAC_CSR7, tmp);
1867 
1868 	DPRINTF("setting BSSID to %6D\n", bssid, ":");
1869 }
1870 
1871 static void
1872 ural_set_macaddr(struct ural_softc *sc, const uint8_t *addr)
1873 {
1874 	uint16_t tmp;
1875 
1876 	tmp = addr[0] | addr[1] << 8;
1877 	ural_write(sc, RAL_MAC_CSR2, tmp);
1878 
1879 	tmp = addr[2] | addr[3] << 8;
1880 	ural_write(sc, RAL_MAC_CSR3, tmp);
1881 
1882 	tmp = addr[4] | addr[5] << 8;
1883 	ural_write(sc, RAL_MAC_CSR4, tmp);
1884 
1885 	DPRINTF("setting MAC address to %6D\n", addr, ":");
1886 }
1887 
1888 static void
1889 ural_setpromisc(struct ural_softc *sc)
1890 {
1891 	uint32_t tmp;
1892 
1893 	tmp = ural_read(sc, RAL_TXRX_CSR2);
1894 
1895 	tmp &= ~RAL_DROP_NOT_TO_ME;
1896 	if (sc->sc_ic.ic_promisc == 0)
1897 		tmp |= RAL_DROP_NOT_TO_ME;
1898 
1899 	ural_write(sc, RAL_TXRX_CSR2, tmp);
1900 
1901 	DPRINTF("%s promiscuous mode\n", sc->sc_ic.ic_promisc ?
1902 	    "entering" : "leaving");
1903 }
1904 
1905 static void
1906 ural_update_promisc(struct ieee80211com *ic)
1907 {
1908 	struct ural_softc *sc = ic->ic_softc;
1909 
1910 	RAL_LOCK(sc);
1911 	if (sc->sc_running)
1912 		ural_setpromisc(sc);
1913 	RAL_UNLOCK(sc);
1914 }
1915 
1916 static const char *
1917 ural_get_rf(int rev)
1918 {
1919 	switch (rev) {
1920 	case RAL_RF_2522:	return "RT2522";
1921 	case RAL_RF_2523:	return "RT2523";
1922 	case RAL_RF_2524:	return "RT2524";
1923 	case RAL_RF_2525:	return "RT2525";
1924 	case RAL_RF_2525E:	return "RT2525e";
1925 	case RAL_RF_2526:	return "RT2526";
1926 	case RAL_RF_5222:	return "RT5222";
1927 	default:		return "unknown";
1928 	}
1929 }
1930 
1931 static void
1932 ural_read_eeprom(struct ural_softc *sc)
1933 {
1934 	struct ieee80211com *ic = &sc->sc_ic;
1935 	uint16_t val;
1936 
1937 	ural_eeprom_read(sc, RAL_EEPROM_CONFIG0, &val, 2);
1938 	val = le16toh(val);
1939 	sc->rf_rev =   (val >> 11) & 0x7;
1940 	sc->hw_radio = (val >> 10) & 0x1;
1941 	sc->led_mode = (val >> 6)  & 0x7;
1942 	sc->rx_ant =   (val >> 4)  & 0x3;
1943 	sc->tx_ant =   (val >> 2)  & 0x3;
1944 	sc->nb_ant =   val & 0x3;
1945 
1946 	/* read MAC address */
1947 	ural_eeprom_read(sc, RAL_EEPROM_ADDRESS, ic->ic_macaddr, 6);
1948 
1949 	/* read default values for BBP registers */
1950 	ural_eeprom_read(sc, RAL_EEPROM_BBP_BASE, sc->bbp_prom, 2 * 16);
1951 
1952 	/* read Tx power for all b/g channels */
1953 	ural_eeprom_read(sc, RAL_EEPROM_TXPOWER, sc->txpow, 14);
1954 }
1955 
1956 static int
1957 ural_bbp_init(struct ural_softc *sc)
1958 {
1959 	int i, ntries;
1960 
1961 	/* wait for BBP to be ready */
1962 	for (ntries = 0; ntries < 100; ntries++) {
1963 		if (ural_bbp_read(sc, RAL_BBP_VERSION) != 0)
1964 			break;
1965 		if (ural_pause(sc, hz / 100))
1966 			break;
1967 	}
1968 	if (ntries == 100) {
1969 		device_printf(sc->sc_dev, "timeout waiting for BBP\n");
1970 		return EIO;
1971 	}
1972 
1973 	/* initialize BBP registers to default values */
1974 	for (i = 0; i < nitems(ural_def_bbp); i++)
1975 		ural_bbp_write(sc, ural_def_bbp[i].reg, ural_def_bbp[i].val);
1976 
1977 #if 0
1978 	/* initialize BBP registers to values stored in EEPROM */
1979 	for (i = 0; i < 16; i++) {
1980 		if (sc->bbp_prom[i].reg == 0xff)
1981 			continue;
1982 		ural_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
1983 	}
1984 #endif
1985 
1986 	return 0;
1987 }
1988 
1989 static void
1990 ural_set_txantenna(struct ural_softc *sc, int antenna)
1991 {
1992 	uint16_t tmp;
1993 	uint8_t tx;
1994 
1995 	tx = ural_bbp_read(sc, RAL_BBP_TX) & ~RAL_BBP_ANTMASK;
1996 	if (antenna == 1)
1997 		tx |= RAL_BBP_ANTA;
1998 	else if (antenna == 2)
1999 		tx |= RAL_BBP_ANTB;
2000 	else
2001 		tx |= RAL_BBP_DIVERSITY;
2002 
2003 	/* need to force I/Q flip for RF 2525e, 2526 and 5222 */
2004 	if (sc->rf_rev == RAL_RF_2525E || sc->rf_rev == RAL_RF_2526 ||
2005 	    sc->rf_rev == RAL_RF_5222)
2006 		tx |= RAL_BBP_FLIPIQ;
2007 
2008 	ural_bbp_write(sc, RAL_BBP_TX, tx);
2009 
2010 	/* update values in PHY_CSR5 and PHY_CSR6 */
2011 	tmp = ural_read(sc, RAL_PHY_CSR5) & ~0x7;
2012 	ural_write(sc, RAL_PHY_CSR5, tmp | (tx & 0x7));
2013 
2014 	tmp = ural_read(sc, RAL_PHY_CSR6) & ~0x7;
2015 	ural_write(sc, RAL_PHY_CSR6, tmp | (tx & 0x7));
2016 }
2017 
2018 static void
2019 ural_set_rxantenna(struct ural_softc *sc, int antenna)
2020 {
2021 	uint8_t rx;
2022 
2023 	rx = ural_bbp_read(sc, RAL_BBP_RX) & ~RAL_BBP_ANTMASK;
2024 	if (antenna == 1)
2025 		rx |= RAL_BBP_ANTA;
2026 	else if (antenna == 2)
2027 		rx |= RAL_BBP_ANTB;
2028 	else
2029 		rx |= RAL_BBP_DIVERSITY;
2030 
2031 	/* need to force no I/Q flip for RF 2525e and 2526 */
2032 	if (sc->rf_rev == RAL_RF_2525E || sc->rf_rev == RAL_RF_2526)
2033 		rx &= ~RAL_BBP_FLIPIQ;
2034 
2035 	ural_bbp_write(sc, RAL_BBP_RX, rx);
2036 }
2037 
2038 static void
2039 ural_init(struct ural_softc *sc)
2040 {
2041 	struct ieee80211com *ic = &sc->sc_ic;
2042 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2043 	uint16_t tmp;
2044 	int i, ntries;
2045 
2046 	RAL_LOCK_ASSERT(sc, MA_OWNED);
2047 
2048 	ural_set_testmode(sc);
2049 	ural_write(sc, 0x308, 0x00f0);	/* XXX magic */
2050 
2051 	ural_stop(sc);
2052 
2053 	/* initialize MAC registers to default values */
2054 	for (i = 0; i < nitems(ural_def_mac); i++)
2055 		ural_write(sc, ural_def_mac[i].reg, ural_def_mac[i].val);
2056 
2057 	/* wait for BBP and RF to wake up (this can take a long time!) */
2058 	for (ntries = 0; ntries < 100; ntries++) {
2059 		tmp = ural_read(sc, RAL_MAC_CSR17);
2060 		if ((tmp & (RAL_BBP_AWAKE | RAL_RF_AWAKE)) ==
2061 		    (RAL_BBP_AWAKE | RAL_RF_AWAKE))
2062 			break;
2063 		if (ural_pause(sc, hz / 100))
2064 			break;
2065 	}
2066 	if (ntries == 100) {
2067 		device_printf(sc->sc_dev,
2068 		    "timeout waiting for BBP/RF to wakeup\n");
2069 		goto fail;
2070 	}
2071 
2072 	/* we're ready! */
2073 	ural_write(sc, RAL_MAC_CSR1, RAL_HOST_READY);
2074 
2075 	/* set basic rate set (will be updated later) */
2076 	ural_write(sc, RAL_TXRX_CSR11, 0x15f);
2077 
2078 	if (ural_bbp_init(sc) != 0)
2079 		goto fail;
2080 
2081 	ural_set_chan(sc, ic->ic_curchan);
2082 
2083 	/* clear statistic registers (STA_CSR0 to STA_CSR10) */
2084 	ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof sc->sta);
2085 
2086 	ural_set_txantenna(sc, sc->tx_ant);
2087 	ural_set_rxantenna(sc, sc->rx_ant);
2088 
2089 	ural_set_macaddr(sc, vap ? vap->iv_myaddr : ic->ic_macaddr);
2090 
2091 	/*
2092 	 * Allocate Tx and Rx xfer queues.
2093 	 */
2094 	ural_setup_tx_list(sc);
2095 
2096 	/* kick Rx */
2097 	tmp = RAL_DROP_PHY | RAL_DROP_CRC;
2098 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2099 		tmp |= RAL_DROP_CTL | RAL_DROP_BAD_VERSION;
2100 		if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2101 			tmp |= RAL_DROP_TODS;
2102 		if (ic->ic_promisc == 0)
2103 			tmp |= RAL_DROP_NOT_TO_ME;
2104 	}
2105 	ural_write(sc, RAL_TXRX_CSR2, tmp);
2106 
2107 	sc->sc_running = 1;
2108 	usbd_xfer_set_stall(sc->sc_xfer[URAL_BULK_WR]);
2109 	usbd_transfer_start(sc->sc_xfer[URAL_BULK_RD]);
2110 	return;
2111 
2112 fail:	ural_stop(sc);
2113 }
2114 
2115 static void
2116 ural_stop(struct ural_softc *sc)
2117 {
2118 
2119 	RAL_LOCK_ASSERT(sc, MA_OWNED);
2120 
2121 	sc->sc_running = 0;
2122 
2123 	/*
2124 	 * Drain all the transfers, if not already drained:
2125 	 */
2126 	RAL_UNLOCK(sc);
2127 	usbd_transfer_drain(sc->sc_xfer[URAL_BULK_WR]);
2128 	usbd_transfer_drain(sc->sc_xfer[URAL_BULK_RD]);
2129 	RAL_LOCK(sc);
2130 
2131 	ural_unsetup_tx_list(sc);
2132 
2133 	/* disable Rx */
2134 	ural_write(sc, RAL_TXRX_CSR2, RAL_DISABLE_RX);
2135 	/* reset ASIC and BBP (but won't reset MAC registers!) */
2136 	ural_write(sc, RAL_MAC_CSR1, RAL_RESET_ASIC | RAL_RESET_BBP);
2137 	/* wait a little */
2138 	ural_pause(sc, hz / 10);
2139 	ural_write(sc, RAL_MAC_CSR1, 0);
2140 	/* wait a little */
2141 	ural_pause(sc, hz / 10);
2142 }
2143 
2144 static int
2145 ural_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
2146 	const struct ieee80211_bpf_params *params)
2147 {
2148 	struct ieee80211com *ic = ni->ni_ic;
2149 	struct ural_softc *sc = ic->ic_softc;
2150 
2151 	RAL_LOCK(sc);
2152 	/* prevent management frames from being sent if we're not ready */
2153 	if (!sc->sc_running) {
2154 		RAL_UNLOCK(sc);
2155 		m_freem(m);
2156 		return ENETDOWN;
2157 	}
2158 	if (sc->tx_nfree < RAL_TX_MINFREE) {
2159 		RAL_UNLOCK(sc);
2160 		m_freem(m);
2161 		return EIO;
2162 	}
2163 
2164 	if (params == NULL) {
2165 		/*
2166 		 * Legacy path; interpret frame contents to decide
2167 		 * precisely how to send the frame.
2168 		 */
2169 		if (ural_tx_mgt(sc, m, ni) != 0)
2170 			goto bad;
2171 	} else {
2172 		/*
2173 		 * Caller supplied explicit parameters to use in
2174 		 * sending the frame.
2175 		 */
2176 		if (ural_tx_raw(sc, m, ni, params) != 0)
2177 			goto bad;
2178 	}
2179 	RAL_UNLOCK(sc);
2180 	return 0;
2181 bad:
2182 	RAL_UNLOCK(sc);
2183 	return EIO;		/* XXX */
2184 }
2185 
2186 static void
2187 ural_ratectl_start(struct ural_softc *sc, struct ieee80211_node *ni)
2188 {
2189 	struct ieee80211vap *vap = ni->ni_vap;
2190 	struct ural_vap *uvp = URAL_VAP(vap);
2191 
2192 	/* clear statistic registers (STA_CSR0 to STA_CSR10) */
2193 	ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof sc->sta);
2194 
2195 	usb_callout_reset(&uvp->ratectl_ch, hz, ural_ratectl_timeout, uvp);
2196 }
2197 
2198 static void
2199 ural_ratectl_timeout(void *arg)
2200 {
2201 	struct ural_vap *uvp = arg;
2202 	struct ieee80211vap *vap = &uvp->vap;
2203 	struct ieee80211com *ic = vap->iv_ic;
2204 
2205 	ieee80211_runtask(ic, &uvp->ratectl_task);
2206 }
2207 
2208 static void
2209 ural_ratectl_task(void *arg, int pending)
2210 {
2211 	struct ural_vap *uvp = arg;
2212 	struct ieee80211vap *vap = &uvp->vap;
2213 	struct ural_softc *sc = vap->iv_ic->ic_softc;
2214 	struct ieee80211_ratectl_tx_stats *txs = &sc->sc_txs;
2215 	int fail;
2216 
2217 	RAL_LOCK(sc);
2218 	/* read and clear statistic registers (STA_CSR0 to STA_CSR10) */
2219 	ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof(sc->sta));
2220 
2221 	txs->flags = IEEE80211_RATECTL_TX_STATS_RETRIES;
2222 	txs->nsuccess = sc->sta[7] +	/* TX ok w/o retry */
2223 			sc->sta[8];	/* TX ok w/ retry */
2224 	fail = sc->sta[9];		/* TX retry-fail count */
2225 	txs->nframes = txs->nsuccess + fail;
2226 	/* XXX fail * maxretry */
2227 	txs->nretries = sc->sta[8] + fail;
2228 
2229 	ieee80211_ratectl_tx_update(vap, txs);
2230 
2231 	/* count TX retry-fail as Tx errors */
2232 	if_inc_counter(vap->iv_ifp, IFCOUNTER_OERRORS, fail);
2233 
2234 	usb_callout_reset(&uvp->ratectl_ch, hz, ural_ratectl_timeout, uvp);
2235 	RAL_UNLOCK(sc);
2236 }
2237 
2238 static int
2239 ural_pause(struct ural_softc *sc, int timeout)
2240 {
2241 
2242 	usb_pause_mtx(&sc->sc_mtx, timeout);
2243 	return (0);
2244 }
2245