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