if_rum.c revision 1.66
1/*	$OpenBSD: if_rum.c,v 1.40 2006/09/18 16:20:20 damien Exp $	*/
2/*	$NetBSD: if_rum.c,v 1.66 2020/01/29 06:35:28 thorpej Exp $	*/
3
4/*-
5 * Copyright (c) 2005-2007 Damien Bergamini <damien.bergamini@free.fr>
6 * Copyright (c) 2006 Niall O'Higgins <niallo@openbsd.org>
7 *
8 * Permission to use, copy, modify, and distribute this software for any
9 * purpose with or without fee is hereby granted, provided that the above
10 * copyright notice and this permission notice appear in all copies.
11 *
12 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 */
20
21/*-
22 * Ralink Technology RT2501USB/RT2601USB chipset driver
23 * http://www.ralinktech.com.tw/
24 */
25
26#include <sys/cdefs.h>
27__KERNEL_RCSID(0, "$NetBSD: if_rum.c,v 1.66 2020/01/29 06:35:28 thorpej Exp $");
28
29#ifdef _KERNEL_OPT
30#include "opt_usb.h"
31#endif
32
33#include <sys/param.h>
34#include <sys/sockio.h>
35#include <sys/sysctl.h>
36#include <sys/mbuf.h>
37#include <sys/kernel.h>
38#include <sys/socket.h>
39#include <sys/systm.h>
40#include <sys/module.h>
41#include <sys/conf.h>
42#include <sys/device.h>
43
44#include <sys/bus.h>
45#include <machine/endian.h>
46#include <sys/intr.h>
47
48#include <net/bpf.h>
49#include <net/if.h>
50#include <net/if_arp.h>
51#include <net/if_dl.h>
52#include <net/if_ether.h>
53#include <net/if_media.h>
54#include <net/if_types.h>
55
56#include <netinet/in.h>
57#include <netinet/in_systm.h>
58#include <netinet/in_var.h>
59#include <netinet/ip.h>
60
61#include <net80211/ieee80211_netbsd.h>
62#include <net80211/ieee80211_var.h>
63#include <net80211/ieee80211_amrr.h>
64#include <net80211/ieee80211_radiotap.h>
65
66#include <dev/firmload.h>
67
68#include <dev/usb/usb.h>
69#include <dev/usb/usbdi.h>
70#include <dev/usb/usbdi_util.h>
71#include <dev/usb/usbdevs.h>
72
73#include <dev/usb/if_rumreg.h>
74#include <dev/usb/if_rumvar.h>
75
76#ifdef RUM_DEBUG
77#define DPRINTF(x)	do { if (rum_debug) printf x; } while (0)
78#define DPRINTFN(n, x)	do { if (rum_debug >= (n)) printf x; } while (0)
79int rum_debug = 1;
80#else
81#define DPRINTF(x)
82#define DPRINTFN(n, x)
83#endif
84
85/* various supported device vendors/products */
86static const struct usb_devno rum_devs[] = {
87	{ USB_VENDOR_ABOCOM,		USB_PRODUCT_ABOCOM_HWU54DM },
88	{ USB_VENDOR_ABOCOM,		USB_PRODUCT_ABOCOM_RT2573_2 },
89	{ USB_VENDOR_ABOCOM,		USB_PRODUCT_ABOCOM_RT2573_3 },
90	{ USB_VENDOR_ABOCOM,		USB_PRODUCT_ABOCOM_RT2573_4 },
91	{ USB_VENDOR_ABOCOM,		USB_PRODUCT_ABOCOM_WUG2700 },
92	{ USB_VENDOR_AMIT,		USB_PRODUCT_AMIT_CGWLUSB2GO },
93	{ USB_VENDOR_ASUSTEK,		USB_PRODUCT_ASUSTEK_WL167G_2 },
94	{ USB_VENDOR_ASUSTEK,		USB_PRODUCT_ASUSTEK_WL167G_3 },
95	{ USB_VENDOR_BELKIN,		USB_PRODUCT_BELKIN_F5D7050A },
96	{ USB_VENDOR_BELKIN,		USB_PRODUCT_BELKIN_F5D9050V3 },
97	{ USB_VENDOR_BELKIN,		USB_PRODUCT_BELKIN_F5D9050C },
98	{ USB_VENDOR_CISCOLINKSYS,	USB_PRODUCT_CISCOLINKSYS_WUSB200 },
99	{ USB_VENDOR_CISCOLINKSYS,	USB_PRODUCT_CISCOLINKSYS_WUSB54GC },
100	{ USB_VENDOR_CISCOLINKSYS,	USB_PRODUCT_CISCOLINKSYS_WUSB54GR },
101	{ USB_VENDOR_CONCEPTRONIC,	USB_PRODUCT_CONCEPTRONIC_C54RU2 },
102	{ USB_VENDOR_CONCEPTRONIC,	USB_PRODUCT_CONCEPTRONIC_RT2573 },
103	{ USB_VENDOR_COREGA,		USB_PRODUCT_COREGA_CGWLUSB2GL },
104	{ USB_VENDOR_COREGA,		USB_PRODUCT_COREGA_CGWLUSB2GPX },
105	{ USB_VENDOR_DICKSMITH,		USB_PRODUCT_DICKSMITH_CWD854F },
106	{ USB_VENDOR_DICKSMITH,		USB_PRODUCT_DICKSMITH_RT2573 },
107	{ USB_VENDOR_DLINK2,		USB_PRODUCT_DLINK2_DWLG122C1 },
108	{ USB_VENDOR_DLINK2,		USB_PRODUCT_DLINK2_WUA1340 },
109	{ USB_VENDOR_DLINK2,		USB_PRODUCT_DLINK2_DWA110 },
110	{ USB_VENDOR_DLINK2,		USB_PRODUCT_DLINK2_DWA111 },
111	{ USB_VENDOR_EDIMAX,		USB_PRODUCT_EDIMAX_EW7318 },
112	{ USB_VENDOR_EDIMAX,		USB_PRODUCT_EDIMAX_EW7618 },
113	{ USB_VENDOR_GIGABYTE,		USB_PRODUCT_GIGABYTE_GNWB01GS },
114	{ USB_VENDOR_GIGABYTE,		USB_PRODUCT_GIGABYTE_GNWI05GS },
115	{ USB_VENDOR_GIGASET,		USB_PRODUCT_GIGASET_RT2573 },
116	{ USB_VENDOR_GOODWAY,		USB_PRODUCT_GOODWAY_RT2573 },
117	{ USB_VENDOR_GUILLEMOT,		USB_PRODUCT_GUILLEMOT_HWGUSB254LB },
118	{ USB_VENDOR_GUILLEMOT,		USB_PRODUCT_GUILLEMOT_HWGUSB254V2AP },
119	{ USB_VENDOR_HUAWEI3COM,	USB_PRODUCT_HUAWEI3COM_RT2573 },
120	{ USB_VENDOR_MELCO,		USB_PRODUCT_MELCO_G54HP },
121	{ USB_VENDOR_MELCO,		USB_PRODUCT_MELCO_SG54HP },
122	{ USB_VENDOR_MELCO,		USB_PRODUCT_MELCO_SG54HG },
123	{ USB_VENDOR_MELCO,		USB_PRODUCT_MELCO_WLIUCG },
124	{ USB_VENDOR_MSI,		USB_PRODUCT_MSI_RT2573 },
125	{ USB_VENDOR_MSI,		USB_PRODUCT_MSI_RT2573_2 },
126	{ USB_VENDOR_MSI,		USB_PRODUCT_MSI_RT2573_3 },
127	{ USB_VENDOR_MSI,		USB_PRODUCT_MSI_RT2573_4 },
128	{ USB_VENDOR_NOVATECH,		USB_PRODUCT_NOVATECH_RT2573 },
129	{ USB_VENDOR_PLANEX2,		USB_PRODUCT_PLANEX2_GWUS54HP },
130	{ USB_VENDOR_PLANEX2,		USB_PRODUCT_PLANEX2_GWUS54MINI2 },
131	{ USB_VENDOR_PLANEX2,		USB_PRODUCT_PLANEX2_GWUSMM },
132	{ USB_VENDOR_QCOM,		USB_PRODUCT_QCOM_RT2573 },
133	{ USB_VENDOR_QCOM,		USB_PRODUCT_QCOM_RT2573_2 },
134	{ USB_VENDOR_QCOM,		USB_PRODUCT_QCOM_RT2573_3 },
135	{ USB_VENDOR_RALINK,		USB_PRODUCT_RALINK_RT2573 },
136	{ USB_VENDOR_RALINK,		USB_PRODUCT_RALINK_RT2671 },
137	{ USB_VENDOR_SITECOMEU,		USB_PRODUCT_SITECOMEU_WL113R2 },
138	{ USB_VENDOR_SITECOMEU,		USB_PRODUCT_SITECOMEU_WL172 },
139	{ USB_VENDOR_SPARKLAN,		USB_PRODUCT_SPARKLAN_RT2573 },
140	{ USB_VENDOR_SURECOM,		USB_PRODUCT_SURECOM_RT2573 },
141	{ USB_VENDOR_SYNET,		USB_PRODUCT_SYNET_MWP54SS },
142	{ USB_VENDOR_ZYXEL,		USB_PRODUCT_ZYXEL_RT2573 }
143};
144
145static int		rum_attachhook(void *);
146static int		rum_alloc_tx_list(struct rum_softc *);
147static void		rum_free_tx_list(struct rum_softc *);
148static int		rum_alloc_rx_list(struct rum_softc *);
149static void		rum_free_rx_list(struct rum_softc *);
150static int		rum_media_change(struct ifnet *);
151static void		rum_next_scan(void *);
152static void		rum_task(void *);
153static int		rum_newstate(struct ieee80211com *,
154			    enum ieee80211_state, int);
155static void		rum_txeof(struct usbd_xfer *, void *,
156			    usbd_status);
157static void		rum_rxeof(struct usbd_xfer *, void *,
158			    usbd_status);
159static uint8_t		rum_rxrate(const struct rum_rx_desc *);
160static int		rum_ack_rate(struct ieee80211com *, int);
161static uint16_t		rum_txtime(int, int, uint32_t);
162static uint8_t		rum_plcp_signal(int);
163static void		rum_setup_tx_desc(struct rum_softc *,
164			    struct rum_tx_desc *, uint32_t, uint16_t, int,
165			    int);
166static int		rum_tx_data(struct rum_softc *, struct mbuf *,
167			    struct ieee80211_node *);
168static void		rum_start(struct ifnet *);
169static void		rum_watchdog(struct ifnet *);
170static int		rum_ioctl(struct ifnet *, u_long, void *);
171static void		rum_eeprom_read(struct rum_softc *, uint16_t, void *,
172			    int);
173static uint32_t		rum_read(struct rum_softc *, uint16_t);
174static void		rum_read_multi(struct rum_softc *, uint16_t, void *,
175			    int);
176static void		rum_write(struct rum_softc *, uint16_t, uint32_t);
177static void		rum_write_multi(struct rum_softc *, uint16_t, void *,
178			    size_t);
179static void		rum_bbp_write(struct rum_softc *, uint8_t, uint8_t);
180static uint8_t		rum_bbp_read(struct rum_softc *, uint8_t);
181static void		rum_rf_write(struct rum_softc *, uint8_t, uint32_t);
182static void		rum_select_antenna(struct rum_softc *);
183static void		rum_enable_mrr(struct rum_softc *);
184static void		rum_set_txpreamble(struct rum_softc *);
185static void		rum_set_basicrates(struct rum_softc *);
186static void		rum_select_band(struct rum_softc *,
187			    struct ieee80211_channel *);
188static void		rum_set_chan(struct rum_softc *,
189			    struct ieee80211_channel *);
190static void		rum_enable_tsf_sync(struct rum_softc *);
191static void		rum_update_slot(struct rum_softc *);
192static void		rum_set_bssid(struct rum_softc *, const uint8_t *);
193static void		rum_set_macaddr(struct rum_softc *, const uint8_t *);
194static void		rum_update_promisc(struct rum_softc *);
195static const char	*rum_get_rf(int);
196static void		rum_read_eeprom(struct rum_softc *);
197static int		rum_bbp_init(struct rum_softc *);
198static int		rum_init(struct ifnet *);
199static void		rum_stop(struct ifnet *, int);
200static int		rum_load_microcode(struct rum_softc *, const u_char *,
201			    size_t);
202static int		rum_prepare_beacon(struct rum_softc *);
203static void		rum_newassoc(struct ieee80211_node *, int);
204static void		rum_amrr_start(struct rum_softc *,
205			    struct ieee80211_node *);
206static void		rum_amrr_timeout(void *);
207static void		rum_amrr_update(struct usbd_xfer *, void *,
208			    usbd_status);
209
210static const struct {
211	uint32_t	reg;
212	uint32_t	val;
213} rum_def_mac[] = {
214	RT2573_DEF_MAC
215};
216
217static const struct {
218	uint8_t	reg;
219	uint8_t	val;
220} rum_def_bbp[] = {
221	RT2573_DEF_BBP
222};
223
224static const struct rfprog {
225	uint8_t		chan;
226	uint32_t	r1, r2, r3, r4;
227}  rum_rf5226[] = {
228	RT2573_RF5226
229}, rum_rf5225[] = {
230	RT2573_RF5225
231};
232
233static int rum_match(device_t, cfdata_t, void *);
234static void rum_attach(device_t, device_t, void *);
235static int rum_detach(device_t, int);
236static int rum_activate(device_t, enum devact);
237
238CFATTACH_DECL_NEW(rum, sizeof(struct rum_softc), rum_match, rum_attach,
239    rum_detach, rum_activate);
240
241static int
242rum_match(device_t parent, cfdata_t match, void *aux)
243{
244	struct usb_attach_arg *uaa = aux;
245
246	return (usb_lookup(rum_devs, uaa->uaa_vendor, uaa->uaa_product) != NULL) ?
247	    UMATCH_VENDOR_PRODUCT : UMATCH_NONE;
248}
249
250static int
251rum_attachhook(void *xsc)
252{
253	struct rum_softc *sc = xsc;
254	firmware_handle_t fwh;
255	const char *name = "rum-rt2573";
256	u_char *ucode;
257	size_t size;
258	int error;
259
260	if ((error = firmware_open("rum", name, &fwh)) != 0) {
261		printf("%s: failed firmware_open of file %s (error %d)\n",
262		    device_xname(sc->sc_dev), name, error);
263		return error;
264	}
265	size = firmware_get_size(fwh);
266	ucode = firmware_malloc(size);
267	if (ucode == NULL) {
268		printf("%s: failed to allocate firmware memory\n",
269		    device_xname(sc->sc_dev));
270		firmware_close(fwh);
271		return ENOMEM;
272	}
273	error = firmware_read(fwh, 0, ucode, size);
274	firmware_close(fwh);
275	if (error != 0) {
276		printf("%s: failed to read firmware (error %d)\n",
277		    device_xname(sc->sc_dev), error);
278		firmware_free(ucode, size);
279		return error;
280	}
281
282	if (rum_load_microcode(sc, ucode, size) != 0) {
283		printf("%s: could not load 8051 microcode\n",
284		    device_xname(sc->sc_dev));
285		firmware_free(ucode, size);
286		return ENXIO;
287	}
288
289	firmware_free(ucode, size);
290	sc->sc_flags |= RT2573_FWLOADED;
291
292	return 0;
293}
294
295static void
296rum_attach(device_t parent, device_t self, void *aux)
297{
298	struct rum_softc *sc = device_private(self);
299	struct usb_attach_arg *uaa = aux;
300	struct ieee80211com *ic = &sc->sc_ic;
301	struct ifnet *ifp = &sc->sc_if;
302	usb_interface_descriptor_t *id;
303	usb_endpoint_descriptor_t *ed;
304	usbd_status error;
305	char *devinfop;
306	int i, ntries;
307	uint32_t tmp;
308
309	sc->sc_dev = self;
310	sc->sc_udev = uaa->uaa_device;
311	sc->sc_flags = 0;
312
313	aprint_naive("\n");
314	aprint_normal("\n");
315
316	devinfop = usbd_devinfo_alloc(sc->sc_udev, 0);
317	aprint_normal_dev(self, "%s\n", devinfop);
318	usbd_devinfo_free(devinfop);
319
320	error = usbd_set_config_no(sc->sc_udev, RT2573_CONFIG_NO, 0);
321	if (error != 0) {
322		aprint_error_dev(self, "failed to set configuration"
323		    ", err=%s\n", usbd_errstr(error));
324		return;
325	}
326
327	/* get the first interface handle */
328	error = usbd_device2interface_handle(sc->sc_udev, RT2573_IFACE_INDEX,
329	    &sc->sc_iface);
330	if (error != 0) {
331		aprint_error_dev(self, "could not get interface handle\n");
332		return;
333	}
334
335	/*
336	 * Find endpoints.
337	 */
338	id = usbd_get_interface_descriptor(sc->sc_iface);
339
340	sc->sc_rx_no = sc->sc_tx_no = -1;
341	for (i = 0; i < id->bNumEndpoints; i++) {
342		ed = usbd_interface2endpoint_descriptor(sc->sc_iface, i);
343		if (ed == NULL) {
344			aprint_error_dev(self,
345			    "no endpoint descriptor for iface %d\n", i);
346			return;
347		}
348
349		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
350		    UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK)
351			sc->sc_rx_no = ed->bEndpointAddress;
352		else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT &&
353		    UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK)
354			sc->sc_tx_no = ed->bEndpointAddress;
355	}
356	if (sc->sc_rx_no == -1 || sc->sc_tx_no == -1) {
357		aprint_error_dev(self, "missing endpoint\n");
358		return;
359	}
360
361	usb_init_task(&sc->sc_task, rum_task, sc, 0);
362	callout_init(&sc->sc_scan_ch, 0);
363
364	sc->amrr.amrr_min_success_threshold =  1;
365	sc->amrr.amrr_max_success_threshold = 10;
366	callout_init(&sc->sc_amrr_ch, 0);
367
368	/* retrieve RT2573 rev. no */
369	for (ntries = 0; ntries < 1000; ntries++) {
370		if ((tmp = rum_read(sc, RT2573_MAC_CSR0)) != 0)
371			break;
372		DELAY(1000);
373	}
374	if (ntries == 1000) {
375		aprint_error_dev(self, "timeout waiting for chip to settle\n");
376		return;
377	}
378
379	/* retrieve MAC address and various other things from EEPROM */
380	rum_read_eeprom(sc);
381
382	aprint_normal_dev(self,
383	    "MAC/BBP RT%04x (rev 0x%05x), RF %s, address %s\n",
384	    sc->macbbp_rev, tmp,
385	    rum_get_rf(sc->rf_rev), ether_sprintf(ic->ic_myaddr));
386
387	ic->ic_ifp = ifp;
388	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
389	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
390	ic->ic_state = IEEE80211_S_INIT;
391
392	/* set device capabilities */
393	ic->ic_caps =
394	    IEEE80211_C_IBSS |		/* IBSS mode supported */
395	    IEEE80211_C_MONITOR |	/* monitor mode supported */
396	    IEEE80211_C_HOSTAP |	/* HostAp mode supported */
397	    IEEE80211_C_TXPMGT |	/* tx power management */
398	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
399	    IEEE80211_C_SHSLOT |	/* short slot time supported */
400	    IEEE80211_C_WPA;		/* 802.11i */
401
402	if (sc->rf_rev == RT2573_RF_5225 || sc->rf_rev == RT2573_RF_5226) {
403		/* set supported .11a rates */
404		ic->ic_sup_rates[IEEE80211_MODE_11A] = ieee80211_std_rateset_11a;
405
406		/* set supported .11a channels */
407		for (i = 34; i <= 46; i += 4) {
408			ic->ic_channels[i].ic_freq =
409			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
410			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
411		}
412		for (i = 36; i <= 64; i += 4) {
413			ic->ic_channels[i].ic_freq =
414			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
415			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
416		}
417		for (i = 100; i <= 140; i += 4) {
418			ic->ic_channels[i].ic_freq =
419			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
420			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
421		}
422		for (i = 149; i <= 165; i += 4) {
423			ic->ic_channels[i].ic_freq =
424			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
425			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
426		}
427	}
428
429	/* set supported .11b and .11g rates */
430	ic->ic_sup_rates[IEEE80211_MODE_11B] = ieee80211_std_rateset_11b;
431	ic->ic_sup_rates[IEEE80211_MODE_11G] = ieee80211_std_rateset_11g;
432
433	/* set supported .11b and .11g channels (1 through 14) */
434	for (i = 1; i <= 14; i++) {
435		ic->ic_channels[i].ic_freq =
436		    ieee80211_ieee2mhz(i, IEEE80211_CHAN_2GHZ);
437		ic->ic_channels[i].ic_flags =
438		    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
439		    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
440	}
441
442	ifp->if_softc = sc;
443	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
444	ifp->if_init = rum_init;
445	ifp->if_ioctl = rum_ioctl;
446	ifp->if_start = rum_start;
447	ifp->if_watchdog = rum_watchdog;
448	IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
449	IFQ_SET_READY(&ifp->if_snd);
450	memcpy(ifp->if_xname, device_xname(sc->sc_dev), IFNAMSIZ);
451
452	if_attach(ifp);
453	ieee80211_ifattach(ic);
454	ic->ic_newassoc = rum_newassoc;
455
456	/* override state transition machine */
457	sc->sc_newstate = ic->ic_newstate;
458	ic->ic_newstate = rum_newstate;
459	ieee80211_media_init(ic, rum_media_change, ieee80211_media_status);
460
461	bpf_attach2(ifp, DLT_IEEE802_11_RADIO,
462	    sizeof(struct ieee80211_frame) + IEEE80211_RADIOTAP_HDRLEN,
463	    &sc->sc_drvbpf);
464
465	sc->sc_rxtap_len = sizeof(sc->sc_rxtapu);
466	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
467	sc->sc_rxtap.wr_ihdr.it_present = htole32(RT2573_RX_RADIOTAP_PRESENT);
468
469	sc->sc_txtap_len = sizeof(sc->sc_txtapu);
470	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
471	sc->sc_txtap.wt_ihdr.it_present = htole32(RT2573_TX_RADIOTAP_PRESENT);
472
473	ieee80211_announce(ic);
474
475	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev, sc->sc_dev);
476
477	if (!pmf_device_register(self, NULL, NULL))
478		aprint_error_dev(self, "couldn't establish power handler\n");
479
480	return;
481}
482
483static int
484rum_detach(device_t self, int flags)
485{
486	struct rum_softc *sc = device_private(self);
487	struct ieee80211com *ic = &sc->sc_ic;
488	struct ifnet *ifp = &sc->sc_if;
489	int s;
490
491	if (!ifp->if_softc)
492		return 0;
493
494	pmf_device_deregister(self);
495
496	s = splusb();
497
498	rum_stop(ifp, 1);
499	callout_halt(&sc->sc_scan_ch, NULL);
500	callout_halt(&sc->sc_amrr_ch, NULL);
501	usb_rem_task_wait(sc->sc_udev, &sc->sc_task, USB_TASKQ_DRIVER, NULL);
502
503	bpf_detach(ifp);
504	ieee80211_ifdetach(ic);	/* free all nodes */
505	if_detach(ifp);
506
507	splx(s);
508
509	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev, sc->sc_dev);
510
511	return 0;
512}
513
514static int
515rum_alloc_tx_list(struct rum_softc *sc)
516{
517	struct rum_tx_data *data;
518	int i, error;
519
520	sc->tx_cur = sc->tx_queued = 0;
521
522	for (i = 0; i < RUM_TX_LIST_COUNT; i++) {
523		data = &sc->tx_data[i];
524
525		data->sc = sc;
526
527		error = usbd_create_xfer(sc->sc_tx_pipeh,
528		    RT2573_TX_DESC_SIZE + IEEE80211_MAX_LEN,
529		    USBD_FORCE_SHORT_XFER, 0, &data->xfer);
530		if (error) {
531			printf("%s: could not allocate tx xfer\n",
532			    device_xname(sc->sc_dev));
533			goto fail;
534		}
535		data->buf = usbd_get_buffer(data->xfer);
536
537		/* clean Tx descriptor */
538		memset(data->buf, 0, RT2573_TX_DESC_SIZE);
539	}
540
541	return 0;
542
543fail:	rum_free_tx_list(sc);
544	return error;
545}
546
547static void
548rum_free_tx_list(struct rum_softc *sc)
549{
550	struct rum_tx_data *data;
551	int i;
552
553	for (i = 0; i < RUM_TX_LIST_COUNT; i++) {
554		data = &sc->tx_data[i];
555
556		if (data->xfer != NULL) {
557			usbd_destroy_xfer(data->xfer);
558			data->xfer = NULL;
559		}
560
561		if (data->ni != NULL) {
562			ieee80211_free_node(data->ni);
563			data->ni = NULL;
564		}
565	}
566}
567
568static int
569rum_alloc_rx_list(struct rum_softc *sc)
570{
571	struct rum_rx_data *data;
572	int i, error;
573
574	for (i = 0; i < RUM_RX_LIST_COUNT; i++) {
575		data = &sc->rx_data[i];
576
577		data->sc = sc;
578
579		error = usbd_create_xfer(sc->sc_rx_pipeh, MCLBYTES,
580		    0, 0, &data->xfer);
581		if (error) {
582			printf("%s: could not allocate rx xfer\n",
583			    device_xname(sc->sc_dev));
584			goto fail;
585		}
586
587		MGETHDR(data->m, M_DONTWAIT, MT_DATA);
588		if (data->m == NULL) {
589			printf("%s: could not allocate rx mbuf\n",
590			    device_xname(sc->sc_dev));
591			error = ENOMEM;
592			goto fail;
593		}
594
595		MCLGET(data->m, M_DONTWAIT);
596		if (!(data->m->m_flags & M_EXT)) {
597			printf("%s: could not allocate rx mbuf cluster\n",
598			    device_xname(sc->sc_dev));
599			error = ENOMEM;
600			goto fail;
601		}
602
603		data->buf = mtod(data->m, uint8_t *);
604	}
605
606	return 0;
607
608fail:	rum_free_rx_list(sc);
609	return error;
610}
611
612static void
613rum_free_rx_list(struct rum_softc *sc)
614{
615	struct rum_rx_data *data;
616	int i;
617
618	for (i = 0; i < RUM_RX_LIST_COUNT; i++) {
619		data = &sc->rx_data[i];
620
621		if (data->xfer != NULL) {
622			usbd_destroy_xfer(data->xfer);
623			data->xfer = NULL;
624		}
625
626		if (data->m != NULL) {
627			m_freem(data->m);
628			data->m = NULL;
629		}
630	}
631}
632
633static int
634rum_media_change(struct ifnet *ifp)
635{
636	int error;
637
638	error = ieee80211_media_change(ifp);
639	if (error != ENETRESET)
640		return error;
641
642	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
643		rum_init(ifp);
644
645	return 0;
646}
647
648/*
649 * This function is called periodically (every 200ms) during scanning to
650 * switch from one channel to another.
651 */
652static void
653rum_next_scan(void *arg)
654{
655	struct rum_softc *sc = arg;
656	struct ieee80211com *ic = &sc->sc_ic;
657	int s;
658
659	s = splnet();
660	if (ic->ic_state == IEEE80211_S_SCAN)
661		ieee80211_next_scan(ic);
662	splx(s);
663}
664
665static void
666rum_task(void *arg)
667{
668	struct rum_softc *sc = arg;
669	struct ieee80211com *ic = &sc->sc_ic;
670	enum ieee80211_state ostate;
671	struct ieee80211_node *ni;
672	uint32_t tmp;
673
674	ostate = ic->ic_state;
675
676	switch (sc->sc_state) {
677	case IEEE80211_S_INIT:
678		if (ostate == IEEE80211_S_RUN) {
679			/* abort TSF synchronization */
680			tmp = rum_read(sc, RT2573_TXRX_CSR9);
681			rum_write(sc, RT2573_TXRX_CSR9, tmp & ~0x00ffffff);
682		}
683		break;
684
685	case IEEE80211_S_SCAN:
686		rum_set_chan(sc, ic->ic_curchan);
687		callout_reset(&sc->sc_scan_ch, hz / 5, rum_next_scan, sc);
688		break;
689
690	case IEEE80211_S_AUTH:
691		rum_set_chan(sc, ic->ic_curchan);
692		break;
693
694	case IEEE80211_S_ASSOC:
695		rum_set_chan(sc, ic->ic_curchan);
696		break;
697
698	case IEEE80211_S_RUN:
699		rum_set_chan(sc, ic->ic_curchan);
700
701		ni = ic->ic_bss;
702
703		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
704			rum_update_slot(sc);
705			rum_enable_mrr(sc);
706			rum_set_txpreamble(sc);
707			rum_set_basicrates(sc);
708			rum_set_bssid(sc, ni->ni_bssid);
709		}
710
711		if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
712		    ic->ic_opmode == IEEE80211_M_IBSS)
713			rum_prepare_beacon(sc);
714
715		if (ic->ic_opmode != IEEE80211_M_MONITOR)
716			rum_enable_tsf_sync(sc);
717
718		if (ic->ic_opmode == IEEE80211_M_STA) {
719			/* fake a join to init the tx rate */
720			rum_newassoc(ic->ic_bss, 1);
721
722			/* enable automatic rate adaptation in STA mode */
723			if (ic->ic_fixed_rate == IEEE80211_FIXED_RATE_NONE)
724				rum_amrr_start(sc, ni);
725		}
726
727		break;
728	}
729
730	sc->sc_newstate(ic, sc->sc_state, sc->sc_arg);
731}
732
733static int
734rum_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
735{
736	struct rum_softc *sc = ic->ic_ifp->if_softc;
737
738	/*
739	 * XXXSMP: This does not wait for the task, if it is in flight,
740	 * to complete.  If this code works at all, it must rely on the
741	 * kernel lock to serialize with the USB task thread.
742	 */
743	usb_rem_task(sc->sc_udev, &sc->sc_task);
744	callout_stop(&sc->sc_scan_ch);
745	callout_stop(&sc->sc_amrr_ch);
746
747	/* do it in a process context */
748	sc->sc_state = nstate;
749	sc->sc_arg = arg;
750	usb_add_task(sc->sc_udev, &sc->sc_task, USB_TASKQ_DRIVER);
751
752	return 0;
753}
754
755/* quickly determine if a given rate is CCK or OFDM */
756#define RUM_RATE_IS_OFDM(rate)	((rate) >= 12 && (rate) != 22)
757
758#define RUM_ACK_SIZE	14	/* 10 + 4(FCS) */
759#define RUM_CTS_SIZE	14	/* 10 + 4(FCS) */
760
761static void
762rum_txeof(struct usbd_xfer *xfer, void *priv, usbd_status status)
763{
764	struct rum_tx_data *data = priv;
765	struct rum_softc *sc = data->sc;
766	struct ifnet *ifp = &sc->sc_if;
767	int s;
768
769	if (status != USBD_NORMAL_COMPLETION) {
770		if (status == USBD_NOT_STARTED || status == USBD_CANCELLED)
771			return;
772
773		printf("%s: could not transmit buffer: %s\n",
774		    device_xname(sc->sc_dev), usbd_errstr(status));
775
776		if (status == USBD_STALLED)
777			usbd_clear_endpoint_stall_async(sc->sc_tx_pipeh);
778
779		if_statinc(ifp, if_oerrors);
780		return;
781	}
782
783	s = splnet();
784
785	ieee80211_free_node(data->ni);
786	data->ni = NULL;
787
788	sc->tx_queued--;
789	if_statinc(ifp, if_opackets);
790
791	DPRINTFN(10, ("tx done\n"));
792
793	sc->sc_tx_timer = 0;
794	ifp->if_flags &= ~IFF_OACTIVE;
795	rum_start(ifp);
796
797	splx(s);
798}
799
800static void
801rum_rxeof(struct usbd_xfer *xfer, void *priv, usbd_status status)
802{
803	struct rum_rx_data *data = priv;
804	struct rum_softc *sc = data->sc;
805	struct ieee80211com *ic = &sc->sc_ic;
806	struct ifnet *ifp = &sc->sc_if;
807	struct rum_rx_desc *desc;
808	struct ieee80211_frame *wh;
809	struct ieee80211_node *ni;
810	struct mbuf *mnew, *m;
811	int s, len;
812
813	if (status != USBD_NORMAL_COMPLETION) {
814		if (status == USBD_NOT_STARTED || status == USBD_CANCELLED)
815			return;
816
817		if (status == USBD_STALLED)
818			usbd_clear_endpoint_stall_async(sc->sc_rx_pipeh);
819		goto skip;
820	}
821
822	usbd_get_xfer_status(xfer, NULL, NULL, &len, NULL);
823
824	if (len < (int)(RT2573_RX_DESC_SIZE +
825		        sizeof(struct ieee80211_frame_min))) {
826		DPRINTF(("%s: xfer too short %d\n", device_xname(sc->sc_dev),
827		    len));
828		if_statinc(ifp, if_ierrors);
829		goto skip;
830	}
831
832	desc = (struct rum_rx_desc *)data->buf;
833
834	if (le32toh(desc->flags) & RT2573_RX_CRC_ERROR) {
835		/*
836		 * This should not happen since we did not request to receive
837		 * those frames when we filled RT2573_TXRX_CSR0.
838		 */
839		DPRINTFN(5, ("CRC error\n"));
840		if_statinc(ifp, if_ierrors);
841		goto skip;
842	}
843
844	MGETHDR(mnew, M_DONTWAIT, MT_DATA);
845	if (mnew == NULL) {
846		printf("%s: could not allocate rx mbuf\n",
847		    device_xname(sc->sc_dev));
848		if_statinc(ifp, if_ierrors);
849		goto skip;
850	}
851
852	MCLGET(mnew, M_DONTWAIT);
853	if (!(mnew->m_flags & M_EXT)) {
854		printf("%s: could not allocate rx mbuf cluster\n",
855		    device_xname(sc->sc_dev));
856		m_freem(mnew);
857		if_statinc(ifp, if_ierrors);
858		goto skip;
859	}
860
861	m = data->m;
862	data->m = mnew;
863	data->buf = mtod(data->m, uint8_t *);
864
865	/* finalize mbuf */
866	m_set_rcvif(m, ifp);
867	m->m_data = (void *)(desc + 1);
868	m->m_pkthdr.len = m->m_len = (le32toh(desc->flags) >> 16) & 0xfff;
869
870	s = splnet();
871
872	if (sc->sc_drvbpf != NULL) {
873		struct rum_rx_radiotap_header *tap = &sc->sc_rxtap;
874
875		tap->wr_flags = IEEE80211_RADIOTAP_F_FCS;
876		tap->wr_rate = rum_rxrate(desc);
877		tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
878		tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
879		tap->wr_antenna = sc->rx_ant;
880		tap->wr_antsignal = desc->rssi;
881
882		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_rxtap_len, m, BPF_D_IN);
883	}
884
885	wh = mtod(m, struct ieee80211_frame *);
886	ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
887
888	/* send the frame to the 802.11 layer */
889	ieee80211_input(ic, m, ni, desc->rssi, 0);
890
891	/* node is no longer needed */
892	ieee80211_free_node(ni);
893
894	splx(s);
895
896	DPRINTFN(15, ("rx done\n"));
897
898skip:	/* setup a new transfer */
899	usbd_setup_xfer(xfer, data, data->buf, MCLBYTES, USBD_SHORT_XFER_OK,
900	    USBD_NO_TIMEOUT, rum_rxeof);
901	usbd_transfer(xfer);
902}
903
904/*
905 * This function is only used by the Rx radiotap code. It returns the rate at
906 * which a given frame was received.
907 */
908static uint8_t
909rum_rxrate(const struct rum_rx_desc *desc)
910{
911	if (le32toh(desc->flags) & RT2573_RX_OFDM) {
912		/* reverse function of rum_plcp_signal */
913		switch (desc->rate) {
914		case 0xb:	return 12;
915		case 0xf:	return 18;
916		case 0xa:	return 24;
917		case 0xe:	return 36;
918		case 0x9:	return 48;
919		case 0xd:	return 72;
920		case 0x8:	return 96;
921		case 0xc:	return 108;
922		}
923	} else {
924		if (desc->rate == 10)
925			return 2;
926		if (desc->rate == 20)
927			return 4;
928		if (desc->rate == 55)
929			return 11;
930		if (desc->rate == 110)
931			return 22;
932	}
933	return 2;	/* should not get there */
934}
935
936/*
937 * Return the expected ack rate for a frame transmitted at rate `rate'.
938 * XXX: this should depend on the destination node basic rate set.
939 */
940static int
941rum_ack_rate(struct ieee80211com *ic, int rate)
942{
943	switch (rate) {
944	/* CCK rates */
945	case 2:
946		return 2;
947	case 4:
948	case 11:
949	case 22:
950		return (ic->ic_curmode == IEEE80211_MODE_11B) ? 4 : rate;
951
952	/* OFDM rates */
953	case 12:
954	case 18:
955		return 12;
956	case 24:
957	case 36:
958		return 24;
959	case 48:
960	case 72:
961	case 96:
962	case 108:
963		return 48;
964	}
965
966	/* default to 1Mbps */
967	return 2;
968}
969
970/*
971 * Compute the duration (in us) needed to transmit `len' bytes at rate `rate'.
972 * The function automatically determines the operating mode depending on the
973 * given rate. `flags' indicates whether short preamble is in use or not.
974 */
975static uint16_t
976rum_txtime(int len, int rate, uint32_t flags)
977{
978	uint16_t txtime;
979
980	if (RUM_RATE_IS_OFDM(rate)) {
981		/* IEEE Std 802.11a-1999, pp. 37 */
982		txtime = (8 + 4 * len + 3 + rate - 1) / rate;
983		txtime = 16 + 4 + 4 * txtime + 6;
984	} else {
985		/* IEEE Std 802.11b-1999, pp. 28 */
986		txtime = (16 * len + rate - 1) / rate;
987		if (rate != 2 && (flags & IEEE80211_F_SHPREAMBLE))
988			txtime +=  72 + 24;
989		else
990			txtime += 144 + 48;
991	}
992	return txtime;
993}
994
995static uint8_t
996rum_plcp_signal(int rate)
997{
998	switch (rate) {
999	/* CCK rates (returned values are device-dependent) */
1000	case 2:		return 0x0;
1001	case 4:		return 0x1;
1002	case 11:	return 0x2;
1003	case 22:	return 0x3;
1004
1005	/* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
1006	case 12:	return 0xb;
1007	case 18:	return 0xf;
1008	case 24:	return 0xa;
1009	case 36:	return 0xe;
1010	case 48:	return 0x9;
1011	case 72:	return 0xd;
1012	case 96:	return 0x8;
1013	case 108:	return 0xc;
1014
1015	/* unsupported rates (should not get there) */
1016	default:	return 0xff;
1017	}
1018}
1019
1020static void
1021rum_setup_tx_desc(struct rum_softc *sc, struct rum_tx_desc *desc,
1022    uint32_t flags, uint16_t xflags, int len, int rate)
1023{
1024	struct ieee80211com *ic = &sc->sc_ic;
1025	uint16_t plcp_length;
1026	int remainder;
1027
1028	desc->flags = htole32(flags);
1029	desc->flags |= htole32(RT2573_TX_VALID);
1030	desc->flags |= htole32(len << 16);
1031
1032	desc->xflags = htole16(xflags);
1033
1034	desc->wme = htole16(
1035	    RT2573_QID(0) |
1036	    RT2573_AIFSN(2) |
1037	    RT2573_LOGCWMIN(4) |
1038	    RT2573_LOGCWMAX(10));
1039
1040	/* setup PLCP fields */
1041	desc->plcp_signal  = rum_plcp_signal(rate);
1042	desc->plcp_service = 4;
1043
1044	len += IEEE80211_CRC_LEN;
1045	if (RUM_RATE_IS_OFDM(rate)) {
1046		desc->flags |= htole32(RT2573_TX_OFDM);
1047
1048		plcp_length = len & 0xfff;
1049		desc->plcp_length_hi = plcp_length >> 6;
1050		desc->plcp_length_lo = plcp_length & 0x3f;
1051	} else {
1052		plcp_length = (16 * len + rate - 1) / rate;
1053		if (rate == 22) {
1054			remainder = (16 * len) % 22;
1055			if (remainder != 0 && remainder < 7)
1056				desc->plcp_service |= RT2573_PLCP_LENGEXT;
1057		}
1058		desc->plcp_length_hi = plcp_length >> 8;
1059		desc->plcp_length_lo = plcp_length & 0xff;
1060
1061		if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1062			desc->plcp_signal |= 0x08;
1063	}
1064}
1065
1066#define RUM_TX_TIMEOUT	5000
1067
1068static int
1069rum_tx_data(struct rum_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1070{
1071	struct ieee80211com *ic = &sc->sc_ic;
1072	struct rum_tx_desc *desc;
1073	struct rum_tx_data *data;
1074	struct ieee80211_frame *wh;
1075	struct ieee80211_key *k;
1076	uint32_t flags = 0;
1077	uint16_t dur;
1078	usbd_status error;
1079	int rate, xferlen, pktlen, needrts = 0, needcts = 0;
1080
1081	wh = mtod(m0, struct ieee80211_frame *);
1082
1083	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1084		k = ieee80211_crypto_encap(ic, ni, m0);
1085		if (k == NULL) {
1086			m_freem(m0);
1087			return ENOBUFS;
1088		}
1089
1090		/* packet header may have moved, reset our local pointer */
1091		wh = mtod(m0, struct ieee80211_frame *);
1092	}
1093
1094	/* compute actual packet length (including CRC and crypto overhead) */
1095	pktlen = m0->m_pkthdr.len + IEEE80211_CRC_LEN;
1096
1097	/* pickup a rate */
1098	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
1099	    ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
1100	     IEEE80211_FC0_TYPE_MGT)) {
1101		/* mgmt/multicast frames are sent at the lowest avail. rate */
1102		rate = ni->ni_rates.rs_rates[0];
1103	} else if (ic->ic_fixed_rate != IEEE80211_FIXED_RATE_NONE) {
1104		rate = ic->ic_bss->ni_rates.rs_rates[ic->ic_fixed_rate];
1105	} else
1106		rate = ni->ni_rates.rs_rates[ni->ni_txrate];
1107	if (rate == 0)
1108		rate = 2;	/* XXX should not happen */
1109	rate &= IEEE80211_RATE_VAL;
1110
1111	/* check if RTS/CTS or CTS-to-self protection must be used */
1112	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1113		/* multicast frames are not sent at OFDM rates in 802.11b/g */
1114		if (pktlen > ic->ic_rtsthreshold) {
1115			needrts = 1;	/* RTS/CTS based on frame length */
1116		} else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
1117		    RUM_RATE_IS_OFDM(rate)) {
1118			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
1119				needcts = 1;	/* CTS-to-self */
1120			else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
1121				needrts = 1;	/* RTS/CTS */
1122		}
1123	}
1124	if (needrts || needcts) {
1125		struct mbuf *mprot;
1126		int protrate, ackrate;
1127
1128		protrate = IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) ? 12 : 2;
1129		ackrate  = rum_ack_rate(ic, rate);
1130
1131		dur = rum_txtime(pktlen, rate, ic->ic_flags) +
1132		      rum_txtime(RUM_ACK_SIZE, ackrate, ic->ic_flags) +
1133		      2 * sc->sifs;
1134		if (needrts) {
1135			dur += rum_txtime(RUM_CTS_SIZE, rum_ack_rate(ic,
1136			    protrate), ic->ic_flags) + sc->sifs;
1137			mprot = ieee80211_get_rts(ic, wh, dur);
1138		} else {
1139			mprot = ieee80211_get_cts_to_self(ic, dur);
1140		}
1141		if (mprot == NULL) {
1142			aprint_error_dev(sc->sc_dev,
1143			    "couldn't allocate protection frame\n");
1144			m_freem(m0);
1145			return ENOBUFS;
1146		}
1147
1148		data = &sc->tx_data[sc->tx_cur];
1149		desc = (struct rum_tx_desc *)data->buf;
1150
1151		/* avoid multiple free() of the same node for each fragment */
1152		data->ni = ieee80211_ref_node(ni);
1153
1154		m_copydata(mprot, 0, mprot->m_pkthdr.len,
1155		    data->buf + RT2573_TX_DESC_SIZE);
1156		rum_setup_tx_desc(sc, desc,
1157		    (needrts ? RT2573_TX_NEED_ACK : 0) | RT2573_TX_MORE_FRAG,
1158		    0, mprot->m_pkthdr.len, protrate);
1159
1160		/* no roundup necessary here */
1161		xferlen = RT2573_TX_DESC_SIZE + mprot->m_pkthdr.len;
1162
1163		/* XXX may want to pass the protection frame to BPF */
1164
1165		/* mbuf is no longer needed */
1166		m_freem(mprot);
1167
1168		usbd_setup_xfer(data->xfer, data, data->buf,
1169		    xferlen, USBD_FORCE_SHORT_XFER,
1170		    RUM_TX_TIMEOUT, rum_txeof);
1171		error = usbd_transfer(data->xfer);
1172		if (error != USBD_NORMAL_COMPLETION &&
1173		    error != USBD_IN_PROGRESS) {
1174			m_freem(m0);
1175			return error;
1176		}
1177
1178		sc->tx_queued++;
1179		sc->tx_cur = (sc->tx_cur + 1) % RUM_TX_LIST_COUNT;
1180
1181		flags |= RT2573_TX_LONG_RETRY | RT2573_TX_IFS_SIFS;
1182	}
1183
1184	data = &sc->tx_data[sc->tx_cur];
1185	desc = (struct rum_tx_desc *)data->buf;
1186
1187	data->ni = ni;
1188
1189	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1190		flags |= RT2573_TX_NEED_ACK;
1191
1192		dur = rum_txtime(RUM_ACK_SIZE, rum_ack_rate(ic, rate),
1193		    ic->ic_flags) + sc->sifs;
1194		*(uint16_t *)wh->i_dur = htole16(dur);
1195
1196		/* tell hardware to set timestamp in probe responses */
1197		if ((wh->i_fc[0] &
1198		    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
1199		    (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP))
1200			flags |= RT2573_TX_TIMESTAMP;
1201	}
1202
1203	if (sc->sc_drvbpf != NULL) {
1204		struct rum_tx_radiotap_header *tap = &sc->sc_txtap;
1205
1206		tap->wt_flags = 0;
1207		tap->wt_rate = rate;
1208		tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1209		tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1210		tap->wt_antenna = sc->tx_ant;
1211
1212		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0, BPF_D_OUT);
1213	}
1214
1215	m_copydata(m0, 0, m0->m_pkthdr.len, data->buf + RT2573_TX_DESC_SIZE);
1216	rum_setup_tx_desc(sc, desc, flags, 0, m0->m_pkthdr.len, rate);
1217
1218	/* align end on a 4-bytes boundary */
1219	xferlen = (RT2573_TX_DESC_SIZE + m0->m_pkthdr.len + 3) & ~3;
1220
1221	/*
1222	 * No space left in the last URB to store the extra 4 bytes, force
1223	 * sending of another URB.
1224	 */
1225	if ((xferlen % 64) == 0)
1226		xferlen += 4;
1227
1228	DPRINTFN(10, ("sending data frame len=%zu rate=%u xfer len=%u\n",
1229	    (size_t)m0->m_pkthdr.len + RT2573_TX_DESC_SIZE,
1230	    rate, xferlen));
1231
1232	/* mbuf is no longer needed */
1233	m_freem(m0);
1234
1235	usbd_setup_xfer(data->xfer, data, data->buf, xferlen,
1236	    USBD_FORCE_SHORT_XFER, RUM_TX_TIMEOUT, rum_txeof);
1237	error = usbd_transfer(data->xfer);
1238	if (error != USBD_NORMAL_COMPLETION && error != USBD_IN_PROGRESS)
1239		return error;
1240
1241	sc->tx_queued++;
1242	sc->tx_cur = (sc->tx_cur + 1) % RUM_TX_LIST_COUNT;
1243
1244	return 0;
1245}
1246
1247static void
1248rum_start(struct ifnet *ifp)
1249{
1250	struct rum_softc *sc = ifp->if_softc;
1251	struct ieee80211com *ic = &sc->sc_ic;
1252	struct ether_header *eh;
1253	struct ieee80211_node *ni;
1254	struct mbuf *m0;
1255
1256	if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
1257		return;
1258
1259	for (;;) {
1260		IF_POLL(&ic->ic_mgtq, m0);
1261		if (m0 != NULL) {
1262			if (sc->tx_queued >= RUM_TX_LIST_COUNT - 1) {
1263				ifp->if_flags |= IFF_OACTIVE;
1264				break;
1265			}
1266			IF_DEQUEUE(&ic->ic_mgtq, m0);
1267
1268			ni = M_GETCTX(m0, struct ieee80211_node *);
1269			M_CLEARCTX(m0);
1270			bpf_mtap3(ic->ic_rawbpf, m0, BPF_D_OUT);
1271			if (rum_tx_data(sc, m0, ni) != 0)
1272				break;
1273
1274		} else {
1275			if (ic->ic_state != IEEE80211_S_RUN)
1276				break;
1277			IFQ_POLL(&ifp->if_snd, m0);
1278			if (m0 == NULL)
1279				break;
1280			if (sc->tx_queued >= RUM_TX_LIST_COUNT - 1) {
1281				ifp->if_flags |= IFF_OACTIVE;
1282				break;
1283			}
1284			IFQ_DEQUEUE(&ifp->if_snd, m0);
1285			if (m0->m_len < (int)sizeof(struct ether_header) &&
1286			    !(m0 = m_pullup(m0, sizeof(struct ether_header))))
1287				continue;
1288
1289			eh = mtod(m0, struct ether_header *);
1290			ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1291			if (ni == NULL) {
1292				m_freem(m0);
1293				continue;
1294			}
1295			bpf_mtap(ifp, m0, BPF_D_OUT);
1296			m0 = ieee80211_encap(ic, m0, ni);
1297			if (m0 == NULL) {
1298				ieee80211_free_node(ni);
1299				continue;
1300			}
1301			bpf_mtap3(ic->ic_rawbpf, m0, BPF_D_OUT);
1302			if (rum_tx_data(sc, m0, ni) != 0) {
1303				ieee80211_free_node(ni);
1304				if_statinc(ifp, if_oerrors);
1305				break;
1306			}
1307		}
1308
1309		sc->sc_tx_timer = 5;
1310		ifp->if_timer = 1;
1311	}
1312}
1313
1314static void
1315rum_watchdog(struct ifnet *ifp)
1316{
1317	struct rum_softc *sc = ifp->if_softc;
1318	struct ieee80211com *ic = &sc->sc_ic;
1319
1320	ifp->if_timer = 0;
1321
1322	if (sc->sc_tx_timer > 0) {
1323		if (--sc->sc_tx_timer == 0) {
1324			printf("%s: device timeout\n", device_xname(sc->sc_dev));
1325			/*rum_init(ifp); XXX needs a process context! */
1326			if_statinc(ifp, if_oerrors);
1327			return;
1328		}
1329		ifp->if_timer = 1;
1330	}
1331
1332	ieee80211_watchdog(ic);
1333}
1334
1335static int
1336rum_ioctl(struct ifnet *ifp, u_long cmd, void *data)
1337{
1338#define IS_RUNNING(ifp) \
1339	(((ifp)->if_flags & IFF_UP) && ((ifp)->if_flags & IFF_RUNNING))
1340
1341	struct rum_softc *sc = ifp->if_softc;
1342	struct ieee80211com *ic = &sc->sc_ic;
1343	int s, error = 0;
1344
1345	s = splnet();
1346
1347	switch (cmd) {
1348	case SIOCSIFFLAGS:
1349		if ((error = ifioctl_common(ifp, cmd, data)) != 0)
1350			break;
1351		switch (ifp->if_flags & (IFF_UP|IFF_RUNNING)) {
1352		case IFF_UP|IFF_RUNNING:
1353			rum_update_promisc(sc);
1354			break;
1355		case IFF_UP:
1356			rum_init(ifp);
1357			break;
1358		case IFF_RUNNING:
1359			rum_stop(ifp, 1);
1360			break;
1361		case 0:
1362			break;
1363		}
1364		break;
1365
1366	case SIOCADDMULTI:
1367	case SIOCDELMULTI:
1368		if ((error = ether_ioctl(ifp, cmd, data)) == ENETRESET) {
1369			error = 0;
1370		}
1371		break;
1372
1373	default:
1374		error = ieee80211_ioctl(ic, cmd, data);
1375	}
1376
1377	if (error == ENETRESET) {
1378		if (IS_RUNNING(ifp) &&
1379			(ic->ic_roaming != IEEE80211_ROAMING_MANUAL))
1380			rum_init(ifp);
1381		error = 0;
1382	}
1383
1384	splx(s);
1385
1386	return error;
1387#undef IS_RUNNING
1388}
1389
1390static void
1391rum_eeprom_read(struct rum_softc *sc, uint16_t addr, void *buf, int len)
1392{
1393	usb_device_request_t req;
1394	usbd_status error;
1395
1396	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1397	req.bRequest = RT2573_READ_EEPROM;
1398	USETW(req.wValue, 0);
1399	USETW(req.wIndex, addr);
1400	USETW(req.wLength, len);
1401
1402	error = usbd_do_request(sc->sc_udev, &req, buf);
1403	if (error != 0) {
1404		printf("%s: could not read EEPROM: %s\n",
1405		    device_xname(sc->sc_dev), usbd_errstr(error));
1406	}
1407}
1408
1409static uint32_t
1410rum_read(struct rum_softc *sc, uint16_t reg)
1411{
1412	uint32_t val;
1413
1414	rum_read_multi(sc, reg, &val, sizeof(val));
1415
1416	return le32toh(val);
1417}
1418
1419static void
1420rum_read_multi(struct rum_softc *sc, uint16_t reg, void *buf, int len)
1421{
1422	usb_device_request_t req;
1423	usbd_status error;
1424
1425	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1426	req.bRequest = RT2573_READ_MULTI_MAC;
1427	USETW(req.wValue, 0);
1428	USETW(req.wIndex, reg);
1429	USETW(req.wLength, len);
1430
1431	error = usbd_do_request(sc->sc_udev, &req, buf);
1432	if (error != 0) {
1433		printf("%s: could not multi read MAC register: %s\n",
1434		    device_xname(sc->sc_dev), usbd_errstr(error));
1435	}
1436}
1437
1438static void
1439rum_write(struct rum_softc *sc, uint16_t reg, uint32_t val)
1440{
1441	uint32_t tmp = htole32(val);
1442
1443	rum_write_multi(sc, reg, &tmp, sizeof(tmp));
1444}
1445
1446static void
1447rum_write_multi(struct rum_softc *sc, uint16_t reg, void *buf, size_t len)
1448{
1449	usb_device_request_t req;
1450	usbd_status error;
1451	int offset;
1452
1453	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1454	req.bRequest = RT2573_WRITE_MULTI_MAC;
1455	USETW(req.wValue, 0);
1456
1457	/* write at most 64 bytes at a time */
1458	for (offset = 0; offset < len; offset += 64) {
1459		USETW(req.wIndex, reg + offset);
1460		USETW(req.wLength, MIN(len - offset, 64));
1461
1462		error = usbd_do_request(sc->sc_udev, &req, (char *)buf + offset);
1463		if (error != 0) {
1464			printf("%s: could not multi write MAC register: %s\n",
1465			    device_xname(sc->sc_dev), usbd_errstr(error));
1466		}
1467	}
1468}
1469
1470static void
1471rum_bbp_write(struct rum_softc *sc, uint8_t reg, uint8_t val)
1472{
1473	uint32_t tmp;
1474	int ntries;
1475
1476	for (ntries = 0; ntries < 5; ntries++) {
1477		if (!(rum_read(sc, RT2573_PHY_CSR3) & RT2573_BBP_BUSY))
1478			break;
1479	}
1480	if (ntries == 5) {
1481		printf("%s: could not write to BBP\n", device_xname(sc->sc_dev));
1482		return;
1483	}
1484
1485	tmp = RT2573_BBP_BUSY | (reg & 0x7f) << 8 | val;
1486	rum_write(sc, RT2573_PHY_CSR3, tmp);
1487}
1488
1489static uint8_t
1490rum_bbp_read(struct rum_softc *sc, uint8_t reg)
1491{
1492	uint32_t val;
1493	int ntries;
1494
1495	for (ntries = 0; ntries < 5; ntries++) {
1496		if (!(rum_read(sc, RT2573_PHY_CSR3) & RT2573_BBP_BUSY))
1497			break;
1498	}
1499	if (ntries == 5) {
1500		printf("%s: could not read BBP\n", device_xname(sc->sc_dev));
1501		return 0;
1502	}
1503
1504	val = RT2573_BBP_BUSY | RT2573_BBP_READ | reg << 8;
1505	rum_write(sc, RT2573_PHY_CSR3, val);
1506
1507	for (ntries = 0; ntries < 100; ntries++) {
1508		val = rum_read(sc, RT2573_PHY_CSR3);
1509		if (!(val & RT2573_BBP_BUSY))
1510			return val & 0xff;
1511		DELAY(1);
1512	}
1513
1514	printf("%s: could not read BBP\n", device_xname(sc->sc_dev));
1515	return 0;
1516}
1517
1518static void
1519rum_rf_write(struct rum_softc *sc, uint8_t reg, uint32_t val)
1520{
1521	uint32_t tmp;
1522	int ntries;
1523
1524	for (ntries = 0; ntries < 5; ntries++) {
1525		if (!(rum_read(sc, RT2573_PHY_CSR4) & RT2573_RF_BUSY))
1526			break;
1527	}
1528	if (ntries == 5) {
1529		printf("%s: could not write to RF\n", device_xname(sc->sc_dev));
1530		return;
1531	}
1532
1533	tmp = RT2573_RF_BUSY | RT2573_RF_20BIT | (val & 0xfffff) << 2 |
1534	    (reg & 3);
1535	rum_write(sc, RT2573_PHY_CSR4, tmp);
1536
1537	/* remember last written value in sc */
1538	sc->rf_regs[reg] = val;
1539
1540	DPRINTFN(15, ("RF R[%u] <- 0x%05x\n", reg & 3, val & 0xfffff));
1541}
1542
1543static void
1544rum_select_antenna(struct rum_softc *sc)
1545{
1546	uint8_t bbp4, bbp77;
1547	uint32_t tmp;
1548
1549	bbp4  = rum_bbp_read(sc, 4);
1550	bbp77 = rum_bbp_read(sc, 77);
1551
1552	/* TBD */
1553
1554	/* make sure Rx is disabled before switching antenna */
1555	tmp = rum_read(sc, RT2573_TXRX_CSR0);
1556	rum_write(sc, RT2573_TXRX_CSR0, tmp | RT2573_DISABLE_RX);
1557
1558	rum_bbp_write(sc,  4, bbp4);
1559	rum_bbp_write(sc, 77, bbp77);
1560
1561	rum_write(sc, RT2573_TXRX_CSR0, tmp);
1562}
1563
1564/*
1565 * Enable multi-rate retries for frames sent at OFDM rates.
1566 * In 802.11b/g mode, allow fallback to CCK rates.
1567 */
1568static void
1569rum_enable_mrr(struct rum_softc *sc)
1570{
1571	struct ieee80211com *ic = &sc->sc_ic;
1572	uint32_t tmp;
1573
1574	tmp = rum_read(sc, RT2573_TXRX_CSR4);
1575
1576	tmp &= ~RT2573_MRR_CCK_FALLBACK;
1577	if (!IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan))
1578		tmp |= RT2573_MRR_CCK_FALLBACK;
1579	tmp |= RT2573_MRR_ENABLED;
1580
1581	rum_write(sc, RT2573_TXRX_CSR4, tmp);
1582}
1583
1584static void
1585rum_set_txpreamble(struct rum_softc *sc)
1586{
1587	uint32_t tmp;
1588
1589	tmp = rum_read(sc, RT2573_TXRX_CSR4);
1590
1591	tmp &= ~RT2573_SHORT_PREAMBLE;
1592	if (sc->sc_ic.ic_flags & IEEE80211_F_SHPREAMBLE)
1593		tmp |= RT2573_SHORT_PREAMBLE;
1594
1595	rum_write(sc, RT2573_TXRX_CSR4, tmp);
1596}
1597
1598static void
1599rum_set_basicrates(struct rum_softc *sc)
1600{
1601	struct ieee80211com *ic = &sc->sc_ic;
1602
1603	/* update basic rate set */
1604	if (ic->ic_curmode == IEEE80211_MODE_11B) {
1605		/* 11b basic rates: 1, 2Mbps */
1606		rum_write(sc, RT2573_TXRX_CSR5, 0x3);
1607	} else if (ic->ic_curmode == IEEE80211_MODE_11A) {
1608		/* 11a basic rates: 6, 12, 24Mbps */
1609		rum_write(sc, RT2573_TXRX_CSR5, 0x150);
1610	} else {
1611		/* 11b/g basic rates: 1, 2, 5.5, 11Mbps */
1612		rum_write(sc, RT2573_TXRX_CSR5, 0xf);
1613	}
1614}
1615
1616/*
1617 * Reprogram MAC/BBP to switch to a new band.  Values taken from the reference
1618 * driver.
1619 */
1620static void
1621rum_select_band(struct rum_softc *sc, struct ieee80211_channel *c)
1622{
1623	uint8_t bbp17, bbp35, bbp96, bbp97, bbp98, bbp104;
1624	uint32_t tmp;
1625
1626	/* update all BBP registers that depend on the band */
1627	bbp17 = 0x20; bbp96 = 0x48; bbp104 = 0x2c;
1628	bbp35 = 0x50; bbp97 = 0x48; bbp98  = 0x48;
1629	if (IEEE80211_IS_CHAN_5GHZ(c)) {
1630		bbp17 += 0x08; bbp96 += 0x10; bbp104 += 0x0c;
1631		bbp35 += 0x10; bbp97 += 0x10; bbp98  += 0x10;
1632	}
1633	if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
1634	    (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
1635		bbp17 += 0x10; bbp96 += 0x10; bbp104 += 0x10;
1636	}
1637
1638	sc->bbp17 = bbp17;
1639	rum_bbp_write(sc,  17, bbp17);
1640	rum_bbp_write(sc,  96, bbp96);
1641	rum_bbp_write(sc, 104, bbp104);
1642
1643	if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
1644	    (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
1645		rum_bbp_write(sc, 75, 0x80);
1646		rum_bbp_write(sc, 86, 0x80);
1647		rum_bbp_write(sc, 88, 0x80);
1648	}
1649
1650	rum_bbp_write(sc, 35, bbp35);
1651	rum_bbp_write(sc, 97, bbp97);
1652	rum_bbp_write(sc, 98, bbp98);
1653
1654	tmp = rum_read(sc, RT2573_PHY_CSR0);
1655	tmp &= ~(RT2573_PA_PE_2GHZ | RT2573_PA_PE_5GHZ);
1656	if (IEEE80211_IS_CHAN_2GHZ(c))
1657		tmp |= RT2573_PA_PE_2GHZ;
1658	else
1659		tmp |= RT2573_PA_PE_5GHZ;
1660	rum_write(sc, RT2573_PHY_CSR0, tmp);
1661
1662	/* 802.11a uses a 16 microseconds short interframe space */
1663	sc->sifs = IEEE80211_IS_CHAN_5GHZ(c) ? 16 : 10;
1664}
1665
1666static void
1667rum_set_chan(struct rum_softc *sc, struct ieee80211_channel *c)
1668{
1669	struct ieee80211com *ic = &sc->sc_ic;
1670	const struct rfprog *rfprog;
1671	uint8_t bbp3, bbp94 = RT2573_BBPR94_DEFAULT;
1672	int8_t power;
1673	u_int i, chan;
1674
1675	chan = ieee80211_chan2ieee(ic, c);
1676	if (chan == 0 || chan == IEEE80211_CHAN_ANY)
1677		return;
1678
1679	/* select the appropriate RF settings based on what EEPROM says */
1680	rfprog = (sc->rf_rev == RT2573_RF_5225 ||
1681		  sc->rf_rev == RT2573_RF_2527) ? rum_rf5225 : rum_rf5226;
1682
1683	/* find the settings for this channel (we know it exists) */
1684	for (i = 0; rfprog[i].chan != chan; i++);
1685
1686	power = sc->txpow[i];
1687	if (power < 0) {
1688		bbp94 += power;
1689		power = 0;
1690	} else if (power > 31) {
1691		bbp94 += power - 31;
1692		power = 31;
1693	}
1694
1695	/*
1696	 * If we are switching from the 2GHz band to the 5GHz band or
1697	 * vice-versa, BBP registers need to be reprogrammed.
1698	 */
1699	if (c->ic_flags != ic->ic_curchan->ic_flags) {
1700		rum_select_band(sc, c);
1701		rum_select_antenna(sc);
1702	}
1703	ic->ic_curchan = c;
1704
1705	rum_rf_write(sc, RT2573_RF1, rfprog[i].r1);
1706	rum_rf_write(sc, RT2573_RF2, rfprog[i].r2);
1707	rum_rf_write(sc, RT2573_RF3, rfprog[i].r3 | power << 7);
1708	rum_rf_write(sc, RT2573_RF4, rfprog[i].r4 | sc->rffreq << 10);
1709
1710	rum_rf_write(sc, RT2573_RF1, rfprog[i].r1);
1711	rum_rf_write(sc, RT2573_RF2, rfprog[i].r2);
1712	rum_rf_write(sc, RT2573_RF3, rfprog[i].r3 | power << 7 | 1);
1713	rum_rf_write(sc, RT2573_RF4, rfprog[i].r4 | sc->rffreq << 10);
1714
1715	rum_rf_write(sc, RT2573_RF1, rfprog[i].r1);
1716	rum_rf_write(sc, RT2573_RF2, rfprog[i].r2);
1717	rum_rf_write(sc, RT2573_RF3, rfprog[i].r3 | power << 7);
1718	rum_rf_write(sc, RT2573_RF4, rfprog[i].r4 | sc->rffreq << 10);
1719
1720	DELAY(10);
1721
1722	/* enable smart mode for MIMO-capable RFs */
1723	bbp3 = rum_bbp_read(sc, 3);
1724
1725	bbp3 &= ~RT2573_SMART_MODE;
1726	if (sc->rf_rev == RT2573_RF_5225 || sc->rf_rev == RT2573_RF_2527)
1727		bbp3 |= RT2573_SMART_MODE;
1728
1729	rum_bbp_write(sc, 3, bbp3);
1730
1731	if (bbp94 != RT2573_BBPR94_DEFAULT)
1732		rum_bbp_write(sc, 94, bbp94);
1733}
1734
1735/*
1736 * Enable TSF synchronization and tell h/w to start sending beacons for IBSS
1737 * and HostAP operating modes.
1738 */
1739static void
1740rum_enable_tsf_sync(struct rum_softc *sc)
1741{
1742	struct ieee80211com *ic = &sc->sc_ic;
1743	uint32_t tmp;
1744
1745	if (ic->ic_opmode != IEEE80211_M_STA) {
1746		/*
1747		 * Change default 16ms TBTT adjustment to 8ms.
1748		 * Must be done before enabling beacon generation.
1749		 */
1750		rum_write(sc, RT2573_TXRX_CSR10, 1 << 12 | 8);
1751	}
1752
1753	tmp = rum_read(sc, RT2573_TXRX_CSR9) & 0xff000000;
1754
1755	/* set beacon interval (in 1/16ms unit) */
1756	tmp |= ic->ic_bss->ni_intval * 16;
1757
1758	tmp |= RT2573_TSF_TICKING | RT2573_ENABLE_TBTT;
1759	if (ic->ic_opmode == IEEE80211_M_STA)
1760		tmp |= RT2573_TSF_MODE(1);
1761	else
1762		tmp |= RT2573_TSF_MODE(2) | RT2573_GENERATE_BEACON;
1763
1764	rum_write(sc, RT2573_TXRX_CSR9, tmp);
1765}
1766
1767static void
1768rum_update_slot(struct rum_softc *sc)
1769{
1770	struct ieee80211com *ic = &sc->sc_ic;
1771	uint8_t slottime;
1772	uint32_t tmp;
1773
1774	slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
1775
1776	tmp = rum_read(sc, RT2573_MAC_CSR9);
1777	tmp = (tmp & ~0xff) | slottime;
1778	rum_write(sc, RT2573_MAC_CSR9, tmp);
1779
1780	DPRINTF(("setting slot time to %uus\n", slottime));
1781}
1782
1783static void
1784rum_set_bssid(struct rum_softc *sc, const uint8_t *bssid)
1785{
1786	uint32_t tmp;
1787
1788	tmp = bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24;
1789	rum_write(sc, RT2573_MAC_CSR4, tmp);
1790
1791	tmp = bssid[4] | bssid[5] << 8 | RT2573_ONE_BSSID << 16;
1792	rum_write(sc, RT2573_MAC_CSR5, tmp);
1793}
1794
1795static void
1796rum_set_macaddr(struct rum_softc *sc, const uint8_t *addr)
1797{
1798	uint32_t tmp;
1799
1800	tmp = addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24;
1801	rum_write(sc, RT2573_MAC_CSR2, tmp);
1802
1803	tmp = addr[4] | addr[5] << 8 | 0xff << 16;
1804	rum_write(sc, RT2573_MAC_CSR3, tmp);
1805}
1806
1807static void
1808rum_update_promisc(struct rum_softc *sc)
1809{
1810	struct ifnet *ifp = sc->sc_ic.ic_ifp;
1811	uint32_t tmp;
1812
1813	tmp = rum_read(sc, RT2573_TXRX_CSR0);
1814
1815	tmp &= ~RT2573_DROP_NOT_TO_ME;
1816	if (!(ifp->if_flags & IFF_PROMISC))
1817		tmp |= RT2573_DROP_NOT_TO_ME;
1818
1819	rum_write(sc, RT2573_TXRX_CSR0, tmp);
1820
1821	DPRINTF(("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
1822	    "entering" : "leaving"));
1823}
1824
1825static const char *
1826rum_get_rf(int rev)
1827{
1828	switch (rev) {
1829	case RT2573_RF_2527:	return "RT2527 (MIMO XR)";
1830	case RT2573_RF_2528:	return "RT2528";
1831	case RT2573_RF_5225:	return "RT5225 (MIMO XR)";
1832	case RT2573_RF_5226:	return "RT5226";
1833	default:		return "unknown";
1834	}
1835}
1836
1837static void
1838rum_read_eeprom(struct rum_softc *sc)
1839{
1840	struct ieee80211com *ic = &sc->sc_ic;
1841	uint16_t val;
1842#ifdef RUM_DEBUG
1843	int i;
1844#endif
1845
1846	/* read MAC/BBP type */
1847	rum_eeprom_read(sc, RT2573_EEPROM_MACBBP, &val, 2);
1848	sc->macbbp_rev = le16toh(val);
1849
1850	/* read MAC address */
1851	rum_eeprom_read(sc, RT2573_EEPROM_ADDRESS, ic->ic_myaddr, 6);
1852
1853	rum_eeprom_read(sc, RT2573_EEPROM_ANTENNA, &val, 2);
1854	val = le16toh(val);
1855	sc->rf_rev =   (val >> 11) & 0x1f;
1856	sc->hw_radio = (val >> 10) & 0x1;
1857	sc->rx_ant =   (val >> 4)  & 0x3;
1858	sc->tx_ant =   (val >> 2)  & 0x3;
1859	sc->nb_ant =   val & 0x3;
1860
1861	DPRINTF(("RF revision=%d\n", sc->rf_rev));
1862
1863	rum_eeprom_read(sc, RT2573_EEPROM_CONFIG2, &val, 2);
1864	val = le16toh(val);
1865	sc->ext_5ghz_lna = (val >> 6) & 0x1;
1866	sc->ext_2ghz_lna = (val >> 4) & 0x1;
1867
1868	DPRINTF(("External 2GHz LNA=%d\nExternal 5GHz LNA=%d\n",
1869	    sc->ext_2ghz_lna, sc->ext_5ghz_lna));
1870
1871	rum_eeprom_read(sc, RT2573_EEPROM_RSSI_2GHZ_OFFSET, &val, 2);
1872	val = le16toh(val);
1873	if ((val & 0xff) != 0xff)
1874		sc->rssi_2ghz_corr = (int8_t)(val & 0xff);	/* signed */
1875
1876	rum_eeprom_read(sc, RT2573_EEPROM_RSSI_5GHZ_OFFSET, &val, 2);
1877	val = le16toh(val);
1878	if ((val & 0xff) != 0xff)
1879		sc->rssi_5ghz_corr = (int8_t)(val & 0xff);	/* signed */
1880
1881	DPRINTF(("RSSI 2GHz corr=%d\nRSSI 5GHz corr=%d\n",
1882	    sc->rssi_2ghz_corr, sc->rssi_5ghz_corr));
1883
1884	rum_eeprom_read(sc, RT2573_EEPROM_FREQ_OFFSET, &val, 2);
1885	val = le16toh(val);
1886	if ((val & 0xff) != 0xff)
1887		sc->rffreq = val & 0xff;
1888
1889	DPRINTF(("RF freq=%d\n", sc->rffreq));
1890
1891	/* read Tx power for all a/b/g channels */
1892	rum_eeprom_read(sc, RT2573_EEPROM_TXPOWER, sc->txpow, 14);
1893	/* XXX default Tx power for 802.11a channels */
1894	memset(sc->txpow + 14, 24, sizeof(sc->txpow) - 14);
1895#ifdef RUM_DEBUG
1896	for (i = 0; i < 14; i++)
1897		DPRINTF(("Channel=%d Tx power=%d\n", i + 1,  sc->txpow[i]));
1898#endif
1899
1900	/* read default values for BBP registers */
1901	rum_eeprom_read(sc, RT2573_EEPROM_BBP_BASE, sc->bbp_prom, 2 * 16);
1902#ifdef RUM_DEBUG
1903	for (i = 0; i < 14; i++) {
1904		if (sc->bbp_prom[i].reg == 0 || sc->bbp_prom[i].reg == 0xff)
1905			continue;
1906		DPRINTF(("BBP R%d=%02x\n", sc->bbp_prom[i].reg,
1907		    sc->bbp_prom[i].val));
1908	}
1909#endif
1910}
1911
1912static int
1913rum_bbp_init(struct rum_softc *sc)
1914{
1915	unsigned int i, ntries;
1916	uint8_t val;
1917
1918	/* wait for BBP to be ready */
1919	for (ntries = 0; ntries < 100; ntries++) {
1920		val = rum_bbp_read(sc, 0);
1921		if (val != 0 && val != 0xff)
1922			break;
1923		DELAY(1000);
1924	}
1925	if (ntries == 100) {
1926		printf("%s: timeout waiting for BBP\n",
1927		    device_xname(sc->sc_dev));
1928		return EIO;
1929	}
1930
1931	/* initialize BBP registers to default values */
1932	for (i = 0; i < __arraycount(rum_def_bbp); i++)
1933		rum_bbp_write(sc, rum_def_bbp[i].reg, rum_def_bbp[i].val);
1934
1935	/* write vendor-specific BBP values (from EEPROM) */
1936	for (i = 0; i < 16; i++) {
1937		if (sc->bbp_prom[i].reg == 0 || sc->bbp_prom[i].reg == 0xff)
1938			continue;
1939		rum_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
1940	}
1941
1942	return 0;
1943}
1944
1945static int
1946rum_init(struct ifnet *ifp)
1947{
1948	struct rum_softc *sc = ifp->if_softc;
1949	struct ieee80211com *ic = &sc->sc_ic;
1950	uint32_t tmp;
1951	usbd_status error = 0;
1952	unsigned int i, ntries;
1953
1954	if ((sc->sc_flags & RT2573_FWLOADED) == 0) {
1955		if (rum_attachhook(sc))
1956			goto fail;
1957	}
1958
1959	rum_stop(ifp, 0);
1960
1961	/* initialize MAC registers to default values */
1962	for (i = 0; i < __arraycount(rum_def_mac); i++)
1963		rum_write(sc, rum_def_mac[i].reg, rum_def_mac[i].val);
1964
1965	/* set host ready */
1966	rum_write(sc, RT2573_MAC_CSR1, 3);
1967	rum_write(sc, RT2573_MAC_CSR1, 0);
1968
1969	/* wait for BBP/RF to wakeup */
1970	for (ntries = 0; ntries < 1000; ntries++) {
1971		if (rum_read(sc, RT2573_MAC_CSR12) & 8)
1972			break;
1973		rum_write(sc, RT2573_MAC_CSR12, 4);	/* force wakeup */
1974		DELAY(1000);
1975	}
1976	if (ntries == 1000) {
1977		printf("%s: timeout waiting for BBP/RF to wakeup\n",
1978		    device_xname(sc->sc_dev));
1979		goto fail;
1980	}
1981
1982	if ((error = rum_bbp_init(sc)) != 0)
1983		goto fail;
1984
1985	/* select default channel */
1986	rum_select_band(sc, ic->ic_curchan);
1987	rum_select_antenna(sc);
1988	rum_set_chan(sc, ic->ic_curchan);
1989
1990	/* clear STA registers */
1991	rum_read_multi(sc, RT2573_STA_CSR0, sc->sta, sizeof(sc->sta));
1992
1993	IEEE80211_ADDR_COPY(ic->ic_myaddr, CLLADDR(ifp->if_sadl));
1994	rum_set_macaddr(sc, ic->ic_myaddr);
1995
1996	/* initialize ASIC */
1997	rum_write(sc, RT2573_MAC_CSR1, 4);
1998
1999	/*
2000	 * Allocate xfer for AMRR statistics requests.
2001	 */
2002	struct usbd_pipe *pipe0 = usbd_get_pipe0(sc->sc_udev);
2003	error = usbd_create_xfer(pipe0, sizeof(sc->sta), 0, 0,
2004	    &sc->amrr_xfer);
2005	if (error) {
2006		printf("%s: could not allocate AMRR xfer\n",
2007		    device_xname(sc->sc_dev));
2008		goto fail;
2009	}
2010
2011	/*
2012	 * Open Tx and Rx USB bulk pipes.
2013	 */
2014	error = usbd_open_pipe(sc->sc_iface, sc->sc_tx_no, USBD_EXCLUSIVE_USE,
2015	    &sc->sc_tx_pipeh);
2016	if (error != 0) {
2017		printf("%s: could not open Tx pipe: %s\n",
2018		    device_xname(sc->sc_dev), usbd_errstr(error));
2019		goto fail;
2020	}
2021
2022	error = usbd_open_pipe(sc->sc_iface, sc->sc_rx_no, USBD_EXCLUSIVE_USE,
2023	    &sc->sc_rx_pipeh);
2024	if (error != 0) {
2025		printf("%s: could not open Rx pipe: %s\n",
2026		    device_xname(sc->sc_dev), usbd_errstr(error));
2027		goto fail;
2028	}
2029
2030	/*
2031	 * Allocate Tx and Rx xfer queues.
2032	 */
2033	error = rum_alloc_tx_list(sc);
2034	if (error != 0) {
2035		printf("%s: could not allocate Tx list\n",
2036		    device_xname(sc->sc_dev));
2037		goto fail;
2038	}
2039
2040	error = rum_alloc_rx_list(sc);
2041	if (error != 0) {
2042		printf("%s: could not allocate Rx list\n",
2043		    device_xname(sc->sc_dev));
2044		goto fail;
2045	}
2046
2047	/*
2048	 * Start up the receive pipe.
2049	 */
2050	for (i = 0; i < RUM_RX_LIST_COUNT; i++) {
2051		struct rum_rx_data *data;
2052
2053		data = &sc->rx_data[i];
2054
2055		usbd_setup_xfer(data->xfer, data, data->buf, MCLBYTES,
2056		    USBD_SHORT_XFER_OK, USBD_NO_TIMEOUT, rum_rxeof);
2057		error = usbd_transfer(data->xfer);
2058		if (error != USBD_NORMAL_COMPLETION &&
2059		    error != USBD_IN_PROGRESS) {
2060			printf("%s: could not queue Rx transfer\n",
2061			    device_xname(sc->sc_dev));
2062			goto fail;
2063		}
2064	}
2065
2066	/* update Rx filter */
2067	tmp = rum_read(sc, RT2573_TXRX_CSR0) & 0xffff;
2068
2069	tmp |= RT2573_DROP_PHY_ERROR | RT2573_DROP_CRC_ERROR;
2070	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2071		tmp |= RT2573_DROP_CTL | RT2573_DROP_VER_ERROR |
2072		       RT2573_DROP_ACKCTS;
2073		if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2074			tmp |= RT2573_DROP_TODS;
2075		if (!(ifp->if_flags & IFF_PROMISC))
2076			tmp |= RT2573_DROP_NOT_TO_ME;
2077	}
2078	rum_write(sc, RT2573_TXRX_CSR0, tmp);
2079
2080	ifp->if_flags &= ~IFF_OACTIVE;
2081	ifp->if_flags |= IFF_RUNNING;
2082
2083	if (ic->ic_opmode == IEEE80211_M_MONITOR)
2084		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
2085	else
2086		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
2087
2088	return 0;
2089
2090fail:	rum_stop(ifp, 1);
2091	return error;
2092}
2093
2094static void
2095rum_stop(struct ifnet *ifp, int disable)
2096{
2097	struct rum_softc *sc = ifp->if_softc;
2098	struct ieee80211com *ic = &sc->sc_ic;
2099	uint32_t tmp;
2100
2101	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);	/* free all nodes */
2102
2103	sc->sc_tx_timer = 0;
2104	ifp->if_timer = 0;
2105	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2106
2107	/* disable Rx */
2108	tmp = rum_read(sc, RT2573_TXRX_CSR0);
2109	rum_write(sc, RT2573_TXRX_CSR0, tmp | RT2573_DISABLE_RX);
2110
2111	/* reset ASIC */
2112	rum_write(sc, RT2573_MAC_CSR1, 3);
2113	rum_write(sc, RT2573_MAC_CSR1, 0);
2114
2115	if (sc->amrr_xfer != NULL) {
2116		usbd_destroy_xfer(sc->amrr_xfer);
2117		sc->amrr_xfer = NULL;
2118	}
2119
2120	if (sc->sc_rx_pipeh != NULL) {
2121		usbd_abort_pipe(sc->sc_rx_pipeh);
2122	}
2123
2124	if (sc->sc_tx_pipeh != NULL) {
2125		usbd_abort_pipe(sc->sc_tx_pipeh);
2126	}
2127
2128	rum_free_rx_list(sc);
2129	rum_free_tx_list(sc);
2130
2131	if (sc->sc_rx_pipeh != NULL) {
2132		usbd_close_pipe(sc->sc_rx_pipeh);
2133		sc->sc_rx_pipeh = NULL;
2134	}
2135
2136	if (sc->sc_tx_pipeh != NULL) {
2137		usbd_close_pipe(sc->sc_tx_pipeh);
2138		sc->sc_tx_pipeh = NULL;
2139	}
2140}
2141
2142static int
2143rum_load_microcode(struct rum_softc *sc, const u_char *ucode, size_t size)
2144{
2145	usb_device_request_t req;
2146	uint16_t reg = RT2573_MCU_CODE_BASE;
2147	usbd_status error;
2148
2149	/* copy firmware image into NIC */
2150	for (; size >= 4; reg += 4, ucode += 4, size -= 4)
2151		rum_write(sc, reg, UGETDW(ucode));
2152
2153	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
2154	req.bRequest = RT2573_MCU_CNTL;
2155	USETW(req.wValue, RT2573_MCU_RUN);
2156	USETW(req.wIndex, 0);
2157	USETW(req.wLength, 0);
2158
2159	error = usbd_do_request(sc->sc_udev, &req, NULL);
2160	if (error != 0) {
2161		printf("%s: could not run firmware: %s\n",
2162		    device_xname(sc->sc_dev), usbd_errstr(error));
2163	}
2164	return error;
2165}
2166
2167static int
2168rum_prepare_beacon(struct rum_softc *sc)
2169{
2170	struct ieee80211com *ic = &sc->sc_ic;
2171	struct rum_tx_desc desc;
2172	struct mbuf *m0;
2173	int rate;
2174
2175	m0 = ieee80211_beacon_alloc(ic, ic->ic_bss, &sc->sc_bo);
2176	if (m0 == NULL) {
2177		aprint_error_dev(sc->sc_dev,
2178		    "could not allocate beacon frame\n");
2179		return ENOBUFS;
2180	}
2181
2182	/* send beacons at the lowest available rate */
2183	rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan) ? 12 : 2;
2184
2185	rum_setup_tx_desc(sc, &desc, RT2573_TX_TIMESTAMP, RT2573_TX_HWSEQ,
2186	    m0->m_pkthdr.len, rate);
2187
2188	/* copy the first 24 bytes of Tx descriptor into NIC memory */
2189	rum_write_multi(sc, RT2573_HW_BEACON_BASE0, (uint8_t *)&desc, 24);
2190
2191	/* copy beacon header and payload into NIC memory */
2192	rum_write_multi(sc, RT2573_HW_BEACON_BASE0 + 24, mtod(m0, uint8_t *),
2193	    m0->m_pkthdr.len);
2194
2195	m_freem(m0);
2196
2197	return 0;
2198}
2199
2200static void
2201rum_newassoc(struct ieee80211_node *ni, int isnew)
2202{
2203	/* start with lowest Tx rate */
2204	ni->ni_txrate = 0;
2205}
2206
2207static void
2208rum_amrr_start(struct rum_softc *sc, struct ieee80211_node *ni)
2209{
2210	int i;
2211
2212	/* clear statistic registers (STA_CSR0 to STA_CSR5) */
2213	rum_read_multi(sc, RT2573_STA_CSR0, sc->sta, sizeof(sc->sta));
2214
2215	ieee80211_amrr_node_init(&sc->amrr, &sc->amn);
2216
2217	/* set rate to some reasonable initial value */
2218	for (i = ni->ni_rates.rs_nrates - 1;
2219	     i > 0 && (ni->ni_rates.rs_rates[i] & IEEE80211_RATE_VAL) > 72;
2220	     i--);
2221	ni->ni_txrate = i;
2222
2223	callout_reset(&sc->sc_amrr_ch, hz, rum_amrr_timeout, sc);
2224}
2225
2226static void
2227rum_amrr_timeout(void *arg)
2228{
2229	struct rum_softc *sc = arg;
2230	usb_device_request_t req;
2231
2232	/*
2233	 * Asynchronously read statistic registers (cleared by read).
2234	 */
2235	req.bmRequestType = UT_READ_VENDOR_DEVICE;
2236	req.bRequest = RT2573_READ_MULTI_MAC;
2237	USETW(req.wValue, 0);
2238	USETW(req.wIndex, RT2573_STA_CSR0);
2239	USETW(req.wLength, sizeof(sc->sta));
2240
2241	usbd_setup_default_xfer(sc->amrr_xfer, sc->sc_udev, sc,
2242	    USBD_DEFAULT_TIMEOUT, &req, sc->sta, sizeof(sc->sta), 0,
2243	    rum_amrr_update);
2244	(void)usbd_transfer(sc->amrr_xfer);
2245}
2246
2247static void
2248rum_amrr_update(struct usbd_xfer *xfer, void *priv,
2249    usbd_status status)
2250{
2251	struct rum_softc *sc = (struct rum_softc *)priv;
2252	struct ifnet *ifp = sc->sc_ic.ic_ifp;
2253
2254	if (status != USBD_NORMAL_COMPLETION) {
2255		printf("%s: could not retrieve Tx statistics - cancelling "
2256		    "automatic rate control\n", device_xname(sc->sc_dev));
2257		return;
2258	}
2259
2260	/* count TX retry-fail as Tx errors */
2261	if_statadd(ifp, if_oerrors, le32toh(sc->sta[5]) >> 16);
2262
2263	sc->amn.amn_retrycnt =
2264	    (le32toh(sc->sta[4]) >> 16) +	/* TX one-retry ok count */
2265	    (le32toh(sc->sta[5]) & 0xffff) +	/* TX more-retry ok count */
2266	    (le32toh(sc->sta[5]) >> 16);	/* TX retry-fail count */
2267
2268	sc->amn.amn_txcnt =
2269	    sc->amn.amn_retrycnt +
2270	    (le32toh(sc->sta[4]) & 0xffff);	/* TX no-retry ok count */
2271
2272	ieee80211_amrr_choose(&sc->amrr, sc->sc_ic.ic_bss, &sc->amn);
2273
2274	callout_reset(&sc->sc_amrr_ch, hz, rum_amrr_timeout, sc);
2275}
2276
2277static int
2278rum_activate(device_t self, enum devact act)
2279{
2280	switch (act) {
2281	case DVACT_DEACTIVATE:
2282		/*if_deactivate(&sc->sc_ic.ic_if);*/
2283		return 0;
2284	default:
2285		return 0;
2286	}
2287}
2288
2289MODULE(MODULE_CLASS_DRIVER, if_rum, NULL);
2290
2291#ifdef _MODULE
2292#include "ioconf.c"
2293#endif
2294
2295static int
2296if_rum_modcmd(modcmd_t cmd, void *aux)
2297{
2298	int error = 0;
2299
2300	switch (cmd) {
2301	case MODULE_CMD_INIT:
2302#ifdef _MODULE
2303		error = config_init_component(cfdriver_ioconf_rum,
2304		    cfattach_ioconf_rum, cfdata_ioconf_rum);
2305#endif
2306		return error;
2307	case MODULE_CMD_FINI:
2308#ifdef _MODULE
2309		error = config_fini_component(cfdriver_ioconf_rum,
2310		    cfattach_ioconf_rum, cfdata_ioconf_rum);
2311#endif
2312		return error;
2313	default:
2314		return ENOTTY;
2315	}
2316}
2317