xref: /freebsd/sys/dev/usb/wlan/if_ural.c (revision b0b1dbdd)
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 	const struct ieee80211_txparam *tp = ni->ni_txparms;
1074 	struct ieee80211com *ic = ni->ni_ic;
1075 	struct ural_tx_data *data;
1076 	struct ieee80211_frame *wh;
1077 	struct ieee80211_key *k;
1078 	uint32_t flags;
1079 	uint16_t dur;
1080 
1081 	RAL_LOCK_ASSERT(sc, MA_OWNED);
1082 
1083 	data = STAILQ_FIRST(&sc->tx_free);
1084 	STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1085 	sc->tx_nfree--;
1086 
1087 	wh = mtod(m0, struct ieee80211_frame *);
1088 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1089 		k = ieee80211_crypto_encap(ni, m0);
1090 		if (k == NULL) {
1091 			m_freem(m0);
1092 			return ENOBUFS;
1093 		}
1094 		wh = mtod(m0, struct ieee80211_frame *);
1095 	}
1096 
1097 	data->m = m0;
1098 	data->ni = ni;
1099 	data->rate = tp->mgmtrate;
1100 
1101 	flags = 0;
1102 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1103 		flags |= RAL_TX_ACK;
1104 
1105 		dur = ieee80211_ack_duration(ic->ic_rt, tp->mgmtrate,
1106 		    ic->ic_flags & IEEE80211_F_SHPREAMBLE);
1107 		USETW(wh->i_dur, dur);
1108 
1109 		/* tell hardware to add timestamp for probe responses */
1110 		if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
1111 		    IEEE80211_FC0_TYPE_MGT &&
1112 		    (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
1113 		    IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1114 			flags |= RAL_TX_TIMESTAMP;
1115 	}
1116 
1117 	ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, tp->mgmtrate);
1118 
1119 	DPRINTFN(10, "sending mgt frame len=%u rate=%u\n",
1120 	    m0->m_pkthdr.len, tp->mgmtrate);
1121 
1122 	STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1123 	usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1124 
1125 	return 0;
1126 }
1127 
1128 static int
1129 ural_sendprot(struct ural_softc *sc,
1130     const struct mbuf *m, struct ieee80211_node *ni, int prot, int rate)
1131 {
1132 	struct ieee80211com *ic = ni->ni_ic;
1133 	const struct ieee80211_frame *wh;
1134 	struct ural_tx_data *data;
1135 	struct mbuf *mprot;
1136 	int protrate, ackrate, pktlen, flags, isshort;
1137 	uint16_t dur;
1138 
1139 	KASSERT(prot == IEEE80211_PROT_RTSCTS || prot == IEEE80211_PROT_CTSONLY,
1140 	    ("protection %d", prot));
1141 
1142 	wh = mtod(m, const struct ieee80211_frame *);
1143 	pktlen = m->m_pkthdr.len + IEEE80211_CRC_LEN;
1144 
1145 	protrate = ieee80211_ctl_rate(ic->ic_rt, rate);
1146 	ackrate = ieee80211_ack_rate(ic->ic_rt, rate);
1147 
1148 	isshort = (ic->ic_flags & IEEE80211_F_SHPREAMBLE) != 0;
1149 	dur = ieee80211_compute_duration(ic->ic_rt, pktlen, rate, isshort)
1150 	    + ieee80211_ack_duration(ic->ic_rt, rate, isshort);
1151 	flags = RAL_TX_RETRY(7);
1152 	if (prot == IEEE80211_PROT_RTSCTS) {
1153 		/* NB: CTS is the same size as an ACK */
1154 		dur += ieee80211_ack_duration(ic->ic_rt, rate, isshort);
1155 		flags |= RAL_TX_ACK;
1156 		mprot = ieee80211_alloc_rts(ic, wh->i_addr1, wh->i_addr2, dur);
1157 	} else {
1158 		mprot = ieee80211_alloc_cts(ic, ni->ni_vap->iv_myaddr, dur);
1159 	}
1160 	if (mprot == NULL) {
1161 		/* XXX stat + msg */
1162 		return ENOBUFS;
1163 	}
1164 	data = STAILQ_FIRST(&sc->tx_free);
1165 	STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1166 	sc->tx_nfree--;
1167 
1168 	data->m = mprot;
1169 	data->ni = ieee80211_ref_node(ni);
1170 	data->rate = protrate;
1171 	ural_setup_tx_desc(sc, &data->desc, flags, mprot->m_pkthdr.len, protrate);
1172 
1173 	STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1174 	usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1175 
1176 	return 0;
1177 }
1178 
1179 static int
1180 ural_tx_raw(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni,
1181     const struct ieee80211_bpf_params *params)
1182 {
1183 	struct ieee80211com *ic = ni->ni_ic;
1184 	struct ural_tx_data *data;
1185 	uint32_t flags;
1186 	int error;
1187 	int rate;
1188 
1189 	RAL_LOCK_ASSERT(sc, MA_OWNED);
1190 	KASSERT(params != NULL, ("no raw xmit params"));
1191 
1192 	rate = params->ibp_rate0;
1193 	if (!ieee80211_isratevalid(ic->ic_rt, rate)) {
1194 		m_freem(m0);
1195 		return EINVAL;
1196 	}
1197 	flags = 0;
1198 	if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
1199 		flags |= RAL_TX_ACK;
1200 	if (params->ibp_flags & (IEEE80211_BPF_RTS|IEEE80211_BPF_CTS)) {
1201 		error = ural_sendprot(sc, m0, ni,
1202 		    params->ibp_flags & IEEE80211_BPF_RTS ?
1203 			 IEEE80211_PROT_RTSCTS : IEEE80211_PROT_CTSONLY,
1204 		    rate);
1205 		if (error || sc->tx_nfree == 0) {
1206 			m_freem(m0);
1207 			return ENOBUFS;
1208 		}
1209 		flags |= RAL_TX_IFS_SIFS;
1210 	}
1211 
1212 	data = STAILQ_FIRST(&sc->tx_free);
1213 	STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1214 	sc->tx_nfree--;
1215 
1216 	data->m = m0;
1217 	data->ni = ni;
1218 	data->rate = rate;
1219 
1220 	/* XXX need to setup descriptor ourself */
1221 	ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, rate);
1222 
1223 	DPRINTFN(10, "sending raw frame len=%u rate=%u\n",
1224 	    m0->m_pkthdr.len, rate);
1225 
1226 	STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1227 	usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1228 
1229 	return 0;
1230 }
1231 
1232 static int
1233 ural_tx_data(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1234 {
1235 	struct ieee80211vap *vap = ni->ni_vap;
1236 	struct ieee80211com *ic = ni->ni_ic;
1237 	struct ural_tx_data *data;
1238 	struct ieee80211_frame *wh;
1239 	const struct ieee80211_txparam *tp = ni->ni_txparms;
1240 	struct ieee80211_key *k;
1241 	uint32_t flags = 0;
1242 	uint16_t dur;
1243 	int error, rate;
1244 
1245 	RAL_LOCK_ASSERT(sc, MA_OWNED);
1246 
1247 	wh = mtod(m0, struct ieee80211_frame *);
1248 
1249 	if (m0->m_flags & M_EAPOL)
1250 		rate = tp->mgmtrate;
1251 	else if (IEEE80211_IS_MULTICAST(wh->i_addr1))
1252 		rate = tp->mcastrate;
1253 	else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
1254 		rate = tp->ucastrate;
1255 	else {
1256 		(void) ieee80211_ratectl_rate(ni, NULL, 0);
1257 		rate = ni->ni_txrate;
1258 	}
1259 
1260 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1261 		k = ieee80211_crypto_encap(ni, m0);
1262 		if (k == NULL) {
1263 			m_freem(m0);
1264 			return ENOBUFS;
1265 		}
1266 		/* packet header may have moved, reset our local pointer */
1267 		wh = mtod(m0, struct ieee80211_frame *);
1268 	}
1269 
1270 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1271 		int prot = IEEE80211_PROT_NONE;
1272 		if (m0->m_pkthdr.len + IEEE80211_CRC_LEN > vap->iv_rtsthreshold)
1273 			prot = IEEE80211_PROT_RTSCTS;
1274 		else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
1275 		    ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM)
1276 			prot = ic->ic_protmode;
1277 		if (prot != IEEE80211_PROT_NONE) {
1278 			error = ural_sendprot(sc, m0, ni, prot, rate);
1279 			if (error || sc->tx_nfree == 0) {
1280 				m_freem(m0);
1281 				return ENOBUFS;
1282 			}
1283 			flags |= RAL_TX_IFS_SIFS;
1284 		}
1285 	}
1286 
1287 	data = STAILQ_FIRST(&sc->tx_free);
1288 	STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1289 	sc->tx_nfree--;
1290 
1291 	data->m = m0;
1292 	data->ni = ni;
1293 	data->rate = rate;
1294 
1295 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1296 		flags |= RAL_TX_ACK;
1297 		flags |= RAL_TX_RETRY(7);
1298 
1299 		dur = ieee80211_ack_duration(ic->ic_rt, rate,
1300 		    ic->ic_flags & IEEE80211_F_SHPREAMBLE);
1301 		USETW(wh->i_dur, dur);
1302 	}
1303 
1304 	ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, rate);
1305 
1306 	DPRINTFN(10, "sending data frame len=%u rate=%u\n",
1307 	    m0->m_pkthdr.len, rate);
1308 
1309 	STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1310 	usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1311 
1312 	return 0;
1313 }
1314 
1315 static int
1316 ural_transmit(struct ieee80211com *ic, struct mbuf *m)
1317 {
1318 	struct ural_softc *sc = ic->ic_softc;
1319 	int error;
1320 
1321 	RAL_LOCK(sc);
1322 	if (!sc->sc_running) {
1323 		RAL_UNLOCK(sc);
1324 		return (ENXIO);
1325 	}
1326 	error = mbufq_enqueue(&sc->sc_snd, m);
1327 	if (error) {
1328 		RAL_UNLOCK(sc);
1329 		return (error);
1330 	}
1331 	ural_start(sc);
1332 	RAL_UNLOCK(sc);
1333 
1334 	return (0);
1335 }
1336 
1337 static void
1338 ural_start(struct ural_softc *sc)
1339 {
1340 	struct ieee80211_node *ni;
1341 	struct mbuf *m;
1342 
1343 	RAL_LOCK_ASSERT(sc, MA_OWNED);
1344 
1345 	if (sc->sc_running == 0)
1346 		return;
1347 
1348 	while (sc->tx_nfree >= RAL_TX_MINFREE &&
1349 	    (m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
1350 		ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1351 		if (ural_tx_data(sc, m, ni) != 0) {
1352 			if_inc_counter(ni->ni_vap->iv_ifp,
1353 			     IFCOUNTER_OERRORS, 1);
1354 			ieee80211_free_node(ni);
1355 			break;
1356 		}
1357 	}
1358 }
1359 
1360 static void
1361 ural_parent(struct ieee80211com *ic)
1362 {
1363 	struct ural_softc *sc = ic->ic_softc;
1364 	int startall = 0;
1365 
1366 	RAL_LOCK(sc);
1367 	if (sc->sc_detached) {
1368 		RAL_UNLOCK(sc);
1369 		return;
1370 	}
1371 	if (ic->ic_nrunning > 0) {
1372 		if (sc->sc_running == 0) {
1373 			ural_init(sc);
1374 			startall = 1;
1375 		} else
1376 			ural_setpromisc(sc);
1377 	} else if (sc->sc_running)
1378 		ural_stop(sc);
1379 	RAL_UNLOCK(sc);
1380 	if (startall)
1381 		ieee80211_start_all(ic);
1382 }
1383 
1384 static void
1385 ural_set_testmode(struct ural_softc *sc)
1386 {
1387 	struct usb_device_request req;
1388 	usb_error_t error;
1389 
1390 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1391 	req.bRequest = RAL_VENDOR_REQUEST;
1392 	USETW(req.wValue, 4);
1393 	USETW(req.wIndex, 1);
1394 	USETW(req.wLength, 0);
1395 
1396 	error = ural_do_request(sc, &req, NULL);
1397 	if (error != 0) {
1398 		device_printf(sc->sc_dev, "could not set test mode: %s\n",
1399 		    usbd_errstr(error));
1400 	}
1401 }
1402 
1403 static void
1404 ural_eeprom_read(struct ural_softc *sc, uint16_t addr, void *buf, int len)
1405 {
1406 	struct usb_device_request req;
1407 	usb_error_t error;
1408 
1409 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1410 	req.bRequest = RAL_READ_EEPROM;
1411 	USETW(req.wValue, 0);
1412 	USETW(req.wIndex, addr);
1413 	USETW(req.wLength, len);
1414 
1415 	error = ural_do_request(sc, &req, buf);
1416 	if (error != 0) {
1417 		device_printf(sc->sc_dev, "could not read EEPROM: %s\n",
1418 		    usbd_errstr(error));
1419 	}
1420 }
1421 
1422 static uint16_t
1423 ural_read(struct ural_softc *sc, uint16_t reg)
1424 {
1425 	struct usb_device_request req;
1426 	usb_error_t error;
1427 	uint16_t val;
1428 
1429 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1430 	req.bRequest = RAL_READ_MAC;
1431 	USETW(req.wValue, 0);
1432 	USETW(req.wIndex, reg);
1433 	USETW(req.wLength, sizeof (uint16_t));
1434 
1435 	error = ural_do_request(sc, &req, &val);
1436 	if (error != 0) {
1437 		device_printf(sc->sc_dev, "could not read MAC register: %s\n",
1438 		    usbd_errstr(error));
1439 		return 0;
1440 	}
1441 
1442 	return le16toh(val);
1443 }
1444 
1445 static void
1446 ural_read_multi(struct ural_softc *sc, uint16_t reg, void *buf, int len)
1447 {
1448 	struct usb_device_request req;
1449 	usb_error_t error;
1450 
1451 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1452 	req.bRequest = RAL_READ_MULTI_MAC;
1453 	USETW(req.wValue, 0);
1454 	USETW(req.wIndex, reg);
1455 	USETW(req.wLength, len);
1456 
1457 	error = ural_do_request(sc, &req, buf);
1458 	if (error != 0) {
1459 		device_printf(sc->sc_dev, "could not read MAC register: %s\n",
1460 		    usbd_errstr(error));
1461 	}
1462 }
1463 
1464 static void
1465 ural_write(struct ural_softc *sc, uint16_t reg, uint16_t val)
1466 {
1467 	struct usb_device_request req;
1468 	usb_error_t error;
1469 
1470 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1471 	req.bRequest = RAL_WRITE_MAC;
1472 	USETW(req.wValue, val);
1473 	USETW(req.wIndex, reg);
1474 	USETW(req.wLength, 0);
1475 
1476 	error = ural_do_request(sc, &req, NULL);
1477 	if (error != 0) {
1478 		device_printf(sc->sc_dev, "could not write MAC register: %s\n",
1479 		    usbd_errstr(error));
1480 	}
1481 }
1482 
1483 static void
1484 ural_write_multi(struct ural_softc *sc, uint16_t reg, void *buf, int len)
1485 {
1486 	struct usb_device_request req;
1487 	usb_error_t error;
1488 
1489 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1490 	req.bRequest = RAL_WRITE_MULTI_MAC;
1491 	USETW(req.wValue, 0);
1492 	USETW(req.wIndex, reg);
1493 	USETW(req.wLength, len);
1494 
1495 	error = ural_do_request(sc, &req, buf);
1496 	if (error != 0) {
1497 		device_printf(sc->sc_dev, "could not write MAC register: %s\n",
1498 		    usbd_errstr(error));
1499 	}
1500 }
1501 
1502 static void
1503 ural_bbp_write(struct ural_softc *sc, uint8_t reg, uint8_t val)
1504 {
1505 	uint16_t tmp;
1506 	int ntries;
1507 
1508 	for (ntries = 0; ntries < 100; ntries++) {
1509 		if (!(ural_read(sc, RAL_PHY_CSR8) & RAL_BBP_BUSY))
1510 			break;
1511 		if (ural_pause(sc, hz / 100))
1512 			break;
1513 	}
1514 	if (ntries == 100) {
1515 		device_printf(sc->sc_dev, "could not write to BBP\n");
1516 		return;
1517 	}
1518 
1519 	tmp = reg << 8 | val;
1520 	ural_write(sc, RAL_PHY_CSR7, tmp);
1521 }
1522 
1523 static uint8_t
1524 ural_bbp_read(struct ural_softc *sc, uint8_t reg)
1525 {
1526 	uint16_t val;
1527 	int ntries;
1528 
1529 	val = RAL_BBP_WRITE | reg << 8;
1530 	ural_write(sc, RAL_PHY_CSR7, val);
1531 
1532 	for (ntries = 0; ntries < 100; ntries++) {
1533 		if (!(ural_read(sc, RAL_PHY_CSR8) & RAL_BBP_BUSY))
1534 			break;
1535 		if (ural_pause(sc, hz / 100))
1536 			break;
1537 	}
1538 	if (ntries == 100) {
1539 		device_printf(sc->sc_dev, "could not read BBP\n");
1540 		return 0;
1541 	}
1542 
1543 	return ural_read(sc, RAL_PHY_CSR7) & 0xff;
1544 }
1545 
1546 static void
1547 ural_rf_write(struct ural_softc *sc, uint8_t reg, uint32_t val)
1548 {
1549 	uint32_t tmp;
1550 	int ntries;
1551 
1552 	for (ntries = 0; ntries < 100; ntries++) {
1553 		if (!(ural_read(sc, RAL_PHY_CSR10) & RAL_RF_LOBUSY))
1554 			break;
1555 		if (ural_pause(sc, hz / 100))
1556 			break;
1557 	}
1558 	if (ntries == 100) {
1559 		device_printf(sc->sc_dev, "could not write to RF\n");
1560 		return;
1561 	}
1562 
1563 	tmp = RAL_RF_BUSY | RAL_RF_20BIT | (val & 0xfffff) << 2 | (reg & 0x3);
1564 	ural_write(sc, RAL_PHY_CSR9,  tmp & 0xffff);
1565 	ural_write(sc, RAL_PHY_CSR10, tmp >> 16);
1566 
1567 	/* remember last written value in sc */
1568 	sc->rf_regs[reg] = val;
1569 
1570 	DPRINTFN(15, "RF R[%u] <- 0x%05x\n", reg & 0x3, val & 0xfffff);
1571 }
1572 
1573 static void
1574 ural_scan_start(struct ieee80211com *ic)
1575 {
1576 	struct ural_softc *sc = ic->ic_softc;
1577 
1578 	RAL_LOCK(sc);
1579 	ural_write(sc, RAL_TXRX_CSR19, 0);
1580 	ural_set_bssid(sc, ieee80211broadcastaddr);
1581 	RAL_UNLOCK(sc);
1582 }
1583 
1584 static void
1585 ural_scan_end(struct ieee80211com *ic)
1586 {
1587 	struct ural_softc *sc = ic->ic_softc;
1588 
1589 	RAL_LOCK(sc);
1590 	ural_enable_tsf_sync(sc);
1591 	ural_set_bssid(sc, sc->sc_bssid);
1592 	RAL_UNLOCK(sc);
1593 
1594 }
1595 
1596 static void
1597 ural_getradiocaps(struct ieee80211com *ic,
1598     int maxchans, int *nchans, struct ieee80211_channel chans[])
1599 {
1600 	struct ural_softc *sc = ic->ic_softc;
1601 	uint8_t bands[IEEE80211_MODE_BYTES];
1602 
1603 	memset(bands, 0, sizeof(bands));
1604 	setbit(bands, IEEE80211_MODE_11B);
1605 	setbit(bands, IEEE80211_MODE_11G);
1606 	ieee80211_add_channel_list_2ghz(chans, maxchans, nchans,
1607 	    ural_chan_2ghz, nitems(ural_chan_2ghz), bands, 0);
1608 
1609 	if (sc->rf_rev == RAL_RF_5222) {
1610 		setbit(bands, IEEE80211_MODE_11A);
1611 		ieee80211_add_channel_list_5ghz(chans, maxchans, nchans,
1612 		    ural_chan_5ghz, nitems(ural_chan_5ghz), bands, 0);
1613 	}
1614 }
1615 
1616 static void
1617 ural_set_channel(struct ieee80211com *ic)
1618 {
1619 	struct ural_softc *sc = ic->ic_softc;
1620 
1621 	RAL_LOCK(sc);
1622 	ural_set_chan(sc, ic->ic_curchan);
1623 	RAL_UNLOCK(sc);
1624 }
1625 
1626 static void
1627 ural_set_chan(struct ural_softc *sc, struct ieee80211_channel *c)
1628 {
1629 	struct ieee80211com *ic = &sc->sc_ic;
1630 	uint8_t power, tmp;
1631 	int i, chan;
1632 
1633 	chan = ieee80211_chan2ieee(ic, c);
1634 	if (chan == 0 || chan == IEEE80211_CHAN_ANY)
1635 		return;
1636 
1637 	if (IEEE80211_IS_CHAN_2GHZ(c))
1638 		power = min(sc->txpow[chan - 1], 31);
1639 	else
1640 		power = 31;
1641 
1642 	/* adjust txpower using ifconfig settings */
1643 	power -= (100 - ic->ic_txpowlimit) / 8;
1644 
1645 	DPRINTFN(2, "setting channel to %u, txpower to %u\n", chan, power);
1646 
1647 	switch (sc->rf_rev) {
1648 	case RAL_RF_2522:
1649 		ural_rf_write(sc, RAL_RF1, 0x00814);
1650 		ural_rf_write(sc, RAL_RF2, ural_rf2522_r2[chan - 1]);
1651 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1652 		break;
1653 
1654 	case RAL_RF_2523:
1655 		ural_rf_write(sc, RAL_RF1, 0x08804);
1656 		ural_rf_write(sc, RAL_RF2, ural_rf2523_r2[chan - 1]);
1657 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x38044);
1658 		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1659 		break;
1660 
1661 	case RAL_RF_2524:
1662 		ural_rf_write(sc, RAL_RF1, 0x0c808);
1663 		ural_rf_write(sc, RAL_RF2, ural_rf2524_r2[chan - 1]);
1664 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1665 		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1666 		break;
1667 
1668 	case RAL_RF_2525:
1669 		ural_rf_write(sc, RAL_RF1, 0x08808);
1670 		ural_rf_write(sc, RAL_RF2, ural_rf2525_hi_r2[chan - 1]);
1671 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1672 		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1673 
1674 		ural_rf_write(sc, RAL_RF1, 0x08808);
1675 		ural_rf_write(sc, RAL_RF2, ural_rf2525_r2[chan - 1]);
1676 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1677 		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1678 		break;
1679 
1680 	case RAL_RF_2525E:
1681 		ural_rf_write(sc, RAL_RF1, 0x08808);
1682 		ural_rf_write(sc, RAL_RF2, ural_rf2525e_r2[chan - 1]);
1683 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1684 		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00286 : 0x00282);
1685 		break;
1686 
1687 	case RAL_RF_2526:
1688 		ural_rf_write(sc, RAL_RF2, ural_rf2526_hi_r2[chan - 1]);
1689 		ural_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381);
1690 		ural_rf_write(sc, RAL_RF1, 0x08804);
1691 
1692 		ural_rf_write(sc, RAL_RF2, ural_rf2526_r2[chan - 1]);
1693 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1694 		ural_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381);
1695 		break;
1696 
1697 	/* dual-band RF */
1698 	case RAL_RF_5222:
1699 		for (i = 0; ural_rf5222[i].chan != chan; i++);
1700 
1701 		ural_rf_write(sc, RAL_RF1, ural_rf5222[i].r1);
1702 		ural_rf_write(sc, RAL_RF2, ural_rf5222[i].r2);
1703 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1704 		ural_rf_write(sc, RAL_RF4, ural_rf5222[i].r4);
1705 		break;
1706 	}
1707 
1708 	if (ic->ic_opmode != IEEE80211_M_MONITOR &&
1709 	    (ic->ic_flags & IEEE80211_F_SCAN) == 0) {
1710 		/* set Japan filter bit for channel 14 */
1711 		tmp = ural_bbp_read(sc, 70);
1712 
1713 		tmp &= ~RAL_JAPAN_FILTER;
1714 		if (chan == 14)
1715 			tmp |= RAL_JAPAN_FILTER;
1716 
1717 		ural_bbp_write(sc, 70, tmp);
1718 
1719 		/* clear CRC errors */
1720 		ural_read(sc, RAL_STA_CSR0);
1721 
1722 		ural_pause(sc, hz / 100);
1723 		ural_disable_rf_tune(sc);
1724 	}
1725 
1726 	/* XXX doesn't belong here */
1727 	/* update basic rate set */
1728 	ural_set_basicrates(sc, c);
1729 
1730 	/* give the hardware some time to do the switchover */
1731 	ural_pause(sc, hz / 100);
1732 }
1733 
1734 /*
1735  * Disable RF auto-tuning.
1736  */
1737 static void
1738 ural_disable_rf_tune(struct ural_softc *sc)
1739 {
1740 	uint32_t tmp;
1741 
1742 	if (sc->rf_rev != RAL_RF_2523) {
1743 		tmp = sc->rf_regs[RAL_RF1] & ~RAL_RF1_AUTOTUNE;
1744 		ural_rf_write(sc, RAL_RF1, tmp);
1745 	}
1746 
1747 	tmp = sc->rf_regs[RAL_RF3] & ~RAL_RF3_AUTOTUNE;
1748 	ural_rf_write(sc, RAL_RF3, tmp);
1749 
1750 	DPRINTFN(2, "disabling RF autotune\n");
1751 }
1752 
1753 /*
1754  * Refer to IEEE Std 802.11-1999 pp. 123 for more information on TSF
1755  * synchronization.
1756  */
1757 static void
1758 ural_enable_tsf_sync(struct ural_softc *sc)
1759 {
1760 	struct ieee80211com *ic = &sc->sc_ic;
1761 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1762 	uint16_t logcwmin, preload, tmp;
1763 
1764 	/* first, disable TSF synchronization */
1765 	ural_write(sc, RAL_TXRX_CSR19, 0);
1766 
1767 	tmp = (16 * vap->iv_bss->ni_intval) << 4;
1768 	ural_write(sc, RAL_TXRX_CSR18, tmp);
1769 
1770 	logcwmin = (ic->ic_opmode == IEEE80211_M_IBSS) ? 2 : 0;
1771 	preload = (ic->ic_opmode == IEEE80211_M_IBSS) ? 320 : 6;
1772 	tmp = logcwmin << 12 | preload;
1773 	ural_write(sc, RAL_TXRX_CSR20, tmp);
1774 
1775 	/* finally, enable TSF synchronization */
1776 	tmp = RAL_ENABLE_TSF | RAL_ENABLE_TBCN;
1777 	if (ic->ic_opmode == IEEE80211_M_STA)
1778 		tmp |= RAL_ENABLE_TSF_SYNC(1);
1779 	else
1780 		tmp |= RAL_ENABLE_TSF_SYNC(2) | RAL_ENABLE_BEACON_GENERATOR;
1781 	ural_write(sc, RAL_TXRX_CSR19, tmp);
1782 
1783 	DPRINTF("enabling TSF synchronization\n");
1784 }
1785 
1786 static void
1787 ural_enable_tsf(struct ural_softc *sc)
1788 {
1789 	/* first, disable TSF synchronization */
1790 	ural_write(sc, RAL_TXRX_CSR19, 0);
1791 	ural_write(sc, RAL_TXRX_CSR19, RAL_ENABLE_TSF | RAL_ENABLE_TSF_SYNC(2));
1792 }
1793 
1794 #define RAL_RXTX_TURNAROUND	5	/* us */
1795 static void
1796 ural_update_slot(struct ural_softc *sc)
1797 {
1798 	struct ieee80211com *ic = &sc->sc_ic;
1799 	uint16_t slottime, sifs, eifs;
1800 
1801 	slottime = IEEE80211_GET_SLOTTIME(ic);
1802 
1803 	/*
1804 	 * These settings may sound a bit inconsistent but this is what the
1805 	 * reference driver does.
1806 	 */
1807 	if (ic->ic_curmode == IEEE80211_MODE_11B) {
1808 		sifs = 16 - RAL_RXTX_TURNAROUND;
1809 		eifs = 364;
1810 	} else {
1811 		sifs = 10 - RAL_RXTX_TURNAROUND;
1812 		eifs = 64;
1813 	}
1814 
1815 	ural_write(sc, RAL_MAC_CSR10, slottime);
1816 	ural_write(sc, RAL_MAC_CSR11, sifs);
1817 	ural_write(sc, RAL_MAC_CSR12, eifs);
1818 }
1819 
1820 static void
1821 ural_set_txpreamble(struct ural_softc *sc)
1822 {
1823 	struct ieee80211com *ic = &sc->sc_ic;
1824 	uint16_t tmp;
1825 
1826 	tmp = ural_read(sc, RAL_TXRX_CSR10);
1827 
1828 	tmp &= ~RAL_SHORT_PREAMBLE;
1829 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
1830 		tmp |= RAL_SHORT_PREAMBLE;
1831 
1832 	ural_write(sc, RAL_TXRX_CSR10, tmp);
1833 }
1834 
1835 static void
1836 ural_set_basicrates(struct ural_softc *sc, const struct ieee80211_channel *c)
1837 {
1838 	/* XXX wrong, take from rate set */
1839 	/* update basic rate set */
1840 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
1841 		/* 11a basic rates: 6, 12, 24Mbps */
1842 		ural_write(sc, RAL_TXRX_CSR11, 0x150);
1843 	} else if (IEEE80211_IS_CHAN_ANYG(c)) {
1844 		/* 11g basic rates: 1, 2, 5.5, 11, 6, 12, 24Mbps */
1845 		ural_write(sc, RAL_TXRX_CSR11, 0x15f);
1846 	} else {
1847 		/* 11b basic rates: 1, 2Mbps */
1848 		ural_write(sc, RAL_TXRX_CSR11, 0x3);
1849 	}
1850 }
1851 
1852 static void
1853 ural_set_bssid(struct ural_softc *sc, const uint8_t *bssid)
1854 {
1855 	uint16_t tmp;
1856 
1857 	tmp = bssid[0] | bssid[1] << 8;
1858 	ural_write(sc, RAL_MAC_CSR5, tmp);
1859 
1860 	tmp = bssid[2] | bssid[3] << 8;
1861 	ural_write(sc, RAL_MAC_CSR6, tmp);
1862 
1863 	tmp = bssid[4] | bssid[5] << 8;
1864 	ural_write(sc, RAL_MAC_CSR7, tmp);
1865 
1866 	DPRINTF("setting BSSID to %6D\n", bssid, ":");
1867 }
1868 
1869 static void
1870 ural_set_macaddr(struct ural_softc *sc, const uint8_t *addr)
1871 {
1872 	uint16_t tmp;
1873 
1874 	tmp = addr[0] | addr[1] << 8;
1875 	ural_write(sc, RAL_MAC_CSR2, tmp);
1876 
1877 	tmp = addr[2] | addr[3] << 8;
1878 	ural_write(sc, RAL_MAC_CSR3, tmp);
1879 
1880 	tmp = addr[4] | addr[5] << 8;
1881 	ural_write(sc, RAL_MAC_CSR4, tmp);
1882 
1883 	DPRINTF("setting MAC address to %6D\n", addr, ":");
1884 }
1885 
1886 static void
1887 ural_setpromisc(struct ural_softc *sc)
1888 {
1889 	uint32_t tmp;
1890 
1891 	tmp = ural_read(sc, RAL_TXRX_CSR2);
1892 
1893 	tmp &= ~RAL_DROP_NOT_TO_ME;
1894 	if (sc->sc_ic.ic_promisc == 0)
1895 		tmp |= RAL_DROP_NOT_TO_ME;
1896 
1897 	ural_write(sc, RAL_TXRX_CSR2, tmp);
1898 
1899 	DPRINTF("%s promiscuous mode\n", sc->sc_ic.ic_promisc ?
1900 	    "entering" : "leaving");
1901 }
1902 
1903 static void
1904 ural_update_promisc(struct ieee80211com *ic)
1905 {
1906 	struct ural_softc *sc = ic->ic_softc;
1907 
1908 	RAL_LOCK(sc);
1909 	if (sc->sc_running)
1910 		ural_setpromisc(sc);
1911 	RAL_UNLOCK(sc);
1912 }
1913 
1914 static const char *
1915 ural_get_rf(int rev)
1916 {
1917 	switch (rev) {
1918 	case RAL_RF_2522:	return "RT2522";
1919 	case RAL_RF_2523:	return "RT2523";
1920 	case RAL_RF_2524:	return "RT2524";
1921 	case RAL_RF_2525:	return "RT2525";
1922 	case RAL_RF_2525E:	return "RT2525e";
1923 	case RAL_RF_2526:	return "RT2526";
1924 	case RAL_RF_5222:	return "RT5222";
1925 	default:		return "unknown";
1926 	}
1927 }
1928 
1929 static void
1930 ural_read_eeprom(struct ural_softc *sc)
1931 {
1932 	struct ieee80211com *ic = &sc->sc_ic;
1933 	uint16_t val;
1934 
1935 	ural_eeprom_read(sc, RAL_EEPROM_CONFIG0, &val, 2);
1936 	val = le16toh(val);
1937 	sc->rf_rev =   (val >> 11) & 0x7;
1938 	sc->hw_radio = (val >> 10) & 0x1;
1939 	sc->led_mode = (val >> 6)  & 0x7;
1940 	sc->rx_ant =   (val >> 4)  & 0x3;
1941 	sc->tx_ant =   (val >> 2)  & 0x3;
1942 	sc->nb_ant =   val & 0x3;
1943 
1944 	/* read MAC address */
1945 	ural_eeprom_read(sc, RAL_EEPROM_ADDRESS, ic->ic_macaddr, 6);
1946 
1947 	/* read default values for BBP registers */
1948 	ural_eeprom_read(sc, RAL_EEPROM_BBP_BASE, sc->bbp_prom, 2 * 16);
1949 
1950 	/* read Tx power for all b/g channels */
1951 	ural_eeprom_read(sc, RAL_EEPROM_TXPOWER, sc->txpow, 14);
1952 }
1953 
1954 static int
1955 ural_bbp_init(struct ural_softc *sc)
1956 {
1957 	int i, ntries;
1958 
1959 	/* wait for BBP to be ready */
1960 	for (ntries = 0; ntries < 100; ntries++) {
1961 		if (ural_bbp_read(sc, RAL_BBP_VERSION) != 0)
1962 			break;
1963 		if (ural_pause(sc, hz / 100))
1964 			break;
1965 	}
1966 	if (ntries == 100) {
1967 		device_printf(sc->sc_dev, "timeout waiting for BBP\n");
1968 		return EIO;
1969 	}
1970 
1971 	/* initialize BBP registers to default values */
1972 	for (i = 0; i < nitems(ural_def_bbp); i++)
1973 		ural_bbp_write(sc, ural_def_bbp[i].reg, ural_def_bbp[i].val);
1974 
1975 #if 0
1976 	/* initialize BBP registers to values stored in EEPROM */
1977 	for (i = 0; i < 16; i++) {
1978 		if (sc->bbp_prom[i].reg == 0xff)
1979 			continue;
1980 		ural_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
1981 	}
1982 #endif
1983 
1984 	return 0;
1985 }
1986 
1987 static void
1988 ural_set_txantenna(struct ural_softc *sc, int antenna)
1989 {
1990 	uint16_t tmp;
1991 	uint8_t tx;
1992 
1993 	tx = ural_bbp_read(sc, RAL_BBP_TX) & ~RAL_BBP_ANTMASK;
1994 	if (antenna == 1)
1995 		tx |= RAL_BBP_ANTA;
1996 	else if (antenna == 2)
1997 		tx |= RAL_BBP_ANTB;
1998 	else
1999 		tx |= RAL_BBP_DIVERSITY;
2000 
2001 	/* need to force I/Q flip for RF 2525e, 2526 and 5222 */
2002 	if (sc->rf_rev == RAL_RF_2525E || sc->rf_rev == RAL_RF_2526 ||
2003 	    sc->rf_rev == RAL_RF_5222)
2004 		tx |= RAL_BBP_FLIPIQ;
2005 
2006 	ural_bbp_write(sc, RAL_BBP_TX, tx);
2007 
2008 	/* update values in PHY_CSR5 and PHY_CSR6 */
2009 	tmp = ural_read(sc, RAL_PHY_CSR5) & ~0x7;
2010 	ural_write(sc, RAL_PHY_CSR5, tmp | (tx & 0x7));
2011 
2012 	tmp = ural_read(sc, RAL_PHY_CSR6) & ~0x7;
2013 	ural_write(sc, RAL_PHY_CSR6, tmp | (tx & 0x7));
2014 }
2015 
2016 static void
2017 ural_set_rxantenna(struct ural_softc *sc, int antenna)
2018 {
2019 	uint8_t rx;
2020 
2021 	rx = ural_bbp_read(sc, RAL_BBP_RX) & ~RAL_BBP_ANTMASK;
2022 	if (antenna == 1)
2023 		rx |= RAL_BBP_ANTA;
2024 	else if (antenna == 2)
2025 		rx |= RAL_BBP_ANTB;
2026 	else
2027 		rx |= RAL_BBP_DIVERSITY;
2028 
2029 	/* need to force no I/Q flip for RF 2525e and 2526 */
2030 	if (sc->rf_rev == RAL_RF_2525E || sc->rf_rev == RAL_RF_2526)
2031 		rx &= ~RAL_BBP_FLIPIQ;
2032 
2033 	ural_bbp_write(sc, RAL_BBP_RX, rx);
2034 }
2035 
2036 static void
2037 ural_init(struct ural_softc *sc)
2038 {
2039 	struct ieee80211com *ic = &sc->sc_ic;
2040 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2041 	uint16_t tmp;
2042 	int i, ntries;
2043 
2044 	RAL_LOCK_ASSERT(sc, MA_OWNED);
2045 
2046 	ural_set_testmode(sc);
2047 	ural_write(sc, 0x308, 0x00f0);	/* XXX magic */
2048 
2049 	ural_stop(sc);
2050 
2051 	/* initialize MAC registers to default values */
2052 	for (i = 0; i < nitems(ural_def_mac); i++)
2053 		ural_write(sc, ural_def_mac[i].reg, ural_def_mac[i].val);
2054 
2055 	/* wait for BBP and RF to wake up (this can take a long time!) */
2056 	for (ntries = 0; ntries < 100; ntries++) {
2057 		tmp = ural_read(sc, RAL_MAC_CSR17);
2058 		if ((tmp & (RAL_BBP_AWAKE | RAL_RF_AWAKE)) ==
2059 		    (RAL_BBP_AWAKE | RAL_RF_AWAKE))
2060 			break;
2061 		if (ural_pause(sc, hz / 100))
2062 			break;
2063 	}
2064 	if (ntries == 100) {
2065 		device_printf(sc->sc_dev,
2066 		    "timeout waiting for BBP/RF to wakeup\n");
2067 		goto fail;
2068 	}
2069 
2070 	/* we're ready! */
2071 	ural_write(sc, RAL_MAC_CSR1, RAL_HOST_READY);
2072 
2073 	/* set basic rate set (will be updated later) */
2074 	ural_write(sc, RAL_TXRX_CSR11, 0x15f);
2075 
2076 	if (ural_bbp_init(sc) != 0)
2077 		goto fail;
2078 
2079 	ural_set_chan(sc, ic->ic_curchan);
2080 
2081 	/* clear statistic registers (STA_CSR0 to STA_CSR10) */
2082 	ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof sc->sta);
2083 
2084 	ural_set_txantenna(sc, sc->tx_ant);
2085 	ural_set_rxantenna(sc, sc->rx_ant);
2086 
2087 	ural_set_macaddr(sc, vap ? vap->iv_myaddr : ic->ic_macaddr);
2088 
2089 	/*
2090 	 * Allocate Tx and Rx xfer queues.
2091 	 */
2092 	ural_setup_tx_list(sc);
2093 
2094 	/* kick Rx */
2095 	tmp = RAL_DROP_PHY | RAL_DROP_CRC;
2096 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2097 		tmp |= RAL_DROP_CTL | RAL_DROP_BAD_VERSION;
2098 		if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2099 			tmp |= RAL_DROP_TODS;
2100 		if (ic->ic_promisc == 0)
2101 			tmp |= RAL_DROP_NOT_TO_ME;
2102 	}
2103 	ural_write(sc, RAL_TXRX_CSR2, tmp);
2104 
2105 	sc->sc_running = 1;
2106 	usbd_xfer_set_stall(sc->sc_xfer[URAL_BULK_WR]);
2107 	usbd_transfer_start(sc->sc_xfer[URAL_BULK_RD]);
2108 	return;
2109 
2110 fail:	ural_stop(sc);
2111 }
2112 
2113 static void
2114 ural_stop(struct ural_softc *sc)
2115 {
2116 
2117 	RAL_LOCK_ASSERT(sc, MA_OWNED);
2118 
2119 	sc->sc_running = 0;
2120 
2121 	/*
2122 	 * Drain all the transfers, if not already drained:
2123 	 */
2124 	RAL_UNLOCK(sc);
2125 	usbd_transfer_drain(sc->sc_xfer[URAL_BULK_WR]);
2126 	usbd_transfer_drain(sc->sc_xfer[URAL_BULK_RD]);
2127 	RAL_LOCK(sc);
2128 
2129 	ural_unsetup_tx_list(sc);
2130 
2131 	/* disable Rx */
2132 	ural_write(sc, RAL_TXRX_CSR2, RAL_DISABLE_RX);
2133 	/* reset ASIC and BBP (but won't reset MAC registers!) */
2134 	ural_write(sc, RAL_MAC_CSR1, RAL_RESET_ASIC | RAL_RESET_BBP);
2135 	/* wait a little */
2136 	ural_pause(sc, hz / 10);
2137 	ural_write(sc, RAL_MAC_CSR1, 0);
2138 	/* wait a little */
2139 	ural_pause(sc, hz / 10);
2140 }
2141 
2142 static int
2143 ural_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
2144 	const struct ieee80211_bpf_params *params)
2145 {
2146 	struct ieee80211com *ic = ni->ni_ic;
2147 	struct ural_softc *sc = ic->ic_softc;
2148 
2149 	RAL_LOCK(sc);
2150 	/* prevent management frames from being sent if we're not ready */
2151 	if (!sc->sc_running) {
2152 		RAL_UNLOCK(sc);
2153 		m_freem(m);
2154 		return ENETDOWN;
2155 	}
2156 	if (sc->tx_nfree < RAL_TX_MINFREE) {
2157 		RAL_UNLOCK(sc);
2158 		m_freem(m);
2159 		return EIO;
2160 	}
2161 
2162 	if (params == NULL) {
2163 		/*
2164 		 * Legacy path; interpret frame contents to decide
2165 		 * precisely how to send the frame.
2166 		 */
2167 		if (ural_tx_mgt(sc, m, ni) != 0)
2168 			goto bad;
2169 	} else {
2170 		/*
2171 		 * Caller supplied explicit parameters to use in
2172 		 * sending the frame.
2173 		 */
2174 		if (ural_tx_raw(sc, m, ni, params) != 0)
2175 			goto bad;
2176 	}
2177 	RAL_UNLOCK(sc);
2178 	return 0;
2179 bad:
2180 	RAL_UNLOCK(sc);
2181 	return EIO;		/* XXX */
2182 }
2183 
2184 static void
2185 ural_ratectl_start(struct ural_softc *sc, struct ieee80211_node *ni)
2186 {
2187 	struct ieee80211vap *vap = ni->ni_vap;
2188 	struct ural_vap *uvp = URAL_VAP(vap);
2189 
2190 	/* clear statistic registers (STA_CSR0 to STA_CSR10) */
2191 	ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof sc->sta);
2192 
2193 	usb_callout_reset(&uvp->ratectl_ch, hz, ural_ratectl_timeout, uvp);
2194 }
2195 
2196 static void
2197 ural_ratectl_timeout(void *arg)
2198 {
2199 	struct ural_vap *uvp = arg;
2200 	struct ieee80211vap *vap = &uvp->vap;
2201 	struct ieee80211com *ic = vap->iv_ic;
2202 
2203 	ieee80211_runtask(ic, &uvp->ratectl_task);
2204 }
2205 
2206 static void
2207 ural_ratectl_task(void *arg, int pending)
2208 {
2209 	struct ural_vap *uvp = arg;
2210 	struct ieee80211vap *vap = &uvp->vap;
2211 	struct ural_softc *sc = vap->iv_ic->ic_softc;
2212 	struct ieee80211_ratectl_tx_stats *txs = &sc->sc_txs;
2213 	int fail;
2214 
2215 	RAL_LOCK(sc);
2216 	/* read and clear statistic registers (STA_CSR0 to STA_CSR10) */
2217 	ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof(sc->sta));
2218 
2219 	txs->flags = IEEE80211_RATECTL_TX_STATS_RETRIES;
2220 	txs->nsuccess = sc->sta[7] +	/* TX ok w/o retry */
2221 			sc->sta[8];	/* TX ok w/ retry */
2222 	fail = sc->sta[9];		/* TX retry-fail count */
2223 	txs->nframes = txs->nsuccess + fail;
2224 	/* XXX fail * maxretry */
2225 	txs->nretries = sc->sta[8] + fail;
2226 
2227 	ieee80211_ratectl_tx_update(vap, txs);
2228 
2229 	/* count TX retry-fail as Tx errors */
2230 	if_inc_counter(vap->iv_ifp, IFCOUNTER_OERRORS, fail);
2231 
2232 	usb_callout_reset(&uvp->ratectl_ch, hz, ural_ratectl_timeout, uvp);
2233 	RAL_UNLOCK(sc);
2234 }
2235 
2236 static int
2237 ural_pause(struct ural_softc *sc, int timeout)
2238 {
2239 
2240 	usb_pause_mtx(&sc->sc_mtx, timeout);
2241 	return (0);
2242 }
2243