xref: /openbsd-src/sys/dev/usb/if_ral.c (revision 1a8dbaac879b9f3335ad7fb25429ce63ac1d6bac)
1 /*	$OpenBSD: if_ral.c,v 1.148 2020/07/31 10:49:32 mglocker Exp $	*/
2 
3 /*-
4  * Copyright (c) 2005, 2006
5  *	Damien Bergamini <damien.bergamini@free.fr>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 /*-
21  * Ralink Technology RT2500USB chipset driver
22  * http://www.ralinktech.com.tw/
23  */
24 
25 #include "bpfilter.h"
26 
27 #include <sys/param.h>
28 #include <sys/sockio.h>
29 #include <sys/mbuf.h>
30 #include <sys/kernel.h>
31 #include <sys/socket.h>
32 #include <sys/systm.h>
33 #include <sys/timeout.h>
34 #include <sys/conf.h>
35 #include <sys/device.h>
36 #include <sys/endian.h>
37 
38 #include <machine/intr.h>
39 
40 #if NBPFILTER > 0
41 #include <net/bpf.h>
42 #endif
43 #include <net/if.h>
44 #include <net/if_dl.h>
45 #include <net/if_media.h>
46 
47 #include <netinet/in.h>
48 #include <netinet/if_ether.h>
49 
50 #include <net80211/ieee80211_var.h>
51 #include <net80211/ieee80211_amrr.h>
52 #include <net80211/ieee80211_radiotap.h>
53 
54 #include <dev/usb/usb.h>
55 #include <dev/usb/usbdi.h>
56 #include <dev/usb/usbdi_util.h>
57 #include <dev/usb/usbdevs.h>
58 
59 #include <dev/usb/if_ralreg.h>
60 #include <dev/usb/if_ralvar.h>
61 
62 #ifdef URAL_DEBUG
63 #define DPRINTF(x)	do { if (ural_debug) printf x; } while (0)
64 #define DPRINTFN(n, x)	do { if (ural_debug >= (n)) printf x; } while (0)
65 int ural_debug = 0;
66 #else
67 #define DPRINTF(x)
68 #define DPRINTFN(n, x)
69 #endif
70 
71 /* various supported device vendors/products */
72 static const struct usb_devno ural_devs[] = {
73 	{ USB_VENDOR_ASUS,		USB_PRODUCT_ASUS_RT2570 },
74 	{ USB_VENDOR_ASUS,		USB_PRODUCT_ASUS_RT2570_2 },
75 	{ USB_VENDOR_BELKIN,		USB_PRODUCT_BELKIN_F5D7050 },
76 	{ USB_VENDOR_CISCOLINKSYS,	USB_PRODUCT_CISCOLINKSYS_WUSB54G },
77 	{ USB_VENDOR_CISCOLINKSYS,	USB_PRODUCT_CISCOLINKSYS_WUSB54GP },
78 	{ USB_VENDOR_CISCOLINKSYS,	USB_PRODUCT_CISCOLINKSYS_HU200TS },
79 	{ USB_VENDOR_CONCEPTRONIC2,	USB_PRODUCT_CONCEPTRONIC2_C54RU },
80 	{ USB_VENDOR_DLINK,		USB_PRODUCT_DLINK_RT2570 },
81 	{ USB_VENDOR_GIGABYTE,		USB_PRODUCT_GIGABYTE_GNWBKG },
82 	{ USB_VENDOR_GUILLEMOT,		USB_PRODUCT_GUILLEMOT_HWGUSB254 },
83 	{ USB_VENDOR_MELCO,		USB_PRODUCT_MELCO_KG54 },
84 	{ USB_VENDOR_MELCO,		USB_PRODUCT_MELCO_KG54AI },
85 	{ USB_VENDOR_MELCO,		USB_PRODUCT_MELCO_KG54YB },
86 	{ USB_VENDOR_MELCO,		USB_PRODUCT_MELCO_NINWIFI },
87 	{ USB_VENDOR_MSI,		USB_PRODUCT_MSI_RT2570 },
88 	{ USB_VENDOR_MSI,		USB_PRODUCT_MSI_RT2570_2 },
89 	{ USB_VENDOR_MSI,		USB_PRODUCT_MSI_RT2570_3 },
90 	{ USB_VENDOR_NOVATECH,		USB_PRODUCT_NOVATECH_NV902W },
91 	{ USB_VENDOR_RALINK,		USB_PRODUCT_RALINK_RT2570 },
92 	{ USB_VENDOR_RALINK,		USB_PRODUCT_RALINK_RT2570_2 },
93 	{ USB_VENDOR_RALINK,		USB_PRODUCT_RALINK_RT2570_3 },
94 	{ USB_VENDOR_SPHAIRON,		USB_PRODUCT_SPHAIRON_UB801R },
95 	{ USB_VENDOR_SURECOM,		USB_PRODUCT_SURECOM_RT2570 },
96 	{ USB_VENDOR_VTECH,		USB_PRODUCT_VTECH_RT2570 },
97 	{ USB_VENDOR_ZINWELL,		USB_PRODUCT_ZINWELL_RT2570 }
98 };
99 
100 int		ural_alloc_tx_list(struct ural_softc *);
101 void		ural_free_tx_list(struct ural_softc *);
102 int		ural_alloc_rx_list(struct ural_softc *);
103 void		ural_free_rx_list(struct ural_softc *);
104 int		ural_media_change(struct ifnet *);
105 void		ural_next_scan(void *);
106 void		ural_task(void *);
107 int		ural_newstate(struct ieee80211com *, enum ieee80211_state,
108 		    int);
109 void		ural_txeof(struct usbd_xfer *, void *, usbd_status);
110 void		ural_rxeof(struct usbd_xfer *, void *, usbd_status);
111 #if NBPFILTER > 0
112 uint8_t		ural_rxrate(const struct ural_rx_desc *);
113 #endif
114 int		ural_ack_rate(struct ieee80211com *, int);
115 uint16_t	ural_txtime(int, int, uint32_t);
116 uint8_t		ural_plcp_signal(int);
117 void		ural_setup_tx_desc(struct ural_softc *, struct ural_tx_desc *,
118 		    uint32_t, int, int);
119 #ifndef IEEE80211_STA_ONLY
120 int		ural_tx_bcn(struct ural_softc *, struct mbuf *,
121 		    struct ieee80211_node *);
122 #endif
123 int		ural_tx_data(struct ural_softc *, struct mbuf *,
124 		    struct ieee80211_node *);
125 void		ural_start(struct ifnet *);
126 void		ural_watchdog(struct ifnet *);
127 int		ural_ioctl(struct ifnet *, u_long, caddr_t);
128 void		ural_eeprom_read(struct ural_softc *, uint16_t, void *, int);
129 uint16_t	ural_read(struct ural_softc *, uint16_t);
130 void		ural_read_multi(struct ural_softc *, uint16_t, void *, int);
131 void		ural_write(struct ural_softc *, uint16_t, uint16_t);
132 void		ural_write_multi(struct ural_softc *, uint16_t, void *, int);
133 void		ural_bbp_write(struct ural_softc *, uint8_t, uint8_t);
134 uint8_t		ural_bbp_read(struct ural_softc *, uint8_t);
135 void		ural_rf_write(struct ural_softc *, uint8_t, uint32_t);
136 void		ural_set_chan(struct ural_softc *, struct ieee80211_channel *);
137 void		ural_disable_rf_tune(struct ural_softc *);
138 void		ural_enable_tsf_sync(struct ural_softc *);
139 void		ural_update_slot(struct ural_softc *);
140 void		ural_set_txpreamble(struct ural_softc *);
141 void		ural_set_basicrates(struct ural_softc *);
142 void		ural_set_bssid(struct ural_softc *, const uint8_t *);
143 void		ural_set_macaddr(struct ural_softc *, const uint8_t *);
144 void		ural_update_promisc(struct ural_softc *);
145 const char	*ural_get_rf(int);
146 void		ural_read_eeprom(struct ural_softc *);
147 int		ural_bbp_init(struct ural_softc *);
148 void		ural_set_txantenna(struct ural_softc *, int);
149 void		ural_set_rxantenna(struct ural_softc *, int);
150 int		ural_init(struct ifnet *);
151 void		ural_stop(struct ifnet *, int);
152 void		ural_newassoc(struct ieee80211com *, struct ieee80211_node *,
153 		    int);
154 void		ural_amrr_start(struct ural_softc *, struct ieee80211_node *);
155 void		ural_amrr_timeout(void *);
156 void		ural_amrr_update(struct usbd_xfer *, void *,
157 		    usbd_status status);
158 
159 static const struct {
160 	uint16_t	reg;
161 	uint16_t	val;
162 } ural_def_mac[] = {
163 	RAL_DEF_MAC
164 };
165 
166 static const struct {
167 	uint8_t	reg;
168 	uint8_t	val;
169 } ural_def_bbp[] = {
170 	RAL_DEF_BBP
171 };
172 
173 static const uint32_t ural_rf2522_r2[] =    RAL_RF2522_R2;
174 static const uint32_t ural_rf2523_r2[] =    RAL_RF2523_R2;
175 static const uint32_t ural_rf2524_r2[] =    RAL_RF2524_R2;
176 static const uint32_t ural_rf2525_r2[] =    RAL_RF2525_R2;
177 static const uint32_t ural_rf2525_hi_r2[] = RAL_RF2525_HI_R2;
178 static const uint32_t ural_rf2525e_r2[] =   RAL_RF2525E_R2;
179 static const uint32_t ural_rf2526_hi_r2[] = RAL_RF2526_HI_R2;
180 static const uint32_t ural_rf2526_r2[] =    RAL_RF2526_R2;
181 
182 int ural_match(struct device *, void *, void *);
183 void ural_attach(struct device *, struct device *, void *);
184 int ural_detach(struct device *, int);
185 
186 struct cfdriver ural_cd = {
187 	NULL, "ural", DV_IFNET
188 };
189 
190 const struct cfattach ural_ca = {
191 	sizeof(struct ural_softc), ural_match, ural_attach, ural_detach
192 };
193 
194 int
195 ural_match(struct device *parent, void *match, void *aux)
196 {
197 	struct usb_attach_arg *uaa = aux;
198 
199 	if (uaa->configno != RAL_CONFIG_NO || uaa->ifaceno != RAL_IFACE_NO)
200 		return UMATCH_NONE;
201 
202 	return (usb_lookup(ural_devs, uaa->vendor, uaa->product) != NULL) ?
203 	    UMATCH_VENDOR_PRODUCT : UMATCH_NONE;
204 }
205 
206 void
207 ural_attach(struct device *parent, struct device *self, void *aux)
208 {
209 	struct ural_softc *sc = (struct ural_softc *)self;
210 	struct usb_attach_arg *uaa = aux;
211 	struct ieee80211com *ic = &sc->sc_ic;
212 	struct ifnet *ifp = &ic->ic_if;
213 	usb_interface_descriptor_t *id;
214 	usb_endpoint_descriptor_t *ed;
215 	int i;
216 
217 	sc->sc_udev = uaa->device;
218 	sc->sc_iface = uaa->iface;
219 
220 	/*
221 	 * Find endpoints.
222 	 */
223 	id = usbd_get_interface_descriptor(sc->sc_iface);
224 
225 	sc->sc_rx_no = sc->sc_tx_no = -1;
226 	for (i = 0; i < id->bNumEndpoints; i++) {
227 		ed = usbd_interface2endpoint_descriptor(sc->sc_iface, i);
228 		if (ed == NULL) {
229 			printf("%s: no endpoint descriptor for iface %d\n",
230 			    sc->sc_dev.dv_xname, i);
231 			return;
232 		}
233 
234 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
235 		    UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK)
236 			sc->sc_rx_no = ed->bEndpointAddress;
237 		else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT &&
238 		    UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK)
239 			sc->sc_tx_no = ed->bEndpointAddress;
240 	}
241 	if (sc->sc_rx_no == -1 || sc->sc_tx_no == -1) {
242 		printf("%s: missing endpoint\n", sc->sc_dev.dv_xname);
243 		return;
244 	}
245 
246 	usb_init_task(&sc->sc_task, ural_task, sc, USB_TASK_TYPE_GENERIC);
247 	timeout_set(&sc->scan_to, ural_next_scan, sc);
248 
249 	sc->amrr.amrr_min_success_threshold =  1;
250 	sc->amrr.amrr_max_success_threshold = 10;
251 	timeout_set(&sc->amrr_to, ural_amrr_timeout, sc);
252 
253 	/* retrieve RT2570 rev. no */
254 	sc->asic_rev = ural_read(sc, RAL_MAC_CSR0);
255 
256 	/* retrieve MAC address and various other things from EEPROM */
257 	ural_read_eeprom(sc);
258 
259 	printf("%s: MAC/BBP RT%04x (rev 0x%02x), RF %s, address %s\n",
260 	    sc->sc_dev.dv_xname, sc->macbbp_rev, sc->asic_rev,
261 	    ural_get_rf(sc->rf_rev), ether_sprintf(ic->ic_myaddr));
262 
263 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
264 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
265 	ic->ic_state = IEEE80211_S_INIT;
266 
267 	/* set device capabilities */
268 	ic->ic_caps =
269 	    IEEE80211_C_MONITOR |	/* monitor mode supported */
270 #ifndef IEEE80211_STA_ONLY
271 	    IEEE80211_C_IBSS |		/* IBSS mode supported */
272 	    IEEE80211_C_HOSTAP |	/* HostAp mode supported */
273 #endif
274 	    IEEE80211_C_TXPMGT |	/* tx power management */
275 	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
276 	    IEEE80211_C_SHSLOT |	/* short slot time supported */
277 	    IEEE80211_C_WEP |		/* s/w WEP */
278 	    IEEE80211_C_RSN;		/* WPA/RSN */
279 
280 	/* set supported .11b and .11g rates */
281 	ic->ic_sup_rates[IEEE80211_MODE_11B] = ieee80211_std_rateset_11b;
282 	ic->ic_sup_rates[IEEE80211_MODE_11G] = ieee80211_std_rateset_11g;
283 
284 	/* set supported .11b and .11g channels (1 through 14) */
285 	for (i = 1; i <= 14; i++) {
286 		ic->ic_channels[i].ic_freq =
287 		    ieee80211_ieee2mhz(i, IEEE80211_CHAN_2GHZ);
288 		ic->ic_channels[i].ic_flags =
289 		    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
290 		    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
291 	}
292 
293 	ifp->if_softc = sc;
294 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
295 	ifp->if_ioctl = ural_ioctl;
296 	ifp->if_start = ural_start;
297 	ifp->if_watchdog = ural_watchdog;
298 	memcpy(ifp->if_xname, sc->sc_dev.dv_xname, IFNAMSIZ);
299 
300 	if_attach(ifp);
301 	ieee80211_ifattach(ifp);
302 	ic->ic_newassoc = ural_newassoc;
303 
304 	/* override state transition machine */
305 	sc->sc_newstate = ic->ic_newstate;
306 	ic->ic_newstate = ural_newstate;
307 	ieee80211_media_init(ifp, ural_media_change, ieee80211_media_status);
308 
309 #if NBPFILTER > 0
310 	bpfattach(&sc->sc_drvbpf, ifp, DLT_IEEE802_11_RADIO,
311 	    sizeof (struct ieee80211_frame) + 64);
312 
313 	sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
314 	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
315 	sc->sc_rxtap.wr_ihdr.it_present = htole32(RAL_RX_RADIOTAP_PRESENT);
316 
317 	sc->sc_txtap_len = sizeof sc->sc_txtapu;
318 	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
319 	sc->sc_txtap.wt_ihdr.it_present = htole32(RAL_TX_RADIOTAP_PRESENT);
320 #endif
321 }
322 
323 int
324 ural_detach(struct device *self, int flags)
325 {
326 	struct ural_softc *sc = (struct ural_softc *)self;
327 	struct ifnet *ifp = &sc->sc_ic.ic_if;
328 	int s;
329 
330 	s = splusb();
331 
332 	if (timeout_initialized(&sc->scan_to))
333 		timeout_del(&sc->scan_to);
334 	if (timeout_initialized(&sc->amrr_to))
335 		timeout_del(&sc->amrr_to);
336 
337 	usb_rem_wait_task(sc->sc_udev, &sc->sc_task);
338 
339 	usbd_ref_wait(sc->sc_udev);
340 
341 	if (ifp->if_softc != NULL) {
342 		ieee80211_ifdetach(ifp);	/* free all nodes */
343 		if_detach(ifp);
344 	}
345 
346 	if (sc->amrr_xfer != NULL) {
347 		usbd_free_xfer(sc->amrr_xfer);
348 		sc->amrr_xfer = NULL;
349 	}
350 
351 	if (sc->sc_rx_pipeh != NULL)
352 		usbd_close_pipe(sc->sc_rx_pipeh);
353 
354 	if (sc->sc_tx_pipeh != NULL)
355 		usbd_close_pipe(sc->sc_tx_pipeh);
356 
357 	ural_free_rx_list(sc);
358 	ural_free_tx_list(sc);
359 
360 	splx(s);
361 
362 	return 0;
363 }
364 
365 int
366 ural_alloc_tx_list(struct ural_softc *sc)
367 {
368 	int i, error;
369 
370 	sc->tx_cur = sc->tx_queued = 0;
371 
372 	for (i = 0; i < RAL_TX_LIST_COUNT; i++) {
373 		struct ural_tx_data *data = &sc->tx_data[i];
374 
375 		data->sc = sc;
376 
377 		data->xfer = usbd_alloc_xfer(sc->sc_udev);
378 		if (data->xfer == NULL) {
379 			printf("%s: could not allocate tx xfer\n",
380 			    sc->sc_dev.dv_xname);
381 			error = ENOMEM;
382 			goto fail;
383 		}
384 		data->buf = usbd_alloc_buffer(data->xfer,
385 		    RAL_TX_DESC_SIZE + IEEE80211_MAX_LEN);
386 		if (data->buf == NULL) {
387 			printf("%s: could not allocate tx buffer\n",
388 			    sc->sc_dev.dv_xname);
389 			error = ENOMEM;
390 			goto fail;
391 		}
392 	}
393 
394 	return 0;
395 
396 fail:	ural_free_tx_list(sc);
397 	return error;
398 }
399 
400 void
401 ural_free_tx_list(struct ural_softc *sc)
402 {
403 	int i;
404 
405 	for (i = 0; i < RAL_TX_LIST_COUNT; i++) {
406 		struct ural_tx_data *data = &sc->tx_data[i];
407 
408 		if (data->xfer != NULL) {
409 			usbd_free_xfer(data->xfer);
410 			data->xfer = NULL;
411 		}
412 		/*
413 		 * The node has already been freed at that point so don't call
414 		 * ieee80211_release_node() here.
415 		 */
416 		data->ni = NULL;
417 	}
418 }
419 
420 int
421 ural_alloc_rx_list(struct ural_softc *sc)
422 {
423 	int i, error;
424 
425 	for (i = 0; i < RAL_RX_LIST_COUNT; i++) {
426 		struct ural_rx_data *data = &sc->rx_data[i];
427 
428 		data->sc = sc;
429 
430 		data->xfer = usbd_alloc_xfer(sc->sc_udev);
431 		if (data->xfer == NULL) {
432 			printf("%s: could not allocate rx xfer\n",
433 			    sc->sc_dev.dv_xname);
434 			error = ENOMEM;
435 			goto fail;
436 		}
437 		if (usbd_alloc_buffer(data->xfer, MCLBYTES) == NULL) {
438 			printf("%s: could not allocate rx buffer\n",
439 			    sc->sc_dev.dv_xname);
440 			error = ENOMEM;
441 			goto fail;
442 		}
443 
444 		MGETHDR(data->m, M_DONTWAIT, MT_DATA);
445 		if (data->m == NULL) {
446 			printf("%s: could not allocate rx mbuf\n",
447 			    sc->sc_dev.dv_xname);
448 			error = ENOMEM;
449 			goto fail;
450 		}
451 		MCLGET(data->m, M_DONTWAIT);
452 		if (!(data->m->m_flags & M_EXT)) {
453 			printf("%s: could not allocate rx mbuf cluster\n",
454 			    sc->sc_dev.dv_xname);
455 			error = ENOMEM;
456 			goto fail;
457 		}
458 		data->buf = mtod(data->m, uint8_t *);
459 	}
460 
461 	return 0;
462 
463 fail:	ural_free_rx_list(sc);
464 	return error;
465 }
466 
467 void
468 ural_free_rx_list(struct ural_softc *sc)
469 {
470 	int i;
471 
472 	for (i = 0; i < RAL_RX_LIST_COUNT; i++) {
473 		struct ural_rx_data *data = &sc->rx_data[i];
474 
475 		if (data->xfer != NULL) {
476 			usbd_free_xfer(data->xfer);
477 			data->xfer = NULL;
478 		}
479 		if (data->m != NULL) {
480 			m_freem(data->m);
481 			data->m = NULL;
482 		}
483 	}
484 }
485 
486 int
487 ural_media_change(struct ifnet *ifp)
488 {
489 	int error;
490 
491 	error = ieee80211_media_change(ifp);
492 	if (error != ENETRESET)
493 		return error;
494 
495 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
496 		error = ural_init(ifp);
497 
498 	return error;
499 }
500 
501 /*
502  * This function is called periodically (every 200ms) during scanning to
503  * switch from one channel to another.
504  */
505 void
506 ural_next_scan(void *arg)
507 {
508 	struct ural_softc *sc = arg;
509 	struct ieee80211com *ic = &sc->sc_ic;
510 	struct ifnet *ifp = &ic->ic_if;
511 
512 	if (usbd_is_dying(sc->sc_udev))
513 		return;
514 
515 	usbd_ref_incr(sc->sc_udev);
516 
517 	if (ic->ic_state == IEEE80211_S_SCAN)
518 		ieee80211_next_scan(ifp);
519 
520 	usbd_ref_decr(sc->sc_udev);
521 }
522 
523 void
524 ural_task(void *arg)
525 {
526 	struct ural_softc *sc = arg;
527 	struct ieee80211com *ic = &sc->sc_ic;
528 	enum ieee80211_state ostate;
529 	struct ieee80211_node *ni;
530 
531 	if (usbd_is_dying(sc->sc_udev))
532 		return;
533 
534 	ostate = ic->ic_state;
535 
536 	switch (sc->sc_state) {
537 	case IEEE80211_S_INIT:
538 		if (ostate == IEEE80211_S_RUN) {
539 			/* abort TSF synchronization */
540 			ural_write(sc, RAL_TXRX_CSR19, 0);
541 
542 			/* force tx led to stop blinking */
543 			ural_write(sc, RAL_MAC_CSR20, 0);
544 		}
545 		break;
546 
547 	case IEEE80211_S_SCAN:
548 		ural_set_chan(sc, ic->ic_bss->ni_chan);
549 		if (!usbd_is_dying(sc->sc_udev))
550 			timeout_add_msec(&sc->scan_to, 200);
551 		break;
552 
553 	case IEEE80211_S_AUTH:
554 		ural_set_chan(sc, ic->ic_bss->ni_chan);
555 		break;
556 
557 	case IEEE80211_S_ASSOC:
558 		ural_set_chan(sc, ic->ic_bss->ni_chan);
559 		break;
560 
561 	case IEEE80211_S_RUN:
562 		ural_set_chan(sc, ic->ic_bss->ni_chan);
563 
564 		ni = ic->ic_bss;
565 
566 		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
567 			ural_update_slot(sc);
568 			ural_set_txpreamble(sc);
569 			ural_set_basicrates(sc);
570 			ural_set_bssid(sc, ni->ni_bssid);
571 		}
572 
573 #ifndef IEEE80211_STA_ONLY
574 		if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
575 		    ic->ic_opmode == IEEE80211_M_IBSS) {
576 			struct mbuf *m = ieee80211_beacon_alloc(ic, ni);
577 			if (m == NULL) {
578 				printf("%s: could not allocate beacon\n",
579 				    sc->sc_dev.dv_xname);
580 				return;
581 			}
582 
583 			if (ural_tx_bcn(sc, m, ni) != 0) {
584 				m_freem(m);
585 				printf("%s: could not transmit beacon\n",
586 				    sc->sc_dev.dv_xname);
587 				return;
588 			}
589 
590 			/* beacon is no longer needed */
591 			m_freem(m);
592 		}
593 #endif
594 
595 		/* make tx led blink on tx (controlled by ASIC) */
596 		ural_write(sc, RAL_MAC_CSR20, 1);
597 
598 		if (ic->ic_opmode != IEEE80211_M_MONITOR)
599 			ural_enable_tsf_sync(sc);
600 
601 		if (ic->ic_opmode == IEEE80211_M_STA) {
602 			/* fake a join to init the tx rate */
603 			ural_newassoc(ic, ic->ic_bss, 1);
604 
605 			/* enable automatic rate control in STA mode */
606 			if (ic->ic_fixed_rate == -1)
607 				ural_amrr_start(sc, ic->ic_bss);
608 		}
609 
610 		break;
611 	}
612 
613 	sc->sc_newstate(ic, sc->sc_state, sc->sc_arg);
614 }
615 
616 int
617 ural_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
618 {
619 	struct ural_softc *sc = ic->ic_if.if_softc;
620 
621 	usb_rem_task(sc->sc_udev, &sc->sc_task);
622 	timeout_del(&sc->scan_to);
623 	timeout_del(&sc->amrr_to);
624 
625 	/* do it in a process context */
626 	sc->sc_state = nstate;
627 	sc->sc_arg = arg;
628 	usb_add_task(sc->sc_udev, &sc->sc_task);
629 	return 0;
630 }
631 
632 /* quickly determine if a given rate is CCK or OFDM */
633 #define RAL_RATE_IS_OFDM(rate) ((rate) >= 12 && (rate) != 22)
634 
635 #define RAL_ACK_SIZE	14	/* 10 + 4(FCS) */
636 #define RAL_CTS_SIZE	14	/* 10 + 4(FCS) */
637 
638 #define RAL_SIFS		10	/* us */
639 
640 #define RAL_RXTX_TURNAROUND	5	/* us */
641 
642 void
643 ural_txeof(struct usbd_xfer *xfer, void *priv, usbd_status status)
644 {
645 	struct ural_tx_data *data = priv;
646 	struct ural_softc *sc = data->sc;
647 	struct ieee80211com *ic = &sc->sc_ic;
648 	struct ifnet *ifp = &ic->ic_if;
649 	int s;
650 
651 	if (status != USBD_NORMAL_COMPLETION) {
652 		if (status == USBD_NOT_STARTED || status == USBD_CANCELLED)
653 			return;
654 
655 		printf("%s: could not transmit buffer: %s\n",
656 		    sc->sc_dev.dv_xname, usbd_errstr(status));
657 
658 		if (status == USBD_STALLED)
659 			usbd_clear_endpoint_stall_async(sc->sc_tx_pipeh);
660 
661 		ifp->if_oerrors++;
662 		return;
663 	}
664 
665 	s = splnet();
666 
667 	ieee80211_release_node(ic, data->ni);
668 	data->ni = NULL;
669 
670 	sc->tx_queued--;
671 
672 	DPRINTFN(10, ("tx done\n"));
673 
674 	sc->sc_tx_timer = 0;
675 	ifq_clr_oactive(&ifp->if_snd);
676 	ural_start(ifp);
677 
678 	splx(s);
679 }
680 
681 void
682 ural_rxeof(struct usbd_xfer *xfer, void *priv, usbd_status status)
683 {
684 	struct ural_rx_data *data = priv;
685 	struct ural_softc *sc = data->sc;
686 	struct ieee80211com *ic = &sc->sc_ic;
687 	struct ifnet *ifp = &ic->ic_if;
688 	const struct ural_rx_desc *desc;
689 	struct ieee80211_frame *wh;
690 	struct ieee80211_rxinfo rxi;
691 	struct ieee80211_node *ni;
692 	struct mbuf *mnew, *m;
693 	int s, len;
694 
695 	if (status != USBD_NORMAL_COMPLETION) {
696 		if (status == USBD_NOT_STARTED || status == USBD_CANCELLED)
697 			return;
698 
699 		if (status == USBD_STALLED)
700 			usbd_clear_endpoint_stall_async(sc->sc_rx_pipeh);
701 		goto skip;
702 	}
703 
704 	usbd_get_xfer_status(xfer, NULL, NULL, &len, NULL);
705 
706 	if (len < RAL_RX_DESC_SIZE + IEEE80211_MIN_LEN) {
707 		DPRINTF(("%s: xfer too short %d\n", sc->sc_dev.dv_xname,
708 		    len));
709 		ifp->if_ierrors++;
710 		goto skip;
711 	}
712 
713 	/* rx descriptor is located at the end */
714 	desc = (struct ural_rx_desc *)(data->buf + len - RAL_RX_DESC_SIZE);
715 
716 	if (letoh32(desc->flags) & (RAL_RX_PHY_ERROR | RAL_RX_CRC_ERROR)) {
717 		/*
718 		 * This should not happen since we did not request to receive
719 		 * those frames when we filled RAL_TXRX_CSR2.
720 		 */
721 		DPRINTFN(5, ("PHY or CRC error\n"));
722 		ifp->if_ierrors++;
723 		goto skip;
724 	}
725 
726 	MGETHDR(mnew, M_DONTWAIT, MT_DATA);
727 	if (mnew == NULL) {
728 		printf("%s: could not allocate rx mbuf\n",
729 		    sc->sc_dev.dv_xname);
730 		ifp->if_ierrors++;
731 		goto skip;
732 	}
733 	MCLGET(mnew, M_DONTWAIT);
734 	if (!(mnew->m_flags & M_EXT)) {
735 		printf("%s: could not allocate rx mbuf cluster\n",
736 		    sc->sc_dev.dv_xname);
737 		m_freem(mnew);
738 		ifp->if_ierrors++;
739 		goto skip;
740 	}
741 	m = data->m;
742 	data->m = mnew;
743 	data->buf = mtod(data->m, uint8_t *);
744 
745 	/* finalize mbuf */
746 	m->m_pkthdr.len = m->m_len = (letoh32(desc->flags) >> 16) & 0xfff;
747 
748 	s = splnet();
749 
750 #if NBPFILTER > 0
751 	if (sc->sc_drvbpf != NULL) {
752 		struct mbuf mb;
753 		struct ural_rx_radiotap_header *tap = &sc->sc_rxtap;
754 
755 		tap->wr_flags = IEEE80211_RADIOTAP_F_FCS;
756 		tap->wr_rate = ural_rxrate(desc);
757 		tap->wr_chan_freq = htole16(ic->ic_bss->ni_chan->ic_freq);
758 		tap->wr_chan_flags = htole16(ic->ic_bss->ni_chan->ic_flags);
759 		tap->wr_antenna = sc->rx_ant;
760 		tap->wr_antsignal = desc->rssi;
761 
762 		mb.m_data = (caddr_t)tap;
763 		mb.m_len = sc->sc_rxtap_len;
764 		mb.m_next = m;
765 		mb.m_nextpkt = NULL;
766 		mb.m_type = 0;
767 		mb.m_flags = 0;
768 		bpf_mtap(sc->sc_drvbpf, &mb, BPF_DIRECTION_IN);
769 	}
770 #endif
771 	m_adj(m, -IEEE80211_CRC_LEN);	/* trim FCS */
772 
773 	wh = mtod(m, struct ieee80211_frame *);
774 	ni = ieee80211_find_rxnode(ic, wh);
775 
776 	/* send the frame to the 802.11 layer */
777 	rxi.rxi_flags = 0;
778 	rxi.rxi_rssi = desc->rssi;
779 	rxi.rxi_tstamp = 0;	/* unused */
780 	ieee80211_input(ifp, m, ni, &rxi);
781 
782 	/* node is no longer needed */
783 	ieee80211_release_node(ic, ni);
784 
785 	splx(s);
786 
787 	DPRINTFN(15, ("rx done\n"));
788 
789 skip:	/* setup a new transfer */
790 	usbd_setup_xfer(xfer, sc->sc_rx_pipeh, data, data->buf, MCLBYTES,
791 	    USBD_SHORT_XFER_OK, USBD_NO_TIMEOUT, ural_rxeof);
792 	(void)usbd_transfer(xfer);
793 }
794 
795 /*
796  * This function is only used by the Rx radiotap code. It returns the rate at
797  * which a given frame was received.
798  */
799 #if NBPFILTER > 0
800 uint8_t
801 ural_rxrate(const struct ural_rx_desc *desc)
802 {
803 	if (letoh32(desc->flags) & RAL_RX_OFDM) {
804 		/* reverse function of ural_plcp_signal */
805 		switch (desc->rate) {
806 		case 0xb:	return 12;
807 		case 0xf:	return 18;
808 		case 0xa:	return 24;
809 		case 0xe:	return 36;
810 		case 0x9:	return 48;
811 		case 0xd:	return 72;
812 		case 0x8:	return 96;
813 		case 0xc:	return 108;
814 		}
815 	} else {
816 		if (desc->rate == 10)
817 			return 2;
818 		if (desc->rate == 20)
819 			return 4;
820 		if (desc->rate == 55)
821 			return 11;
822 		if (desc->rate == 110)
823 			return 22;
824 	}
825 	return 2;	/* should not get there */
826 }
827 #endif
828 
829 /*
830  * Return the expected ack rate for a frame transmitted at rate `rate'.
831  */
832 int
833 ural_ack_rate(struct ieee80211com *ic, int rate)
834 {
835 	switch (rate) {
836 	/* CCK rates */
837 	case 2:
838 		return 2;
839 	case 4:
840 	case 11:
841 	case 22:
842 		return (ic->ic_curmode == IEEE80211_MODE_11B) ? 4 : rate;
843 
844 	/* OFDM rates */
845 	case 12:
846 	case 18:
847 		return 12;
848 	case 24:
849 	case 36:
850 		return 24;
851 	case 48:
852 	case 72:
853 	case 96:
854 	case 108:
855 		return 48;
856 	}
857 
858 	/* default to 1Mbps */
859 	return 2;
860 }
861 
862 /*
863  * Compute the duration (in us) needed to transmit `len' bytes at rate `rate'.
864  * The function automatically determines the operating mode depending on the
865  * given rate. `flags' indicates whether short preamble is in use or not.
866  */
867 uint16_t
868 ural_txtime(int len, int rate, uint32_t flags)
869 {
870 	uint16_t txtime;
871 
872 	if (RAL_RATE_IS_OFDM(rate)) {
873 		/* IEEE Std 802.11g-2003, pp. 44 */
874 		txtime = (8 + 4 * len + 3 + rate - 1) / rate;
875 		txtime = 16 + 4 + 4 * txtime + 6;
876 	} else {
877 		/* IEEE Std 802.11b-1999, pp. 28 */
878 		txtime = (16 * len + rate - 1) / rate;
879 		if (rate != 2 && (flags & IEEE80211_F_SHPREAMBLE))
880 			txtime +=  72 + 24;
881 		else
882 			txtime += 144 + 48;
883 	}
884 	return txtime;
885 }
886 
887 uint8_t
888 ural_plcp_signal(int rate)
889 {
890 	switch (rate) {
891 	/* CCK rates (returned values are device-dependent) */
892 	case 2:		return 0x0;
893 	case 4:		return 0x1;
894 	case 11:	return 0x2;
895 	case 22:	return 0x3;
896 
897 	/* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
898 	case 12:	return 0xb;
899 	case 18:	return 0xf;
900 	case 24:	return 0xa;
901 	case 36:	return 0xe;
902 	case 48:	return 0x9;
903 	case 72:	return 0xd;
904 	case 96:	return 0x8;
905 	case 108:	return 0xc;
906 
907 	/* unsupported rates (should not get there) */
908 	default:	return 0xff;
909 	}
910 }
911 
912 void
913 ural_setup_tx_desc(struct ural_softc *sc, struct ural_tx_desc *desc,
914     uint32_t flags, int len, int rate)
915 {
916 	struct ieee80211com *ic = &sc->sc_ic;
917 	uint16_t plcp_length;
918 	int remainder;
919 
920 	desc->flags = htole32(flags);
921 	desc->flags |= htole32(len << 16);
922 
923 	desc->wme = htole16(
924 	    RAL_AIFSN(2) |
925 	    RAL_LOGCWMIN(3) |
926 	    RAL_LOGCWMAX(5));
927 
928 	/* setup PLCP fields */
929 	desc->plcp_signal  = ural_plcp_signal(rate);
930 	desc->plcp_service = 4;
931 
932 	len += IEEE80211_CRC_LEN;
933 	if (RAL_RATE_IS_OFDM(rate)) {
934 		desc->flags |= htole32(RAL_TX_OFDM);
935 
936 		plcp_length = len & 0xfff;
937 		desc->plcp_length_hi = plcp_length >> 6;
938 		desc->plcp_length_lo = plcp_length & 0x3f;
939 	} else {
940 		plcp_length = (16 * len + rate - 1) / rate;
941 		if (rate == 22) {
942 			remainder = (16 * len) % 22;
943 			if (remainder != 0 && remainder < 7)
944 				desc->plcp_service |= RAL_PLCP_LENGEXT;
945 		}
946 		desc->plcp_length_hi = plcp_length >> 8;
947 		desc->plcp_length_lo = plcp_length & 0xff;
948 
949 		if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
950 			desc->plcp_signal |= 0x08;
951 	}
952 
953 	desc->iv = 0;
954 	desc->eiv = 0;
955 }
956 
957 #define RAL_TX_TIMEOUT	5000
958 
959 #ifndef IEEE80211_STA_ONLY
960 int
961 ural_tx_bcn(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
962 {
963 	struct ural_tx_desc *desc;
964 	struct usbd_xfer *xfer;
965 	usbd_status error;
966 	uint8_t cmd = 0;
967 	uint8_t *buf;
968 	int xferlen, rate = 2;
969 
970 	xfer = usbd_alloc_xfer(sc->sc_udev);
971 	if (xfer == NULL)
972 		return ENOMEM;
973 
974 	/* xfer length needs to be a multiple of two! */
975 	xferlen = (RAL_TX_DESC_SIZE + m0->m_pkthdr.len + 1) & ~1;
976 
977 	buf = usbd_alloc_buffer(xfer, xferlen);
978 	if (buf == NULL) {
979 		usbd_free_xfer(xfer);
980 		return ENOMEM;
981 	}
982 
983 	usbd_setup_xfer(xfer, sc->sc_tx_pipeh, NULL, &cmd, sizeof cmd,
984 	    USBD_FORCE_SHORT_XFER | USBD_SYNCHRONOUS, RAL_TX_TIMEOUT, NULL);
985 
986 	error = usbd_transfer(xfer);
987 	if (error != 0) {
988 		usbd_free_xfer(xfer);
989 		return error;
990 	}
991 
992 	desc = (struct ural_tx_desc *)buf;
993 
994 	m_copydata(m0, 0, m0->m_pkthdr.len, buf + RAL_TX_DESC_SIZE);
995 	ural_setup_tx_desc(sc, desc, RAL_TX_IFS_NEWBACKOFF | RAL_TX_TIMESTAMP,
996 	    m0->m_pkthdr.len, rate);
997 
998 	DPRINTFN(10, ("sending beacon frame len=%u rate=%u xfer len=%u\n",
999 	    m0->m_pkthdr.len, rate, xferlen));
1000 
1001 	usbd_setup_xfer(xfer, sc->sc_tx_pipeh, NULL, buf, xferlen,
1002 	    USBD_FORCE_SHORT_XFER | USBD_NO_COPY | USBD_SYNCHRONOUS,
1003 	    RAL_TX_TIMEOUT, NULL);
1004 
1005 	error = usbd_transfer(xfer);
1006 	usbd_free_xfer(xfer);
1007 
1008 	return error;
1009 }
1010 #endif
1011 
1012 int
1013 ural_tx_data(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1014 {
1015 	struct ieee80211com *ic = &sc->sc_ic;
1016 	struct ural_tx_desc *desc;
1017 	struct ural_tx_data *data;
1018 	struct ieee80211_frame *wh;
1019 	struct ieee80211_key *k;
1020 	uint32_t flags = RAL_TX_NEWSEQ;
1021 	uint16_t dur;
1022 	usbd_status error;
1023 	int rate, xferlen, pktlen, needrts = 0, needcts = 0;
1024 
1025 	wh = mtod(m0, struct ieee80211_frame *);
1026 
1027 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1028 		k = ieee80211_get_txkey(ic, wh, ni);
1029 
1030 		if ((m0 = ieee80211_encrypt(ic, m0, k)) == NULL)
1031 			return ENOBUFS;
1032 
1033 		/* packet header may have moved, reset our local pointer */
1034 		wh = mtod(m0, struct ieee80211_frame *);
1035 	}
1036 
1037 	/* compute actual packet length (including CRC and crypto overhead) */
1038 	pktlen = m0->m_pkthdr.len + IEEE80211_CRC_LEN;
1039 
1040 	/* pickup a rate */
1041 	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
1042 	    ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
1043 	     IEEE80211_FC0_TYPE_MGT)) {
1044 		/* mgmt/multicast frames are sent at the lowest avail. rate */
1045 		rate = ni->ni_rates.rs_rates[0];
1046 	} else if (ic->ic_fixed_rate != -1) {
1047 		rate = ic->ic_sup_rates[ic->ic_curmode].
1048 		    rs_rates[ic->ic_fixed_rate];
1049 	} else
1050 			rate = ni->ni_rates.rs_rates[ni->ni_txrate];
1051 	if (rate == 0)
1052 		rate = 2;	/* XXX should not happen */
1053 	rate &= IEEE80211_RATE_VAL;
1054 
1055 	/* check if RTS/CTS or CTS-to-self protection must be used */
1056 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1057 		/* multicast frames are not sent at OFDM rates in 802.11b/g */
1058 		if (pktlen > ic->ic_rtsthreshold) {
1059 			needrts = 1;	/* RTS/CTS based on frame length */
1060 		} else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
1061 		    RAL_RATE_IS_OFDM(rate)) {
1062 			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
1063 				needcts = 1;	/* CTS-to-self */
1064 			else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
1065 				needrts = 1;	/* RTS/CTS */
1066 		}
1067 	}
1068 	if (needrts || needcts) {
1069 		struct mbuf *mprot;
1070 		int protrate, ackrate;
1071 		uint16_t dur;
1072 
1073 		protrate = 2;
1074 		ackrate  = ural_ack_rate(ic, rate);
1075 
1076 		dur = ural_txtime(pktlen, rate, ic->ic_flags) +
1077 		      ural_txtime(RAL_ACK_SIZE, ackrate, ic->ic_flags) +
1078 		      2 * RAL_SIFS;
1079 		if (needrts) {
1080 			dur += ural_txtime(RAL_CTS_SIZE, ural_ack_rate(ic,
1081 			    protrate), ic->ic_flags) + RAL_SIFS;
1082 			mprot = ieee80211_get_rts(ic, wh, dur);
1083 		} else {
1084 			mprot = ieee80211_get_cts_to_self(ic, dur);
1085 		}
1086 		if (mprot == NULL) {
1087 			printf("%s: could not allocate protection frame\n",
1088 			    sc->sc_dev.dv_xname);
1089 			m_freem(m0);
1090 			return ENOBUFS;
1091 		}
1092 
1093 		data = &sc->tx_data[sc->tx_cur];
1094 		desc = (struct ural_tx_desc *)data->buf;
1095 
1096 		/* avoid multiple free() of the same node for each fragment */
1097 		data->ni = ieee80211_ref_node(ni);
1098 
1099 		m_copydata(mprot, 0, mprot->m_pkthdr.len,
1100 		    data->buf + RAL_TX_DESC_SIZE);
1101 		ural_setup_tx_desc(sc, desc,
1102 		    (needrts ? RAL_TX_NEED_ACK : 0) | RAL_TX_RETRY(7),
1103 		    mprot->m_pkthdr.len, protrate);
1104 
1105 		/* no roundup necessary here */
1106 		xferlen = RAL_TX_DESC_SIZE + mprot->m_pkthdr.len;
1107 
1108 		/* XXX may want to pass the protection frame to BPF */
1109 
1110 		/* mbuf is no longer needed */
1111 		m_freem(mprot);
1112 
1113 		usbd_setup_xfer(data->xfer, sc->sc_tx_pipeh, data, data->buf,
1114 		    xferlen, USBD_FORCE_SHORT_XFER | USBD_NO_COPY,
1115 		    RAL_TX_TIMEOUT, ural_txeof);
1116 		error = usbd_transfer(data->xfer);
1117 		if (error != 0 && error != USBD_IN_PROGRESS) {
1118 			m_freem(m0);
1119 			return error;
1120 		}
1121 
1122 		sc->tx_queued++;
1123 		sc->tx_cur = (sc->tx_cur + 1) % RAL_TX_LIST_COUNT;
1124 
1125 		flags |= RAL_TX_IFS_SIFS;
1126 	}
1127 
1128 	data = &sc->tx_data[sc->tx_cur];
1129 	desc = (struct ural_tx_desc *)data->buf;
1130 
1131 	data->ni = ni;
1132 
1133 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1134 		flags |= RAL_TX_NEED_ACK;
1135 		flags |= RAL_TX_RETRY(7);
1136 
1137 		dur = ural_txtime(RAL_ACK_SIZE, ural_ack_rate(ic, rate),
1138 		    ic->ic_flags) + RAL_SIFS;
1139 		*(uint16_t *)wh->i_dur = htole16(dur);
1140 
1141 #ifndef IEEE80211_STA_ONLY
1142 		/* tell hardware to set timestamp in probe responses */
1143 		if ((wh->i_fc[0] &
1144 		    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
1145 		    (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP))
1146 			flags |= RAL_TX_TIMESTAMP;
1147 #endif
1148 	}
1149 
1150 #if NBPFILTER > 0
1151 	if (sc->sc_drvbpf != NULL) {
1152 		struct mbuf mb;
1153 		struct ural_tx_radiotap_header *tap = &sc->sc_txtap;
1154 
1155 		tap->wt_flags = 0;
1156 		tap->wt_rate = rate;
1157 		tap->wt_chan_freq = htole16(ic->ic_bss->ni_chan->ic_freq);
1158 		tap->wt_chan_flags = htole16(ic->ic_bss->ni_chan->ic_flags);
1159 		tap->wt_antenna = sc->tx_ant;
1160 
1161 		mb.m_data = (caddr_t)tap;
1162 		mb.m_len = sc->sc_txtap_len;
1163 		mb.m_next = m0;
1164 		mb.m_nextpkt = NULL;
1165 		mb.m_type = 0;
1166 		mb.m_flags = 0;
1167 		bpf_mtap(sc->sc_drvbpf, &mb, BPF_DIRECTION_OUT);
1168 	}
1169 #endif
1170 
1171 	m_copydata(m0, 0, m0->m_pkthdr.len, data->buf + RAL_TX_DESC_SIZE);
1172 	ural_setup_tx_desc(sc, desc, flags, m0->m_pkthdr.len, rate);
1173 
1174 	/* align end on a 2-bytes boundary */
1175 	xferlen = (RAL_TX_DESC_SIZE + m0->m_pkthdr.len + 1) & ~1;
1176 
1177 	/*
1178 	 * No space left in the last URB to store the extra 2 bytes, force
1179 	 * sending of another URB.
1180 	 */
1181 	if ((xferlen % 64) == 0)
1182 		xferlen += 2;
1183 
1184 	DPRINTFN(10, ("sending frame len=%u rate=%u xfer len=%u\n",
1185 	    m0->m_pkthdr.len, rate, xferlen));
1186 
1187 	/* mbuf is no longer needed */
1188 	m_freem(m0);
1189 
1190 	usbd_setup_xfer(data->xfer, sc->sc_tx_pipeh, data, data->buf, xferlen,
1191 	    USBD_FORCE_SHORT_XFER | USBD_NO_COPY, RAL_TX_TIMEOUT, ural_txeof);
1192 	error = usbd_transfer(data->xfer);
1193 	if (error != 0 && error != USBD_IN_PROGRESS)
1194 		return error;
1195 
1196 	sc->tx_queued++;
1197 	sc->tx_cur = (sc->tx_cur + 1) % RAL_TX_LIST_COUNT;
1198 
1199 	return 0;
1200 }
1201 
1202 void
1203 ural_start(struct ifnet *ifp)
1204 {
1205 	struct ural_softc *sc = ifp->if_softc;
1206 	struct ieee80211com *ic = &sc->sc_ic;
1207 	struct ieee80211_node *ni;
1208 	struct mbuf *m0;
1209 
1210 	/*
1211 	 * net80211 may still try to send management frames even if the
1212 	 * IFF_RUNNING flag is not set...
1213 	 */
1214 	if (!(ifp->if_flags & IFF_RUNNING) || ifq_is_oactive(&ifp->if_snd))
1215 		return;
1216 
1217 	for (;;) {
1218 		if (sc->tx_queued >= RAL_TX_LIST_COUNT - 1) {
1219 			ifq_set_oactive(&ifp->if_snd);
1220 			break;
1221 		}
1222 
1223 		m0 = mq_dequeue(&ic->ic_mgtq);
1224 		if (m0 != NULL) {
1225 			ni = m0->m_pkthdr.ph_cookie;
1226 #if NBPFILTER > 0
1227 			if (ic->ic_rawbpf != NULL)
1228 				bpf_mtap(ic->ic_rawbpf, m0, BPF_DIRECTION_OUT);
1229 #endif
1230 			if (ural_tx_data(sc, m0, ni) != 0)
1231 				break;
1232 
1233 		} else {
1234 			if (ic->ic_state != IEEE80211_S_RUN)
1235 				break;
1236 
1237 			m0 = ifq_dequeue(&ifp->if_snd);
1238 			if (m0 == NULL)
1239 				break;
1240 #if NBPFILTER > 0
1241 			if (ifp->if_bpf != NULL)
1242 				bpf_mtap(ifp->if_bpf, m0, BPF_DIRECTION_OUT);
1243 #endif
1244 			m0 = ieee80211_encap(ifp, m0, &ni);
1245 			if (m0 == NULL)
1246 				continue;
1247 #if NBPFILTER > 0
1248 			if (ic->ic_rawbpf != NULL)
1249 				bpf_mtap(ic->ic_rawbpf, m0, BPF_DIRECTION_OUT);
1250 #endif
1251 			if (ural_tx_data(sc, m0, ni) != 0) {
1252 				if (ni != NULL)
1253 					ieee80211_release_node(ic, ni);
1254 				ifp->if_oerrors++;
1255 				break;
1256 			}
1257 		}
1258 
1259 		sc->sc_tx_timer = 5;
1260 		ifp->if_timer = 1;
1261 	}
1262 }
1263 
1264 void
1265 ural_watchdog(struct ifnet *ifp)
1266 {
1267 	struct ural_softc *sc = ifp->if_softc;
1268 
1269 	ifp->if_timer = 0;
1270 
1271 	if (sc->sc_tx_timer > 0) {
1272 		if (--sc->sc_tx_timer == 0) {
1273 			printf("%s: device timeout\n", sc->sc_dev.dv_xname);
1274 			/*ural_init(ifp); XXX needs a process context! */
1275 			ifp->if_oerrors++;
1276 			return;
1277 		}
1278 		ifp->if_timer = 1;
1279 	}
1280 
1281 	ieee80211_watchdog(ifp);
1282 }
1283 
1284 int
1285 ural_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1286 {
1287 	struct ural_softc *sc = ifp->if_softc;
1288 	struct ieee80211com *ic = &sc->sc_ic;
1289 	int s, error = 0;
1290 
1291 	if (usbd_is_dying(sc->sc_udev))
1292 		return ENXIO;
1293 
1294 	usbd_ref_incr(sc->sc_udev);
1295 
1296 	s = splnet();
1297 
1298 	switch (cmd) {
1299 	case SIOCSIFADDR:
1300 		ifp->if_flags |= IFF_UP;
1301 		/* FALLTHROUGH */
1302 	case SIOCSIFFLAGS:
1303 		if (ifp->if_flags & IFF_UP) {
1304 			if (ifp->if_flags & IFF_RUNNING)
1305 				ural_update_promisc(sc);
1306 			else
1307 				ural_init(ifp);
1308 		} else {
1309 			if (ifp->if_flags & IFF_RUNNING)
1310 				ural_stop(ifp, 1);
1311 		}
1312 		break;
1313 
1314 	case SIOCS80211CHANNEL:
1315 		/*
1316 		 * This allows for fast channel switching in monitor mode
1317 		 * (used by kismet). In IBSS mode, we must explicitly reset
1318 		 * the interface to generate a new beacon frame.
1319 		 */
1320 		error = ieee80211_ioctl(ifp, cmd, data);
1321 		if (error == ENETRESET &&
1322 		    ic->ic_opmode == IEEE80211_M_MONITOR) {
1323 			if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
1324 			    (IFF_UP | IFF_RUNNING))
1325 				ural_set_chan(sc, ic->ic_ibss_chan);
1326 			error = 0;
1327 		}
1328 		break;
1329 
1330 	default:
1331 		error = ieee80211_ioctl(ifp, cmd, data);
1332 	}
1333 
1334 	if (error == ENETRESET) {
1335 		if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
1336 		    (IFF_UP | IFF_RUNNING))
1337 			ural_init(ifp);
1338 		error = 0;
1339 	}
1340 
1341 	splx(s);
1342 
1343 	usbd_ref_decr(sc->sc_udev);
1344 
1345 	return error;
1346 }
1347 
1348 void
1349 ural_eeprom_read(struct ural_softc *sc, uint16_t addr, void *buf, int len)
1350 {
1351 	usb_device_request_t req;
1352 	usbd_status error;
1353 
1354 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1355 	req.bRequest = RAL_READ_EEPROM;
1356 	USETW(req.wValue, 0);
1357 	USETW(req.wIndex, addr);
1358 	USETW(req.wLength, len);
1359 
1360 	error = usbd_do_request(sc->sc_udev, &req, buf);
1361 	if (error != 0) {
1362 		printf("%s: could not read EEPROM: %s\n",
1363 		    sc->sc_dev.dv_xname, usbd_errstr(error));
1364 	}
1365 }
1366 
1367 uint16_t
1368 ural_read(struct ural_softc *sc, uint16_t reg)
1369 {
1370 	usb_device_request_t req;
1371 	usbd_status error;
1372 	uint16_t val;
1373 
1374 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1375 	req.bRequest = RAL_READ_MAC;
1376 	USETW(req.wValue, 0);
1377 	USETW(req.wIndex, reg);
1378 	USETW(req.wLength, sizeof (uint16_t));
1379 
1380 	error = usbd_do_request(sc->sc_udev, &req, &val);
1381 	if (error != 0) {
1382 		printf("%s: could not read MAC register: %s\n",
1383 		    sc->sc_dev.dv_xname, usbd_errstr(error));
1384 		return 0;
1385 	}
1386 	return letoh16(val);
1387 }
1388 
1389 void
1390 ural_read_multi(struct ural_softc *sc, uint16_t reg, void *buf, int len)
1391 {
1392 	usb_device_request_t req;
1393 	usbd_status error;
1394 
1395 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1396 	req.bRequest = RAL_READ_MULTI_MAC;
1397 	USETW(req.wValue, 0);
1398 	USETW(req.wIndex, reg);
1399 	USETW(req.wLength, len);
1400 
1401 	error = usbd_do_request(sc->sc_udev, &req, buf);
1402 	if (error != 0) {
1403 		printf("%s: could not read MAC register: %s\n",
1404 		    sc->sc_dev.dv_xname, usbd_errstr(error));
1405 	}
1406 }
1407 
1408 void
1409 ural_write(struct ural_softc *sc, uint16_t reg, uint16_t val)
1410 {
1411 	usb_device_request_t req;
1412 	usbd_status error;
1413 
1414 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1415 	req.bRequest = RAL_WRITE_MAC;
1416 	USETW(req.wValue, val);
1417 	USETW(req.wIndex, reg);
1418 	USETW(req.wLength, 0);
1419 
1420 	error = usbd_do_request(sc->sc_udev, &req, NULL);
1421 	if (error != 0) {
1422 		printf("%s: could not write MAC register: %s\n",
1423 		    sc->sc_dev.dv_xname, usbd_errstr(error));
1424 	}
1425 }
1426 
1427 void
1428 ural_write_multi(struct ural_softc *sc, uint16_t reg, void *buf, int len)
1429 {
1430 	usb_device_request_t req;
1431 	usbd_status error;
1432 
1433 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1434 	req.bRequest = RAL_WRITE_MULTI_MAC;
1435 	USETW(req.wValue, 0);
1436 	USETW(req.wIndex, reg);
1437 	USETW(req.wLength, len);
1438 
1439 	error = usbd_do_request(sc->sc_udev, &req, buf);
1440 	if (error != 0) {
1441 		printf("%s: could not write MAC register: %s\n",
1442 		    sc->sc_dev.dv_xname, usbd_errstr(error));
1443 	}
1444 }
1445 
1446 void
1447 ural_bbp_write(struct ural_softc *sc, uint8_t reg, uint8_t val)
1448 {
1449 	uint16_t tmp;
1450 	int ntries;
1451 
1452 	for (ntries = 0; ntries < 5; ntries++) {
1453 		if (!(ural_read(sc, RAL_PHY_CSR8) & RAL_BBP_BUSY))
1454 			break;
1455 	}
1456 	if (ntries == 5) {
1457 		printf("%s: could not write to BBP\n", sc->sc_dev.dv_xname);
1458 		return;
1459 	}
1460 
1461 	tmp = reg << 8 | val;
1462 	ural_write(sc, RAL_PHY_CSR7, tmp);
1463 }
1464 
1465 uint8_t
1466 ural_bbp_read(struct ural_softc *sc, uint8_t reg)
1467 {
1468 	uint16_t val;
1469 	int ntries;
1470 
1471 	val = RAL_BBP_WRITE | reg << 8;
1472 	ural_write(sc, RAL_PHY_CSR7, val);
1473 
1474 	for (ntries = 0; ntries < 5; ntries++) {
1475 		if (!(ural_read(sc, RAL_PHY_CSR8) & RAL_BBP_BUSY))
1476 			break;
1477 	}
1478 	if (ntries == 5) {
1479 		printf("%s: could not read BBP\n", sc->sc_dev.dv_xname);
1480 		return 0;
1481 	}
1482 	return ural_read(sc, RAL_PHY_CSR7) & 0xff;
1483 }
1484 
1485 void
1486 ural_rf_write(struct ural_softc *sc, uint8_t reg, uint32_t val)
1487 {
1488 	uint32_t tmp;
1489 	int ntries;
1490 
1491 	for (ntries = 0; ntries < 5; ntries++) {
1492 		if (!(ural_read(sc, RAL_PHY_CSR10) & RAL_RF_LOBUSY))
1493 			break;
1494 	}
1495 	if (ntries == 5) {
1496 		printf("%s: could not write to RF\n", sc->sc_dev.dv_xname);
1497 		return;
1498 	}
1499 
1500 	tmp = RAL_RF_BUSY | RAL_RF_20BIT | (val & 0xfffff) << 2 | (reg & 0x3);
1501 	ural_write(sc, RAL_PHY_CSR9,  tmp & 0xffff);
1502 	ural_write(sc, RAL_PHY_CSR10, tmp >> 16);
1503 
1504 	/* remember last written value in sc */
1505 	sc->rf_regs[reg] = val;
1506 
1507 	DPRINTFN(15, ("RF R[%u] <- 0x%05x\n", reg & 0x3, val & 0xfffff));
1508 }
1509 
1510 void
1511 ural_set_chan(struct ural_softc *sc, struct ieee80211_channel *c)
1512 {
1513 	struct ieee80211com *ic = &sc->sc_ic;
1514 	uint8_t power, tmp;
1515 	u_int chan;
1516 
1517 	chan = ieee80211_chan2ieee(ic, c);
1518 	if (chan == 0 || chan == IEEE80211_CHAN_ANY)
1519 		return;
1520 
1521 	power = min(sc->txpow[chan - 1], 31);
1522 
1523 	DPRINTFN(2, ("setting channel to %u, txpower to %u\n", chan, power));
1524 
1525 	switch (sc->rf_rev) {
1526 	case RAL_RF_2522:
1527 		ural_rf_write(sc, RAL_RF1, 0x00814);
1528 		ural_rf_write(sc, RAL_RF2, ural_rf2522_r2[chan - 1]);
1529 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1530 		break;
1531 
1532 	case RAL_RF_2523:
1533 		ural_rf_write(sc, RAL_RF1, 0x08804);
1534 		ural_rf_write(sc, RAL_RF2, ural_rf2523_r2[chan - 1]);
1535 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x38044);
1536 		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1537 		break;
1538 
1539 	case RAL_RF_2524:
1540 		ural_rf_write(sc, RAL_RF1, 0x0c808);
1541 		ural_rf_write(sc, RAL_RF2, ural_rf2524_r2[chan - 1]);
1542 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1543 		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1544 		break;
1545 
1546 	case RAL_RF_2525:
1547 		ural_rf_write(sc, RAL_RF1, 0x08808);
1548 		ural_rf_write(sc, RAL_RF2, ural_rf2525_hi_r2[chan - 1]);
1549 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1550 		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1551 
1552 		ural_rf_write(sc, RAL_RF1, 0x08808);
1553 		ural_rf_write(sc, RAL_RF2, ural_rf2525_r2[chan - 1]);
1554 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1555 		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1556 		break;
1557 
1558 	case RAL_RF_2525E:
1559 		ural_rf_write(sc, RAL_RF1, 0x08808);
1560 		ural_rf_write(sc, RAL_RF2, ural_rf2525e_r2[chan - 1]);
1561 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1562 		ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00286 : 0x00282);
1563 		break;
1564 
1565 	case RAL_RF_2526:
1566 		ural_rf_write(sc, RAL_RF2, ural_rf2526_hi_r2[chan - 1]);
1567 		ural_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381);
1568 		ural_rf_write(sc, RAL_RF1, 0x08804);
1569 
1570 		ural_rf_write(sc, RAL_RF2, ural_rf2526_r2[chan - 1]);
1571 		ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1572 		ural_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381);
1573 		break;
1574 	}
1575 
1576 	if (ic->ic_opmode != IEEE80211_M_MONITOR &&
1577 	    ic->ic_state != IEEE80211_S_SCAN) {
1578 		/* set Japan filter bit for channel 14 */
1579 		tmp = ural_bbp_read(sc, 70);
1580 
1581 		tmp &= ~RAL_JAPAN_FILTER;
1582 		if (chan == 14)
1583 			tmp |= RAL_JAPAN_FILTER;
1584 
1585 		ural_bbp_write(sc, 70, tmp);
1586 
1587 		/* clear CRC errors */
1588 		ural_read(sc, RAL_STA_CSR0);
1589 
1590 		DELAY(1000); /* RF needs a 1ms delay here */
1591 		ural_disable_rf_tune(sc);
1592 	}
1593 }
1594 
1595 /*
1596  * Disable RF auto-tuning.
1597  */
1598 void
1599 ural_disable_rf_tune(struct ural_softc *sc)
1600 {
1601 	uint32_t tmp;
1602 
1603 	if (sc->rf_rev != RAL_RF_2523) {
1604 		tmp = sc->rf_regs[RAL_RF1] & ~RAL_RF1_AUTOTUNE;
1605 		ural_rf_write(sc, RAL_RF1, tmp);
1606 	}
1607 
1608 	tmp = sc->rf_regs[RAL_RF3] & ~RAL_RF3_AUTOTUNE;
1609 	ural_rf_write(sc, RAL_RF3, tmp);
1610 
1611 	DPRINTFN(2, ("disabling RF autotune\n"));
1612 }
1613 
1614 /*
1615  * Refer to IEEE Std 802.11-1999 pp. 123 for more information on TSF
1616  * synchronization.
1617  */
1618 void
1619 ural_enable_tsf_sync(struct ural_softc *sc)
1620 {
1621 	struct ieee80211com *ic = &sc->sc_ic;
1622 	uint16_t logcwmin, preload, tmp;
1623 
1624 	/* first, disable TSF synchronization */
1625 	ural_write(sc, RAL_TXRX_CSR19, 0);
1626 
1627 	tmp = (16 * ic->ic_bss->ni_intval) << 4;
1628 	ural_write(sc, RAL_TXRX_CSR18, tmp);
1629 
1630 #ifndef IEEE80211_STA_ONLY
1631 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
1632 		logcwmin = 2;
1633 		preload = 320;
1634 	} else
1635 #endif
1636 	{
1637 		logcwmin = 0;
1638 		preload = 6;
1639 	}
1640 	tmp = logcwmin << 12 | preload;
1641 	ural_write(sc, RAL_TXRX_CSR20, tmp);
1642 
1643 	/* finally, enable TSF synchronization */
1644 	tmp = RAL_ENABLE_TSF | RAL_ENABLE_TBCN;
1645 	if (ic->ic_opmode == IEEE80211_M_STA)
1646 		tmp |= RAL_ENABLE_TSF_SYNC(1);
1647 #ifndef IEEE80211_STA_ONLY
1648 	else
1649 		tmp |= RAL_ENABLE_TSF_SYNC(2) | RAL_ENABLE_BEACON_GENERATOR;
1650 #endif
1651 	ural_write(sc, RAL_TXRX_CSR19, tmp);
1652 
1653 	DPRINTF(("enabling TSF synchronization\n"));
1654 }
1655 
1656 void
1657 ural_update_slot(struct ural_softc *sc)
1658 {
1659 	struct ieee80211com *ic = &sc->sc_ic;
1660 	uint16_t slottime, sifs, eifs;
1661 
1662 	slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ?
1663 	    IEEE80211_DUR_DS_SHSLOT : IEEE80211_DUR_DS_SLOT;
1664 
1665 	/*
1666 	 * These settings may sound a bit inconsistent but this is what the
1667 	 * reference driver does.
1668 	 */
1669 	if (ic->ic_curmode == IEEE80211_MODE_11B) {
1670 		sifs = 16 - RAL_RXTX_TURNAROUND;
1671 		eifs = 364;
1672 	} else {
1673 		sifs = 10 - RAL_RXTX_TURNAROUND;
1674 		eifs = 64;
1675 	}
1676 
1677 	ural_write(sc, RAL_MAC_CSR10, slottime);
1678 	ural_write(sc, RAL_MAC_CSR11, sifs);
1679 	ural_write(sc, RAL_MAC_CSR12, eifs);
1680 }
1681 
1682 void
1683 ural_set_txpreamble(struct ural_softc *sc)
1684 {
1685 	uint16_t tmp;
1686 
1687 	tmp = ural_read(sc, RAL_TXRX_CSR10);
1688 
1689 	tmp &= ~RAL_SHORT_PREAMBLE;
1690 	if (sc->sc_ic.ic_flags & IEEE80211_F_SHPREAMBLE)
1691 		tmp |= RAL_SHORT_PREAMBLE;
1692 
1693 	ural_write(sc, RAL_TXRX_CSR10, tmp);
1694 }
1695 
1696 void
1697 ural_set_basicrates(struct ural_softc *sc)
1698 {
1699 	struct ieee80211com *ic = &sc->sc_ic;
1700 
1701 	/* update basic rate set */
1702 	if (ic->ic_curmode == IEEE80211_MODE_11B) {
1703 		/* 11b basic rates: 1, 2Mbps */
1704 		ural_write(sc, RAL_TXRX_CSR11, 0x3);
1705 	} else {
1706 		/* 11b/g basic rates: 1, 2, 5.5, 11Mbps */
1707 		ural_write(sc, RAL_TXRX_CSR11, 0xf);
1708 	}
1709 }
1710 
1711 void
1712 ural_set_bssid(struct ural_softc *sc, const uint8_t *bssid)
1713 {
1714 	uint16_t tmp;
1715 
1716 	tmp = bssid[0] | bssid[1] << 8;
1717 	ural_write(sc, RAL_MAC_CSR5, tmp);
1718 
1719 	tmp = bssid[2] | bssid[3] << 8;
1720 	ural_write(sc, RAL_MAC_CSR6, tmp);
1721 
1722 	tmp = bssid[4] | bssid[5] << 8;
1723 	ural_write(sc, RAL_MAC_CSR7, tmp);
1724 
1725 	DPRINTF(("setting BSSID to %s\n", ether_sprintf((uint8_t *)bssid)));
1726 }
1727 
1728 void
1729 ural_set_macaddr(struct ural_softc *sc, const uint8_t *addr)
1730 {
1731 	uint16_t tmp;
1732 
1733 	tmp = addr[0] | addr[1] << 8;
1734 	ural_write(sc, RAL_MAC_CSR2, tmp);
1735 
1736 	tmp = addr[2] | addr[3] << 8;
1737 	ural_write(sc, RAL_MAC_CSR3, tmp);
1738 
1739 	tmp = addr[4] | addr[5] << 8;
1740 	ural_write(sc, RAL_MAC_CSR4, tmp);
1741 
1742 	DPRINTF(("setting MAC address to %s\n",
1743 	    ether_sprintf((uint8_t *)addr)));
1744 }
1745 
1746 void
1747 ural_update_promisc(struct ural_softc *sc)
1748 {
1749 	struct ifnet *ifp = &sc->sc_ic.ic_if;
1750 	uint16_t tmp;
1751 
1752 	tmp = ural_read(sc, RAL_TXRX_CSR2);
1753 
1754 	tmp &= ~RAL_DROP_NOT_TO_ME;
1755 	if (!(ifp->if_flags & IFF_PROMISC))
1756 		tmp |= RAL_DROP_NOT_TO_ME;
1757 
1758 	ural_write(sc, RAL_TXRX_CSR2, tmp);
1759 
1760 	DPRINTF(("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
1761 	    "entering" : "leaving"));
1762 }
1763 
1764 const char *
1765 ural_get_rf(int rev)
1766 {
1767 	switch (rev) {
1768 	case RAL_RF_2522:	return "RT2522";
1769 	case RAL_RF_2523:	return "RT2523";
1770 	case RAL_RF_2524:	return "RT2524";
1771 	case RAL_RF_2525:	return "RT2525";
1772 	case RAL_RF_2525E:	return "RT2525e";
1773 	case RAL_RF_2526:	return "RT2526";
1774 	case RAL_RF_5222:	return "RT5222";
1775 	default:		return "unknown";
1776 	}
1777 }
1778 
1779 void
1780 ural_read_eeprom(struct ural_softc *sc)
1781 {
1782 	struct ieee80211com *ic = &sc->sc_ic;
1783 	uint16_t val;
1784 
1785 	/* retrieve MAC/BBP type */
1786 	ural_eeprom_read(sc, RAL_EEPROM_MACBBP, &val, 2);
1787 	sc->macbbp_rev = letoh16(val);
1788 
1789 	ural_eeprom_read(sc, RAL_EEPROM_CONFIG0, &val, 2);
1790 	val = letoh16(val);
1791 	sc->rf_rev =   (val >> 11) & 0x7;
1792 	sc->hw_radio = (val >> 10) & 0x1;
1793 	sc->led_mode = (val >> 6)  & 0x7;
1794 	sc->rx_ant =   (val >> 4)  & 0x3;
1795 	sc->tx_ant =   (val >> 2)  & 0x3;
1796 	sc->nb_ant =   val & 0x3;
1797 
1798 	/* read MAC address */
1799 	ural_eeprom_read(sc, RAL_EEPROM_ADDRESS, ic->ic_myaddr, 6);
1800 
1801 	/* read default values for BBP registers */
1802 	ural_eeprom_read(sc, RAL_EEPROM_BBP_BASE, sc->bbp_prom, 2 * 16);
1803 
1804 	/* read Tx power for all b/g channels */
1805 	ural_eeprom_read(sc, RAL_EEPROM_TXPOWER, sc->txpow, 14);
1806 }
1807 
1808 int
1809 ural_bbp_init(struct ural_softc *sc)
1810 {
1811 	int i, ntries;
1812 
1813 	/* wait for BBP to be ready */
1814 	for (ntries = 0; ntries < 100; ntries++) {
1815 		if (ural_bbp_read(sc, RAL_BBP_VERSION) != 0)
1816 			break;
1817 		DELAY(1000);
1818 	}
1819 	if (ntries == 100) {
1820 		printf("%s: timeout waiting for BBP\n", sc->sc_dev.dv_xname);
1821 		return EIO;
1822 	}
1823 
1824 	/* initialize BBP registers to default values */
1825 	for (i = 0; i < nitems(ural_def_bbp); i++)
1826 		ural_bbp_write(sc, ural_def_bbp[i].reg, ural_def_bbp[i].val);
1827 
1828 #if 0
1829 	/* initialize BBP registers to values stored in EEPROM */
1830 	for (i = 0; i < 16; i++) {
1831 		if (sc->bbp_prom[i].reg == 0xff)
1832 			continue;
1833 		ural_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
1834 	}
1835 #endif
1836 
1837 	return 0;
1838 }
1839 
1840 void
1841 ural_set_txantenna(struct ural_softc *sc, int antenna)
1842 {
1843 	uint16_t tmp;
1844 	uint8_t tx;
1845 
1846 	tx = ural_bbp_read(sc, RAL_BBP_TX) & ~RAL_BBP_ANTMASK;
1847 	if (antenna == 1)
1848 		tx |= RAL_BBP_ANTA;
1849 	else if (antenna == 2)
1850 		tx |= RAL_BBP_ANTB;
1851 	else
1852 		tx |= RAL_BBP_DIVERSITY;
1853 
1854 	/* need to force I/Q flip for RF 2525e, 2526 and 5222 */
1855 	if (sc->rf_rev == RAL_RF_2525E || sc->rf_rev == RAL_RF_2526 ||
1856 	    sc->rf_rev == RAL_RF_5222)
1857 		tx |= RAL_BBP_FLIPIQ;
1858 
1859 	ural_bbp_write(sc, RAL_BBP_TX, tx);
1860 
1861 	/* update flags in PHY_CSR5 and PHY_CSR6 too */
1862 	tmp = ural_read(sc, RAL_PHY_CSR5) & ~0x7;
1863 	ural_write(sc, RAL_PHY_CSR5, tmp | (tx & 0x7));
1864 
1865 	tmp = ural_read(sc, RAL_PHY_CSR6) & ~0x7;
1866 	ural_write(sc, RAL_PHY_CSR6, tmp | (tx & 0x7));
1867 }
1868 
1869 void
1870 ural_set_rxantenna(struct ural_softc *sc, int antenna)
1871 {
1872 	uint8_t rx;
1873 
1874 	rx = ural_bbp_read(sc, RAL_BBP_RX) & ~RAL_BBP_ANTMASK;
1875 	if (antenna == 1)
1876 		rx |= RAL_BBP_ANTA;
1877 	else if (antenna == 2)
1878 		rx |= RAL_BBP_ANTB;
1879 	else
1880 		rx |= RAL_BBP_DIVERSITY;
1881 
1882 	/* need to force no I/Q flip for RF 2525e and 2526 */
1883 	if (sc->rf_rev == RAL_RF_2525E || sc->rf_rev == RAL_RF_2526)
1884 		rx &= ~RAL_BBP_FLIPIQ;
1885 
1886 	ural_bbp_write(sc, RAL_BBP_RX, rx);
1887 }
1888 
1889 int
1890 ural_init(struct ifnet *ifp)
1891 {
1892 	struct ural_softc *sc = ifp->if_softc;
1893 	struct ieee80211com *ic = &sc->sc_ic;
1894 	uint16_t tmp;
1895 	usbd_status error;
1896 	int i, ntries;
1897 
1898 	ural_stop(ifp, 0);
1899 
1900 	/* initialize MAC registers to default values */
1901 	for (i = 0; i < nitems(ural_def_mac); i++)
1902 		ural_write(sc, ural_def_mac[i].reg, ural_def_mac[i].val);
1903 
1904 	/* wait for BBP and RF to wake up (this can take a long time!) */
1905 	for (ntries = 0; ntries < 100; ntries++) {
1906 		tmp = ural_read(sc, RAL_MAC_CSR17);
1907 		if ((tmp & (RAL_BBP_AWAKE | RAL_RF_AWAKE)) ==
1908 		    (RAL_BBP_AWAKE | RAL_RF_AWAKE))
1909 			break;
1910 		DELAY(1000);
1911 	}
1912 	if (ntries == 100) {
1913 		printf("%s: timeout waiting for BBP/RF to wakeup\n",
1914 		    sc->sc_dev.dv_xname);
1915 		error = EIO;
1916 		goto fail;
1917 	}
1918 
1919 	/* we're ready! */
1920 	ural_write(sc, RAL_MAC_CSR1, RAL_HOST_READY);
1921 
1922 	/* set basic rate set (will be updated later) */
1923 	ural_write(sc, RAL_TXRX_CSR11, 0x153);
1924 
1925 	error = ural_bbp_init(sc);
1926 	if (error != 0)
1927 		goto fail;
1928 
1929 	/* set default BSS channel */
1930 	ic->ic_bss->ni_chan = ic->ic_ibss_chan;
1931 	ural_set_chan(sc, ic->ic_bss->ni_chan);
1932 
1933 	/* clear statistic registers (STA_CSR0 to STA_CSR10) */
1934 	ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof sc->sta);
1935 
1936 	/* set default sensitivity */
1937 	ural_bbp_write(sc, 17, 0x48);
1938 
1939 	ural_set_txantenna(sc, 1);
1940 	ural_set_rxantenna(sc, 1);
1941 
1942 	IEEE80211_ADDR_COPY(ic->ic_myaddr, LLADDR(ifp->if_sadl));
1943 	ural_set_macaddr(sc, ic->ic_myaddr);
1944 
1945 	/*
1946 	 * Copy WEP keys into adapter's memory (SEC_CSR0 to SEC_CSR31).
1947 	 */
1948 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
1949 		struct ieee80211_key *k = &ic->ic_nw_keys[i];
1950 		ural_write_multi(sc, RAL_SEC_CSR0 + i * IEEE80211_KEYBUF_SIZE,
1951 		    k->k_key, IEEE80211_KEYBUF_SIZE);
1952 	}
1953 
1954 	/*
1955 	 * Allocate xfer for AMRR statistics requests.
1956 	 */
1957 	sc->amrr_xfer = usbd_alloc_xfer(sc->sc_udev);
1958 	if (sc->amrr_xfer == NULL) {
1959 		printf("%s: could not allocate AMRR xfer\n",
1960 		    sc->sc_dev.dv_xname);
1961 		goto fail;
1962 	}
1963 
1964 	/*
1965 	 * Open Tx and Rx USB bulk pipes.
1966 	 */
1967 	error = usbd_open_pipe(sc->sc_iface, sc->sc_tx_no, USBD_EXCLUSIVE_USE,
1968 	    &sc->sc_tx_pipeh);
1969 	if (error != 0) {
1970 		printf("%s: could not open Tx pipe: %s\n",
1971 		    sc->sc_dev.dv_xname, usbd_errstr(error));
1972 		goto fail;
1973 	}
1974 	error = usbd_open_pipe(sc->sc_iface, sc->sc_rx_no, USBD_EXCLUSIVE_USE,
1975 	    &sc->sc_rx_pipeh);
1976 	if (error != 0) {
1977 		printf("%s: could not open Rx pipe: %s\n",
1978 		    sc->sc_dev.dv_xname, usbd_errstr(error));
1979 		goto fail;
1980 	}
1981 
1982 	/*
1983 	 * Allocate Tx and Rx xfer queues.
1984 	 */
1985 	error = ural_alloc_tx_list(sc);
1986 	if (error != 0) {
1987 		printf("%s: could not allocate Tx list\n",
1988 		    sc->sc_dev.dv_xname);
1989 		goto fail;
1990 	}
1991 	error = ural_alloc_rx_list(sc);
1992 	if (error != 0) {
1993 		printf("%s: could not allocate Rx list\n",
1994 		    sc->sc_dev.dv_xname);
1995 		goto fail;
1996 	}
1997 
1998 	/*
1999 	 * Start up the receive pipe.
2000 	 */
2001 	for (i = 0; i < RAL_RX_LIST_COUNT; i++) {
2002 		struct ural_rx_data *data = &sc->rx_data[i];
2003 
2004 		usbd_setup_xfer(data->xfer, sc->sc_rx_pipeh, data, data->buf,
2005 		    MCLBYTES, USBD_SHORT_XFER_OK, USBD_NO_TIMEOUT, ural_rxeof);
2006 		error = usbd_transfer(data->xfer);
2007 		if (error != 0 && error != USBD_IN_PROGRESS) {
2008 			printf("%s: could not queue Rx transfer\n",
2009 			    sc->sc_dev.dv_xname);
2010 			goto fail;
2011 		}
2012 	}
2013 
2014 	/* kick Rx */
2015 	tmp = RAL_DROP_PHY_ERROR | RAL_DROP_CRC_ERROR;
2016 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2017 		tmp |= RAL_DROP_CTL | RAL_DROP_VERSION_ERROR;
2018 #ifndef IEEE80211_STA_ONLY
2019 		if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2020 #endif
2021 			tmp |= RAL_DROP_TODS;
2022 		if (!(ifp->if_flags & IFF_PROMISC))
2023 			tmp |= RAL_DROP_NOT_TO_ME;
2024 	}
2025 	ural_write(sc, RAL_TXRX_CSR2, tmp);
2026 
2027 	ifq_clr_oactive(&ifp->if_snd);
2028 	ifp->if_flags |= IFF_RUNNING;
2029 
2030 	if (ic->ic_opmode == IEEE80211_M_MONITOR)
2031 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
2032 	else
2033 		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
2034 
2035 	return 0;
2036 
2037 fail:	ural_stop(ifp, 1);
2038 	return error;
2039 }
2040 
2041 void
2042 ural_stop(struct ifnet *ifp, int disable)
2043 {
2044 	struct ural_softc *sc = ifp->if_softc;
2045 	struct ieee80211com *ic = &sc->sc_ic;
2046 
2047 	sc->sc_tx_timer = 0;
2048 	ifp->if_timer = 0;
2049 	ifp->if_flags &= ~IFF_RUNNING;
2050 	ifq_clr_oactive(&ifp->if_snd);
2051 
2052 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);	/* free all nodes */
2053 
2054 	/* disable Rx */
2055 	ural_write(sc, RAL_TXRX_CSR2, RAL_DISABLE_RX);
2056 
2057 	/* reset ASIC and BBP (but won't reset MAC registers!) */
2058 	ural_write(sc, RAL_MAC_CSR1, RAL_RESET_ASIC | RAL_RESET_BBP);
2059 	ural_write(sc, RAL_MAC_CSR1, 0);
2060 
2061 	if (sc->amrr_xfer != NULL) {
2062 		usbd_free_xfer(sc->amrr_xfer);
2063 		sc->amrr_xfer = NULL;
2064 	}
2065 	if (sc->sc_rx_pipeh != NULL) {
2066 		usbd_close_pipe(sc->sc_rx_pipeh);
2067 		sc->sc_rx_pipeh = NULL;
2068 	}
2069 	if (sc->sc_tx_pipeh != NULL) {
2070 		usbd_close_pipe(sc->sc_tx_pipeh);
2071 		sc->sc_tx_pipeh = NULL;
2072 	}
2073 
2074 	ural_free_rx_list(sc);
2075 	ural_free_tx_list(sc);
2076 }
2077 
2078 void
2079 ural_newassoc(struct ieee80211com *ic, struct ieee80211_node *ni, int isnew)
2080 {
2081 	/* start with lowest Tx rate */
2082 	ni->ni_txrate = 0;
2083 }
2084 
2085 void
2086 ural_amrr_start(struct ural_softc *sc, struct ieee80211_node *ni)
2087 {
2088 	int i;
2089 
2090 	/* clear statistic registers (STA_CSR0 to STA_CSR10) */
2091 	ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof sc->sta);
2092 
2093 	ieee80211_amrr_node_init(&sc->amrr, &sc->amn);
2094 
2095 	/* set rate to some reasonable initial value */
2096 	for (i = ni->ni_rates.rs_nrates - 1;
2097 	     i > 0 && (ni->ni_rates.rs_rates[i] & IEEE80211_RATE_VAL) > 72;
2098 	     i--);
2099 	ni->ni_txrate = i;
2100 
2101 	if (!usbd_is_dying(sc->sc_udev))
2102 		timeout_add_sec(&sc->amrr_to, 1);
2103 }
2104 
2105 void
2106 ural_amrr_timeout(void *arg)
2107 {
2108 	struct ural_softc *sc = arg;
2109 	usb_device_request_t req;
2110 	int s;
2111 
2112 	if (usbd_is_dying(sc->sc_udev))
2113 		return;
2114 
2115 	usbd_ref_incr(sc->sc_udev);
2116 
2117 	s = splusb();
2118 
2119 	/*
2120 	 * Asynchronously read statistic registers (cleared by read).
2121 	 */
2122 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
2123 	req.bRequest = RAL_READ_MULTI_MAC;
2124 	USETW(req.wValue, 0);
2125 	USETW(req.wIndex, RAL_STA_CSR0);
2126 	USETW(req.wLength, sizeof sc->sta);
2127 
2128 	usbd_setup_default_xfer(sc->amrr_xfer, sc->sc_udev, sc,
2129 	    USBD_DEFAULT_TIMEOUT, &req, sc->sta, sizeof sc->sta, 0,
2130 	    ural_amrr_update);
2131 	(void)usbd_transfer(sc->amrr_xfer);
2132 
2133 	splx(s);
2134 
2135 	usbd_ref_decr(sc->sc_udev);
2136 }
2137 
2138 void
2139 ural_amrr_update(struct usbd_xfer *xfer, void *priv,
2140     usbd_status status)
2141 {
2142 	struct ural_softc *sc = (struct ural_softc *)priv;
2143 	struct ifnet *ifp = &sc->sc_ic.ic_if;
2144 
2145 	if (status != USBD_NORMAL_COMPLETION) {
2146 		printf("%s: could not retrieve Tx statistics - cancelling "
2147 		    "automatic rate control\n", sc->sc_dev.dv_xname);
2148 		return;
2149 	}
2150 
2151 	/* count TX retry-fail as Tx errors */
2152 	ifp->if_oerrors += letoh16(sc->sta[9]);
2153 
2154 	sc->amn.amn_retrycnt =
2155 	    letoh16(sc->sta[7]) +	/* TX one-retry ok count */
2156 	    letoh16(sc->sta[8]) +	/* TX more-retry ok count */
2157 	    letoh16(sc->sta[9]);	/* TX retry-fail count */
2158 
2159 	sc->amn.amn_txcnt =
2160 	    sc->amn.amn_retrycnt +
2161 	    letoh16(sc->sta[6]);	/* TX no-retry ok count */
2162 
2163 	ieee80211_amrr_choose(&sc->amrr, sc->sc_ic.ic_bss, &sc->amn);
2164 
2165 	if (!usbd_is_dying(sc->sc_udev))
2166 		timeout_add_sec(&sc->amrr_to, 1);
2167 }
2168