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