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