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