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