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