if_ural.c revision 257176
1129198Scognet/*	$FreeBSD: head/sys/dev/usb/wlan/if_ural.c 257176 2013-10-26 17:58:36Z glebius $	*/
2129198Scognet
3139735Simp/*-
4129198Scognet * Copyright (c) 2005, 2006
5129198Scognet *	Damien Bergamini <damien.bergamini@free.fr>
6129198Scognet *
7129198Scognet * Copyright (c) 2006, 2008
8129198Scognet *	Hans Petter Selasky <hselasky@FreeBSD.org>
9129198Scognet *
10129198Scognet * Permission to use, copy, modify, and distribute this software for any
11129198Scognet * purpose with or without fee is hereby granted, provided that the above
12129198Scognet * copyright notice and this permission notice appear in all copies.
13129198Scognet *
14129198Scognet * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
15129198Scognet * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
16129198Scognet * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
17129198Scognet * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
18129198Scognet * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
19129198Scognet * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
20129198Scognet * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21129198Scognet */
22129198Scognet
23129198Scognet#include <sys/cdefs.h>
24129198Scognet__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_ural.c 257176 2013-10-26 17:58:36Z glebius $");
25129198Scognet
26129198Scognet/*-
27129198Scognet * Ralink Technology RT2500USB chipset driver
28129198Scognet * http://www.ralinktech.com/
29129198Scognet */
30129198Scognet
31129198Scognet#include <sys/param.h>
32129198Scognet#include <sys/sockio.h>
33129198Scognet#include <sys/sysctl.h>
34129198Scognet#include <sys/lock.h>
35129198Scognet#include <sys/mutex.h>
36129198Scognet#include <sys/mbuf.h>
37129198Scognet#include <sys/kernel.h>
38129198Scognet#include <sys/socket.h>
39129198Scognet#include <sys/systm.h>
40129198Scognet#include <sys/malloc.h>
41129198Scognet#include <sys/module.h>
42276032Sandrew#include <sys/bus.h>
43276032Sandrew#include <sys/endian.h>
44276032Sandrew#include <sys/kdb.h>
45276032Sandrew
46289529Sian#include <machine/bus.h>
47289529Sian#include <machine/resource.h>
48289529Sian#include <sys/rman.h>
49289529Sian
50289529Sian#include <net/bpf.h>
51289529Sian#include <net/if.h>
52295459Sadrian#include <net/if_var.h>
53289529Sian#include <net/if_arp.h>
54296138Sskra#include <net/ethernet.h>
55297230Sskra#include <net/if_dl.h>
56297230Sskra#include <net/if_media.h>
57296138Sskra#include <net/if_types.h>
58297230Sskra
59297230Sskra#ifdef INET
60296138Sskra#include <netinet/in.h>
61297230Sskra#include <netinet/in_systm.h>
62297230Sskra#include <netinet/in_var.h>
63297230Sskra#include <netinet/if_ether.h>
64297230Sskra#include <netinet/ip.h>
65296138Sskra#endif
66289529Sian
67289529Sian#include <net80211/ieee80211_var.h>
68186352Ssam#include <net80211/ieee80211_regdomain.h>
69170827Scognet#include <net80211/ieee80211_radiotap.h>
70170827Scognet#include <net80211/ieee80211_ratectl.h>
71179595Sbenno
72179595Sbenno#include <dev/usb/usb.h>
73179595Sbenno#include <dev/usb/usbdi.h>
74183840Sraj#include "usbdevs.h"
75183840Sraj
76186352Ssam#define	USB_DEBUG_VAR ural_debug
77186352Ssam#include <dev/usb/usb_debug.h>
78141820Scognet
79239268Sgonzo#include <dev/usb/wlan/if_uralreg.h>
80270884Sbr#include <dev/usb/wlan/if_uralvar.h>
81259640Sganbold
82259640Sganbold#ifdef USB_DEBUG
83280824Sandrewstatic int ural_debug = 0;
84239688Sgonzo
85240488Sgberstatic SYSCTL_NODE(_hw_usb, OID_AUTO, ural, CTLFLAG_RW, 0, "USB ural");
86240492SgberSYSCTL_INT(_hw_usb_ural, OID_AUTO, debug, CTLFLAG_RW, &ural_debug, 0,
87240492Sgber    "Debug level");
88240492Sgber#endif
89240492Sgber
90240492Sgber#define URAL_RSSI(rssi)					\
91240492Sgber	((rssi) > (RAL_NOISE_FLOOR + RAL_RSSI_CORR) ?	\
92141820Scognet	 ((rssi) - (RAL_NOISE_FLOOR + RAL_RSSI_CORR)) : 0)
93135650Scognet
94141820Scognet/* various supported device vendors/products */
95129198Scognetstatic const STRUCT_USB_HOST_ID ural_devs[] = {
96193847Smarcel#define	URAL_DEV(v,p)  { USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##p) }
97147166Scognet	URAL_DEV(ASUS, WL167G),
98147166Scognet	URAL_DEV(ASUS, RT2570),
99245637Sian	URAL_DEV(BELKIN, F5D7050),
100236992Simp	URAL_DEV(BELKIN, F5D7051),
101236992Simp	URAL_DEV(CISCOLINKSYS, HU200TS),
102182933Sraj	URAL_DEV(CISCOLINKSYS, WUSB54G),
103178366Scognet	URAL_DEV(CISCOLINKSYS, WUSB54GP),
104260161Szbb	URAL_DEV(CONCEPTRONIC2, C54RU),
105260161Szbb	URAL_DEV(DLINK, DWLG122),
106239268Sgonzo	URAL_DEV(GIGABYTE, GN54G),
107292426Sadrian	URAL_DEV(GIGABYTE, GNWBKG),
108239268Sgonzo	URAL_DEV(GUILLEMOT, HWGUSB254),
109276032Sandrew	URAL_DEV(MELCO, KG54),
110289548Sian	URAL_DEV(MELCO, KG54AI),
111292426Sadrian	URAL_DEV(MELCO, KG54YB),
112276032Sandrew	URAL_DEV(MELCO, NINWIFI),
113276032Sandrew	URAL_DEV(MSI, RT2570),
114289529Sian	URAL_DEV(MSI, RT2570_2),
115289529Sian	URAL_DEV(MSI, RT2570_3),
116289529Sian	URAL_DEV(NOVATECH, NV902),
117289529Sian	URAL_DEV(RALINK, RT2570),
118129198Scognet	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	ieee80211_vap_setup(ic, vap, name, unit, opmode,
594	    flags | IEEE80211_CLONE_NOBEACONS, bssid, mac);
595
596	/* override state transition machine */
597	uvp->newstate = vap->iv_newstate;
598	vap->iv_newstate = ural_newstate;
599
600	usb_callout_init_mtx(&uvp->ratectl_ch, &sc->sc_mtx, 0);
601	TASK_INIT(&uvp->ratectl_task, 0, ural_ratectl_task, uvp);
602	ieee80211_ratectl_init(vap);
603	ieee80211_ratectl_setinterval(vap, 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->ratectl_ch);
618	ieee80211_draintask(ic, &uvp->ratectl_task);
619	ieee80211_ratectl_deinit(vap);
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->ratectl_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 = ieee80211_ref_node(vap->iv_bss);
719
720		if (vap->iv_opmode != IEEE80211_M_MONITOR) {
721			if (ic->ic_bsschan == IEEE80211_CHAN_ANYC) {
722				RAL_UNLOCK(sc);
723				IEEE80211_LOCK(ic);
724				ieee80211_free_node(ni);
725				return (-1);
726			}
727			ural_update_slot(ic->ic_ifp);
728			ural_set_txpreamble(sc);
729			ural_set_basicrates(sc, ic->ic_bsschan);
730			IEEE80211_ADDR_COPY(sc->sc_bssid, ni->ni_bssid);
731			ural_set_bssid(sc, sc->sc_bssid);
732		}
733
734		if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
735		    vap->iv_opmode == IEEE80211_M_IBSS) {
736			m = ieee80211_beacon_alloc(ni, &uvp->bo);
737			if (m == NULL) {
738				device_printf(sc->sc_dev,
739				    "could not allocate beacon\n");
740				RAL_UNLOCK(sc);
741				IEEE80211_LOCK(ic);
742				ieee80211_free_node(ni);
743				return (-1);
744			}
745			ieee80211_ref_node(ni);
746			if (ural_tx_bcn(sc, m, ni) != 0) {
747				device_printf(sc->sc_dev,
748				    "could not send beacon\n");
749				RAL_UNLOCK(sc);
750				IEEE80211_LOCK(ic);
751				ieee80211_free_node(ni);
752				return (-1);
753			}
754		}
755
756		/* make tx led blink on tx (controlled by ASIC) */
757		ural_write(sc, RAL_MAC_CSR20, 1);
758
759		if (vap->iv_opmode != IEEE80211_M_MONITOR)
760			ural_enable_tsf_sync(sc);
761		else
762			ural_enable_tsf(sc);
763
764		/* enable automatic rate adaptation */
765		/* XXX should use ic_bsschan but not valid until after newstate call below */
766		tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
767		if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
768			ural_ratectl_start(sc, ni);
769		ieee80211_free_node(ni);
770		break;
771
772	default:
773		break;
774	}
775	RAL_UNLOCK(sc);
776	IEEE80211_LOCK(ic);
777	return (uvp->newstate(vap, nstate, arg));
778}
779
780
781static void
782ural_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
783{
784	struct ural_softc *sc = usbd_xfer_softc(xfer);
785	struct ifnet *ifp = sc->sc_ifp;
786	struct ieee80211vap *vap;
787	struct ural_tx_data *data;
788	struct mbuf *m;
789	struct usb_page_cache *pc;
790	int len;
791
792	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
793
794	switch (USB_GET_STATE(xfer)) {
795	case USB_ST_TRANSFERRED:
796		DPRINTFN(11, "transfer complete, %d bytes\n", len);
797
798		/* free resources */
799		data = usbd_xfer_get_priv(xfer);
800		ural_tx_free(data, 0);
801		usbd_xfer_set_priv(xfer, NULL);
802
803		ifp->if_opackets++;
804		ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
805
806		/* FALLTHROUGH */
807	case USB_ST_SETUP:
808tr_setup:
809		data = STAILQ_FIRST(&sc->tx_q);
810		if (data) {
811			STAILQ_REMOVE_HEAD(&sc->tx_q, next);
812			m = data->m;
813
814			if (m->m_pkthdr.len > (int)(RAL_FRAME_SIZE + RAL_TX_DESC_SIZE)) {
815				DPRINTFN(0, "data overflow, %u bytes\n",
816				    m->m_pkthdr.len);
817				m->m_pkthdr.len = (RAL_FRAME_SIZE + RAL_TX_DESC_SIZE);
818			}
819			pc = usbd_xfer_get_frame(xfer, 0);
820			usbd_copy_in(pc, 0, &data->desc, RAL_TX_DESC_SIZE);
821			usbd_m_copy_in(pc, RAL_TX_DESC_SIZE, m, 0,
822			    m->m_pkthdr.len);
823
824			vap = data->ni->ni_vap;
825			if (ieee80211_radiotap_active_vap(vap)) {
826				struct ural_tx_radiotap_header *tap = &sc->sc_txtap;
827
828				tap->wt_flags = 0;
829				tap->wt_rate = data->rate;
830				tap->wt_antenna = sc->tx_ant;
831
832				ieee80211_radiotap_tx(vap, m);
833			}
834
835			/* xfer length needs to be a multiple of two! */
836			len = (RAL_TX_DESC_SIZE + m->m_pkthdr.len + 1) & ~1;
837			if ((len % 64) == 0)
838				len += 2;
839
840			DPRINTFN(11, "sending frame len=%u xferlen=%u\n",
841			    m->m_pkthdr.len, len);
842
843			usbd_xfer_set_frame_len(xfer, 0, len);
844			usbd_xfer_set_priv(xfer, data);
845
846			usbd_transfer_submit(xfer);
847		}
848		RAL_UNLOCK(sc);
849		ural_start(ifp);
850		RAL_LOCK(sc);
851		break;
852
853	default:			/* Error */
854		DPRINTFN(11, "transfer error, %s\n",
855		    usbd_errstr(error));
856
857		ifp->if_oerrors++;
858		data = usbd_xfer_get_priv(xfer);
859		if (data != NULL) {
860			ural_tx_free(data, error);
861			usbd_xfer_set_priv(xfer, NULL);
862		}
863
864		if (error == USB_ERR_STALLED) {
865			/* try to clear stall first */
866			usbd_xfer_set_stall(xfer);
867			goto tr_setup;
868		}
869		if (error == USB_ERR_TIMEOUT)
870			device_printf(sc->sc_dev, "device timeout\n");
871		break;
872	}
873}
874
875static void
876ural_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
877{
878	struct ural_softc *sc = usbd_xfer_softc(xfer);
879	struct ifnet *ifp = sc->sc_ifp;
880	struct ieee80211com *ic = ifp->if_l2com;
881	struct ieee80211_node *ni;
882	struct mbuf *m = NULL;
883	struct usb_page_cache *pc;
884	uint32_t flags;
885	int8_t rssi = 0, nf = 0;
886	int len;
887
888	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
889
890	switch (USB_GET_STATE(xfer)) {
891	case USB_ST_TRANSFERRED:
892
893		DPRINTFN(15, "rx done, actlen=%d\n", len);
894
895		if (len < (int)(RAL_RX_DESC_SIZE + IEEE80211_MIN_LEN)) {
896			DPRINTF("%s: xfer too short %d\n",
897			    device_get_nameunit(sc->sc_dev), len);
898			ifp->if_ierrors++;
899			goto tr_setup;
900		}
901
902		len -= RAL_RX_DESC_SIZE;
903		/* rx descriptor is located at the end */
904		pc = usbd_xfer_get_frame(xfer, 0);
905		usbd_copy_out(pc, len, &sc->sc_rx_desc, RAL_RX_DESC_SIZE);
906
907		rssi = URAL_RSSI(sc->sc_rx_desc.rssi);
908		nf = RAL_NOISE_FLOOR;
909		flags = le32toh(sc->sc_rx_desc.flags);
910		if (flags & (RAL_RX_PHY_ERROR | RAL_RX_CRC_ERROR)) {
911			/*
912		         * This should not happen since we did not
913		         * request to receive those frames when we
914		         * filled RAL_TXRX_CSR2:
915		         */
916			DPRINTFN(5, "PHY or CRC error\n");
917			ifp->if_ierrors++;
918			goto tr_setup;
919		}
920
921		m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
922		if (m == NULL) {
923			DPRINTF("could not allocate mbuf\n");
924			ifp->if_ierrors++;
925			goto tr_setup;
926		}
927		usbd_copy_out(pc, 0, mtod(m, uint8_t *), len);
928
929		/* finalize mbuf */
930		m->m_pkthdr.rcvif = ifp;
931		m->m_pkthdr.len = m->m_len = (flags >> 16) & 0xfff;
932
933		if (ieee80211_radiotap_active(ic)) {
934			struct ural_rx_radiotap_header *tap = &sc->sc_rxtap;
935
936			/* XXX set once */
937			tap->wr_flags = 0;
938			tap->wr_rate = ieee80211_plcp2rate(sc->sc_rx_desc.rate,
939			    (flags & RAL_RX_OFDM) ?
940			    IEEE80211_T_OFDM : IEEE80211_T_CCK);
941			tap->wr_antenna = sc->rx_ant;
942			tap->wr_antsignal = nf + rssi;
943			tap->wr_antnoise = nf;
944		}
945		/* Strip trailing 802.11 MAC FCS. */
946		m_adj(m, -IEEE80211_CRC_LEN);
947
948		/* FALLTHROUGH */
949	case USB_ST_SETUP:
950tr_setup:
951		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
952		usbd_transfer_submit(xfer);
953
954		/*
955		 * At the end of a USB callback it is always safe to unlock
956		 * the private mutex of a device! That is why we do the
957		 * "ieee80211_input" here, and not some lines up!
958		 */
959		RAL_UNLOCK(sc);
960		if (m) {
961			ni = ieee80211_find_rxnode(ic,
962			    mtod(m, struct ieee80211_frame_min *));
963			if (ni != NULL) {
964				(void) ieee80211_input(ni, m, rssi, nf);
965				ieee80211_free_node(ni);
966			} else
967				(void) ieee80211_input_all(ic, m, rssi, nf);
968		}
969		if ((ifp->if_drv_flags & IFF_DRV_OACTIVE) == 0 &&
970		    !IFQ_IS_EMPTY(&ifp->if_snd))
971			ural_start(ifp);
972		RAL_LOCK(sc);
973		return;
974
975	default:			/* Error */
976		if (error != USB_ERR_CANCELLED) {
977			/* try to clear stall first */
978			usbd_xfer_set_stall(xfer);
979			goto tr_setup;
980		}
981		return;
982	}
983}
984
985static uint8_t
986ural_plcp_signal(int rate)
987{
988	switch (rate) {
989	/* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
990	case 12:	return 0xb;
991	case 18:	return 0xf;
992	case 24:	return 0xa;
993	case 36:	return 0xe;
994	case 48:	return 0x9;
995	case 72:	return 0xd;
996	case 96:	return 0x8;
997	case 108:	return 0xc;
998
999	/* CCK rates (NB: not IEEE std, device-specific) */
1000	case 2:		return 0x0;
1001	case 4:		return 0x1;
1002	case 11:	return 0x2;
1003	case 22:	return 0x3;
1004	}
1005	return 0xff;		/* XXX unsupported/unknown rate */
1006}
1007
1008static void
1009ural_setup_tx_desc(struct ural_softc *sc, struct ural_tx_desc *desc,
1010    uint32_t flags, int len, int rate)
1011{
1012	struct ifnet *ifp = sc->sc_ifp;
1013	struct ieee80211com *ic = ifp->if_l2com;
1014	uint16_t plcp_length;
1015	int remainder;
1016
1017	desc->flags = htole32(flags);
1018	desc->flags |= htole32(RAL_TX_NEWSEQ);
1019	desc->flags |= htole32(len << 16);
1020
1021	desc->wme = htole16(RAL_AIFSN(2) | RAL_LOGCWMIN(3) | RAL_LOGCWMAX(5));
1022	desc->wme |= htole16(RAL_IVOFFSET(sizeof (struct ieee80211_frame)));
1023
1024	/* setup PLCP fields */
1025	desc->plcp_signal  = ural_plcp_signal(rate);
1026	desc->plcp_service = 4;
1027
1028	len += IEEE80211_CRC_LEN;
1029	if (ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM) {
1030		desc->flags |= htole32(RAL_TX_OFDM);
1031
1032		plcp_length = len & 0xfff;
1033		desc->plcp_length_hi = plcp_length >> 6;
1034		desc->plcp_length_lo = plcp_length & 0x3f;
1035	} else {
1036		plcp_length = (16 * len + rate - 1) / rate;
1037		if (rate == 22) {
1038			remainder = (16 * len) % 22;
1039			if (remainder != 0 && remainder < 7)
1040				desc->plcp_service |= RAL_PLCP_LENGEXT;
1041		}
1042		desc->plcp_length_hi = plcp_length >> 8;
1043		desc->plcp_length_lo = plcp_length & 0xff;
1044
1045		if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1046			desc->plcp_signal |= 0x08;
1047	}
1048
1049	desc->iv = 0;
1050	desc->eiv = 0;
1051}
1052
1053#define RAL_TX_TIMEOUT	5000
1054
1055static int
1056ural_tx_bcn(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1057{
1058	struct ieee80211vap *vap = ni->ni_vap;
1059	struct ieee80211com *ic = ni->ni_ic;
1060	struct ifnet *ifp = sc->sc_ifp;
1061	const struct ieee80211_txparam *tp;
1062	struct ural_tx_data *data;
1063
1064	if (sc->tx_nfree == 0) {
1065		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1066		m_freem(m0);
1067		ieee80211_free_node(ni);
1068		return (EIO);
1069	}
1070	if (ic->ic_bsschan == IEEE80211_CHAN_ANYC) {
1071		m_freem(m0);
1072		ieee80211_free_node(ni);
1073		return (ENXIO);
1074	}
1075	data = STAILQ_FIRST(&sc->tx_free);
1076	STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1077	sc->tx_nfree--;
1078	tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_bsschan)];
1079
1080	data->m = m0;
1081	data->ni = ni;
1082	data->rate = tp->mgmtrate;
1083
1084	ural_setup_tx_desc(sc, &data->desc,
1085	    RAL_TX_IFS_NEWBACKOFF | RAL_TX_TIMESTAMP, m0->m_pkthdr.len,
1086	    tp->mgmtrate);
1087
1088	DPRINTFN(10, "sending beacon frame len=%u rate=%u\n",
1089	    m0->m_pkthdr.len, tp->mgmtrate);
1090
1091	STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1092	usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1093
1094	return (0);
1095}
1096
1097static int
1098ural_tx_mgt(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1099{
1100	struct ieee80211vap *vap = ni->ni_vap;
1101	struct ieee80211com *ic = ni->ni_ic;
1102	const struct ieee80211_txparam *tp;
1103	struct ural_tx_data *data;
1104	struct ieee80211_frame *wh;
1105	struct ieee80211_key *k;
1106	uint32_t flags;
1107	uint16_t dur;
1108
1109	RAL_LOCK_ASSERT(sc, MA_OWNED);
1110
1111	data = STAILQ_FIRST(&sc->tx_free);
1112	STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1113	sc->tx_nfree--;
1114
1115	tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
1116
1117	wh = mtod(m0, struct ieee80211_frame *);
1118	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1119		k = ieee80211_crypto_encap(ni, m0);
1120		if (k == NULL) {
1121			m_freem(m0);
1122			return ENOBUFS;
1123		}
1124		wh = mtod(m0, struct ieee80211_frame *);
1125	}
1126
1127	data->m = m0;
1128	data->ni = ni;
1129	data->rate = tp->mgmtrate;
1130
1131	flags = 0;
1132	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1133		flags |= RAL_TX_ACK;
1134
1135		dur = ieee80211_ack_duration(ic->ic_rt, tp->mgmtrate,
1136		    ic->ic_flags & IEEE80211_F_SHPREAMBLE);
1137		*(uint16_t *)wh->i_dur = htole16(dur);
1138
1139		/* tell hardware to add timestamp for probe responses */
1140		if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
1141		    IEEE80211_FC0_TYPE_MGT &&
1142		    (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
1143		    IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1144			flags |= RAL_TX_TIMESTAMP;
1145	}
1146
1147	ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, tp->mgmtrate);
1148
1149	DPRINTFN(10, "sending mgt frame len=%u rate=%u\n",
1150	    m0->m_pkthdr.len, tp->mgmtrate);
1151
1152	STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1153	usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1154
1155	return 0;
1156}
1157
1158static int
1159ural_sendprot(struct ural_softc *sc,
1160    const struct mbuf *m, struct ieee80211_node *ni, int prot, int rate)
1161{
1162	struct ieee80211com *ic = ni->ni_ic;
1163	const struct ieee80211_frame *wh;
1164	struct ural_tx_data *data;
1165	struct mbuf *mprot;
1166	int protrate, ackrate, pktlen, flags, isshort;
1167	uint16_t dur;
1168
1169	KASSERT(prot == IEEE80211_PROT_RTSCTS || prot == IEEE80211_PROT_CTSONLY,
1170	    ("protection %d", prot));
1171
1172	wh = mtod(m, const struct ieee80211_frame *);
1173	pktlen = m->m_pkthdr.len + IEEE80211_CRC_LEN;
1174
1175	protrate = ieee80211_ctl_rate(ic->ic_rt, rate);
1176	ackrate = ieee80211_ack_rate(ic->ic_rt, rate);
1177
1178	isshort = (ic->ic_flags & IEEE80211_F_SHPREAMBLE) != 0;
1179	dur = ieee80211_compute_duration(ic->ic_rt, pktlen, rate, isshort)
1180	    + ieee80211_ack_duration(ic->ic_rt, rate, isshort);
1181	flags = RAL_TX_RETRY(7);
1182	if (prot == IEEE80211_PROT_RTSCTS) {
1183		/* NB: CTS is the same size as an ACK */
1184		dur += ieee80211_ack_duration(ic->ic_rt, rate, isshort);
1185		flags |= RAL_TX_ACK;
1186		mprot = ieee80211_alloc_rts(ic, wh->i_addr1, wh->i_addr2, dur);
1187	} else {
1188		mprot = ieee80211_alloc_cts(ic, ni->ni_vap->iv_myaddr, dur);
1189	}
1190	if (mprot == NULL) {
1191		/* XXX stat + msg */
1192		return ENOBUFS;
1193	}
1194	data = STAILQ_FIRST(&sc->tx_free);
1195	STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1196	sc->tx_nfree--;
1197
1198	data->m = mprot;
1199	data->ni = ieee80211_ref_node(ni);
1200	data->rate = protrate;
1201	ural_setup_tx_desc(sc, &data->desc, flags, mprot->m_pkthdr.len, protrate);
1202
1203	STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1204	usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1205
1206	return 0;
1207}
1208
1209static int
1210ural_tx_raw(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni,
1211    const struct ieee80211_bpf_params *params)
1212{
1213	struct ieee80211com *ic = ni->ni_ic;
1214	struct ural_tx_data *data;
1215	uint32_t flags;
1216	int error;
1217	int rate;
1218
1219	RAL_LOCK_ASSERT(sc, MA_OWNED);
1220	KASSERT(params != NULL, ("no raw xmit params"));
1221
1222	rate = params->ibp_rate0;
1223	if (!ieee80211_isratevalid(ic->ic_rt, rate)) {
1224		m_freem(m0);
1225		return EINVAL;
1226	}
1227	flags = 0;
1228	if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
1229		flags |= RAL_TX_ACK;
1230	if (params->ibp_flags & (IEEE80211_BPF_RTS|IEEE80211_BPF_CTS)) {
1231		error = ural_sendprot(sc, m0, ni,
1232		    params->ibp_flags & IEEE80211_BPF_RTS ?
1233			 IEEE80211_PROT_RTSCTS : IEEE80211_PROT_CTSONLY,
1234		    rate);
1235		if (error || sc->tx_nfree == 0) {
1236			m_freem(m0);
1237			return ENOBUFS;
1238		}
1239		flags |= RAL_TX_IFS_SIFS;
1240	}
1241
1242	data = STAILQ_FIRST(&sc->tx_free);
1243	STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1244	sc->tx_nfree--;
1245
1246	data->m = m0;
1247	data->ni = ni;
1248	data->rate = rate;
1249
1250	/* XXX need to setup descriptor ourself */
1251	ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, rate);
1252
1253	DPRINTFN(10, "sending raw frame len=%u rate=%u\n",
1254	    m0->m_pkthdr.len, rate);
1255
1256	STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1257	usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1258
1259	return 0;
1260}
1261
1262static int
1263ural_tx_data(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1264{
1265	struct ieee80211vap *vap = ni->ni_vap;
1266	struct ieee80211com *ic = ni->ni_ic;
1267	struct ural_tx_data *data;
1268	struct ieee80211_frame *wh;
1269	const struct ieee80211_txparam *tp;
1270	struct ieee80211_key *k;
1271	uint32_t flags = 0;
1272	uint16_t dur;
1273	int error, rate;
1274
1275	RAL_LOCK_ASSERT(sc, MA_OWNED);
1276
1277	wh = mtod(m0, struct ieee80211_frame *);
1278
1279	tp = &vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)];
1280	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
1281		rate = tp->mcastrate;
1282	else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
1283		rate = tp->ucastrate;
1284	else
1285		rate = ni->ni_txrate;
1286
1287	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1288		k = ieee80211_crypto_encap(ni, m0);
1289		if (k == NULL) {
1290			m_freem(m0);
1291			return ENOBUFS;
1292		}
1293		/* packet header may have moved, reset our local pointer */
1294		wh = mtod(m0, struct ieee80211_frame *);
1295	}
1296
1297	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1298		int prot = IEEE80211_PROT_NONE;
1299		if (m0->m_pkthdr.len + IEEE80211_CRC_LEN > vap->iv_rtsthreshold)
1300			prot = IEEE80211_PROT_RTSCTS;
1301		else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
1302		    ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM)
1303			prot = ic->ic_protmode;
1304		if (prot != IEEE80211_PROT_NONE) {
1305			error = ural_sendprot(sc, m0, ni, prot, rate);
1306			if (error || sc->tx_nfree == 0) {
1307				m_freem(m0);
1308				return ENOBUFS;
1309			}
1310			flags |= RAL_TX_IFS_SIFS;
1311		}
1312	}
1313
1314	data = STAILQ_FIRST(&sc->tx_free);
1315	STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1316	sc->tx_nfree--;
1317
1318	data->m = m0;
1319	data->ni = ni;
1320	data->rate = rate;
1321
1322	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1323		flags |= RAL_TX_ACK;
1324		flags |= RAL_TX_RETRY(7);
1325
1326		dur = ieee80211_ack_duration(ic->ic_rt, rate,
1327		    ic->ic_flags & IEEE80211_F_SHPREAMBLE);
1328		*(uint16_t *)wh->i_dur = htole16(dur);
1329	}
1330
1331	ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, rate);
1332
1333	DPRINTFN(10, "sending data frame len=%u rate=%u\n",
1334	    m0->m_pkthdr.len, rate);
1335
1336	STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1337	usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1338
1339	return 0;
1340}
1341
1342static void
1343ural_start(struct ifnet *ifp)
1344{
1345	struct ural_softc *sc = ifp->if_softc;
1346	struct ieee80211_node *ni;
1347	struct mbuf *m;
1348
1349	RAL_LOCK(sc);
1350	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1351		RAL_UNLOCK(sc);
1352		return;
1353	}
1354	for (;;) {
1355		IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
1356		if (m == NULL)
1357			break;
1358		if (sc->tx_nfree < RAL_TX_MINFREE) {
1359			IFQ_DRV_PREPEND(&ifp->if_snd, m);
1360			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1361			break;
1362		}
1363		ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1364		if (ural_tx_data(sc, m, ni) != 0) {
1365			ieee80211_free_node(ni);
1366			ifp->if_oerrors++;
1367			break;
1368		}
1369	}
1370	RAL_UNLOCK(sc);
1371}
1372
1373static int
1374ural_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1375{
1376	struct ural_softc *sc = ifp->if_softc;
1377	struct ieee80211com *ic = ifp->if_l2com;
1378	struct ifreq *ifr = (struct ifreq *) data;
1379	int error;
1380	int startall = 0;
1381
1382	RAL_LOCK(sc);
1383	error = sc->sc_detached ? ENXIO : 0;
1384	RAL_UNLOCK(sc);
1385	if (error)
1386		return (error);
1387
1388	switch (cmd) {
1389	case SIOCSIFFLAGS:
1390		RAL_LOCK(sc);
1391		if (ifp->if_flags & IFF_UP) {
1392			if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1393				ural_init_locked(sc);
1394				startall = 1;
1395			} else
1396				ural_setpromisc(sc);
1397		} else {
1398			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1399				ural_stop(sc);
1400		}
1401		RAL_UNLOCK(sc);
1402		if (startall)
1403			ieee80211_start_all(ic);
1404		break;
1405	case SIOCGIFMEDIA:
1406	case SIOCSIFMEDIA:
1407		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
1408		break;
1409	default:
1410		error = ether_ioctl(ifp, cmd, data);
1411		break;
1412	}
1413	return error;
1414}
1415
1416static void
1417ural_set_testmode(struct ural_softc *sc)
1418{
1419	struct usb_device_request req;
1420	usb_error_t error;
1421
1422	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1423	req.bRequest = RAL_VENDOR_REQUEST;
1424	USETW(req.wValue, 4);
1425	USETW(req.wIndex, 1);
1426	USETW(req.wLength, 0);
1427
1428	error = ural_do_request(sc, &req, NULL);
1429	if (error != 0) {
1430		device_printf(sc->sc_dev, "could not set test mode: %s\n",
1431		    usbd_errstr(error));
1432	}
1433}
1434
1435static void
1436ural_eeprom_read(struct ural_softc *sc, uint16_t addr, void *buf, int len)
1437{
1438	struct usb_device_request req;
1439	usb_error_t error;
1440
1441	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1442	req.bRequest = RAL_READ_EEPROM;
1443	USETW(req.wValue, 0);
1444	USETW(req.wIndex, addr);
1445	USETW(req.wLength, len);
1446
1447	error = ural_do_request(sc, &req, buf);
1448	if (error != 0) {
1449		device_printf(sc->sc_dev, "could not read EEPROM: %s\n",
1450		    usbd_errstr(error));
1451	}
1452}
1453
1454static uint16_t
1455ural_read(struct ural_softc *sc, uint16_t reg)
1456{
1457	struct usb_device_request req;
1458	usb_error_t error;
1459	uint16_t val;
1460
1461	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1462	req.bRequest = RAL_READ_MAC;
1463	USETW(req.wValue, 0);
1464	USETW(req.wIndex, reg);
1465	USETW(req.wLength, sizeof (uint16_t));
1466
1467	error = ural_do_request(sc, &req, &val);
1468	if (error != 0) {
1469		device_printf(sc->sc_dev, "could not read MAC register: %s\n",
1470		    usbd_errstr(error));
1471		return 0;
1472	}
1473
1474	return le16toh(val);
1475}
1476
1477static void
1478ural_read_multi(struct ural_softc *sc, uint16_t reg, void *buf, int len)
1479{
1480	struct usb_device_request req;
1481	usb_error_t error;
1482
1483	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1484	req.bRequest = RAL_READ_MULTI_MAC;
1485	USETW(req.wValue, 0);
1486	USETW(req.wIndex, reg);
1487	USETW(req.wLength, len);
1488
1489	error = ural_do_request(sc, &req, buf);
1490	if (error != 0) {
1491		device_printf(sc->sc_dev, "could not read MAC register: %s\n",
1492		    usbd_errstr(error));
1493	}
1494}
1495
1496static void
1497ural_write(struct ural_softc *sc, uint16_t reg, uint16_t val)
1498{
1499	struct usb_device_request req;
1500	usb_error_t error;
1501
1502	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1503	req.bRequest = RAL_WRITE_MAC;
1504	USETW(req.wValue, val);
1505	USETW(req.wIndex, reg);
1506	USETW(req.wLength, 0);
1507
1508	error = ural_do_request(sc, &req, NULL);
1509	if (error != 0) {
1510		device_printf(sc->sc_dev, "could not write MAC register: %s\n",
1511		    usbd_errstr(error));
1512	}
1513}
1514
1515static void
1516ural_write_multi(struct ural_softc *sc, uint16_t reg, void *buf, int len)
1517{
1518	struct usb_device_request req;
1519	usb_error_t error;
1520
1521	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1522	req.bRequest = RAL_WRITE_MULTI_MAC;
1523	USETW(req.wValue, 0);
1524	USETW(req.wIndex, reg);
1525	USETW(req.wLength, len);
1526
1527	error = ural_do_request(sc, &req, buf);
1528	if (error != 0) {
1529		device_printf(sc->sc_dev, "could not write MAC register: %s\n",
1530		    usbd_errstr(error));
1531	}
1532}
1533
1534static void
1535ural_bbp_write(struct ural_softc *sc, uint8_t reg, uint8_t val)
1536{
1537	uint16_t tmp;
1538	int ntries;
1539
1540	for (ntries = 0; ntries < 100; ntries++) {
1541		if (!(ural_read(sc, RAL_PHY_CSR8) & RAL_BBP_BUSY))
1542			break;
1543		if (ural_pause(sc, hz / 100))
1544			break;
1545	}
1546	if (ntries == 100) {
1547		device_printf(sc->sc_dev, "could not write to BBP\n");
1548		return;
1549	}
1550
1551	tmp = reg << 8 | val;
1552	ural_write(sc, RAL_PHY_CSR7, tmp);
1553}
1554
1555static uint8_t
1556ural_bbp_read(struct ural_softc *sc, uint8_t reg)
1557{
1558	uint16_t val;
1559	int ntries;
1560
1561	val = RAL_BBP_WRITE | reg << 8;
1562	ural_write(sc, RAL_PHY_CSR7, val);
1563
1564	for (ntries = 0; ntries < 100; ntries++) {
1565		if (!(ural_read(sc, RAL_PHY_CSR8) & RAL_BBP_BUSY))
1566			break;
1567		if (ural_pause(sc, hz / 100))
1568			break;
1569	}
1570	if (ntries == 100) {
1571		device_printf(sc->sc_dev, "could not read BBP\n");
1572		return 0;
1573	}
1574
1575	return ural_read(sc, RAL_PHY_CSR7) & 0xff;
1576}
1577
1578static void
1579ural_rf_write(struct ural_softc *sc, uint8_t reg, uint32_t val)
1580{
1581	uint32_t tmp;
1582	int ntries;
1583
1584	for (ntries = 0; ntries < 100; ntries++) {
1585		if (!(ural_read(sc, RAL_PHY_CSR10) & RAL_RF_LOBUSY))
1586			break;
1587		if (ural_pause(sc, hz / 100))
1588			break;
1589	}
1590	if (ntries == 100) {
1591		device_printf(sc->sc_dev, "could not write to RF\n");
1592		return;
1593	}
1594
1595	tmp = RAL_RF_BUSY | RAL_RF_20BIT | (val & 0xfffff) << 2 | (reg & 0x3);
1596	ural_write(sc, RAL_PHY_CSR9,  tmp & 0xffff);
1597	ural_write(sc, RAL_PHY_CSR10, tmp >> 16);
1598
1599	/* remember last written value in sc */
1600	sc->rf_regs[reg] = val;
1601
1602	DPRINTFN(15, "RF R[%u] <- 0x%05x\n", reg & 0x3, val & 0xfffff);
1603}
1604
1605static void
1606ural_scan_start(struct ieee80211com *ic)
1607{
1608	struct ifnet *ifp = ic->ic_ifp;
1609	struct ural_softc *sc = ifp->if_softc;
1610
1611	RAL_LOCK(sc);
1612	ural_write(sc, RAL_TXRX_CSR19, 0);
1613	ural_set_bssid(sc, ifp->if_broadcastaddr);
1614	RAL_UNLOCK(sc);
1615}
1616
1617static void
1618ural_scan_end(struct ieee80211com *ic)
1619{
1620	struct ural_softc *sc = ic->ic_ifp->if_softc;
1621
1622	RAL_LOCK(sc);
1623	ural_enable_tsf_sync(sc);
1624	ural_set_bssid(sc, sc->sc_bssid);
1625	RAL_UNLOCK(sc);
1626
1627}
1628
1629static void
1630ural_set_channel(struct ieee80211com *ic)
1631{
1632	struct ural_softc *sc = ic->ic_ifp->if_softc;
1633
1634	RAL_LOCK(sc);
1635	ural_set_chan(sc, ic->ic_curchan);
1636	RAL_UNLOCK(sc);
1637}
1638
1639static void
1640ural_set_chan(struct ural_softc *sc, struct ieee80211_channel *c)
1641{
1642	struct ifnet *ifp = sc->sc_ifp;
1643	struct ieee80211com *ic = ifp->if_l2com;
1644	uint8_t power, tmp;
1645	int i, chan;
1646
1647	chan = ieee80211_chan2ieee(ic, c);
1648	if (chan == 0 || chan == IEEE80211_CHAN_ANY)
1649		return;
1650
1651	if (IEEE80211_IS_CHAN_2GHZ(c))
1652		power = min(sc->txpow[chan - 1], 31);
1653	else
1654		power = 31;
1655
1656	/* adjust txpower using ifconfig settings */
1657	power -= (100 - ic->ic_txpowlimit) / 8;
1658
1659	DPRINTFN(2, "setting channel to %u, txpower to %u\n", chan, power);
1660
1661	switch (sc->rf_rev) {
1662	case RAL_RF_2522:
1663		ural_rf_write(sc, RAL_RF1, 0x00814);
1664		ural_rf_write(sc, RAL_RF2, ural_rf2522_r2[chan - 1]);
1665		ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1666		break;
1667
1668	case RAL_RF_2523:
1669		ural_rf_write(sc, RAL_RF1, 0x08804);
1670		ural_rf_write(sc, RAL_RF2, ural_rf2523_r2[chan - 1]);
1671		ural_rf_write(sc, RAL_RF3, power << 7 | 0x38044);
1672		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1673		break;
1674
1675	case RAL_RF_2524:
1676		ural_rf_write(sc, RAL_RF1, 0x0c808);
1677		ural_rf_write(sc, RAL_RF2, ural_rf2524_r2[chan - 1]);
1678		ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1679		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1680		break;
1681
1682	case RAL_RF_2525:
1683		ural_rf_write(sc, RAL_RF1, 0x08808);
1684		ural_rf_write(sc, RAL_RF2, ural_rf2525_hi_r2[chan - 1]);
1685		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1686		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1687
1688		ural_rf_write(sc, RAL_RF1, 0x08808);
1689		ural_rf_write(sc, RAL_RF2, ural_rf2525_r2[chan - 1]);
1690		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1691		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1692		break;
1693
1694	case RAL_RF_2525E:
1695		ural_rf_write(sc, RAL_RF1, 0x08808);
1696		ural_rf_write(sc, RAL_RF2, ural_rf2525e_r2[chan - 1]);
1697		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1698		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00286 : 0x00282);
1699		break;
1700
1701	case RAL_RF_2526:
1702		ural_rf_write(sc, RAL_RF2, ural_rf2526_hi_r2[chan - 1]);
1703		ural_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381);
1704		ural_rf_write(sc, RAL_RF1, 0x08804);
1705
1706		ural_rf_write(sc, RAL_RF2, ural_rf2526_r2[chan - 1]);
1707		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1708		ural_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381);
1709		break;
1710
1711	/* dual-band RF */
1712	case RAL_RF_5222:
1713		for (i = 0; ural_rf5222[i].chan != chan; i++);
1714
1715		ural_rf_write(sc, RAL_RF1, ural_rf5222[i].r1);
1716		ural_rf_write(sc, RAL_RF2, ural_rf5222[i].r2);
1717		ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1718		ural_rf_write(sc, RAL_RF4, ural_rf5222[i].r4);
1719		break;
1720	}
1721
1722	if (ic->ic_opmode != IEEE80211_M_MONITOR &&
1723	    (ic->ic_flags & IEEE80211_F_SCAN) == 0) {
1724		/* set Japan filter bit for channel 14 */
1725		tmp = ural_bbp_read(sc, 70);
1726
1727		tmp &= ~RAL_JAPAN_FILTER;
1728		if (chan == 14)
1729			tmp |= RAL_JAPAN_FILTER;
1730
1731		ural_bbp_write(sc, 70, tmp);
1732
1733		/* clear CRC errors */
1734		ural_read(sc, RAL_STA_CSR0);
1735
1736		ural_pause(sc, hz / 100);
1737		ural_disable_rf_tune(sc);
1738	}
1739
1740	/* XXX doesn't belong here */
1741	/* update basic rate set */
1742	ural_set_basicrates(sc, c);
1743
1744	/* give the hardware some time to do the switchover */
1745	ural_pause(sc, hz / 100);
1746}
1747
1748/*
1749 * Disable RF auto-tuning.
1750 */
1751static void
1752ural_disable_rf_tune(struct ural_softc *sc)
1753{
1754	uint32_t tmp;
1755
1756	if (sc->rf_rev != RAL_RF_2523) {
1757		tmp = sc->rf_regs[RAL_RF1] & ~RAL_RF1_AUTOTUNE;
1758		ural_rf_write(sc, RAL_RF1, tmp);
1759	}
1760
1761	tmp = sc->rf_regs[RAL_RF3] & ~RAL_RF3_AUTOTUNE;
1762	ural_rf_write(sc, RAL_RF3, tmp);
1763
1764	DPRINTFN(2, "disabling RF autotune\n");
1765}
1766
1767/*
1768 * Refer to IEEE Std 802.11-1999 pp. 123 for more information on TSF
1769 * synchronization.
1770 */
1771static void
1772ural_enable_tsf_sync(struct ural_softc *sc)
1773{
1774	struct ifnet *ifp = sc->sc_ifp;
1775	struct ieee80211com *ic = ifp->if_l2com;
1776	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1777	uint16_t logcwmin, preload, tmp;
1778
1779	/* first, disable TSF synchronization */
1780	ural_write(sc, RAL_TXRX_CSR19, 0);
1781
1782	tmp = (16 * vap->iv_bss->ni_intval) << 4;
1783	ural_write(sc, RAL_TXRX_CSR18, tmp);
1784
1785	logcwmin = (ic->ic_opmode == IEEE80211_M_IBSS) ? 2 : 0;
1786	preload = (ic->ic_opmode == IEEE80211_M_IBSS) ? 320 : 6;
1787	tmp = logcwmin << 12 | preload;
1788	ural_write(sc, RAL_TXRX_CSR20, tmp);
1789
1790	/* finally, enable TSF synchronization */
1791	tmp = RAL_ENABLE_TSF | RAL_ENABLE_TBCN;
1792	if (ic->ic_opmode == IEEE80211_M_STA)
1793		tmp |= RAL_ENABLE_TSF_SYNC(1);
1794	else
1795		tmp |= RAL_ENABLE_TSF_SYNC(2) | RAL_ENABLE_BEACON_GENERATOR;
1796	ural_write(sc, RAL_TXRX_CSR19, tmp);
1797
1798	DPRINTF("enabling TSF synchronization\n");
1799}
1800
1801static void
1802ural_enable_tsf(struct ural_softc *sc)
1803{
1804	/* first, disable TSF synchronization */
1805	ural_write(sc, RAL_TXRX_CSR19, 0);
1806	ural_write(sc, RAL_TXRX_CSR19, RAL_ENABLE_TSF | RAL_ENABLE_TSF_SYNC(2));
1807}
1808
1809#define RAL_RXTX_TURNAROUND	5	/* us */
1810static void
1811ural_update_slot(struct ifnet *ifp)
1812{
1813	struct ural_softc *sc = ifp->if_softc;
1814	struct ieee80211com *ic = ifp->if_l2com;
1815	uint16_t slottime, sifs, eifs;
1816
1817	slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
1818
1819	/*
1820	 * These settings may sound a bit inconsistent but this is what the
1821	 * reference driver does.
1822	 */
1823	if (ic->ic_curmode == IEEE80211_MODE_11B) {
1824		sifs = 16 - RAL_RXTX_TURNAROUND;
1825		eifs = 364;
1826	} else {
1827		sifs = 10 - RAL_RXTX_TURNAROUND;
1828		eifs = 64;
1829	}
1830
1831	ural_write(sc, RAL_MAC_CSR10, slottime);
1832	ural_write(sc, RAL_MAC_CSR11, sifs);
1833	ural_write(sc, RAL_MAC_CSR12, eifs);
1834}
1835
1836static void
1837ural_set_txpreamble(struct ural_softc *sc)
1838{
1839	struct ifnet *ifp = sc->sc_ifp;
1840	struct ieee80211com *ic = ifp->if_l2com;
1841	uint16_t tmp;
1842
1843	tmp = ural_read(sc, RAL_TXRX_CSR10);
1844
1845	tmp &= ~RAL_SHORT_PREAMBLE;
1846	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
1847		tmp |= RAL_SHORT_PREAMBLE;
1848
1849	ural_write(sc, RAL_TXRX_CSR10, tmp);
1850}
1851
1852static void
1853ural_set_basicrates(struct ural_softc *sc, const struct ieee80211_channel *c)
1854{
1855	/* XXX wrong, take from rate set */
1856	/* update basic rate set */
1857	if (IEEE80211_IS_CHAN_5GHZ(c)) {
1858		/* 11a basic rates: 6, 12, 24Mbps */
1859		ural_write(sc, RAL_TXRX_CSR11, 0x150);
1860	} else if (IEEE80211_IS_CHAN_ANYG(c)) {
1861		/* 11g basic rates: 1, 2, 5.5, 11, 6, 12, 24Mbps */
1862		ural_write(sc, RAL_TXRX_CSR11, 0x15f);
1863	} else {
1864		/* 11b basic rates: 1, 2Mbps */
1865		ural_write(sc, RAL_TXRX_CSR11, 0x3);
1866	}
1867}
1868
1869static void
1870ural_set_bssid(struct ural_softc *sc, const uint8_t *bssid)
1871{
1872	uint16_t tmp;
1873
1874	tmp = bssid[0] | bssid[1] << 8;
1875	ural_write(sc, RAL_MAC_CSR5, tmp);
1876
1877	tmp = bssid[2] | bssid[3] << 8;
1878	ural_write(sc, RAL_MAC_CSR6, tmp);
1879
1880	tmp = bssid[4] | bssid[5] << 8;
1881	ural_write(sc, RAL_MAC_CSR7, tmp);
1882
1883	DPRINTF("setting BSSID to %6D\n", bssid, ":");
1884}
1885
1886static void
1887ural_set_macaddr(struct ural_softc *sc, uint8_t *addr)
1888{
1889	uint16_t tmp;
1890
1891	tmp = addr[0] | addr[1] << 8;
1892	ural_write(sc, RAL_MAC_CSR2, tmp);
1893
1894	tmp = addr[2] | addr[3] << 8;
1895	ural_write(sc, RAL_MAC_CSR3, tmp);
1896
1897	tmp = addr[4] | addr[5] << 8;
1898	ural_write(sc, RAL_MAC_CSR4, tmp);
1899
1900	DPRINTF("setting MAC address to %6D\n", addr, ":");
1901}
1902
1903static void
1904ural_setpromisc(struct ural_softc *sc)
1905{
1906	struct ifnet *ifp = sc->sc_ifp;
1907	uint32_t tmp;
1908
1909	tmp = ural_read(sc, RAL_TXRX_CSR2);
1910
1911	tmp &= ~RAL_DROP_NOT_TO_ME;
1912	if (!(ifp->if_flags & IFF_PROMISC))
1913		tmp |= RAL_DROP_NOT_TO_ME;
1914
1915	ural_write(sc, RAL_TXRX_CSR2, tmp);
1916
1917	DPRINTF("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
1918	    "entering" : "leaving");
1919}
1920
1921static void
1922ural_update_promisc(struct ifnet *ifp)
1923{
1924	struct ural_softc *sc = ifp->if_softc;
1925
1926	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
1927		return;
1928
1929	RAL_LOCK(sc);
1930	ural_setpromisc(sc);
1931	RAL_UNLOCK(sc);
1932}
1933
1934static const char *
1935ural_get_rf(int rev)
1936{
1937	switch (rev) {
1938	case RAL_RF_2522:	return "RT2522";
1939	case RAL_RF_2523:	return "RT2523";
1940	case RAL_RF_2524:	return "RT2524";
1941	case RAL_RF_2525:	return "RT2525";
1942	case RAL_RF_2525E:	return "RT2525e";
1943	case RAL_RF_2526:	return "RT2526";
1944	case RAL_RF_5222:	return "RT5222";
1945	default:		return "unknown";
1946	}
1947}
1948
1949static void
1950ural_read_eeprom(struct ural_softc *sc)
1951{
1952	uint16_t val;
1953
1954	ural_eeprom_read(sc, RAL_EEPROM_CONFIG0, &val, 2);
1955	val = le16toh(val);
1956	sc->rf_rev =   (val >> 11) & 0x7;
1957	sc->hw_radio = (val >> 10) & 0x1;
1958	sc->led_mode = (val >> 6)  & 0x7;
1959	sc->rx_ant =   (val >> 4)  & 0x3;
1960	sc->tx_ant =   (val >> 2)  & 0x3;
1961	sc->nb_ant =   val & 0x3;
1962
1963	/* read MAC address */
1964	ural_eeprom_read(sc, RAL_EEPROM_ADDRESS, sc->sc_bssid, 6);
1965
1966	/* read default values for BBP registers */
1967	ural_eeprom_read(sc, RAL_EEPROM_BBP_BASE, sc->bbp_prom, 2 * 16);
1968
1969	/* read Tx power for all b/g channels */
1970	ural_eeprom_read(sc, RAL_EEPROM_TXPOWER, sc->txpow, 14);
1971}
1972
1973static int
1974ural_bbp_init(struct ural_softc *sc)
1975{
1976#define N(a)	((int)(sizeof (a) / sizeof ((a)[0])))
1977	int i, ntries;
1978
1979	/* wait for BBP to be ready */
1980	for (ntries = 0; ntries < 100; ntries++) {
1981		if (ural_bbp_read(sc, RAL_BBP_VERSION) != 0)
1982			break;
1983		if (ural_pause(sc, hz / 100))
1984			break;
1985	}
1986	if (ntries == 100) {
1987		device_printf(sc->sc_dev, "timeout waiting for BBP\n");
1988		return EIO;
1989	}
1990
1991	/* initialize BBP registers to default values */
1992	for (i = 0; i < N(ural_def_bbp); i++)
1993		ural_bbp_write(sc, ural_def_bbp[i].reg, ural_def_bbp[i].val);
1994
1995#if 0
1996	/* initialize BBP registers to values stored in EEPROM */
1997	for (i = 0; i < 16; i++) {
1998		if (sc->bbp_prom[i].reg == 0xff)
1999			continue;
2000		ural_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
2001	}
2002#endif
2003
2004	return 0;
2005#undef N
2006}
2007
2008static void
2009ural_set_txantenna(struct ural_softc *sc, int antenna)
2010{
2011	uint16_t tmp;
2012	uint8_t tx;
2013
2014	tx = ural_bbp_read(sc, RAL_BBP_TX) & ~RAL_BBP_ANTMASK;
2015	if (antenna == 1)
2016		tx |= RAL_BBP_ANTA;
2017	else if (antenna == 2)
2018		tx |= RAL_BBP_ANTB;
2019	else
2020		tx |= RAL_BBP_DIVERSITY;
2021
2022	/* need to force I/Q flip for RF 2525e, 2526 and 5222 */
2023	if (sc->rf_rev == RAL_RF_2525E || sc->rf_rev == RAL_RF_2526 ||
2024	    sc->rf_rev == RAL_RF_5222)
2025		tx |= RAL_BBP_FLIPIQ;
2026
2027	ural_bbp_write(sc, RAL_BBP_TX, tx);
2028
2029	/* update values in PHY_CSR5 and PHY_CSR6 */
2030	tmp = ural_read(sc, RAL_PHY_CSR5) & ~0x7;
2031	ural_write(sc, RAL_PHY_CSR5, tmp | (tx & 0x7));
2032
2033	tmp = ural_read(sc, RAL_PHY_CSR6) & ~0x7;
2034	ural_write(sc, RAL_PHY_CSR6, tmp | (tx & 0x7));
2035}
2036
2037static void
2038ural_set_rxantenna(struct ural_softc *sc, int antenna)
2039{
2040	uint8_t rx;
2041
2042	rx = ural_bbp_read(sc, RAL_BBP_RX) & ~RAL_BBP_ANTMASK;
2043	if (antenna == 1)
2044		rx |= RAL_BBP_ANTA;
2045	else if (antenna == 2)
2046		rx |= RAL_BBP_ANTB;
2047	else
2048		rx |= RAL_BBP_DIVERSITY;
2049
2050	/* need to force no I/Q flip for RF 2525e and 2526 */
2051	if (sc->rf_rev == RAL_RF_2525E || sc->rf_rev == RAL_RF_2526)
2052		rx &= ~RAL_BBP_FLIPIQ;
2053
2054	ural_bbp_write(sc, RAL_BBP_RX, rx);
2055}
2056
2057static void
2058ural_init_locked(struct ural_softc *sc)
2059{
2060#define N(a)	((int)(sizeof (a) / sizeof ((a)[0])))
2061	struct ifnet *ifp = sc->sc_ifp;
2062	struct ieee80211com *ic = ifp->if_l2com;
2063	uint16_t tmp;
2064	int i, ntries;
2065
2066	RAL_LOCK_ASSERT(sc, MA_OWNED);
2067
2068	ural_set_testmode(sc);
2069	ural_write(sc, 0x308, 0x00f0);	/* XXX magic */
2070
2071	ural_stop(sc);
2072
2073	/* initialize MAC registers to default values */
2074	for (i = 0; i < N(ural_def_mac); i++)
2075		ural_write(sc, ural_def_mac[i].reg, ural_def_mac[i].val);
2076
2077	/* wait for BBP and RF to wake up (this can take a long time!) */
2078	for (ntries = 0; ntries < 100; ntries++) {
2079		tmp = ural_read(sc, RAL_MAC_CSR17);
2080		if ((tmp & (RAL_BBP_AWAKE | RAL_RF_AWAKE)) ==
2081		    (RAL_BBP_AWAKE | RAL_RF_AWAKE))
2082			break;
2083		if (ural_pause(sc, hz / 100))
2084			break;
2085	}
2086	if (ntries == 100) {
2087		device_printf(sc->sc_dev,
2088		    "timeout waiting for BBP/RF to wakeup\n");
2089		goto fail;
2090	}
2091
2092	/* we're ready! */
2093	ural_write(sc, RAL_MAC_CSR1, RAL_HOST_READY);
2094
2095	/* set basic rate set (will be updated later) */
2096	ural_write(sc, RAL_TXRX_CSR11, 0x15f);
2097
2098	if (ural_bbp_init(sc) != 0)
2099		goto fail;
2100
2101	ural_set_chan(sc, ic->ic_curchan);
2102
2103	/* clear statistic registers (STA_CSR0 to STA_CSR10) */
2104	ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof sc->sta);
2105
2106	ural_set_txantenna(sc, sc->tx_ant);
2107	ural_set_rxantenna(sc, sc->rx_ant);
2108
2109	ural_set_macaddr(sc, IF_LLADDR(ifp));
2110
2111	/*
2112	 * Allocate Tx and Rx xfer queues.
2113	 */
2114	ural_setup_tx_list(sc);
2115
2116	/* kick Rx */
2117	tmp = RAL_DROP_PHY | RAL_DROP_CRC;
2118	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2119		tmp |= RAL_DROP_CTL | RAL_DROP_BAD_VERSION;
2120		if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2121			tmp |= RAL_DROP_TODS;
2122		if (!(ifp->if_flags & IFF_PROMISC))
2123			tmp |= RAL_DROP_NOT_TO_ME;
2124	}
2125	ural_write(sc, RAL_TXRX_CSR2, tmp);
2126
2127	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2128	ifp->if_drv_flags |= IFF_DRV_RUNNING;
2129	usbd_xfer_set_stall(sc->sc_xfer[URAL_BULK_WR]);
2130	usbd_transfer_start(sc->sc_xfer[URAL_BULK_RD]);
2131	return;
2132
2133fail:	ural_stop(sc);
2134#undef N
2135}
2136
2137static void
2138ural_init(void *priv)
2139{
2140	struct ural_softc *sc = priv;
2141	struct ifnet *ifp = sc->sc_ifp;
2142	struct ieee80211com *ic = ifp->if_l2com;
2143
2144	RAL_LOCK(sc);
2145	ural_init_locked(sc);
2146	RAL_UNLOCK(sc);
2147
2148	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2149		ieee80211_start_all(ic);		/* start all vap's */
2150}
2151
2152static void
2153ural_stop(struct ural_softc *sc)
2154{
2155	struct ifnet *ifp = sc->sc_ifp;
2156
2157	RAL_LOCK_ASSERT(sc, MA_OWNED);
2158
2159	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2160
2161	/*
2162	 * Drain all the transfers, if not already drained:
2163	 */
2164	RAL_UNLOCK(sc);
2165	usbd_transfer_drain(sc->sc_xfer[URAL_BULK_WR]);
2166	usbd_transfer_drain(sc->sc_xfer[URAL_BULK_RD]);
2167	RAL_LOCK(sc);
2168
2169	ural_unsetup_tx_list(sc);
2170
2171	/* disable Rx */
2172	ural_write(sc, RAL_TXRX_CSR2, RAL_DISABLE_RX);
2173	/* reset ASIC and BBP (but won't reset MAC registers!) */
2174	ural_write(sc, RAL_MAC_CSR1, RAL_RESET_ASIC | RAL_RESET_BBP);
2175	/* wait a little */
2176	ural_pause(sc, hz / 10);
2177	ural_write(sc, RAL_MAC_CSR1, 0);
2178	/* wait a little */
2179	ural_pause(sc, hz / 10);
2180}
2181
2182static int
2183ural_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
2184	const struct ieee80211_bpf_params *params)
2185{
2186	struct ieee80211com *ic = ni->ni_ic;
2187	struct ifnet *ifp = ic->ic_ifp;
2188	struct ural_softc *sc = ifp->if_softc;
2189
2190	RAL_LOCK(sc);
2191	/* prevent management frames from being sent if we're not ready */
2192	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
2193		RAL_UNLOCK(sc);
2194		m_freem(m);
2195		ieee80211_free_node(ni);
2196		return ENETDOWN;
2197	}
2198	if (sc->tx_nfree < RAL_TX_MINFREE) {
2199		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2200		RAL_UNLOCK(sc);
2201		m_freem(m);
2202		ieee80211_free_node(ni);
2203		return EIO;
2204	}
2205
2206	ifp->if_opackets++;
2207
2208	if (params == NULL) {
2209		/*
2210		 * Legacy path; interpret frame contents to decide
2211		 * precisely how to send the frame.
2212		 */
2213		if (ural_tx_mgt(sc, m, ni) != 0)
2214			goto bad;
2215	} else {
2216		/*
2217		 * Caller supplied explicit parameters to use in
2218		 * sending the frame.
2219		 */
2220		if (ural_tx_raw(sc, m, ni, params) != 0)
2221			goto bad;
2222	}
2223	RAL_UNLOCK(sc);
2224	return 0;
2225bad:
2226	ifp->if_oerrors++;
2227	RAL_UNLOCK(sc);
2228	ieee80211_free_node(ni);
2229	return EIO;		/* XXX */
2230}
2231
2232static void
2233ural_ratectl_start(struct ural_softc *sc, struct ieee80211_node *ni)
2234{
2235	struct ieee80211vap *vap = ni->ni_vap;
2236	struct ural_vap *uvp = URAL_VAP(vap);
2237
2238	/* clear statistic registers (STA_CSR0 to STA_CSR10) */
2239	ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof sc->sta);
2240
2241	usb_callout_reset(&uvp->ratectl_ch, hz, ural_ratectl_timeout, uvp);
2242}
2243
2244static void
2245ural_ratectl_timeout(void *arg)
2246{
2247	struct ural_vap *uvp = arg;
2248	struct ieee80211vap *vap = &uvp->vap;
2249	struct ieee80211com *ic = vap->iv_ic;
2250
2251	ieee80211_runtask(ic, &uvp->ratectl_task);
2252}
2253
2254static void
2255ural_ratectl_task(void *arg, int pending)
2256{
2257	struct ural_vap *uvp = arg;
2258	struct ieee80211vap *vap = &uvp->vap;
2259	struct ieee80211com *ic = vap->iv_ic;
2260	struct ifnet *ifp = ic->ic_ifp;
2261	struct ural_softc *sc = ifp->if_softc;
2262	struct ieee80211_node *ni;
2263	int ok, fail;
2264	int sum, retrycnt;
2265
2266	ni = ieee80211_ref_node(vap->iv_bss);
2267	RAL_LOCK(sc);
2268	/* read and clear statistic registers (STA_CSR0 to STA_CSR10) */
2269	ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof(sc->sta));
2270
2271	ok = sc->sta[7] +		/* TX ok w/o retry */
2272	     sc->sta[8];		/* TX ok w/ retry */
2273	fail = sc->sta[9];		/* TX retry-fail count */
2274	sum = ok+fail;
2275	retrycnt = sc->sta[8] + fail;
2276
2277	ieee80211_ratectl_tx_update(vap, ni, &sum, &ok, &retrycnt);
2278	(void) ieee80211_ratectl_rate(ni, NULL, 0);
2279
2280	ifp->if_oerrors += fail;	/* count TX retry-fail as Tx errors */
2281
2282	usb_callout_reset(&uvp->ratectl_ch, hz, ural_ratectl_timeout, uvp);
2283	RAL_UNLOCK(sc);
2284	ieee80211_free_node(ni);
2285}
2286
2287static int
2288ural_pause(struct ural_softc *sc, int timeout)
2289{
2290
2291	usb_pause_mtx(&sc->sc_mtx, timeout);
2292	return (0);
2293}
2294