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