if_ural.c revision 276701
1/*	$FreeBSD: head/sys/dev/usb/wlan/if_ural.c 276701 2015-01-05 15:04:17Z hselasky $	*/
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 276701 2015-01-05 15:04:17Z hselasky $");
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 void		ural_start(struct ifnet *);
153static int		ural_ioctl(struct ifnet *, u_long, caddr_t);
154static void		ural_set_testmode(struct ural_softc *);
155static void		ural_eeprom_read(struct ural_softc *, uint16_t, void *,
156			    int);
157static uint16_t		ural_read(struct ural_softc *, uint16_t);
158static void		ural_read_multi(struct ural_softc *, uint16_t, void *,
159			    int);
160static void		ural_write(struct ural_softc *, uint16_t, uint16_t);
161static void		ural_write_multi(struct ural_softc *, uint16_t, void *,
162			    int) __unused;
163static void		ural_bbp_write(struct ural_softc *, uint8_t, uint8_t);
164static uint8_t		ural_bbp_read(struct ural_softc *, uint8_t);
165static void		ural_rf_write(struct ural_softc *, uint8_t, uint32_t);
166static void		ural_scan_start(struct ieee80211com *);
167static void		ural_scan_end(struct ieee80211com *);
168static void		ural_set_channel(struct ieee80211com *);
169static void		ural_set_chan(struct ural_softc *,
170			    struct ieee80211_channel *);
171static void		ural_disable_rf_tune(struct ural_softc *);
172static void		ural_enable_tsf_sync(struct ural_softc *);
173static void 		ural_enable_tsf(struct ural_softc *);
174static void		ural_update_slot(struct ifnet *);
175static void		ural_set_txpreamble(struct ural_softc *);
176static void		ural_set_basicrates(struct ural_softc *,
177			    const struct ieee80211_channel *);
178static void		ural_set_bssid(struct ural_softc *, const uint8_t *);
179static void		ural_set_macaddr(struct ural_softc *, uint8_t *);
180static void		ural_update_promisc(struct ifnet *);
181static void		ural_setpromisc(struct ural_softc *);
182static const char	*ural_get_rf(int);
183static void		ural_read_eeprom(struct ural_softc *);
184static int		ural_bbp_init(struct ural_softc *);
185static void		ural_set_txantenna(struct ural_softc *, int);
186static void		ural_set_rxantenna(struct ural_softc *, int);
187static void		ural_init_locked(struct ural_softc *);
188static void		ural_init(void *);
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 ifnet *ifp;
426	struct ieee80211com *ic;
427	uint8_t iface_index, bands;
428	int error;
429
430	device_set_usb_desc(self);
431	sc->sc_udev = uaa->device;
432	sc->sc_dev = self;
433
434	mtx_init(&sc->sc_mtx, device_get_nameunit(self),
435	    MTX_NETWORK_LOCK, MTX_DEF);
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	ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
459	if (ifp == NULL) {
460		device_printf(sc->sc_dev, "can not if_alloc()\n");
461		goto detach;
462	}
463	ic = ifp->if_l2com;
464
465	ifp->if_softc = sc;
466	if_initname(ifp, "ural", device_get_unit(sc->sc_dev));
467	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
468	ifp->if_init = ural_init;
469	ifp->if_ioctl = ural_ioctl;
470	ifp->if_start = ural_start;
471	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
472	ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
473	IFQ_SET_READY(&ifp->if_snd);
474
475	ic->ic_ifp = ifp;
476	ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
477
478	/* set device capabilities */
479	ic->ic_caps =
480	      IEEE80211_C_STA		/* station mode supported */
481	    | IEEE80211_C_IBSS		/* IBSS mode supported */
482	    | IEEE80211_C_MONITOR	/* monitor mode supported */
483	    | IEEE80211_C_HOSTAP	/* HostAp mode supported */
484	    | IEEE80211_C_TXPMGT	/* tx power management */
485	    | IEEE80211_C_SHPREAMBLE	/* short preamble supported */
486	    | IEEE80211_C_SHSLOT	/* short slot time supported */
487	    | IEEE80211_C_BGSCAN	/* bg scanning supported */
488	    | IEEE80211_C_WPA		/* 802.11i */
489	    ;
490
491	bands = 0;
492	setbit(&bands, IEEE80211_MODE_11B);
493	setbit(&bands, IEEE80211_MODE_11G);
494	if (sc->rf_rev == RAL_RF_5222)
495		setbit(&bands, IEEE80211_MODE_11A);
496	ieee80211_init_channels(ic, NULL, &bands);
497
498	ieee80211_ifattach(ic, sc->sc_bssid);
499	ic->ic_update_promisc = ural_update_promisc;
500	ic->ic_raw_xmit = ural_raw_xmit;
501	ic->ic_scan_start = ural_scan_start;
502	ic->ic_scan_end = ural_scan_end;
503	ic->ic_set_channel = ural_set_channel;
504
505	ic->ic_vap_create = ural_vap_create;
506	ic->ic_vap_delete = ural_vap_delete;
507
508	ieee80211_radiotap_attach(ic,
509	    &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
510		RAL_TX_RADIOTAP_PRESENT,
511	    &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
512		RAL_RX_RADIOTAP_PRESENT);
513
514	if (bootverbose)
515		ieee80211_announce(ic);
516
517	return (0);
518
519detach:
520	ural_detach(self);
521	return (ENXIO);			/* failure */
522}
523
524static int
525ural_detach(device_t self)
526{
527	struct ural_softc *sc = device_get_softc(self);
528	struct ifnet *ifp = sc->sc_ifp;
529	struct ieee80211com *ic;
530
531	/* prevent further ioctls */
532	RAL_LOCK(sc);
533	sc->sc_detached = 1;
534	RAL_UNLOCK(sc);
535
536	/* stop all USB transfers */
537	usbd_transfer_unsetup(sc->sc_xfer, URAL_N_TRANSFER);
538
539	/* free TX list, if any */
540	RAL_LOCK(sc);
541	ural_unsetup_tx_list(sc);
542	RAL_UNLOCK(sc);
543
544	if (ifp) {
545		ic = ifp->if_l2com;
546		ieee80211_ifdetach(ic);
547		if_free(ifp);
548	}
549	mtx_destroy(&sc->sc_mtx);
550
551	return (0);
552}
553
554static usb_error_t
555ural_do_request(struct ural_softc *sc,
556    struct usb_device_request *req, void *data)
557{
558	usb_error_t err;
559	int ntries = 10;
560
561	while (ntries--) {
562		err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx,
563		    req, data, 0, NULL, 250 /* ms */);
564		if (err == 0)
565			break;
566
567		DPRINTFN(1, "Control request failed, %s (retrying)\n",
568		    usbd_errstr(err));
569		if (ural_pause(sc, hz / 100))
570			break;
571	}
572	return (err);
573}
574
575static struct ieee80211vap *
576ural_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
577    enum ieee80211_opmode opmode, int flags,
578    const uint8_t bssid[IEEE80211_ADDR_LEN],
579    const uint8_t mac[IEEE80211_ADDR_LEN])
580{
581	struct ural_softc *sc = ic->ic_ifp->if_softc;
582	struct ural_vap *uvp;
583	struct ieee80211vap *vap;
584
585	if (!TAILQ_EMPTY(&ic->ic_vaps))		/* only one at a time */
586		return NULL;
587	uvp = (struct ural_vap *) malloc(sizeof(struct ural_vap),
588	    M_80211_VAP, M_NOWAIT | M_ZERO);
589	if (uvp == NULL)
590		return NULL;
591	vap = &uvp->vap;
592	/* enable s/w bmiss handling for sta mode */
593
594	if (ieee80211_vap_setup(ic, vap, name, unit, opmode,
595	    flags | IEEE80211_CLONE_NOBEACONS, bssid, mac) != 0) {
596		/* out of memory */
597		free(uvp, M_80211_VAP);
598		return (NULL);
599	}
600
601	/* override state transition machine */
602	uvp->newstate = vap->iv_newstate;
603	vap->iv_newstate = ural_newstate;
604
605	usb_callout_init_mtx(&uvp->ratectl_ch, &sc->sc_mtx, 0);
606	TASK_INIT(&uvp->ratectl_task, 0, ural_ratectl_task, uvp);
607	ieee80211_ratectl_init(vap);
608	ieee80211_ratectl_setinterval(vap, 1000 /* 1 sec */);
609
610	/* complete setup */
611	ieee80211_vap_attach(vap, ieee80211_media_change, ieee80211_media_status);
612	ic->ic_opmode = opmode;
613	return vap;
614}
615
616static void
617ural_vap_delete(struct ieee80211vap *vap)
618{
619	struct ural_vap *uvp = URAL_VAP(vap);
620	struct ieee80211com *ic = vap->iv_ic;
621
622	usb_callout_drain(&uvp->ratectl_ch);
623	ieee80211_draintask(ic, &uvp->ratectl_task);
624	ieee80211_ratectl_deinit(vap);
625	ieee80211_vap_detach(vap);
626	free(uvp, M_80211_VAP);
627}
628
629static void
630ural_tx_free(struct ural_tx_data *data, int txerr)
631{
632	struct ural_softc *sc = data->sc;
633
634	if (data->m != NULL) {
635		if (data->m->m_flags & M_TXCB)
636			ieee80211_process_callback(data->ni, data->m,
637			    txerr ? ETIMEDOUT : 0);
638		m_freem(data->m);
639		data->m = NULL;
640
641		ieee80211_free_node(data->ni);
642		data->ni = NULL;
643	}
644	STAILQ_INSERT_TAIL(&sc->tx_free, data, next);
645	sc->tx_nfree++;
646}
647
648static void
649ural_setup_tx_list(struct ural_softc *sc)
650{
651	struct ural_tx_data *data;
652	int i;
653
654	sc->tx_nfree = 0;
655	STAILQ_INIT(&sc->tx_q);
656	STAILQ_INIT(&sc->tx_free);
657
658	for (i = 0; i < RAL_TX_LIST_COUNT; i++) {
659		data = &sc->tx_data[i];
660
661		data->sc = sc;
662		STAILQ_INSERT_TAIL(&sc->tx_free, data, next);
663		sc->tx_nfree++;
664	}
665}
666
667static void
668ural_unsetup_tx_list(struct ural_softc *sc)
669{
670	struct ural_tx_data *data;
671	int i;
672
673	/* make sure any subsequent use of the queues will fail */
674	sc->tx_nfree = 0;
675	STAILQ_INIT(&sc->tx_q);
676	STAILQ_INIT(&sc->tx_free);
677
678	/* free up all node references and mbufs */
679	for (i = 0; i < RAL_TX_LIST_COUNT; i++) {
680		data = &sc->tx_data[i];
681
682		if (data->m != NULL) {
683			m_freem(data->m);
684			data->m = NULL;
685		}
686		if (data->ni != NULL) {
687			ieee80211_free_node(data->ni);
688			data->ni = NULL;
689		}
690	}
691}
692
693static int
694ural_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
695{
696	struct ural_vap *uvp = URAL_VAP(vap);
697	struct ieee80211com *ic = vap->iv_ic;
698	struct ural_softc *sc = ic->ic_ifp->if_softc;
699	const struct ieee80211_txparam *tp;
700	struct ieee80211_node *ni;
701	struct mbuf *m;
702
703	DPRINTF("%s -> %s\n",
704		ieee80211_state_name[vap->iv_state],
705		ieee80211_state_name[nstate]);
706
707	IEEE80211_UNLOCK(ic);
708	RAL_LOCK(sc);
709	usb_callout_stop(&uvp->ratectl_ch);
710
711	switch (nstate) {
712	case IEEE80211_S_INIT:
713		if (vap->iv_state == IEEE80211_S_RUN) {
714			/* abort TSF synchronization */
715			ural_write(sc, RAL_TXRX_CSR19, 0);
716
717			/* force tx led to stop blinking */
718			ural_write(sc, RAL_MAC_CSR20, 0);
719		}
720		break;
721
722	case IEEE80211_S_RUN:
723		ni = ieee80211_ref_node(vap->iv_bss);
724
725		if (vap->iv_opmode != IEEE80211_M_MONITOR) {
726			if (ic->ic_bsschan == IEEE80211_CHAN_ANYC) {
727				RAL_UNLOCK(sc);
728				IEEE80211_LOCK(ic);
729				ieee80211_free_node(ni);
730				return (-1);
731			}
732			ural_update_slot(ic->ic_ifp);
733			ural_set_txpreamble(sc);
734			ural_set_basicrates(sc, ic->ic_bsschan);
735			IEEE80211_ADDR_COPY(sc->sc_bssid, ni->ni_bssid);
736			ural_set_bssid(sc, sc->sc_bssid);
737		}
738
739		if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
740		    vap->iv_opmode == IEEE80211_M_IBSS) {
741			m = ieee80211_beacon_alloc(ni, &uvp->bo);
742			if (m == NULL) {
743				device_printf(sc->sc_dev,
744				    "could not allocate beacon\n");
745				RAL_UNLOCK(sc);
746				IEEE80211_LOCK(ic);
747				ieee80211_free_node(ni);
748				return (-1);
749			}
750			ieee80211_ref_node(ni);
751			if (ural_tx_bcn(sc, m, ni) != 0) {
752				device_printf(sc->sc_dev,
753				    "could not send beacon\n");
754				RAL_UNLOCK(sc);
755				IEEE80211_LOCK(ic);
756				ieee80211_free_node(ni);
757				return (-1);
758			}
759		}
760
761		/* make tx led blink on tx (controlled by ASIC) */
762		ural_write(sc, RAL_MAC_CSR20, 1);
763
764		if (vap->iv_opmode != IEEE80211_M_MONITOR)
765			ural_enable_tsf_sync(sc);
766		else
767			ural_enable_tsf(sc);
768
769		/* enable automatic rate adaptation */
770		/* XXX should use ic_bsschan but not valid until after newstate call below */
771		tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
772		if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
773			ural_ratectl_start(sc, ni);
774		ieee80211_free_node(ni);
775		break;
776
777	default:
778		break;
779	}
780	RAL_UNLOCK(sc);
781	IEEE80211_LOCK(ic);
782	return (uvp->newstate(vap, nstate, arg));
783}
784
785
786static void
787ural_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
788{
789	struct ural_softc *sc = usbd_xfer_softc(xfer);
790	struct ifnet *ifp = sc->sc_ifp;
791	struct ieee80211vap *vap;
792	struct ural_tx_data *data;
793	struct mbuf *m;
794	struct usb_page_cache *pc;
795	int len;
796
797	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
798
799	switch (USB_GET_STATE(xfer)) {
800	case USB_ST_TRANSFERRED:
801		DPRINTFN(11, "transfer complete, %d bytes\n", len);
802
803		/* free resources */
804		data = usbd_xfer_get_priv(xfer);
805		ural_tx_free(data, 0);
806		usbd_xfer_set_priv(xfer, NULL);
807
808		if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
809		ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
810
811		/* FALLTHROUGH */
812	case USB_ST_SETUP:
813tr_setup:
814		data = STAILQ_FIRST(&sc->tx_q);
815		if (data) {
816			STAILQ_REMOVE_HEAD(&sc->tx_q, next);
817			m = data->m;
818
819			if (m->m_pkthdr.len > (int)(RAL_FRAME_SIZE + RAL_TX_DESC_SIZE)) {
820				DPRINTFN(0, "data overflow, %u bytes\n",
821				    m->m_pkthdr.len);
822				m->m_pkthdr.len = (RAL_FRAME_SIZE + RAL_TX_DESC_SIZE);
823			}
824			pc = usbd_xfer_get_frame(xfer, 0);
825			usbd_copy_in(pc, 0, &data->desc, RAL_TX_DESC_SIZE);
826			usbd_m_copy_in(pc, RAL_TX_DESC_SIZE, m, 0,
827			    m->m_pkthdr.len);
828
829			vap = data->ni->ni_vap;
830			if (ieee80211_radiotap_active_vap(vap)) {
831				struct ural_tx_radiotap_header *tap = &sc->sc_txtap;
832
833				tap->wt_flags = 0;
834				tap->wt_rate = data->rate;
835				tap->wt_antenna = sc->tx_ant;
836
837				ieee80211_radiotap_tx(vap, m);
838			}
839
840			/* xfer length needs to be a multiple of two! */
841			len = (RAL_TX_DESC_SIZE + m->m_pkthdr.len + 1) & ~1;
842			if ((len % 64) == 0)
843				len += 2;
844
845			DPRINTFN(11, "sending frame len=%u xferlen=%u\n",
846			    m->m_pkthdr.len, len);
847
848			usbd_xfer_set_frame_len(xfer, 0, len);
849			usbd_xfer_set_priv(xfer, data);
850
851			usbd_transfer_submit(xfer);
852		}
853		RAL_UNLOCK(sc);
854		ural_start(ifp);
855		RAL_LOCK(sc);
856		break;
857
858	default:			/* Error */
859		DPRINTFN(11, "transfer error, %s\n",
860		    usbd_errstr(error));
861
862		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
863		data = usbd_xfer_get_priv(xfer);
864		if (data != NULL) {
865			ural_tx_free(data, error);
866			usbd_xfer_set_priv(xfer, NULL);
867		}
868
869		if (error == USB_ERR_STALLED) {
870			/* try to clear stall first */
871			usbd_xfer_set_stall(xfer);
872			goto tr_setup;
873		}
874		if (error == USB_ERR_TIMEOUT)
875			device_printf(sc->sc_dev, "device timeout\n");
876		break;
877	}
878}
879
880static void
881ural_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
882{
883	struct ural_softc *sc = usbd_xfer_softc(xfer);
884	struct ifnet *ifp = sc->sc_ifp;
885	struct ieee80211com *ic = ifp->if_l2com;
886	struct ieee80211_node *ni;
887	struct mbuf *m = NULL;
888	struct usb_page_cache *pc;
889	uint32_t flags;
890	int8_t rssi = 0, nf = 0;
891	int len;
892
893	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
894
895	switch (USB_GET_STATE(xfer)) {
896	case USB_ST_TRANSFERRED:
897
898		DPRINTFN(15, "rx done, actlen=%d\n", len);
899
900		if (len < (int)(RAL_RX_DESC_SIZE + IEEE80211_MIN_LEN)) {
901			DPRINTF("%s: xfer too short %d\n",
902			    device_get_nameunit(sc->sc_dev), len);
903			if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
904			goto tr_setup;
905		}
906
907		len -= RAL_RX_DESC_SIZE;
908		/* rx descriptor is located at the end */
909		pc = usbd_xfer_get_frame(xfer, 0);
910		usbd_copy_out(pc, len, &sc->sc_rx_desc, RAL_RX_DESC_SIZE);
911
912		rssi = URAL_RSSI(sc->sc_rx_desc.rssi);
913		nf = RAL_NOISE_FLOOR;
914		flags = le32toh(sc->sc_rx_desc.flags);
915		if (flags & (RAL_RX_PHY_ERROR | RAL_RX_CRC_ERROR)) {
916			/*
917		         * This should not happen since we did not
918		         * request to receive those frames when we
919		         * filled RAL_TXRX_CSR2:
920		         */
921			DPRINTFN(5, "PHY or CRC error\n");
922			if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
923			goto tr_setup;
924		}
925
926		m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
927		if (m == NULL) {
928			DPRINTF("could not allocate mbuf\n");
929			if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
930			goto tr_setup;
931		}
932		usbd_copy_out(pc, 0, mtod(m, uint8_t *), len);
933
934		/* finalize mbuf */
935		m->m_pkthdr.rcvif = ifp;
936		m->m_pkthdr.len = m->m_len = (flags >> 16) & 0xfff;
937
938		if (ieee80211_radiotap_active(ic)) {
939			struct ural_rx_radiotap_header *tap = &sc->sc_rxtap;
940
941			/* XXX set once */
942			tap->wr_flags = 0;
943			tap->wr_rate = ieee80211_plcp2rate(sc->sc_rx_desc.rate,
944			    (flags & RAL_RX_OFDM) ?
945			    IEEE80211_T_OFDM : IEEE80211_T_CCK);
946			tap->wr_antenna = sc->rx_ant;
947			tap->wr_antsignal = nf + rssi;
948			tap->wr_antnoise = nf;
949		}
950		/* Strip trailing 802.11 MAC FCS. */
951		m_adj(m, -IEEE80211_CRC_LEN);
952
953		/* FALLTHROUGH */
954	case USB_ST_SETUP:
955tr_setup:
956		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
957		usbd_transfer_submit(xfer);
958
959		/*
960		 * At the end of a USB callback it is always safe to unlock
961		 * the private mutex of a device! That is why we do the
962		 * "ieee80211_input" here, and not some lines up!
963		 */
964		RAL_UNLOCK(sc);
965		if (m) {
966			ni = ieee80211_find_rxnode(ic,
967			    mtod(m, struct ieee80211_frame_min *));
968			if (ni != NULL) {
969				(void) ieee80211_input(ni, m, rssi, nf);
970				ieee80211_free_node(ni);
971			} else
972				(void) ieee80211_input_all(ic, m, rssi, nf);
973		}
974		if ((ifp->if_drv_flags & IFF_DRV_OACTIVE) == 0 &&
975		    !IFQ_IS_EMPTY(&ifp->if_snd))
976			ural_start(ifp);
977		RAL_LOCK(sc);
978		return;
979
980	default:			/* Error */
981		if (error != USB_ERR_CANCELLED) {
982			/* try to clear stall first */
983			usbd_xfer_set_stall(xfer);
984			goto tr_setup;
985		}
986		return;
987	}
988}
989
990static uint8_t
991ural_plcp_signal(int rate)
992{
993	switch (rate) {
994	/* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
995	case 12:	return 0xb;
996	case 18:	return 0xf;
997	case 24:	return 0xa;
998	case 36:	return 0xe;
999	case 48:	return 0x9;
1000	case 72:	return 0xd;
1001	case 96:	return 0x8;
1002	case 108:	return 0xc;
1003
1004	/* CCK rates (NB: not IEEE std, device-specific) */
1005	case 2:		return 0x0;
1006	case 4:		return 0x1;
1007	case 11:	return 0x2;
1008	case 22:	return 0x3;
1009	}
1010	return 0xff;		/* XXX unsupported/unknown rate */
1011}
1012
1013static void
1014ural_setup_tx_desc(struct ural_softc *sc, struct ural_tx_desc *desc,
1015    uint32_t flags, int len, int rate)
1016{
1017	struct ifnet *ifp = sc->sc_ifp;
1018	struct ieee80211com *ic = ifp->if_l2com;
1019	uint16_t plcp_length;
1020	int remainder;
1021
1022	desc->flags = htole32(flags);
1023	desc->flags |= htole32(RAL_TX_NEWSEQ);
1024	desc->flags |= htole32(len << 16);
1025
1026	desc->wme = htole16(RAL_AIFSN(2) | RAL_LOGCWMIN(3) | RAL_LOGCWMAX(5));
1027	desc->wme |= htole16(RAL_IVOFFSET(sizeof (struct ieee80211_frame)));
1028
1029	/* setup PLCP fields */
1030	desc->plcp_signal  = ural_plcp_signal(rate);
1031	desc->plcp_service = 4;
1032
1033	len += IEEE80211_CRC_LEN;
1034	if (ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM) {
1035		desc->flags |= htole32(RAL_TX_OFDM);
1036
1037		plcp_length = len & 0xfff;
1038		desc->plcp_length_hi = plcp_length >> 6;
1039		desc->plcp_length_lo = plcp_length & 0x3f;
1040	} else {
1041		if (rate == 0)
1042			rate = 2;	/* avoid division by zero */
1043		plcp_length = (16 * len + rate - 1) / rate;
1044		if (rate == 22) {
1045			remainder = (16 * len) % 22;
1046			if (remainder != 0 && remainder < 7)
1047				desc->plcp_service |= RAL_PLCP_LENGEXT;
1048		}
1049		desc->plcp_length_hi = plcp_length >> 8;
1050		desc->plcp_length_lo = plcp_length & 0xff;
1051
1052		if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1053			desc->plcp_signal |= 0x08;
1054	}
1055
1056	desc->iv = 0;
1057	desc->eiv = 0;
1058}
1059
1060#define RAL_TX_TIMEOUT	5000
1061
1062static int
1063ural_tx_bcn(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	struct ifnet *ifp = sc->sc_ifp;
1068	const struct ieee80211_txparam *tp;
1069	struct ural_tx_data *data;
1070
1071	if (sc->tx_nfree == 0) {
1072		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1073		m_freem(m0);
1074		ieee80211_free_node(ni);
1075		return (EIO);
1076	}
1077	if (ic->ic_bsschan == IEEE80211_CHAN_ANYC) {
1078		m_freem(m0);
1079		ieee80211_free_node(ni);
1080		return (ENXIO);
1081	}
1082	data = STAILQ_FIRST(&sc->tx_free);
1083	STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1084	sc->tx_nfree--;
1085	tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_bsschan)];
1086
1087	data->m = m0;
1088	data->ni = ni;
1089	data->rate = tp->mgmtrate;
1090
1091	ural_setup_tx_desc(sc, &data->desc,
1092	    RAL_TX_IFS_NEWBACKOFF | RAL_TX_TIMESTAMP, m0->m_pkthdr.len,
1093	    tp->mgmtrate);
1094
1095	DPRINTFN(10, "sending beacon frame len=%u rate=%u\n",
1096	    m0->m_pkthdr.len, tp->mgmtrate);
1097
1098	STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1099	usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1100
1101	return (0);
1102}
1103
1104static int
1105ural_tx_mgt(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1106{
1107	struct ieee80211vap *vap = ni->ni_vap;
1108	struct ieee80211com *ic = ni->ni_ic;
1109	const struct ieee80211_txparam *tp;
1110	struct ural_tx_data *data;
1111	struct ieee80211_frame *wh;
1112	struct ieee80211_key *k;
1113	uint32_t flags;
1114	uint16_t dur;
1115
1116	RAL_LOCK_ASSERT(sc, MA_OWNED);
1117
1118	data = STAILQ_FIRST(&sc->tx_free);
1119	STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1120	sc->tx_nfree--;
1121
1122	tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
1123
1124	wh = mtod(m0, struct ieee80211_frame *);
1125	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1126		k = ieee80211_crypto_encap(ni, m0);
1127		if (k == NULL) {
1128			m_freem(m0);
1129			return ENOBUFS;
1130		}
1131		wh = mtod(m0, struct ieee80211_frame *);
1132	}
1133
1134	data->m = m0;
1135	data->ni = ni;
1136	data->rate = tp->mgmtrate;
1137
1138	flags = 0;
1139	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1140		flags |= RAL_TX_ACK;
1141
1142		dur = ieee80211_ack_duration(ic->ic_rt, tp->mgmtrate,
1143		    ic->ic_flags & IEEE80211_F_SHPREAMBLE);
1144		USETW(wh->i_dur, dur);
1145
1146		/* tell hardware to add timestamp for probe responses */
1147		if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
1148		    IEEE80211_FC0_TYPE_MGT &&
1149		    (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
1150		    IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1151			flags |= RAL_TX_TIMESTAMP;
1152	}
1153
1154	ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, tp->mgmtrate);
1155
1156	DPRINTFN(10, "sending mgt frame len=%u rate=%u\n",
1157	    m0->m_pkthdr.len, tp->mgmtrate);
1158
1159	STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1160	usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1161
1162	return 0;
1163}
1164
1165static int
1166ural_sendprot(struct ural_softc *sc,
1167    const struct mbuf *m, struct ieee80211_node *ni, int prot, int rate)
1168{
1169	struct ieee80211com *ic = ni->ni_ic;
1170	const struct ieee80211_frame *wh;
1171	struct ural_tx_data *data;
1172	struct mbuf *mprot;
1173	int protrate, ackrate, pktlen, flags, isshort;
1174	uint16_t dur;
1175
1176	KASSERT(prot == IEEE80211_PROT_RTSCTS || prot == IEEE80211_PROT_CTSONLY,
1177	    ("protection %d", prot));
1178
1179	wh = mtod(m, const struct ieee80211_frame *);
1180	pktlen = m->m_pkthdr.len + IEEE80211_CRC_LEN;
1181
1182	protrate = ieee80211_ctl_rate(ic->ic_rt, rate);
1183	ackrate = ieee80211_ack_rate(ic->ic_rt, rate);
1184
1185	isshort = (ic->ic_flags & IEEE80211_F_SHPREAMBLE) != 0;
1186	dur = ieee80211_compute_duration(ic->ic_rt, pktlen, rate, isshort)
1187	    + ieee80211_ack_duration(ic->ic_rt, rate, isshort);
1188	flags = RAL_TX_RETRY(7);
1189	if (prot == IEEE80211_PROT_RTSCTS) {
1190		/* NB: CTS is the same size as an ACK */
1191		dur += ieee80211_ack_duration(ic->ic_rt, rate, isshort);
1192		flags |= RAL_TX_ACK;
1193		mprot = ieee80211_alloc_rts(ic, wh->i_addr1, wh->i_addr2, dur);
1194	} else {
1195		mprot = ieee80211_alloc_cts(ic, ni->ni_vap->iv_myaddr, dur);
1196	}
1197	if (mprot == NULL) {
1198		/* XXX stat + msg */
1199		return ENOBUFS;
1200	}
1201	data = STAILQ_FIRST(&sc->tx_free);
1202	STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1203	sc->tx_nfree--;
1204
1205	data->m = mprot;
1206	data->ni = ieee80211_ref_node(ni);
1207	data->rate = protrate;
1208	ural_setup_tx_desc(sc, &data->desc, flags, mprot->m_pkthdr.len, protrate);
1209
1210	STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1211	usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1212
1213	return 0;
1214}
1215
1216static int
1217ural_tx_raw(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni,
1218    const struct ieee80211_bpf_params *params)
1219{
1220	struct ieee80211com *ic = ni->ni_ic;
1221	struct ural_tx_data *data;
1222	uint32_t flags;
1223	int error;
1224	int rate;
1225
1226	RAL_LOCK_ASSERT(sc, MA_OWNED);
1227	KASSERT(params != NULL, ("no raw xmit params"));
1228
1229	rate = params->ibp_rate0;
1230	if (!ieee80211_isratevalid(ic->ic_rt, rate)) {
1231		m_freem(m0);
1232		return EINVAL;
1233	}
1234	flags = 0;
1235	if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
1236		flags |= RAL_TX_ACK;
1237	if (params->ibp_flags & (IEEE80211_BPF_RTS|IEEE80211_BPF_CTS)) {
1238		error = ural_sendprot(sc, m0, ni,
1239		    params->ibp_flags & IEEE80211_BPF_RTS ?
1240			 IEEE80211_PROT_RTSCTS : IEEE80211_PROT_CTSONLY,
1241		    rate);
1242		if (error || sc->tx_nfree == 0) {
1243			m_freem(m0);
1244			return ENOBUFS;
1245		}
1246		flags |= RAL_TX_IFS_SIFS;
1247	}
1248
1249	data = STAILQ_FIRST(&sc->tx_free);
1250	STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1251	sc->tx_nfree--;
1252
1253	data->m = m0;
1254	data->ni = ni;
1255	data->rate = rate;
1256
1257	/* XXX need to setup descriptor ourself */
1258	ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, rate);
1259
1260	DPRINTFN(10, "sending raw frame len=%u rate=%u\n",
1261	    m0->m_pkthdr.len, rate);
1262
1263	STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1264	usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1265
1266	return 0;
1267}
1268
1269static int
1270ural_tx_data(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1271{
1272	struct ieee80211vap *vap = ni->ni_vap;
1273	struct ieee80211com *ic = ni->ni_ic;
1274	struct ural_tx_data *data;
1275	struct ieee80211_frame *wh;
1276	const struct ieee80211_txparam *tp;
1277	struct ieee80211_key *k;
1278	uint32_t flags = 0;
1279	uint16_t dur;
1280	int error, rate;
1281
1282	RAL_LOCK_ASSERT(sc, MA_OWNED);
1283
1284	wh = mtod(m0, struct ieee80211_frame *);
1285
1286	tp = &vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)];
1287	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
1288		rate = tp->mcastrate;
1289	else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
1290		rate = tp->ucastrate;
1291	else
1292		rate = ni->ni_txrate;
1293
1294	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1295		k = ieee80211_crypto_encap(ni, m0);
1296		if (k == NULL) {
1297			m_freem(m0);
1298			return ENOBUFS;
1299		}
1300		/* packet header may have moved, reset our local pointer */
1301		wh = mtod(m0, struct ieee80211_frame *);
1302	}
1303
1304	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1305		int prot = IEEE80211_PROT_NONE;
1306		if (m0->m_pkthdr.len + IEEE80211_CRC_LEN > vap->iv_rtsthreshold)
1307			prot = IEEE80211_PROT_RTSCTS;
1308		else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
1309		    ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM)
1310			prot = ic->ic_protmode;
1311		if (prot != IEEE80211_PROT_NONE) {
1312			error = ural_sendprot(sc, m0, ni, prot, rate);
1313			if (error || sc->tx_nfree == 0) {
1314				m_freem(m0);
1315				return ENOBUFS;
1316			}
1317			flags |= RAL_TX_IFS_SIFS;
1318		}
1319	}
1320
1321	data = STAILQ_FIRST(&sc->tx_free);
1322	STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1323	sc->tx_nfree--;
1324
1325	data->m = m0;
1326	data->ni = ni;
1327	data->rate = rate;
1328
1329	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1330		flags |= RAL_TX_ACK;
1331		flags |= RAL_TX_RETRY(7);
1332
1333		dur = ieee80211_ack_duration(ic->ic_rt, rate,
1334		    ic->ic_flags & IEEE80211_F_SHPREAMBLE);
1335		USETW(wh->i_dur, dur);
1336	}
1337
1338	ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, rate);
1339
1340	DPRINTFN(10, "sending data frame len=%u rate=%u\n",
1341	    m0->m_pkthdr.len, rate);
1342
1343	STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1344	usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1345
1346	return 0;
1347}
1348
1349static void
1350ural_start(struct ifnet *ifp)
1351{
1352	struct ural_softc *sc = ifp->if_softc;
1353	struct ieee80211_node *ni;
1354	struct mbuf *m;
1355
1356	RAL_LOCK(sc);
1357	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1358		RAL_UNLOCK(sc);
1359		return;
1360	}
1361	for (;;) {
1362		IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
1363		if (m == NULL)
1364			break;
1365		if (sc->tx_nfree < RAL_TX_MINFREE) {
1366			IFQ_DRV_PREPEND(&ifp->if_snd, m);
1367			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1368			break;
1369		}
1370		ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1371		if (ural_tx_data(sc, m, ni) != 0) {
1372			ieee80211_free_node(ni);
1373			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
1374			break;
1375		}
1376	}
1377	RAL_UNLOCK(sc);
1378}
1379
1380static int
1381ural_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1382{
1383	struct ural_softc *sc = ifp->if_softc;
1384	struct ieee80211com *ic = ifp->if_l2com;
1385	struct ifreq *ifr = (struct ifreq *) data;
1386	int error;
1387	int startall = 0;
1388
1389	RAL_LOCK(sc);
1390	error = sc->sc_detached ? ENXIO : 0;
1391	RAL_UNLOCK(sc);
1392	if (error)
1393		return (error);
1394
1395	switch (cmd) {
1396	case SIOCSIFFLAGS:
1397		RAL_LOCK(sc);
1398		if (ifp->if_flags & IFF_UP) {
1399			if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1400				ural_init_locked(sc);
1401				startall = 1;
1402			} else
1403				ural_setpromisc(sc);
1404		} else {
1405			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1406				ural_stop(sc);
1407		}
1408		RAL_UNLOCK(sc);
1409		if (startall)
1410			ieee80211_start_all(ic);
1411		break;
1412	case SIOCGIFMEDIA:
1413	case SIOCSIFMEDIA:
1414		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
1415		break;
1416	default:
1417		error = ether_ioctl(ifp, cmd, data);
1418		break;
1419	}
1420	return error;
1421}
1422
1423static void
1424ural_set_testmode(struct ural_softc *sc)
1425{
1426	struct usb_device_request req;
1427	usb_error_t error;
1428
1429	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1430	req.bRequest = RAL_VENDOR_REQUEST;
1431	USETW(req.wValue, 4);
1432	USETW(req.wIndex, 1);
1433	USETW(req.wLength, 0);
1434
1435	error = ural_do_request(sc, &req, NULL);
1436	if (error != 0) {
1437		device_printf(sc->sc_dev, "could not set test mode: %s\n",
1438		    usbd_errstr(error));
1439	}
1440}
1441
1442static void
1443ural_eeprom_read(struct ural_softc *sc, uint16_t addr, void *buf, int len)
1444{
1445	struct usb_device_request req;
1446	usb_error_t error;
1447
1448	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1449	req.bRequest = RAL_READ_EEPROM;
1450	USETW(req.wValue, 0);
1451	USETW(req.wIndex, addr);
1452	USETW(req.wLength, len);
1453
1454	error = ural_do_request(sc, &req, buf);
1455	if (error != 0) {
1456		device_printf(sc->sc_dev, "could not read EEPROM: %s\n",
1457		    usbd_errstr(error));
1458	}
1459}
1460
1461static uint16_t
1462ural_read(struct ural_softc *sc, uint16_t reg)
1463{
1464	struct usb_device_request req;
1465	usb_error_t error;
1466	uint16_t val;
1467
1468	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1469	req.bRequest = RAL_READ_MAC;
1470	USETW(req.wValue, 0);
1471	USETW(req.wIndex, reg);
1472	USETW(req.wLength, sizeof (uint16_t));
1473
1474	error = ural_do_request(sc, &req, &val);
1475	if (error != 0) {
1476		device_printf(sc->sc_dev, "could not read MAC register: %s\n",
1477		    usbd_errstr(error));
1478		return 0;
1479	}
1480
1481	return le16toh(val);
1482}
1483
1484static void
1485ural_read_multi(struct ural_softc *sc, uint16_t reg, void *buf, int len)
1486{
1487	struct usb_device_request req;
1488	usb_error_t error;
1489
1490	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1491	req.bRequest = RAL_READ_MULTI_MAC;
1492	USETW(req.wValue, 0);
1493	USETW(req.wIndex, reg);
1494	USETW(req.wLength, len);
1495
1496	error = ural_do_request(sc, &req, buf);
1497	if (error != 0) {
1498		device_printf(sc->sc_dev, "could not read MAC register: %s\n",
1499		    usbd_errstr(error));
1500	}
1501}
1502
1503static void
1504ural_write(struct ural_softc *sc, uint16_t reg, uint16_t val)
1505{
1506	struct usb_device_request req;
1507	usb_error_t error;
1508
1509	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1510	req.bRequest = RAL_WRITE_MAC;
1511	USETW(req.wValue, val);
1512	USETW(req.wIndex, reg);
1513	USETW(req.wLength, 0);
1514
1515	error = ural_do_request(sc, &req, NULL);
1516	if (error != 0) {
1517		device_printf(sc->sc_dev, "could not write MAC register: %s\n",
1518		    usbd_errstr(error));
1519	}
1520}
1521
1522static void
1523ural_write_multi(struct ural_softc *sc, uint16_t reg, void *buf, int len)
1524{
1525	struct usb_device_request req;
1526	usb_error_t error;
1527
1528	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1529	req.bRequest = RAL_WRITE_MULTI_MAC;
1530	USETW(req.wValue, 0);
1531	USETW(req.wIndex, reg);
1532	USETW(req.wLength, len);
1533
1534	error = ural_do_request(sc, &req, buf);
1535	if (error != 0) {
1536		device_printf(sc->sc_dev, "could not write MAC register: %s\n",
1537		    usbd_errstr(error));
1538	}
1539}
1540
1541static void
1542ural_bbp_write(struct ural_softc *sc, uint8_t reg, uint8_t val)
1543{
1544	uint16_t tmp;
1545	int ntries;
1546
1547	for (ntries = 0; ntries < 100; ntries++) {
1548		if (!(ural_read(sc, RAL_PHY_CSR8) & RAL_BBP_BUSY))
1549			break;
1550		if (ural_pause(sc, hz / 100))
1551			break;
1552	}
1553	if (ntries == 100) {
1554		device_printf(sc->sc_dev, "could not write to BBP\n");
1555		return;
1556	}
1557
1558	tmp = reg << 8 | val;
1559	ural_write(sc, RAL_PHY_CSR7, tmp);
1560}
1561
1562static uint8_t
1563ural_bbp_read(struct ural_softc *sc, uint8_t reg)
1564{
1565	uint16_t val;
1566	int ntries;
1567
1568	val = RAL_BBP_WRITE | reg << 8;
1569	ural_write(sc, RAL_PHY_CSR7, val);
1570
1571	for (ntries = 0; ntries < 100; ntries++) {
1572		if (!(ural_read(sc, RAL_PHY_CSR8) & RAL_BBP_BUSY))
1573			break;
1574		if (ural_pause(sc, hz / 100))
1575			break;
1576	}
1577	if (ntries == 100) {
1578		device_printf(sc->sc_dev, "could not read BBP\n");
1579		return 0;
1580	}
1581
1582	return ural_read(sc, RAL_PHY_CSR7) & 0xff;
1583}
1584
1585static void
1586ural_rf_write(struct ural_softc *sc, uint8_t reg, uint32_t val)
1587{
1588	uint32_t tmp;
1589	int ntries;
1590
1591	for (ntries = 0; ntries < 100; ntries++) {
1592		if (!(ural_read(sc, RAL_PHY_CSR10) & RAL_RF_LOBUSY))
1593			break;
1594		if (ural_pause(sc, hz / 100))
1595			break;
1596	}
1597	if (ntries == 100) {
1598		device_printf(sc->sc_dev, "could not write to RF\n");
1599		return;
1600	}
1601
1602	tmp = RAL_RF_BUSY | RAL_RF_20BIT | (val & 0xfffff) << 2 | (reg & 0x3);
1603	ural_write(sc, RAL_PHY_CSR9,  tmp & 0xffff);
1604	ural_write(sc, RAL_PHY_CSR10, tmp >> 16);
1605
1606	/* remember last written value in sc */
1607	sc->rf_regs[reg] = val;
1608
1609	DPRINTFN(15, "RF R[%u] <- 0x%05x\n", reg & 0x3, val & 0xfffff);
1610}
1611
1612static void
1613ural_scan_start(struct ieee80211com *ic)
1614{
1615	struct ifnet *ifp = ic->ic_ifp;
1616	struct ural_softc *sc = ifp->if_softc;
1617
1618	RAL_LOCK(sc);
1619	ural_write(sc, RAL_TXRX_CSR19, 0);
1620	ural_set_bssid(sc, ifp->if_broadcastaddr);
1621	RAL_UNLOCK(sc);
1622}
1623
1624static void
1625ural_scan_end(struct ieee80211com *ic)
1626{
1627	struct ural_softc *sc = ic->ic_ifp->if_softc;
1628
1629	RAL_LOCK(sc);
1630	ural_enable_tsf_sync(sc);
1631	ural_set_bssid(sc, sc->sc_bssid);
1632	RAL_UNLOCK(sc);
1633
1634}
1635
1636static void
1637ural_set_channel(struct ieee80211com *ic)
1638{
1639	struct ural_softc *sc = ic->ic_ifp->if_softc;
1640
1641	RAL_LOCK(sc);
1642	ural_set_chan(sc, ic->ic_curchan);
1643	RAL_UNLOCK(sc);
1644}
1645
1646static void
1647ural_set_chan(struct ural_softc *sc, struct ieee80211_channel *c)
1648{
1649	struct ifnet *ifp = sc->sc_ifp;
1650	struct ieee80211com *ic = ifp->if_l2com;
1651	uint8_t power, tmp;
1652	int i, chan;
1653
1654	chan = ieee80211_chan2ieee(ic, c);
1655	if (chan == 0 || chan == IEEE80211_CHAN_ANY)
1656		return;
1657
1658	if (IEEE80211_IS_CHAN_2GHZ(c))
1659		power = min(sc->txpow[chan - 1], 31);
1660	else
1661		power = 31;
1662
1663	/* adjust txpower using ifconfig settings */
1664	power -= (100 - ic->ic_txpowlimit) / 8;
1665
1666	DPRINTFN(2, "setting channel to %u, txpower to %u\n", chan, power);
1667
1668	switch (sc->rf_rev) {
1669	case RAL_RF_2522:
1670		ural_rf_write(sc, RAL_RF1, 0x00814);
1671		ural_rf_write(sc, RAL_RF2, ural_rf2522_r2[chan - 1]);
1672		ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1673		break;
1674
1675	case RAL_RF_2523:
1676		ural_rf_write(sc, RAL_RF1, 0x08804);
1677		ural_rf_write(sc, RAL_RF2, ural_rf2523_r2[chan - 1]);
1678		ural_rf_write(sc, RAL_RF3, power << 7 | 0x38044);
1679		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1680		break;
1681
1682	case RAL_RF_2524:
1683		ural_rf_write(sc, RAL_RF1, 0x0c808);
1684		ural_rf_write(sc, RAL_RF2, ural_rf2524_r2[chan - 1]);
1685		ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1686		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1687		break;
1688
1689	case RAL_RF_2525:
1690		ural_rf_write(sc, RAL_RF1, 0x08808);
1691		ural_rf_write(sc, RAL_RF2, ural_rf2525_hi_r2[chan - 1]);
1692		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1693		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1694
1695		ural_rf_write(sc, RAL_RF1, 0x08808);
1696		ural_rf_write(sc, RAL_RF2, ural_rf2525_r2[chan - 1]);
1697		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1698		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1699		break;
1700
1701	case RAL_RF_2525E:
1702		ural_rf_write(sc, RAL_RF1, 0x08808);
1703		ural_rf_write(sc, RAL_RF2, ural_rf2525e_r2[chan - 1]);
1704		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1705		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00286 : 0x00282);
1706		break;
1707
1708	case RAL_RF_2526:
1709		ural_rf_write(sc, RAL_RF2, ural_rf2526_hi_r2[chan - 1]);
1710		ural_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381);
1711		ural_rf_write(sc, RAL_RF1, 0x08804);
1712
1713		ural_rf_write(sc, RAL_RF2, ural_rf2526_r2[chan - 1]);
1714		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1715		ural_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381);
1716		break;
1717
1718	/* dual-band RF */
1719	case RAL_RF_5222:
1720		for (i = 0; ural_rf5222[i].chan != chan; i++);
1721
1722		ural_rf_write(sc, RAL_RF1, ural_rf5222[i].r1);
1723		ural_rf_write(sc, RAL_RF2, ural_rf5222[i].r2);
1724		ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1725		ural_rf_write(sc, RAL_RF4, ural_rf5222[i].r4);
1726		break;
1727	}
1728
1729	if (ic->ic_opmode != IEEE80211_M_MONITOR &&
1730	    (ic->ic_flags & IEEE80211_F_SCAN) == 0) {
1731		/* set Japan filter bit for channel 14 */
1732		tmp = ural_bbp_read(sc, 70);
1733
1734		tmp &= ~RAL_JAPAN_FILTER;
1735		if (chan == 14)
1736			tmp |= RAL_JAPAN_FILTER;
1737
1738		ural_bbp_write(sc, 70, tmp);
1739
1740		/* clear CRC errors */
1741		ural_read(sc, RAL_STA_CSR0);
1742
1743		ural_pause(sc, hz / 100);
1744		ural_disable_rf_tune(sc);
1745	}
1746
1747	/* XXX doesn't belong here */
1748	/* update basic rate set */
1749	ural_set_basicrates(sc, c);
1750
1751	/* give the hardware some time to do the switchover */
1752	ural_pause(sc, hz / 100);
1753}
1754
1755/*
1756 * Disable RF auto-tuning.
1757 */
1758static void
1759ural_disable_rf_tune(struct ural_softc *sc)
1760{
1761	uint32_t tmp;
1762
1763	if (sc->rf_rev != RAL_RF_2523) {
1764		tmp = sc->rf_regs[RAL_RF1] & ~RAL_RF1_AUTOTUNE;
1765		ural_rf_write(sc, RAL_RF1, tmp);
1766	}
1767
1768	tmp = sc->rf_regs[RAL_RF3] & ~RAL_RF3_AUTOTUNE;
1769	ural_rf_write(sc, RAL_RF3, tmp);
1770
1771	DPRINTFN(2, "disabling RF autotune\n");
1772}
1773
1774/*
1775 * Refer to IEEE Std 802.11-1999 pp. 123 for more information on TSF
1776 * synchronization.
1777 */
1778static void
1779ural_enable_tsf_sync(struct ural_softc *sc)
1780{
1781	struct ifnet *ifp = sc->sc_ifp;
1782	struct ieee80211com *ic = ifp->if_l2com;
1783	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1784	uint16_t logcwmin, preload, tmp;
1785
1786	/* first, disable TSF synchronization */
1787	ural_write(sc, RAL_TXRX_CSR19, 0);
1788
1789	tmp = (16 * vap->iv_bss->ni_intval) << 4;
1790	ural_write(sc, RAL_TXRX_CSR18, tmp);
1791
1792	logcwmin = (ic->ic_opmode == IEEE80211_M_IBSS) ? 2 : 0;
1793	preload = (ic->ic_opmode == IEEE80211_M_IBSS) ? 320 : 6;
1794	tmp = logcwmin << 12 | preload;
1795	ural_write(sc, RAL_TXRX_CSR20, tmp);
1796
1797	/* finally, enable TSF synchronization */
1798	tmp = RAL_ENABLE_TSF | RAL_ENABLE_TBCN;
1799	if (ic->ic_opmode == IEEE80211_M_STA)
1800		tmp |= RAL_ENABLE_TSF_SYNC(1);
1801	else
1802		tmp |= RAL_ENABLE_TSF_SYNC(2) | RAL_ENABLE_BEACON_GENERATOR;
1803	ural_write(sc, RAL_TXRX_CSR19, tmp);
1804
1805	DPRINTF("enabling TSF synchronization\n");
1806}
1807
1808static void
1809ural_enable_tsf(struct ural_softc *sc)
1810{
1811	/* first, disable TSF synchronization */
1812	ural_write(sc, RAL_TXRX_CSR19, 0);
1813	ural_write(sc, RAL_TXRX_CSR19, RAL_ENABLE_TSF | RAL_ENABLE_TSF_SYNC(2));
1814}
1815
1816#define RAL_RXTX_TURNAROUND	5	/* us */
1817static void
1818ural_update_slot(struct ifnet *ifp)
1819{
1820	struct ural_softc *sc = ifp->if_softc;
1821	struct ieee80211com *ic = ifp->if_l2com;
1822	uint16_t slottime, sifs, eifs;
1823
1824	slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
1825
1826	/*
1827	 * These settings may sound a bit inconsistent but this is what the
1828	 * reference driver does.
1829	 */
1830	if (ic->ic_curmode == IEEE80211_MODE_11B) {
1831		sifs = 16 - RAL_RXTX_TURNAROUND;
1832		eifs = 364;
1833	} else {
1834		sifs = 10 - RAL_RXTX_TURNAROUND;
1835		eifs = 64;
1836	}
1837
1838	ural_write(sc, RAL_MAC_CSR10, slottime);
1839	ural_write(sc, RAL_MAC_CSR11, sifs);
1840	ural_write(sc, RAL_MAC_CSR12, eifs);
1841}
1842
1843static void
1844ural_set_txpreamble(struct ural_softc *sc)
1845{
1846	struct ifnet *ifp = sc->sc_ifp;
1847	struct ieee80211com *ic = ifp->if_l2com;
1848	uint16_t tmp;
1849
1850	tmp = ural_read(sc, RAL_TXRX_CSR10);
1851
1852	tmp &= ~RAL_SHORT_PREAMBLE;
1853	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
1854		tmp |= RAL_SHORT_PREAMBLE;
1855
1856	ural_write(sc, RAL_TXRX_CSR10, tmp);
1857}
1858
1859static void
1860ural_set_basicrates(struct ural_softc *sc, const struct ieee80211_channel *c)
1861{
1862	/* XXX wrong, take from rate set */
1863	/* update basic rate set */
1864	if (IEEE80211_IS_CHAN_5GHZ(c)) {
1865		/* 11a basic rates: 6, 12, 24Mbps */
1866		ural_write(sc, RAL_TXRX_CSR11, 0x150);
1867	} else if (IEEE80211_IS_CHAN_ANYG(c)) {
1868		/* 11g basic rates: 1, 2, 5.5, 11, 6, 12, 24Mbps */
1869		ural_write(sc, RAL_TXRX_CSR11, 0x15f);
1870	} else {
1871		/* 11b basic rates: 1, 2Mbps */
1872		ural_write(sc, RAL_TXRX_CSR11, 0x3);
1873	}
1874}
1875
1876static void
1877ural_set_bssid(struct ural_softc *sc, const uint8_t *bssid)
1878{
1879	uint16_t tmp;
1880
1881	tmp = bssid[0] | bssid[1] << 8;
1882	ural_write(sc, RAL_MAC_CSR5, tmp);
1883
1884	tmp = bssid[2] | bssid[3] << 8;
1885	ural_write(sc, RAL_MAC_CSR6, tmp);
1886
1887	tmp = bssid[4] | bssid[5] << 8;
1888	ural_write(sc, RAL_MAC_CSR7, tmp);
1889
1890	DPRINTF("setting BSSID to %6D\n", bssid, ":");
1891}
1892
1893static void
1894ural_set_macaddr(struct ural_softc *sc, uint8_t *addr)
1895{
1896	uint16_t tmp;
1897
1898	tmp = addr[0] | addr[1] << 8;
1899	ural_write(sc, RAL_MAC_CSR2, tmp);
1900
1901	tmp = addr[2] | addr[3] << 8;
1902	ural_write(sc, RAL_MAC_CSR3, tmp);
1903
1904	tmp = addr[4] | addr[5] << 8;
1905	ural_write(sc, RAL_MAC_CSR4, tmp);
1906
1907	DPRINTF("setting MAC address to %6D\n", addr, ":");
1908}
1909
1910static void
1911ural_setpromisc(struct ural_softc *sc)
1912{
1913	struct ifnet *ifp = sc->sc_ifp;
1914	uint32_t tmp;
1915
1916	tmp = ural_read(sc, RAL_TXRX_CSR2);
1917
1918	tmp &= ~RAL_DROP_NOT_TO_ME;
1919	if (!(ifp->if_flags & IFF_PROMISC))
1920		tmp |= RAL_DROP_NOT_TO_ME;
1921
1922	ural_write(sc, RAL_TXRX_CSR2, tmp);
1923
1924	DPRINTF("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
1925	    "entering" : "leaving");
1926}
1927
1928static void
1929ural_update_promisc(struct ifnet *ifp)
1930{
1931	struct ural_softc *sc = ifp->if_softc;
1932
1933	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
1934		return;
1935
1936	RAL_LOCK(sc);
1937	ural_setpromisc(sc);
1938	RAL_UNLOCK(sc);
1939}
1940
1941static const char *
1942ural_get_rf(int rev)
1943{
1944	switch (rev) {
1945	case RAL_RF_2522:	return "RT2522";
1946	case RAL_RF_2523:	return "RT2523";
1947	case RAL_RF_2524:	return "RT2524";
1948	case RAL_RF_2525:	return "RT2525";
1949	case RAL_RF_2525E:	return "RT2525e";
1950	case RAL_RF_2526:	return "RT2526";
1951	case RAL_RF_5222:	return "RT5222";
1952	default:		return "unknown";
1953	}
1954}
1955
1956static void
1957ural_read_eeprom(struct ural_softc *sc)
1958{
1959	uint16_t val;
1960
1961	ural_eeprom_read(sc, RAL_EEPROM_CONFIG0, &val, 2);
1962	val = le16toh(val);
1963	sc->rf_rev =   (val >> 11) & 0x7;
1964	sc->hw_radio = (val >> 10) & 0x1;
1965	sc->led_mode = (val >> 6)  & 0x7;
1966	sc->rx_ant =   (val >> 4)  & 0x3;
1967	sc->tx_ant =   (val >> 2)  & 0x3;
1968	sc->nb_ant =   val & 0x3;
1969
1970	/* read MAC address */
1971	ural_eeprom_read(sc, RAL_EEPROM_ADDRESS, sc->sc_bssid, 6);
1972
1973	/* read default values for BBP registers */
1974	ural_eeprom_read(sc, RAL_EEPROM_BBP_BASE, sc->bbp_prom, 2 * 16);
1975
1976	/* read Tx power for all b/g channels */
1977	ural_eeprom_read(sc, RAL_EEPROM_TXPOWER, sc->txpow, 14);
1978}
1979
1980static int
1981ural_bbp_init(struct ural_softc *sc)
1982{
1983#define N(a)	((int)(sizeof (a) / sizeof ((a)[0])))
1984	int i, ntries;
1985
1986	/* wait for BBP to be ready */
1987	for (ntries = 0; ntries < 100; ntries++) {
1988		if (ural_bbp_read(sc, RAL_BBP_VERSION) != 0)
1989			break;
1990		if (ural_pause(sc, hz / 100))
1991			break;
1992	}
1993	if (ntries == 100) {
1994		device_printf(sc->sc_dev, "timeout waiting for BBP\n");
1995		return EIO;
1996	}
1997
1998	/* initialize BBP registers to default values */
1999	for (i = 0; i < N(ural_def_bbp); i++)
2000		ural_bbp_write(sc, ural_def_bbp[i].reg, ural_def_bbp[i].val);
2001
2002#if 0
2003	/* initialize BBP registers to values stored in EEPROM */
2004	for (i = 0; i < 16; i++) {
2005		if (sc->bbp_prom[i].reg == 0xff)
2006			continue;
2007		ural_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
2008	}
2009#endif
2010
2011	return 0;
2012#undef N
2013}
2014
2015static void
2016ural_set_txantenna(struct ural_softc *sc, int antenna)
2017{
2018	uint16_t tmp;
2019	uint8_t tx;
2020
2021	tx = ural_bbp_read(sc, RAL_BBP_TX) & ~RAL_BBP_ANTMASK;
2022	if (antenna == 1)
2023		tx |= RAL_BBP_ANTA;
2024	else if (antenna == 2)
2025		tx |= RAL_BBP_ANTB;
2026	else
2027		tx |= RAL_BBP_DIVERSITY;
2028
2029	/* need to force I/Q flip for RF 2525e, 2526 and 5222 */
2030	if (sc->rf_rev == RAL_RF_2525E || sc->rf_rev == RAL_RF_2526 ||
2031	    sc->rf_rev == RAL_RF_5222)
2032		tx |= RAL_BBP_FLIPIQ;
2033
2034	ural_bbp_write(sc, RAL_BBP_TX, tx);
2035
2036	/* update values in PHY_CSR5 and PHY_CSR6 */
2037	tmp = ural_read(sc, RAL_PHY_CSR5) & ~0x7;
2038	ural_write(sc, RAL_PHY_CSR5, tmp | (tx & 0x7));
2039
2040	tmp = ural_read(sc, RAL_PHY_CSR6) & ~0x7;
2041	ural_write(sc, RAL_PHY_CSR6, tmp | (tx & 0x7));
2042}
2043
2044static void
2045ural_set_rxantenna(struct ural_softc *sc, int antenna)
2046{
2047	uint8_t rx;
2048
2049	rx = ural_bbp_read(sc, RAL_BBP_RX) & ~RAL_BBP_ANTMASK;
2050	if (antenna == 1)
2051		rx |= RAL_BBP_ANTA;
2052	else if (antenna == 2)
2053		rx |= RAL_BBP_ANTB;
2054	else
2055		rx |= RAL_BBP_DIVERSITY;
2056
2057	/* need to force no I/Q flip for RF 2525e and 2526 */
2058	if (sc->rf_rev == RAL_RF_2525E || sc->rf_rev == RAL_RF_2526)
2059		rx &= ~RAL_BBP_FLIPIQ;
2060
2061	ural_bbp_write(sc, RAL_BBP_RX, rx);
2062}
2063
2064static void
2065ural_init_locked(struct ural_softc *sc)
2066{
2067#define N(a)	((int)(sizeof (a) / sizeof ((a)[0])))
2068	struct ifnet *ifp = sc->sc_ifp;
2069	struct ieee80211com *ic = ifp->if_l2com;
2070	uint16_t tmp;
2071	int i, ntries;
2072
2073	RAL_LOCK_ASSERT(sc, MA_OWNED);
2074
2075	ural_set_testmode(sc);
2076	ural_write(sc, 0x308, 0x00f0);	/* XXX magic */
2077
2078	ural_stop(sc);
2079
2080	/* initialize MAC registers to default values */
2081	for (i = 0; i < N(ural_def_mac); i++)
2082		ural_write(sc, ural_def_mac[i].reg, ural_def_mac[i].val);
2083
2084	/* wait for BBP and RF to wake up (this can take a long time!) */
2085	for (ntries = 0; ntries < 100; ntries++) {
2086		tmp = ural_read(sc, RAL_MAC_CSR17);
2087		if ((tmp & (RAL_BBP_AWAKE | RAL_RF_AWAKE)) ==
2088		    (RAL_BBP_AWAKE | RAL_RF_AWAKE))
2089			break;
2090		if (ural_pause(sc, hz / 100))
2091			break;
2092	}
2093	if (ntries == 100) {
2094		device_printf(sc->sc_dev,
2095		    "timeout waiting for BBP/RF to wakeup\n");
2096		goto fail;
2097	}
2098
2099	/* we're ready! */
2100	ural_write(sc, RAL_MAC_CSR1, RAL_HOST_READY);
2101
2102	/* set basic rate set (will be updated later) */
2103	ural_write(sc, RAL_TXRX_CSR11, 0x15f);
2104
2105	if (ural_bbp_init(sc) != 0)
2106		goto fail;
2107
2108	ural_set_chan(sc, ic->ic_curchan);
2109
2110	/* clear statistic registers (STA_CSR0 to STA_CSR10) */
2111	ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof sc->sta);
2112
2113	ural_set_txantenna(sc, sc->tx_ant);
2114	ural_set_rxantenna(sc, sc->rx_ant);
2115
2116	ural_set_macaddr(sc, IF_LLADDR(ifp));
2117
2118	/*
2119	 * Allocate Tx and Rx xfer queues.
2120	 */
2121	ural_setup_tx_list(sc);
2122
2123	/* kick Rx */
2124	tmp = RAL_DROP_PHY | RAL_DROP_CRC;
2125	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2126		tmp |= RAL_DROP_CTL | RAL_DROP_BAD_VERSION;
2127		if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2128			tmp |= RAL_DROP_TODS;
2129		if (!(ifp->if_flags & IFF_PROMISC))
2130			tmp |= RAL_DROP_NOT_TO_ME;
2131	}
2132	ural_write(sc, RAL_TXRX_CSR2, tmp);
2133
2134	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2135	ifp->if_drv_flags |= IFF_DRV_RUNNING;
2136	usbd_xfer_set_stall(sc->sc_xfer[URAL_BULK_WR]);
2137	usbd_transfer_start(sc->sc_xfer[URAL_BULK_RD]);
2138	return;
2139
2140fail:	ural_stop(sc);
2141#undef N
2142}
2143
2144static void
2145ural_init(void *priv)
2146{
2147	struct ural_softc *sc = priv;
2148	struct ifnet *ifp = sc->sc_ifp;
2149	struct ieee80211com *ic = ifp->if_l2com;
2150
2151	RAL_LOCK(sc);
2152	ural_init_locked(sc);
2153	RAL_UNLOCK(sc);
2154
2155	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2156		ieee80211_start_all(ic);		/* start all vap's */
2157}
2158
2159static void
2160ural_stop(struct ural_softc *sc)
2161{
2162	struct ifnet *ifp = sc->sc_ifp;
2163
2164	RAL_LOCK_ASSERT(sc, MA_OWNED);
2165
2166	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2167
2168	/*
2169	 * Drain all the transfers, if not already drained:
2170	 */
2171	RAL_UNLOCK(sc);
2172	usbd_transfer_drain(sc->sc_xfer[URAL_BULK_WR]);
2173	usbd_transfer_drain(sc->sc_xfer[URAL_BULK_RD]);
2174	RAL_LOCK(sc);
2175
2176	ural_unsetup_tx_list(sc);
2177
2178	/* disable Rx */
2179	ural_write(sc, RAL_TXRX_CSR2, RAL_DISABLE_RX);
2180	/* reset ASIC and BBP (but won't reset MAC registers!) */
2181	ural_write(sc, RAL_MAC_CSR1, RAL_RESET_ASIC | RAL_RESET_BBP);
2182	/* wait a little */
2183	ural_pause(sc, hz / 10);
2184	ural_write(sc, RAL_MAC_CSR1, 0);
2185	/* wait a little */
2186	ural_pause(sc, hz / 10);
2187}
2188
2189static int
2190ural_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
2191	const struct ieee80211_bpf_params *params)
2192{
2193	struct ieee80211com *ic = ni->ni_ic;
2194	struct ifnet *ifp = ic->ic_ifp;
2195	struct ural_softc *sc = ifp->if_softc;
2196
2197	RAL_LOCK(sc);
2198	/* prevent management frames from being sent if we're not ready */
2199	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
2200		RAL_UNLOCK(sc);
2201		m_freem(m);
2202		ieee80211_free_node(ni);
2203		return ENETDOWN;
2204	}
2205	if (sc->tx_nfree < RAL_TX_MINFREE) {
2206		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2207		RAL_UNLOCK(sc);
2208		m_freem(m);
2209		ieee80211_free_node(ni);
2210		return EIO;
2211	}
2212
2213	if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
2214
2215	if (params == NULL) {
2216		/*
2217		 * Legacy path; interpret frame contents to decide
2218		 * precisely how to send the frame.
2219		 */
2220		if (ural_tx_mgt(sc, m, ni) != 0)
2221			goto bad;
2222	} else {
2223		/*
2224		 * Caller supplied explicit parameters to use in
2225		 * sending the frame.
2226		 */
2227		if (ural_tx_raw(sc, m, ni, params) != 0)
2228			goto bad;
2229	}
2230	RAL_UNLOCK(sc);
2231	return 0;
2232bad:
2233	if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
2234	RAL_UNLOCK(sc);
2235	ieee80211_free_node(ni);
2236	return EIO;		/* XXX */
2237}
2238
2239static void
2240ural_ratectl_start(struct ural_softc *sc, struct ieee80211_node *ni)
2241{
2242	struct ieee80211vap *vap = ni->ni_vap;
2243	struct ural_vap *uvp = URAL_VAP(vap);
2244
2245	/* clear statistic registers (STA_CSR0 to STA_CSR10) */
2246	ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof sc->sta);
2247
2248	usb_callout_reset(&uvp->ratectl_ch, hz, ural_ratectl_timeout, uvp);
2249}
2250
2251static void
2252ural_ratectl_timeout(void *arg)
2253{
2254	struct ural_vap *uvp = arg;
2255	struct ieee80211vap *vap = &uvp->vap;
2256	struct ieee80211com *ic = vap->iv_ic;
2257
2258	ieee80211_runtask(ic, &uvp->ratectl_task);
2259}
2260
2261static void
2262ural_ratectl_task(void *arg, int pending)
2263{
2264	struct ural_vap *uvp = arg;
2265	struct ieee80211vap *vap = &uvp->vap;
2266	struct ieee80211com *ic = vap->iv_ic;
2267	struct ifnet *ifp = ic->ic_ifp;
2268	struct ural_softc *sc = ifp->if_softc;
2269	struct ieee80211_node *ni;
2270	int ok, fail;
2271	int sum, retrycnt;
2272
2273	ni = ieee80211_ref_node(vap->iv_bss);
2274	RAL_LOCK(sc);
2275	/* read and clear statistic registers (STA_CSR0 to STA_CSR10) */
2276	ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof(sc->sta));
2277
2278	ok = sc->sta[7] +		/* TX ok w/o retry */
2279	     sc->sta[8];		/* TX ok w/ retry */
2280	fail = sc->sta[9];		/* TX retry-fail count */
2281	sum = ok+fail;
2282	retrycnt = sc->sta[8] + fail;
2283
2284	ieee80211_ratectl_tx_update(vap, ni, &sum, &ok, &retrycnt);
2285	(void) ieee80211_ratectl_rate(ni, NULL, 0);
2286
2287	if_inc_counter(ifp, IFCOUNTER_OERRORS, fail);	/* count TX retry-fail as Tx errors */
2288
2289	usb_callout_reset(&uvp->ratectl_ch, hz, ural_ratectl_timeout, uvp);
2290	RAL_UNLOCK(sc);
2291	ieee80211_free_node(ni);
2292}
2293
2294static int
2295ural_pause(struct ural_softc *sc, int timeout)
2296{
2297
2298	usb_pause_mtx(&sc->sc_mtx, timeout);
2299	return (0);
2300}
2301