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