xref: /openbsd/sys/dev/usb/if_otus.c (revision 4cfece93)
1 /*	$OpenBSD: if_otus.c,v 1.66 2020/07/10 13:22:21 patrick Exp $	*/
2 
3 /*-
4  * Copyright (c) 2009 Damien Bergamini <damien.bergamini@free.fr>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 /*
20  * Driver for Atheros AR9001U chipset.
21  */
22 
23 #include "bpfilter.h"
24 
25 #include <sys/param.h>
26 #include <sys/sockio.h>
27 #include <sys/mbuf.h>
28 #include <sys/kernel.h>
29 #include <sys/socket.h>
30 #include <sys/systm.h>
31 #include <sys/timeout.h>
32 #include <sys/conf.h>
33 #include <sys/device.h>
34 #include <sys/endian.h>
35 
36 #include <machine/intr.h>
37 
38 #if NBPFILTER > 0
39 #include <net/bpf.h>
40 #endif
41 #include <net/if.h>
42 #include <net/if_dl.h>
43 #include <net/if_media.h>
44 
45 #include <netinet/in.h>
46 #include <netinet/if_ether.h>
47 
48 #include <net80211/ieee80211_var.h>
49 #include <net80211/ieee80211_amrr.h>
50 #include <net80211/ieee80211_radiotap.h>
51 
52 #include <dev/usb/usb.h>
53 #include <dev/usb/usbdi.h>
54 #include <dev/usb/usbdi_util.h>
55 #include <dev/usb/usbdevs.h>
56 
57 #include <dev/usb/if_otusreg.h>
58 
59 #ifdef OTUS_DEBUG
60 #define DPRINTF(x)	do { if (otus_debug) printf x; } while (0)
61 #define DPRINTFN(n, x)	do { if (otus_debug >= (n)) printf x; } while (0)
62 int otus_debug = 1;
63 #else
64 #define DPRINTF(x)
65 #define DPRINTFN(n, x)
66 #endif
67 
68 static const struct usb_devno otus_devs[] = {
69 	{ USB_VENDOR_ACCTON,		USB_PRODUCT_ACCTON_WN7512 },
70 	{ USB_VENDOR_ATHEROS2,		USB_PRODUCT_ATHEROS2_3CRUSBN275 },
71 	{ USB_VENDOR_ATHEROS2,		USB_PRODUCT_ATHEROS2_TG121N },
72 	{ USB_VENDOR_ATHEROS2,		USB_PRODUCT_ATHEROS2_AR9170 },
73 	{ USB_VENDOR_ATHEROS2,		USB_PRODUCT_ATHEROS2_WN612 },
74 	{ USB_VENDOR_ATHEROS2,		USB_PRODUCT_ATHEROS2_WN821NV2 },
75 	{ USB_VENDOR_AVM,		USB_PRODUCT_AVM_FRITZWLAN },
76 	{ USB_VENDOR_CACE,		USB_PRODUCT_CACE_AIRPCAPNX },
77 	{ USB_VENDOR_DLINK2,		USB_PRODUCT_DLINK2_DWA130D1 },
78 	{ USB_VENDOR_DLINK2,		USB_PRODUCT_DLINK2_DWA160A1 },
79 	{ USB_VENDOR_DLINK2,		USB_PRODUCT_DLINK2_DWA160A2 },
80 	{ USB_VENDOR_IODATA,		USB_PRODUCT_IODATA_WNGDNUS2 },
81 	{ USB_VENDOR_NEC,		USB_PRODUCT_NEC_WL300NUG },
82 	{ USB_VENDOR_NETGEAR,		USB_PRODUCT_NETGEAR_WN111V2 },
83 	{ USB_VENDOR_NETGEAR,		USB_PRODUCT_NETGEAR_WNA1000 },
84 	{ USB_VENDOR_NETGEAR,		USB_PRODUCT_NETGEAR_WNDA3100 },
85 	{ USB_VENDOR_PLANEX2,		USB_PRODUCT_PLANEX2_GW_US300 },
86 	{ USB_VENDOR_WISTRONNEWEB,	USB_PRODUCT_WISTRONNEWEB_O8494 },
87 	{ USB_VENDOR_WISTRONNEWEB,	USB_PRODUCT_WISTRONNEWEB_WNC0600 },
88 	{ USB_VENDOR_ZCOM,		USB_PRODUCT_ZCOM_UB81 },
89 	{ USB_VENDOR_ZCOM,		USB_PRODUCT_ZCOM_UB82 },
90 	{ USB_VENDOR_ZYDAS,		USB_PRODUCT_ZYDAS_ZD1221 },
91 	{ USB_VENDOR_ZYXEL,		USB_PRODUCT_ZYXEL_NWD271N }
92 };
93 
94 int		otus_match(struct device *, void *, void *);
95 void		otus_attach(struct device *, struct device *, void *);
96 int		otus_detach(struct device *, int);
97 void		otus_attachhook(struct device *);
98 void		otus_get_chanlist(struct otus_softc *);
99 int		otus_load_firmware(struct otus_softc *, const char *,
100 		    uint32_t);
101 int		otus_open_pipes(struct otus_softc *);
102 void		otus_close_pipes(struct otus_softc *);
103 int		otus_alloc_tx_cmd(struct otus_softc *);
104 void		otus_free_tx_cmd(struct otus_softc *);
105 int		otus_alloc_tx_data_list(struct otus_softc *);
106 void		otus_free_tx_data_list(struct otus_softc *);
107 int		otus_alloc_rx_data_list(struct otus_softc *);
108 void		otus_free_rx_data_list(struct otus_softc *);
109 void		otus_next_scan(void *);
110 void		otus_task(void *);
111 void		otus_do_async(struct otus_softc *,
112 		    void (*)(struct otus_softc *, void *), void *, int);
113 int		otus_newstate(struct ieee80211com *, enum ieee80211_state,
114 		    int);
115 void		otus_newstate_cb(struct otus_softc *, void *);
116 int		otus_cmd(struct otus_softc *, uint8_t, const void *, int,
117 		    void *);
118 void		otus_write(struct otus_softc *, uint32_t, uint32_t);
119 int		otus_write_barrier(struct otus_softc *);
120 struct		ieee80211_node *otus_node_alloc(struct ieee80211com *);
121 int		otus_media_change(struct ifnet *);
122 int		otus_read_eeprom(struct otus_softc *);
123 void		otus_newassoc(struct ieee80211com *, struct ieee80211_node *,
124 		    int);
125 void		otus_intr(struct usbd_xfer *, void *, usbd_status);
126 void		otus_cmd_rxeof(struct otus_softc *, uint8_t *, int);
127 void		otus_sub_rxeof(struct otus_softc *, uint8_t *, int,
128 		    struct mbuf_list *);
129 void		otus_rxeof(struct usbd_xfer *, void *, usbd_status);
130 void		otus_txeof(struct usbd_xfer *, void *, usbd_status);
131 int		otus_tx(struct otus_softc *, struct mbuf *,
132 		    struct ieee80211_node *);
133 void		otus_start(struct ifnet *);
134 void		otus_watchdog(struct ifnet *);
135 int		otus_ioctl(struct ifnet *, u_long, caddr_t);
136 int		otus_set_multi(struct otus_softc *);
137 void		otus_updateedca(struct ieee80211com *);
138 void		otus_updateedca_cb(struct otus_softc *, void *);
139 void		otus_updateslot(struct ieee80211com *);
140 void		otus_updateslot_cb(struct otus_softc *, void *);
141 int		otus_init_mac(struct otus_softc *);
142 uint32_t	otus_phy_get_def(struct otus_softc *, uint32_t);
143 int		otus_set_board_values(struct otus_softc *,
144 		    struct ieee80211_channel *);
145 int		otus_program_phy(struct otus_softc *,
146 		    struct ieee80211_channel *);
147 int		otus_set_rf_bank4(struct otus_softc *,
148 		    struct ieee80211_channel *);
149 void		otus_get_delta_slope(uint32_t, uint32_t *, uint32_t *);
150 int		otus_set_chan(struct otus_softc *, struct ieee80211_channel *,
151 		    int);
152 int		otus_set_key(struct ieee80211com *, struct ieee80211_node *,
153 		    struct ieee80211_key *);
154 void		otus_set_key_cb(struct otus_softc *, void *);
155 void		otus_delete_key(struct ieee80211com *, struct ieee80211_node *,
156 		    struct ieee80211_key *);
157 void		otus_delete_key_cb(struct otus_softc *, void *);
158 void		otus_calibrate_to(void *);
159 int		otus_set_bssid(struct otus_softc *, const uint8_t *);
160 int		otus_set_macaddr(struct otus_softc *, const uint8_t *);
161 void		otus_led_newstate_type1(struct otus_softc *);
162 void		otus_led_newstate_type2(struct otus_softc *);
163 void		otus_led_newstate_type3(struct otus_softc *);
164 int		otus_init(struct ifnet *);
165 void		otus_stop(struct ifnet *);
166 
167 struct cfdriver otus_cd = {
168 	NULL, "otus", DV_IFNET
169 };
170 
171 const struct cfattach otus_ca = {
172 	sizeof (struct otus_softc), otus_match, otus_attach, otus_detach
173 };
174 
175 int
176 otus_match(struct device *parent, void *match, void *aux)
177 {
178 	struct usb_attach_arg *uaa = aux;
179 
180 	if (uaa->iface == NULL || uaa->configno != 1)
181 		return UMATCH_NONE;
182 
183 	return (usb_lookup(otus_devs, uaa->vendor, uaa->product) != NULL) ?
184 	    UMATCH_VENDOR_PRODUCT : UMATCH_NONE;
185 }
186 
187 void
188 otus_attach(struct device *parent, struct device *self, void *aux)
189 {
190 	struct otus_softc *sc = (struct otus_softc *)self;
191 	struct usb_attach_arg *uaa = aux;
192 	int error;
193 
194 	sc->sc_udev = uaa->device;
195 
196 	usb_init_task(&sc->sc_task, otus_task, sc, USB_TASK_TYPE_GENERIC);
197 	timeout_set(&sc->scan_to, otus_next_scan, sc);
198 	timeout_set(&sc->calib_to, otus_calibrate_to, sc);
199 
200 	sc->amrr.amrr_min_success_threshold =  1;
201 	sc->amrr.amrr_max_success_threshold = 10;
202 
203 	/* Get the first interface handle. */
204 	error = usbd_device2interface_handle(sc->sc_udev, 0, &sc->sc_iface);
205 	if (error != 0) {
206 		printf("%s: could not get interface handle\n",
207 		    sc->sc_dev.dv_xname);
208 		return;
209 	}
210 
211 	if ((error = otus_open_pipes(sc)) != 0) {
212 		printf("%s: could not open pipes\n", sc->sc_dev.dv_xname);
213 		return;
214 	}
215 
216 	config_mountroot(self, otus_attachhook);
217 }
218 
219 int
220 otus_detach(struct device *self, int flags)
221 {
222 	struct otus_softc *sc = (struct otus_softc *)self;
223 	struct ifnet *ifp = &sc->sc_ic.ic_if;
224 	int s;
225 
226 	s = splusb();
227 
228 	if (timeout_initialized(&sc->scan_to))
229 		timeout_del(&sc->scan_to);
230 	if (timeout_initialized(&sc->calib_to))
231 		timeout_del(&sc->calib_to);
232 
233 	/* Wait for all queued asynchronous commands to complete. */
234 	usb_rem_wait_task(sc->sc_udev, &sc->sc_task);
235 
236 	usbd_ref_wait(sc->sc_udev);
237 
238 	if (ifp->if_softc != NULL) {
239 		ifp->if_flags &= ~IFF_RUNNING;
240 		ifq_clr_oactive(&ifp->if_snd);
241 		ieee80211_ifdetach(ifp);
242 		if_detach(ifp);
243 	}
244 
245 	otus_close_pipes(sc);
246 
247 	splx(s);
248 
249 	return 0;
250 }
251 
252 void
253 otus_attachhook(struct device *self)
254 {
255 	struct otus_softc *sc = (struct otus_softc *)self;
256 	struct ieee80211com *ic = &sc->sc_ic;
257 	struct ifnet *ifp = &ic->ic_if;
258 	usb_device_request_t req;
259 	uint32_t in, out;
260 	int error;
261 
262 	error = otus_load_firmware(sc, "otus-init", AR_FW_INIT_ADDR);
263 	if (error != 0) {
264 		printf("%s: could not load %s firmware\n",
265 		    sc->sc_dev.dv_xname, "init");
266 		return;
267 	}
268 
269 	usbd_delay_ms(sc->sc_udev, 1000);
270 
271 	error = otus_load_firmware(sc, "otus-main", AR_FW_MAIN_ADDR);
272 	if (error != 0) {
273 		printf("%s: could not load %s firmware\n",
274 		    sc->sc_dev.dv_xname, "main");
275 		return;
276 	}
277 
278 	/* Tell device that firmware transfer is complete. */
279 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
280 	req.bRequest = AR_FW_DOWNLOAD_COMPLETE;
281 	USETW(req.wValue, 0);
282 	USETW(req.wIndex, 0);
283 	USETW(req.wLength, 0);
284 	if (usbd_do_request(sc->sc_udev, &req, NULL) != 0) {
285 		printf("%s: firmware initialization failed\n",
286 		    sc->sc_dev.dv_xname);
287 		return;
288 	}
289 
290 	/* Send an ECHO command to check that everything is settled. */
291 	in = 0xbadc0ffe;
292 	if (otus_cmd(sc, AR_CMD_ECHO, &in, sizeof in, &out) != 0) {
293 		printf("%s: echo command failed\n", sc->sc_dev.dv_xname);
294 		return;
295 	}
296 	if (in != out) {
297 		printf("%s: echo reply mismatch: 0x%08x!=0x%08x\n",
298 		    sc->sc_dev.dv_xname, in, out);
299 		return;
300 	}
301 
302 	/* Read entire EEPROM. */
303 	if (otus_read_eeprom(sc) != 0) {
304 		printf("%s: could not read EEPROM\n", sc->sc_dev.dv_xname);
305 		return;
306 	}
307 
308 	sc->txmask = sc->eeprom.baseEepHeader.txMask;
309 	sc->rxmask = sc->eeprom.baseEepHeader.rxMask;
310 	sc->capflags = sc->eeprom.baseEepHeader.opCapFlags;
311 	IEEE80211_ADDR_COPY(ic->ic_myaddr, sc->eeprom.baseEepHeader.macAddr);
312 	sc->sc_led_newstate = otus_led_newstate_type3;	/* XXX */
313 
314 	printf("%s: MAC/BBP AR9170, RF AR%X, MIMO %dT%dR, address %s\n",
315 	    sc->sc_dev.dv_xname, (sc->capflags & AR5416_OPFLAGS_11A) ?
316 	        0x9104 : ((sc->txmask == 0x5) ? 0x9102 : 0x9101),
317 	    (sc->txmask == 0x5) ? 2 : 1, (sc->rxmask == 0x5) ? 2 : 1,
318 	    ether_sprintf(ic->ic_myaddr));
319 
320 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
321 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
322 	ic->ic_state = IEEE80211_S_INIT;
323 
324 	/* Set device capabilities. */
325 	ic->ic_caps =
326 	    IEEE80211_C_MONITOR |	/* monitor mode supported */
327 	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
328 	    IEEE80211_C_SHSLOT |	/* short slot time supported */
329 	    IEEE80211_C_WEP |		/* WEP */
330 	    IEEE80211_C_RSN;		/* WPA/RSN */
331 
332 	if (sc->eeprom.baseEepHeader.opCapFlags & AR5416_OPFLAGS_11G) {
333 		/* Set supported .11b and .11g rates. */
334 		ic->ic_sup_rates[IEEE80211_MODE_11B] =
335 		    ieee80211_std_rateset_11b;
336 		ic->ic_sup_rates[IEEE80211_MODE_11G] =
337 		    ieee80211_std_rateset_11g;
338 	}
339 	if (sc->eeprom.baseEepHeader.opCapFlags & AR5416_OPFLAGS_11A) {
340 		/* Set supported .11a rates. */
341 		ic->ic_sup_rates[IEEE80211_MODE_11A] =
342 		    ieee80211_std_rateset_11a;
343 	}
344 
345 	/* Build the list of supported channels. */
346 	otus_get_chanlist(sc);
347 
348 	ifp->if_softc = sc;
349 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
350 	ifp->if_ioctl = otus_ioctl;
351 	ifp->if_start = otus_start;
352 	ifp->if_watchdog = otus_watchdog;
353 	memcpy(ifp->if_xname, sc->sc_dev.dv_xname, IFNAMSIZ);
354 
355 	if_attach(ifp);
356 	ieee80211_ifattach(ifp);
357 	ic->ic_node_alloc = otus_node_alloc;
358 	ic->ic_newassoc = otus_newassoc;
359 	ic->ic_updateslot = otus_updateslot;
360 	ic->ic_updateedca = otus_updateedca;
361 #ifdef notyet
362 	ic->ic_set_key = otus_set_key;
363 	ic->ic_delete_key = otus_delete_key;
364 #endif
365 	/* Override state transition machine. */
366 	sc->sc_newstate = ic->ic_newstate;
367 	ic->ic_newstate = otus_newstate;
368 	ieee80211_media_init(ifp, otus_media_change, ieee80211_media_status);
369 
370 #if NBPFILTER > 0
371 	bpfattach(&sc->sc_drvbpf, ifp, DLT_IEEE802_11_RADIO,
372 	    sizeof (struct ieee80211_frame) + IEEE80211_RADIOTAP_HDRLEN);
373 
374 	sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
375 	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
376 	sc->sc_rxtap.wr_ihdr.it_present = htole32(OTUS_RX_RADIOTAP_PRESENT);
377 
378 	sc->sc_txtap_len = sizeof sc->sc_txtapu;
379 	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
380 	sc->sc_txtap.wt_ihdr.it_present = htole32(OTUS_TX_RADIOTAP_PRESENT);
381 #endif
382 }
383 
384 void
385 otus_get_chanlist(struct otus_softc *sc)
386 {
387 	struct ieee80211com *ic = &sc->sc_ic;
388 	uint16_t domain;
389 	uint8_t chan;
390 	int i;
391 
392 	/* XXX regulatory domain. */
393 	domain = letoh16(sc->eeprom.baseEepHeader.regDmn[0]);
394 	DPRINTF(("regdomain=0x%04x\n", domain));
395 
396 	if (sc->eeprom.baseEepHeader.opCapFlags & AR5416_OPFLAGS_11G) {
397 		for (i = 0; i < 14; i++) {
398 			chan = ar_chans[i];
399 			ic->ic_channels[chan].ic_freq =
400 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_2GHZ);
401 			ic->ic_channels[chan].ic_flags =
402 			    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
403 			    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
404 		}
405 	}
406 	if (sc->eeprom.baseEepHeader.opCapFlags & AR5416_OPFLAGS_11A) {
407 		for (i = 14; i < nitems(ar_chans); i++) {
408 			chan = ar_chans[i];
409 			ic->ic_channels[chan].ic_freq =
410 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_5GHZ);
411 			ic->ic_channels[chan].ic_flags = IEEE80211_CHAN_A;
412 		}
413 	}
414 }
415 
416 int
417 otus_load_firmware(struct otus_softc *sc, const char *name, uint32_t addr)
418 {
419 	usb_device_request_t req;
420 	size_t fwsize, size;
421 	u_char *fw, *ptr;
422 	int mlen, error;
423 
424 	/* Read firmware image from the filesystem. */
425 	if ((error = loadfirmware(name, &fw, &fwsize)) != 0) {
426 		printf("%s: failed loadfirmware of file %s (error %d)\n",
427 		    sc->sc_dev.dv_xname, name, error);
428 		return error;
429 	}
430 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
431 	req.bRequest = AR_FW_DOWNLOAD;
432 	USETW(req.wIndex, 0);
433 
434 	ptr = fw;
435 	size = fwsize;
436 	addr >>= 8;
437 	while (size > 0) {
438 		mlen = MIN(size, 4096);
439 
440 		USETW(req.wValue, addr);
441 		USETW(req.wLength, mlen);
442 		if (usbd_do_request(sc->sc_udev, &req, ptr) != 0) {
443 			error = EIO;
444 			break;
445 		}
446 		addr += mlen >> 8;
447 		ptr  += mlen;
448 		size -= mlen;
449 	}
450 	free(fw, M_DEVBUF, fwsize);
451 	return error;
452 }
453 
454 int
455 otus_open_pipes(struct otus_softc *sc)
456 {
457 	usb_endpoint_descriptor_t *ed;
458 	int i, isize, error;
459 
460 	error = usbd_open_pipe(sc->sc_iface, AR_EPT_BULK_RX_NO, 0,
461 	    &sc->data_rx_pipe);
462 	if (error != 0) {
463 		printf("%s: could not open Rx bulk pipe\n",
464 		    sc->sc_dev.dv_xname);
465 		goto fail;
466 	}
467 
468 	ed = usbd_get_endpoint_descriptor(sc->sc_iface, AR_EPT_INTR_RX_NO);
469 	if (ed == NULL) {
470 		printf("%s: could not retrieve Rx intr pipe descriptor\n",
471 		    sc->sc_dev.dv_xname);
472 		goto fail;
473 	}
474 	isize = UGETW(ed->wMaxPacketSize);
475 	if (isize == 0) {
476 		printf("%s: invalid Rx intr pipe descriptor\n",
477 		    sc->sc_dev.dv_xname);
478 		goto fail;
479 	}
480 	sc->ibuf = malloc(isize, M_USBDEV, M_NOWAIT);
481 	if (sc->ibuf == NULL) {
482 		printf("%s: could not allocate Rx intr buffer\n",
483 		    sc->sc_dev.dv_xname);
484 		goto fail;
485 	}
486 	sc->ibuflen = isize;
487 	error = usbd_open_pipe_intr(sc->sc_iface, AR_EPT_INTR_RX_NO,
488 	    USBD_SHORT_XFER_OK, &sc->cmd_rx_pipe, sc, sc->ibuf, isize,
489 	    otus_intr, USBD_DEFAULT_INTERVAL);
490 	if (error != 0) {
491 		printf("%s: could not open Rx intr pipe\n",
492 		    sc->sc_dev.dv_xname);
493 		goto fail;
494 	}
495 
496 	error = usbd_open_pipe(sc->sc_iface, AR_EPT_BULK_TX_NO, 0,
497 	    &sc->data_tx_pipe);
498 	if (error != 0) {
499 		printf("%s: could not open Tx bulk pipe\n",
500 		    sc->sc_dev.dv_xname);
501 		goto fail;
502 	}
503 
504 	error = usbd_open_pipe(sc->sc_iface, AR_EPT_INTR_TX_NO, 0,
505 	    &sc->cmd_tx_pipe);
506 	if (error != 0) {
507 		printf("%s: could not open Tx intr pipe\n",
508 		    sc->sc_dev.dv_xname);
509 		goto fail;
510 	}
511 
512 	if (otus_alloc_tx_cmd(sc) != 0) {
513 		printf("%s: could not allocate command xfer\n",
514 		    sc->sc_dev.dv_xname);
515 		goto fail;
516 	}
517 
518 	if (otus_alloc_tx_data_list(sc) != 0) {
519 		printf("%s: could not allocate Tx xfers\n",
520 		    sc->sc_dev.dv_xname);
521 		goto fail;
522 	}
523 
524 	if (otus_alloc_rx_data_list(sc) != 0) {
525 		printf("%s: could not allocate Rx xfers\n",
526 		    sc->sc_dev.dv_xname);
527 		goto fail;
528 	}
529 
530 	for (i = 0; i < OTUS_RX_DATA_LIST_COUNT; i++) {
531 		struct otus_rx_data *data = &sc->rx_data[i];
532 
533 		usbd_setup_xfer(data->xfer, sc->data_rx_pipe, data, data->buf,
534 		    OTUS_RXBUFSZ, USBD_SHORT_XFER_OK | USBD_NO_COPY,
535 		    USBD_NO_TIMEOUT, otus_rxeof);
536 		error = usbd_transfer(data->xfer);
537 		if (error != USBD_IN_PROGRESS && error != 0) {
538 			printf("%s: could not queue Rx xfer\n",
539 			    sc->sc_dev.dv_xname);
540 			goto fail;
541 		}
542 	}
543 	return 0;
544 
545  fail:	otus_close_pipes(sc);
546 	return error;
547 }
548 
549 void
550 otus_close_pipes(struct otus_softc *sc)
551 {
552 	otus_free_tx_cmd(sc);
553 	otus_free_tx_data_list(sc);
554 	otus_free_rx_data_list(sc);
555 
556 	if (sc->data_rx_pipe != NULL)
557 		usbd_close_pipe(sc->data_rx_pipe);
558 	if (sc->cmd_rx_pipe != NULL) {
559 		usbd_abort_pipe(sc->cmd_rx_pipe);
560 		usbd_close_pipe(sc->cmd_rx_pipe);
561 	}
562 	if (sc->ibuf != NULL)
563 		free(sc->ibuf, M_USBDEV, sc->ibuflen);
564 	if (sc->data_tx_pipe != NULL)
565 		usbd_close_pipe(sc->data_tx_pipe);
566 	if (sc->cmd_tx_pipe != NULL)
567 		usbd_close_pipe(sc->cmd_tx_pipe);
568 }
569 
570 int
571 otus_alloc_tx_cmd(struct otus_softc *sc)
572 {
573 	struct otus_tx_cmd *cmd = &sc->tx_cmd;
574 
575 	cmd->xfer = usbd_alloc_xfer(sc->sc_udev);
576 	if (cmd->xfer == NULL) {
577 		printf("%s: could not allocate xfer\n",
578 		    sc->sc_dev.dv_xname);
579 		return ENOMEM;
580 	}
581 	cmd->buf = usbd_alloc_buffer(cmd->xfer, OTUS_MAX_TXCMDSZ);
582 	if (cmd->buf == NULL) {
583 		printf("%s: could not allocate xfer buffer\n",
584 		    sc->sc_dev.dv_xname);
585 		usbd_free_xfer(cmd->xfer);
586 		cmd->xfer = NULL;
587 		return ENOMEM;
588 	}
589 	return 0;
590 }
591 
592 void
593 otus_free_tx_cmd(struct otus_softc *sc)
594 {
595 	/* Make sure no transfers are pending. */
596 	usbd_abort_pipe(sc->cmd_tx_pipe);
597 
598 	if (sc->tx_cmd.xfer != NULL)
599 		usbd_free_xfer(sc->tx_cmd.xfer);
600 }
601 
602 int
603 otus_alloc_tx_data_list(struct otus_softc *sc)
604 {
605 	struct otus_tx_data *data;
606 	int i, error;
607 
608 	for (i = 0; i < OTUS_TX_DATA_LIST_COUNT; i++) {
609 		data = &sc->tx_data[i];
610 
611 		data->sc = sc;  /* Backpointer for callbacks. */
612 
613 		data->xfer = usbd_alloc_xfer(sc->sc_udev);
614 		if (data->xfer == NULL) {
615 			printf("%s: could not allocate xfer\n",
616 			    sc->sc_dev.dv_xname);
617 			error = ENOMEM;
618 			goto fail;
619 		}
620 		data->buf = usbd_alloc_buffer(data->xfer, OTUS_TXBUFSZ);
621 		if (data->buf == NULL) {
622 			printf("%s: could not allocate xfer buffer\n",
623 			    sc->sc_dev.dv_xname);
624 			error = ENOMEM;
625 			goto fail;
626 		}
627 	}
628 	return 0;
629 
630 fail:	otus_free_tx_data_list(sc);
631 	return error;
632 }
633 
634 void
635 otus_free_tx_data_list(struct otus_softc *sc)
636 {
637 	int i;
638 
639 	/* Make sure no transfers are pending. */
640 	usbd_abort_pipe(sc->data_tx_pipe);
641 
642 	for (i = 0; i < OTUS_TX_DATA_LIST_COUNT; i++)
643 		if (sc->tx_data[i].xfer != NULL)
644 			usbd_free_xfer(sc->tx_data[i].xfer);
645 }
646 
647 int
648 otus_alloc_rx_data_list(struct otus_softc *sc)
649 {
650 	struct otus_rx_data *data;
651 	int i, error;
652 
653 	for (i = 0; i < OTUS_RX_DATA_LIST_COUNT; i++) {
654 		data = &sc->rx_data[i];
655 
656 		data->sc = sc;	/* Backpointer for callbacks. */
657 
658 		data->xfer = usbd_alloc_xfer(sc->sc_udev);
659 		if (data->xfer == NULL) {
660 			printf("%s: could not allocate xfer\n",
661 			    sc->sc_dev.dv_xname);
662 			error = ENOMEM;
663 			goto fail;
664 		}
665 		data->buf = usbd_alloc_buffer(data->xfer, OTUS_RXBUFSZ);
666 		if (data->buf == NULL) {
667 			printf("%s: could not allocate xfer buffer\n",
668 			    sc->sc_dev.dv_xname);
669 			error = ENOMEM;
670 			goto fail;
671 		}
672 	}
673 	return 0;
674 
675 fail:	otus_free_rx_data_list(sc);
676 	return error;
677 }
678 
679 void
680 otus_free_rx_data_list(struct otus_softc *sc)
681 {
682 	int i;
683 
684 	/* Make sure no transfers are pending. */
685 	usbd_abort_pipe(sc->data_rx_pipe);
686 
687 	for (i = 0; i < OTUS_RX_DATA_LIST_COUNT; i++)
688 		if (sc->rx_data[i].xfer != NULL)
689 			usbd_free_xfer(sc->rx_data[i].xfer);
690 }
691 
692 void
693 otus_next_scan(void *arg)
694 {
695 	struct otus_softc *sc = arg;
696 	struct ieee80211com *ic = &sc->sc_ic;
697 	struct ifnet *ifp = &ic->ic_if;
698 
699 	if (usbd_is_dying(sc->sc_udev))
700 		return;
701 
702 	usbd_ref_incr(sc->sc_udev);
703 
704 	if (sc->sc_ic.ic_state == IEEE80211_S_SCAN &&
705 	    (ifp->if_flags & IFF_RUNNING))
706 		ieee80211_next_scan(&sc->sc_ic.ic_if);
707 
708 	usbd_ref_decr(sc->sc_udev);
709 }
710 
711 void
712 otus_task(void *arg)
713 {
714 	struct otus_softc *sc = arg;
715 	struct otus_host_cmd_ring *ring = &sc->cmdq;
716 	struct otus_host_cmd *cmd;
717 	int s;
718 
719 	/* Process host commands. */
720 	s = splusb();
721 	while (ring->next != ring->cur) {
722 		cmd = &ring->cmd[ring->next];
723 		splx(s);
724 		/* Callback. */
725 		cmd->cb(sc, cmd->data);
726 		s = splusb();
727 		ring->queued--;
728 		ring->next = (ring->next + 1) % OTUS_HOST_CMD_RING_COUNT;
729 	}
730 	splx(s);
731 }
732 
733 void
734 otus_do_async(struct otus_softc *sc, void (*cb)(struct otus_softc *, void *),
735     void *arg, int len)
736 {
737 	struct otus_host_cmd_ring *ring = &sc->cmdq;
738 	struct otus_host_cmd *cmd;
739 	int s;
740 
741 	s = splusb();
742 	cmd = &ring->cmd[ring->cur];
743 	cmd->cb = cb;
744 	KASSERT(len <= sizeof (cmd->data));
745 	memcpy(cmd->data, arg, len);
746 	ring->cur = (ring->cur + 1) % OTUS_HOST_CMD_RING_COUNT;
747 
748 	/* If there is no pending command already, schedule a task. */
749 	if (++ring->queued == 1)
750 		usb_add_task(sc->sc_udev, &sc->sc_task);
751 	splx(s);
752 }
753 
754 int
755 otus_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
756 {
757 	struct otus_softc *sc = ic->ic_softc;
758 	struct otus_cmd_newstate cmd;
759 
760 	/* Do it in a process context. */
761 	cmd.state = nstate;
762 	cmd.arg = arg;
763 	otus_do_async(sc, otus_newstate_cb, &cmd, sizeof cmd);
764 	return 0;
765 }
766 
767 void
768 otus_newstate_cb(struct otus_softc *sc, void *arg)
769 {
770 	struct otus_cmd_newstate *cmd = arg;
771 	struct ieee80211com *ic = &sc->sc_ic;
772 	struct ieee80211_node *ni;
773 	int s;
774 
775 	s = splnet();
776 
777 	switch (cmd->state) {
778 	case IEEE80211_S_INIT:
779 		break;
780 
781 	case IEEE80211_S_SCAN:
782 		(void)otus_set_chan(sc, ic->ic_bss->ni_chan, 0);
783 		if (!usbd_is_dying(sc->sc_udev))
784 			timeout_add_msec(&sc->scan_to, 200);
785 		break;
786 
787 	case IEEE80211_S_AUTH:
788 	case IEEE80211_S_ASSOC:
789 		(void)otus_set_chan(sc, ic->ic_bss->ni_chan, 0);
790 		break;
791 
792 	case IEEE80211_S_RUN:
793 		(void)otus_set_chan(sc, ic->ic_bss->ni_chan, 1);
794 
795 		ni = ic->ic_bss;
796 
797 		if (ic->ic_opmode == IEEE80211_M_STA) {
798 			otus_updateslot(ic);
799 			otus_set_bssid(sc, ni->ni_bssid);
800 
801 			/* Fake a join to init the Tx rate. */
802 			otus_newassoc(ic, ni, 1);
803 
804 			/* Start calibration timer. */
805 			if (!usbd_is_dying(sc->sc_udev))
806 				timeout_add_sec(&sc->calib_to, 1);
807 		}
808 		break;
809 	}
810 
811 	sc->sc_led_newstate(sc);
812 	(void)sc->sc_newstate(ic, cmd->state, cmd->arg);
813 
814 	splx(s);
815 }
816 
817 int
818 otus_cmd(struct otus_softc *sc, uint8_t code, const void *idata, int ilen,
819     void *odata)
820 {
821 	struct otus_tx_cmd *cmd = &sc->tx_cmd;
822 	struct ar_cmd_hdr *hdr;
823 	int s, xferlen, error;
824 
825 	/* Always bulk-out a multiple of 4 bytes. */
826 	xferlen = (sizeof (*hdr) + ilen + 3) & ~3;
827 
828 	hdr = (struct ar_cmd_hdr *)cmd->buf;
829 	hdr->code  = code;
830 	hdr->len   = ilen;
831 	hdr->token = ++cmd->token;	/* Don't care about endianness. */
832 	memcpy((uint8_t *)&hdr[1], idata, ilen);
833 
834 	DPRINTFN(2, ("sending command code=0x%02x len=%d token=%d\n",
835 	    code, ilen, hdr->token));
836 
837 	s = splusb();
838 	cmd->odata = odata;
839 	cmd->done = 0;
840 
841 	usbd_setup_xfer(cmd->xfer, sc->cmd_tx_pipe, cmd, cmd->buf, xferlen,
842 	    USBD_FORCE_SHORT_XFER | USBD_NO_COPY | USBD_SYNCHRONOUS,
843 	    OTUS_CMD_TIMEOUT, NULL);
844 	error = usbd_transfer(cmd->xfer);
845 	if (error != 0) {
846 		splx(s);
847 		printf("%s: could not send command 0x%x (error=%s)\n",
848 		    sc->sc_dev.dv_xname, code, usbd_errstr(error));
849 		return EIO;
850 	}
851 	if (!cmd->done)
852 		error = tsleep_nsec(cmd, PCATCH, "otuscmd", SEC_TO_NSEC(1));
853 	cmd->odata = NULL;	/* In case answer is received too late. */
854 	splx(s);
855 	if (error != 0) {
856 		printf("%s: timeout waiting for command 0x%02x reply\n",
857 		    sc->sc_dev.dv_xname, code);
858 	}
859 	return error;
860 }
861 
862 void
863 otus_write(struct otus_softc *sc, uint32_t reg, uint32_t val)
864 {
865 	sc->write_buf[sc->write_idx].reg = htole32(reg);
866 	sc->write_buf[sc->write_idx].val = htole32(val);
867 
868 	if (++sc->write_idx > AR_MAX_WRITE_IDX)
869 		(void)otus_write_barrier(sc);
870 }
871 
872 int
873 otus_write_barrier(struct otus_softc *sc)
874 {
875 	int error;
876 
877 	if (sc->write_idx == 0)
878 		return 0;	/* Nothing to flush. */
879 
880 	error = otus_cmd(sc, AR_CMD_WREG, sc->write_buf,
881 	    sizeof (sc->write_buf[0]) * sc->write_idx, NULL);
882 	sc->write_idx = 0;
883 	return error;
884 }
885 
886 struct ieee80211_node *
887 otus_node_alloc(struct ieee80211com *ic)
888 {
889 	return malloc(sizeof (struct otus_node), M_DEVBUF, M_NOWAIT | M_ZERO);
890 }
891 
892 int
893 otus_media_change(struct ifnet *ifp)
894 {
895 	struct otus_softc *sc = ifp->if_softc;
896 	struct ieee80211com *ic = &sc->sc_ic;
897 	uint8_t rate, ridx;
898 	int error;
899 
900 	error = ieee80211_media_change(ifp);
901 	if (error != ENETRESET)
902 		return error;
903 
904 	if (ic->ic_fixed_rate != -1) {
905 		rate = ic->ic_sup_rates[ic->ic_curmode].
906 		    rs_rates[ic->ic_fixed_rate] & IEEE80211_RATE_VAL;
907 		for (ridx = 0; ridx <= OTUS_RIDX_MAX; ridx++)
908 			if (otus_rates[ridx].rate == rate)
909 				break;
910 		sc->fixed_ridx = ridx;
911 	}
912 
913 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
914 		error = otus_init(ifp);
915 
916 	return error;
917 }
918 
919 int
920 otus_read_eeprom(struct otus_softc *sc)
921 {
922 	uint32_t regs[8], reg;
923 	uint8_t *eep;
924 	int i, j, error;
925 
926 	/* Read EEPROM by blocks of 32 bytes. */
927 	eep = (uint8_t *)&sc->eeprom;
928 	reg = AR_EEPROM_OFFSET;
929 	for (i = 0; i < sizeof (sc->eeprom) / 32; i++) {
930 		for (j = 0; j < 8; j++, reg += 4)
931 			regs[j] = htole32(reg);
932 		error = otus_cmd(sc, AR_CMD_RREG, regs, sizeof regs, eep);
933 		if (error != 0)
934 			break;
935 		eep += 32;
936 	}
937 	return error;
938 }
939 
940 void
941 otus_newassoc(struct ieee80211com *ic, struct ieee80211_node *ni, int isnew)
942 {
943 	struct otus_softc *sc = ic->ic_softc;
944 	struct otus_node *on = (void *)ni;
945 	struct ieee80211_rateset *rs = &ni->ni_rates;
946 	uint8_t rate;
947 	int ridx, i;
948 
949 	DPRINTF(("new assoc isnew=%d addr=%s\n",
950 	    isnew, ether_sprintf(ni->ni_macaddr)));
951 
952 	ieee80211_amrr_node_init(&sc->amrr, &on->amn);
953 	/* Start at lowest available bit-rate, AMRR will raise. */
954 	ni->ni_txrate = 0;
955 
956 	for (i = 0; i < rs->rs_nrates; i++) {
957 		rate = rs->rs_rates[i] & IEEE80211_RATE_VAL;
958 		/* Convert 802.11 rate to hardware rate index. */
959 		for (ridx = 0; ridx <= OTUS_RIDX_MAX; ridx++)
960 			if (otus_rates[ridx].rate == rate)
961 				break;
962 		on->ridx[i] = ridx;
963 		DPRINTF(("rate=0x%02x ridx=%d\n",
964 		    rs->rs_rates[i], on->ridx[i]));
965 	}
966 }
967 
968 /* ARGSUSED */
969 void
970 otus_intr(struct usbd_xfer *xfer, void *priv, usbd_status status)
971 {
972 #if 0
973 	struct otus_softc *sc = priv;
974 	int len;
975 
976 	/*
977 	 * The Rx intr pipe is unused with current firmware.  Notifications
978 	 * and replies to commands are sent through the Rx bulk pipe instead
979 	 * (with a magic PLCP header.)
980 	 */
981 	if (__predict_false(status != USBD_NORMAL_COMPLETION)) {
982 		DPRINTF(("intr status=%d\n", status));
983 		if (status == USBD_STALLED)
984 			usbd_clear_endpoint_stall_async(sc->cmd_rx_pipe);
985 		return;
986 	}
987 	usbd_get_xfer_status(xfer, NULL, NULL, &len, NULL);
988 
989 	otus_cmd_rxeof(sc, sc->ibuf, len);
990 #endif
991 }
992 
993 void
994 otus_cmd_rxeof(struct otus_softc *sc, uint8_t *buf, int len)
995 {
996 	struct ieee80211com *ic = &sc->sc_ic;
997 	struct otus_tx_cmd *cmd;
998 	struct ar_cmd_hdr *hdr;
999 	int s;
1000 
1001 	if (__predict_false(len < sizeof (*hdr))) {
1002 		DPRINTF(("cmd too small %d\n", len));
1003 		return;
1004 	}
1005 	hdr = (struct ar_cmd_hdr *)buf;
1006 	if (__predict_false(sizeof (*hdr) + hdr->len > len ||
1007 	    sizeof (*hdr) + hdr->len > 64)) {
1008 		DPRINTF(("cmd too large %d\n", hdr->len));
1009 		return;
1010 	}
1011 
1012 	if ((hdr->code & 0xc0) != 0xc0) {
1013 		DPRINTFN(2, ("received reply code=0x%02x len=%d token=%d\n",
1014 		    hdr->code, hdr->len, hdr->token));
1015 		cmd = &sc->tx_cmd;
1016 		if (__predict_false(hdr->token != cmd->token))
1017 			return;
1018 		/* Copy answer into caller's supplied buffer. */
1019 		if (cmd->odata != NULL)
1020 			memcpy(cmd->odata, &hdr[1], hdr->len);
1021 		cmd->done = 1;
1022 		wakeup(cmd);
1023 		return;
1024 	}
1025 
1026 	/* Received unsolicited notification. */
1027 	DPRINTF(("received notification code=0x%02x len=%d\n",
1028 	    hdr->code, hdr->len));
1029 	switch (hdr->code & 0x3f) {
1030 	case AR_EVT_BEACON:
1031 		break;
1032 	case AR_EVT_TX_COMP:
1033 	{
1034 		struct ar_evt_tx_comp *tx = (struct ar_evt_tx_comp *)&hdr[1];
1035 		struct ieee80211_node *ni;
1036 		struct otus_node *on;
1037 
1038 		DPRINTF(("tx completed %s status=%d phy=0x%x\n",
1039 		    ether_sprintf(tx->macaddr), letoh16(tx->status),
1040 		    letoh32(tx->phy)));
1041 		s = splnet();
1042 #ifdef notyet
1043 #ifndef IEEE80211_STA_ONLY
1044 		if (ic->ic_opmode != IEEE80211_M_STA) {
1045 			ni = ieee80211_find_node(ic, tx->macaddr);
1046 			if (__predict_false(ni == NULL)) {
1047 				splx(s);
1048 				break;
1049 			}
1050 		} else
1051 #endif
1052 #endif
1053 			ni = ic->ic_bss;
1054 		/* Update rate control statistics. */
1055 		on = (void *)ni;
1056 		/* NB: we do not set the TX_MAC_RATE_PROBING flag. */
1057 		if (__predict_true(tx->status != 0))
1058 			on->amn.amn_retrycnt++;
1059 		splx(s);
1060 		break;
1061 	}
1062 	case AR_EVT_TBTT:
1063 		break;
1064 	}
1065 }
1066 
1067 void
1068 otus_sub_rxeof(struct otus_softc *sc, uint8_t *buf, int len,
1069     struct mbuf_list *ml)
1070 {
1071 	struct ieee80211com *ic = &sc->sc_ic;
1072 	struct ifnet *ifp = &ic->ic_if;
1073 	struct ieee80211_rxinfo rxi;
1074 	struct ieee80211_node *ni;
1075 	struct ar_rx_tail *tail;
1076 	struct ieee80211_frame *wh;
1077 	struct mbuf *m;
1078 	uint8_t *plcp;
1079 	int s, mlen, align;
1080 
1081 	if (__predict_false(len < AR_PLCP_HDR_LEN)) {
1082 		DPRINTF(("sub-xfer too short %d\n", len));
1083 		return;
1084 	}
1085 	plcp = buf;
1086 
1087 	/* All bits in the PLCP header are set to 1 for non-MPDU. */
1088 	if (memcmp(plcp, AR_PLCP_HDR_INTR, AR_PLCP_HDR_LEN) == 0) {
1089 		otus_cmd_rxeof(sc, plcp + AR_PLCP_HDR_LEN,
1090 		    len - AR_PLCP_HDR_LEN);
1091 		return;
1092 	}
1093 
1094 	/* Received MPDU. */
1095 	if (__predict_false(len < AR_PLCP_HDR_LEN + sizeof (*tail))) {
1096 		DPRINTF(("MPDU too short %d\n", len));
1097 		ifp->if_ierrors++;
1098 		return;
1099 	}
1100 	tail = (struct ar_rx_tail *)(plcp + len - sizeof (*tail));
1101 
1102 	/* Discard error frames. */
1103 	if (__predict_false(tail->error != 0)) {
1104 		DPRINTF(("error frame 0x%02x\n", tail->error));
1105 		if (tail->error & AR_RX_ERROR_FCS) {
1106 			DPRINTFN(3, ("bad FCS\n"));
1107 		} else if (tail->error & AR_RX_ERROR_MMIC) {
1108 			/* Report Michael MIC failures to net80211. */
1109 			ic->ic_stats.is_rx_locmicfail++;
1110 			ieee80211_michael_mic_failure(ic, 0);
1111 		}
1112 		ifp->if_ierrors++;
1113 		return;
1114 	}
1115 	/* Compute MPDU's length. */
1116 	mlen = len - AR_PLCP_HDR_LEN - sizeof (*tail);
1117 	/* Make sure there's room for an 802.11 header + FCS. */
1118 	if (__predict_false(mlen < IEEE80211_MIN_LEN)) {
1119 		ifp->if_ierrors++;
1120 		return;
1121 	}
1122 	mlen -= IEEE80211_CRC_LEN;	/* strip 802.11 FCS */
1123 	if (mlen > MCLBYTES) {
1124 		DPRINTF(("frame too large: %d\n", mlen));
1125 		ifp->if_ierrors++;
1126 		return;
1127 	}
1128 
1129 	wh = (struct ieee80211_frame *)(plcp + AR_PLCP_HDR_LEN);
1130 	/* Provide a 32-bit aligned protocol header to the stack. */
1131 	align = (ieee80211_has_qos(wh) ^ ieee80211_has_addr4(wh)) ? 2 : 0;
1132 
1133 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1134 	if (__predict_false(m == NULL)) {
1135 		ifp->if_ierrors++;
1136 		return;
1137 	}
1138 	if (align + mlen > MHLEN) {
1139 		MCLGET(m, M_DONTWAIT);
1140 		if (__predict_false(!(m->m_flags & M_EXT))) {
1141 			ifp->if_ierrors++;
1142 			m_freem(m);
1143 			return;
1144 		}
1145 	}
1146 	/* Finalize mbuf. */
1147 	m->m_data += align;
1148 	memcpy(mtod(m, caddr_t), wh, mlen);
1149 	m->m_pkthdr.len = m->m_len = mlen;
1150 
1151 #if NBPFILTER > 0
1152 	if (__predict_false(sc->sc_drvbpf != NULL)) {
1153 		struct otus_rx_radiotap_header *tap = &sc->sc_rxtap;
1154 		struct mbuf mb;
1155 
1156 		tap->wr_flags = 0;
1157 		tap->wr_chan_freq = htole16(ic->ic_ibss_chan->ic_freq);
1158 		tap->wr_chan_flags = htole16(ic->ic_ibss_chan->ic_flags);
1159 		tap->wr_antsignal = tail->rssi;
1160 		tap->wr_rate = 2;	/* In case it can't be found below. */
1161 		switch (tail->status & AR_RX_STATUS_MT_MASK) {
1162 		case AR_RX_STATUS_MT_CCK:
1163 			switch (plcp[0]) {
1164 			case  10: tap->wr_rate =   2; break;
1165 			case  20: tap->wr_rate =   4; break;
1166 			case  55: tap->wr_rate =  11; break;
1167 			case 110: tap->wr_rate =  22; break;
1168 			}
1169 			if (tail->status & AR_RX_STATUS_SHPREAMBLE)
1170 				tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
1171 			break;
1172 		case AR_RX_STATUS_MT_OFDM:
1173 			switch (plcp[0] & 0xf) {
1174 			case 0xb: tap->wr_rate =  12; break;
1175 			case 0xf: tap->wr_rate =  18; break;
1176 			case 0xa: tap->wr_rate =  24; break;
1177 			case 0xe: tap->wr_rate =  36; break;
1178 			case 0x9: tap->wr_rate =  48; break;
1179 			case 0xd: tap->wr_rate =  72; break;
1180 			case 0x8: tap->wr_rate =  96; break;
1181 			case 0xc: tap->wr_rate = 108; break;
1182 			}
1183 			break;
1184 		}
1185 		mb.m_data = (caddr_t)tap;
1186 		mb.m_len = sc->sc_rxtap_len;
1187 		mb.m_next = m;
1188 		mb.m_nextpkt = NULL;
1189 		mb.m_type = 0;
1190 		mb.m_flags = 0;
1191 		bpf_mtap(sc->sc_drvbpf, &mb, BPF_DIRECTION_IN);
1192 	}
1193 #endif
1194 
1195 	s = splnet();
1196 	ni = ieee80211_find_rxnode(ic, wh);
1197 	rxi.rxi_flags = 0;
1198 	rxi.rxi_rssi = tail->rssi;
1199 	rxi.rxi_tstamp = 0;	/* unused */
1200 	ieee80211_inputm(ifp, m, ni, &rxi, ml);
1201 
1202 	/* Node is no longer needed. */
1203 	ieee80211_release_node(ic, ni);
1204 	splx(s);
1205 }
1206 
1207 void
1208 otus_rxeof(struct usbd_xfer *xfer, void *priv, usbd_status status)
1209 {
1210 	struct mbuf_list ml = MBUF_LIST_INITIALIZER();
1211 	struct otus_rx_data *data = priv;
1212 	struct otus_softc *sc = data->sc;
1213 	caddr_t buf = data->buf;
1214 	struct ar_rx_head *head;
1215 	uint16_t hlen;
1216 	int len;
1217 
1218 	if (__predict_false(status != USBD_NORMAL_COMPLETION)) {
1219 		DPRINTF(("RX status=%d\n", status));
1220 		if (status == USBD_STALLED)
1221 			usbd_clear_endpoint_stall_async(sc->data_rx_pipe);
1222 		if (status != USBD_CANCELLED)
1223 			goto resubmit;
1224 		return;
1225 	}
1226 	usbd_get_xfer_status(xfer, NULL, NULL, &len, NULL);
1227 
1228 	while (len >= sizeof (*head)) {
1229 		head = (struct ar_rx_head *)buf;
1230 		if (__predict_false(head->tag != htole16(AR_RX_HEAD_TAG))) {
1231 			DPRINTF(("tag not valid 0x%x\n", letoh16(head->tag)));
1232 			break;
1233 		}
1234 		hlen = letoh16(head->len);
1235 		if (__predict_false(sizeof (*head) + hlen > len)) {
1236 			DPRINTF(("xfer too short %d/%d\n", len, hlen));
1237 			break;
1238 		}
1239 		/* Process sub-xfer. */
1240 		otus_sub_rxeof(sc, (uint8_t *)&head[1], hlen, &ml);
1241 
1242 		/* Next sub-xfer is aligned on a 32-bit boundary. */
1243 		hlen = (sizeof (*head) + hlen + 3) & ~3;
1244 		buf += hlen;
1245 		len -= hlen;
1246 	}
1247 	if_input(&sc->sc_ic.ic_if, &ml);
1248 
1249  resubmit:
1250 	usbd_setup_xfer(xfer, sc->data_rx_pipe, data, data->buf, OTUS_RXBUFSZ,
1251 	    USBD_SHORT_XFER_OK, USBD_NO_TIMEOUT, otus_rxeof);
1252 	(void)usbd_transfer(data->xfer);
1253 }
1254 
1255 void
1256 otus_txeof(struct usbd_xfer *xfer, void *priv, usbd_status status)
1257 {
1258 	struct otus_tx_data *data = priv;
1259 	struct otus_softc *sc = data->sc;
1260 	struct ieee80211com *ic = &sc->sc_ic;
1261 	struct ifnet *ifp = &ic->ic_if;
1262 	int s;
1263 
1264 	s = splnet();
1265 	sc->tx_queued--;
1266 	if (__predict_false(status != USBD_NORMAL_COMPLETION)) {
1267 		DPRINTF(("TX status=%d\n", status));
1268 		if (status == USBD_STALLED)
1269 			usbd_clear_endpoint_stall_async(sc->data_tx_pipe);
1270 		ifp->if_oerrors++;
1271 		splx(s);
1272 		return;
1273 	}
1274 	sc->sc_tx_timer = 0;
1275 	ifq_clr_oactive(&ifp->if_snd);
1276 	otus_start(ifp);
1277 	splx(s);
1278 }
1279 
1280 int
1281 otus_tx(struct otus_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
1282 {
1283 	struct ieee80211com *ic = &sc->sc_ic;
1284 	struct otus_node *on = (void *)ni;
1285 	struct otus_tx_data *data;
1286 	struct ieee80211_frame *wh;
1287 	struct ieee80211_key *k;
1288 	struct ar_tx_head *head;
1289 	uint32_t phyctl;
1290 	uint16_t macctl, qos;
1291 	uint8_t tid, qid;
1292 	int error, ridx, hasqos, xferlen;
1293 
1294 	wh = mtod(m, struct ieee80211_frame *);
1295 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1296 		k = ieee80211_get_txkey(ic, wh, ni);
1297 		if ((m = ieee80211_encrypt(ic, m, k)) == NULL)
1298 			return ENOBUFS;
1299 		wh = mtod(m, struct ieee80211_frame *);
1300 	}
1301 
1302 	if ((hasqos = ieee80211_has_qos(wh))) {
1303 		qos = ieee80211_get_qos(wh);
1304 		tid = qos & IEEE80211_QOS_TID;
1305 		qid = ieee80211_up_to_ac(ic, tid);
1306 	} else {
1307 		qos = 0;
1308 		qid = EDCA_AC_BE;
1309 	}
1310 
1311 	/* Pickup a rate index. */
1312 	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
1313 	    (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_DATA)
1314 		ridx = (ic->ic_curmode == IEEE80211_MODE_11A) ?
1315 		    OTUS_RIDX_OFDM6 : OTUS_RIDX_CCK1;
1316 	else if (ic->ic_fixed_rate != -1)
1317 		ridx = sc->fixed_ridx;
1318 	else
1319 		ridx = on->ridx[ni->ni_txrate];
1320 
1321 	phyctl = 0;
1322 	macctl = AR_TX_MAC_BACKOFF | AR_TX_MAC_HW_DUR | AR_TX_MAC_QID(qid);
1323 
1324 	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
1325 	    (hasqos && ((qos & IEEE80211_QOS_ACK_POLICY_MASK) ==
1326 	     IEEE80211_QOS_ACK_POLICY_NOACK)))
1327 		macctl |= AR_TX_MAC_NOACK;
1328 
1329 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1330 		if (m->m_pkthdr.len + IEEE80211_CRC_LEN >= ic->ic_rtsthreshold)
1331 			macctl |= AR_TX_MAC_RTS;
1332 		else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
1333 		    ridx >= OTUS_RIDX_OFDM6) {
1334 			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
1335 				macctl |= AR_TX_MAC_CTS;
1336 			else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
1337 				macctl |= AR_TX_MAC_RTS;
1338 		}
1339 	}
1340 
1341 	phyctl |= AR_TX_PHY_MCS(otus_rates[ridx].mcs);
1342 	if (ridx >= OTUS_RIDX_OFDM6) {
1343 		phyctl |= AR_TX_PHY_MT_OFDM;
1344 		if (ridx <= OTUS_RIDX_OFDM24)
1345 			phyctl |= AR_TX_PHY_ANTMSK(sc->txmask);
1346 		else
1347 			phyctl |= AR_TX_PHY_ANTMSK(1);
1348 	} else {	/* CCK */
1349 		phyctl |= AR_TX_PHY_MT_CCK;
1350 		phyctl |= AR_TX_PHY_ANTMSK(sc->txmask);
1351 	}
1352 
1353 	/* Update rate control stats for frames that are ACK'ed. */
1354 	if (!(macctl & AR_TX_MAC_NOACK))
1355 		((struct otus_node *)ni)->amn.amn_txcnt++;
1356 
1357 	data = &sc->tx_data[sc->tx_cur];
1358 	/* Fill Tx descriptor. */
1359 	head = (struct ar_tx_head *)data->buf;
1360 	head->len = htole16(m->m_pkthdr.len + IEEE80211_CRC_LEN);
1361 	head->macctl = htole16(macctl);
1362 	head->phyctl = htole32(phyctl);
1363 
1364 #if NBPFILTER > 0
1365 	if (__predict_false(sc->sc_drvbpf != NULL)) {
1366 		struct otus_tx_radiotap_header *tap = &sc->sc_txtap;
1367 		struct mbuf mb;
1368 
1369 		tap->wt_flags = 0;
1370 		tap->wt_rate = otus_rates[ridx].rate;
1371 		tap->wt_chan_freq = htole16(ic->ic_bss->ni_chan->ic_freq);
1372 		tap->wt_chan_flags = htole16(ic->ic_bss->ni_chan->ic_flags);
1373 
1374 		mb.m_data = (caddr_t)tap;
1375 		mb.m_len = sc->sc_txtap_len;
1376 		mb.m_next = m;
1377 		mb.m_nextpkt = NULL;
1378 		mb.m_type = 0;
1379 		mb.m_flags = 0;
1380 		bpf_mtap(sc->sc_drvbpf, &mb, BPF_DIRECTION_OUT);
1381 	}
1382 #endif
1383 
1384 	xferlen = sizeof (*head) + m->m_pkthdr.len;
1385 	m_copydata(m, 0, m->m_pkthdr.len, (caddr_t)&head[1]);
1386 	m_freem(m);
1387 
1388 	DPRINTFN(5, ("tx queued=%d len=%d mac=0x%04x phy=0x%08x rate=%d\n",
1389 	    sc->tx_queued, head->len, head->macctl, head->phyctl,
1390 	    otus_rates[ridx].rate));
1391 	usbd_setup_xfer(data->xfer, sc->data_tx_pipe, data, data->buf, xferlen,
1392 	    USBD_FORCE_SHORT_XFER | USBD_NO_COPY, OTUS_TX_TIMEOUT, otus_txeof);
1393 	error = usbd_transfer(data->xfer);
1394 	if (__predict_false(error != USBD_IN_PROGRESS && error != 0))
1395 		return error;
1396 
1397 	ieee80211_release_node(ic, ni);
1398 
1399 	sc->tx_queued++;
1400 	sc->tx_cur = (sc->tx_cur + 1) % OTUS_TX_DATA_LIST_COUNT;
1401 
1402 	return 0;
1403 }
1404 
1405 void
1406 otus_start(struct ifnet *ifp)
1407 {
1408 	struct otus_softc *sc = ifp->if_softc;
1409 	struct ieee80211com *ic = &sc->sc_ic;
1410 	struct ieee80211_node *ni;
1411 	struct mbuf *m;
1412 
1413 	if (!(ifp->if_flags & IFF_RUNNING) || ifq_is_oactive(&ifp->if_snd))
1414 		return;
1415 
1416 	for (;;) {
1417 		if (sc->tx_queued >= OTUS_TX_DATA_LIST_COUNT) {
1418 			ifq_set_oactive(&ifp->if_snd);
1419 			break;
1420 		}
1421 		/* Send pending management frames first. */
1422 		m = mq_dequeue(&ic->ic_mgtq);
1423 		if (m != NULL) {
1424 			ni = m->m_pkthdr.ph_cookie;
1425 			goto sendit;
1426 		}
1427 		if (ic->ic_state != IEEE80211_S_RUN)
1428 			break;
1429 
1430 		/* Encapsulate and send data frames. */
1431 		m = ifq_dequeue(&ifp->if_snd);
1432 		if (m == NULL)
1433 			break;
1434 #if NBPFILTER > 0
1435 		if (ifp->if_bpf != NULL)
1436 			bpf_mtap(ifp->if_bpf, m, BPF_DIRECTION_OUT);
1437 #endif
1438 		if ((m = ieee80211_encap(ifp, m, &ni)) == NULL)
1439 			continue;
1440 sendit:
1441 #if NBPFILTER > 0
1442 		if (ic->ic_rawbpf != NULL)
1443 			bpf_mtap(ic->ic_rawbpf, m, BPF_DIRECTION_OUT);
1444 #endif
1445 		if (otus_tx(sc, m, ni) != 0) {
1446 			ieee80211_release_node(ic, ni);
1447 			ifp->if_oerrors++;
1448 			continue;
1449 		}
1450 
1451 		sc->sc_tx_timer = 5;
1452 		ifp->if_timer = 1;
1453 	}
1454 }
1455 
1456 void
1457 otus_watchdog(struct ifnet *ifp)
1458 {
1459 	struct otus_softc *sc = ifp->if_softc;
1460 
1461 	ifp->if_timer = 0;
1462 
1463 	if (sc->sc_tx_timer > 0) {
1464 		if (--sc->sc_tx_timer == 0) {
1465 			printf("%s: device timeout\n", sc->sc_dev.dv_xname);
1466 			/* otus_init(ifp); XXX needs a process context! */
1467 			ifp->if_oerrors++;
1468 			return;
1469 		}
1470 		ifp->if_timer = 1;
1471 	}
1472 	ieee80211_watchdog(ifp);
1473 }
1474 
1475 int
1476 otus_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1477 {
1478 	struct otus_softc *sc = ifp->if_softc;
1479 	struct ieee80211com *ic = &sc->sc_ic;
1480 	int s, error = 0;
1481 
1482 	if (usbd_is_dying(sc->sc_udev))
1483 		return ENXIO;
1484 
1485 	usbd_ref_incr(sc->sc_udev);
1486 
1487 	s = splnet();
1488 
1489 	switch (cmd) {
1490 	case SIOCSIFADDR:
1491 		ifp->if_flags |= IFF_UP;
1492 		/* FALLTHROUGH */
1493 	case SIOCSIFFLAGS:
1494 		if (ifp->if_flags & IFF_UP) {
1495 			if ((ifp->if_flags & IFF_RUNNING) &&
1496 			    ((ifp->if_flags ^ sc->sc_if_flags) &
1497 			     (IFF_ALLMULTI | IFF_PROMISC)) != 0) {
1498 				otus_set_multi(sc);
1499 			} else if (!(ifp->if_flags & IFF_RUNNING))
1500 				otus_init(ifp);
1501 
1502 		} else if (ifp->if_flags & IFF_RUNNING)
1503 			otus_stop(ifp);
1504 
1505 		sc->sc_if_flags = ifp->if_flags;
1506 		break;
1507 	case SIOCS80211CHANNEL:
1508 		error = ieee80211_ioctl(ifp, cmd, data);
1509 		if (error == ENETRESET &&
1510 		    ic->ic_opmode == IEEE80211_M_MONITOR) {
1511 			if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
1512 			    (IFF_UP | IFF_RUNNING))
1513 				otus_set_chan(sc, ic->ic_ibss_chan, 0);
1514 			error = 0;
1515 		}
1516 		break;
1517 	default:
1518 		error = ieee80211_ioctl(ifp, cmd, data);
1519 	}
1520 
1521 	if (error == ENETRESET) {
1522 		if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
1523 		    (IFF_UP | IFF_RUNNING))
1524 			otus_init(ifp);
1525 		error = 0;
1526 	}
1527 
1528 	splx(s);
1529 
1530 	usbd_ref_decr(sc->sc_udev);
1531 
1532 	return error;
1533 }
1534 
1535 int
1536 otus_set_multi(struct otus_softc *sc)
1537 {
1538 	struct arpcom *ac = &sc->sc_ic.ic_ac;
1539 	struct ifnet *ifp = &ac->ac_if;
1540 	struct ether_multi *enm;
1541 	struct ether_multistep step;
1542 	uint32_t lo, hi;
1543 	uint8_t bit;
1544 
1545 	if (ac->ac_multirangecnt > 0)
1546 		ifp->if_flags |= IFF_ALLMULTI;
1547 
1548 	if ((ifp->if_flags & (IFF_ALLMULTI | IFF_PROMISC)) != 0) {
1549 		lo = hi = 0xffffffff;
1550 		goto done;
1551 	}
1552 	lo = hi = 0;
1553 	ETHER_FIRST_MULTI(step, ac, enm);
1554 	while (enm != NULL) {
1555 		bit = enm->enm_addrlo[5] >> 2;
1556 		if (bit < 32)
1557 			lo |= 1 << bit;
1558 		else
1559 			hi |= 1 << (bit - 32);
1560 		ETHER_NEXT_MULTI(step, enm);
1561 	}
1562  done:
1563 	hi |= 1U << 31;	/* Make sure the broadcast bit is set. */
1564 	otus_write(sc, AR_MAC_REG_GROUP_HASH_TBL_L, lo);
1565 	otus_write(sc, AR_MAC_REG_GROUP_HASH_TBL_H, hi);
1566 	return otus_write_barrier(sc);
1567 }
1568 
1569 void
1570 otus_updateedca(struct ieee80211com *ic)
1571 {
1572 	/* Do it in a process context. */
1573 	otus_do_async(ic->ic_softc, otus_updateedca_cb, NULL, 0);
1574 }
1575 
1576 /* ARGSUSED */
1577 void
1578 otus_updateedca_cb(struct otus_softc *sc, void *arg)
1579 {
1580 #define EXP2(val)	((1 << (val)) - 1)
1581 #define AIFS(val)	((val) * 9 + 10)
1582 	struct ieee80211com *ic = &sc->sc_ic;
1583 	const struct ieee80211_edca_ac_params *edca;
1584 	int s;
1585 
1586 	s = splnet();
1587 
1588 	edca = (ic->ic_flags & IEEE80211_F_QOS) ?
1589 	    ic->ic_edca_ac : otus_edca_def;
1590 
1591 	/* Set CWmin/CWmax values. */
1592 	otus_write(sc, AR_MAC_REG_AC0_CW,
1593 	    EXP2(edca[EDCA_AC_BE].ac_ecwmax) << 16 |
1594 	    EXP2(edca[EDCA_AC_BE].ac_ecwmin));
1595 	otus_write(sc, AR_MAC_REG_AC1_CW,
1596 	    EXP2(edca[EDCA_AC_BK].ac_ecwmax) << 16 |
1597 	    EXP2(edca[EDCA_AC_BK].ac_ecwmin));
1598 	otus_write(sc, AR_MAC_REG_AC2_CW,
1599 	    EXP2(edca[EDCA_AC_VI].ac_ecwmax) << 16 |
1600 	    EXP2(edca[EDCA_AC_VI].ac_ecwmin));
1601 	otus_write(sc, AR_MAC_REG_AC3_CW,
1602 	    EXP2(edca[EDCA_AC_VO].ac_ecwmax) << 16 |
1603 	    EXP2(edca[EDCA_AC_VO].ac_ecwmin));
1604 	otus_write(sc, AR_MAC_REG_AC4_CW,		/* Special TXQ. */
1605 	    EXP2(edca[EDCA_AC_VO].ac_ecwmax) << 16 |
1606 	    EXP2(edca[EDCA_AC_VO].ac_ecwmin));
1607 
1608 	/* Set AIFSN values. */
1609 	otus_write(sc, AR_MAC_REG_AC1_AC0_AIFS,
1610 	    AIFS(edca[EDCA_AC_VI].ac_aifsn) << 24 |
1611 	    AIFS(edca[EDCA_AC_BK].ac_aifsn) << 12 |
1612 	    AIFS(edca[EDCA_AC_BE].ac_aifsn));
1613 	otus_write(sc, AR_MAC_REG_AC3_AC2_AIFS,
1614 	    AIFS(edca[EDCA_AC_VO].ac_aifsn) << 16 |	/* Special TXQ. */
1615 	    AIFS(edca[EDCA_AC_VO].ac_aifsn) <<  4 |
1616 	    AIFS(edca[EDCA_AC_VI].ac_aifsn) >>  8);
1617 
1618 	/* Set TXOP limit. */
1619 	otus_write(sc, AR_MAC_REG_AC1_AC0_TXOP,
1620 	    edca[EDCA_AC_BK].ac_txoplimit << 16 |
1621 	    edca[EDCA_AC_BE].ac_txoplimit);
1622 	otus_write(sc, AR_MAC_REG_AC3_AC2_TXOP,
1623 	    edca[EDCA_AC_VO].ac_txoplimit << 16 |
1624 	    edca[EDCA_AC_VI].ac_txoplimit);
1625 
1626 	splx(s);
1627 
1628 	(void)otus_write_barrier(sc);
1629 #undef AIFS
1630 #undef EXP2
1631 }
1632 
1633 void
1634 otus_updateslot(struct ieee80211com *ic)
1635 {
1636 	/* Do it in a process context. */
1637 	otus_do_async(ic->ic_softc, otus_updateslot_cb, NULL, 0);
1638 }
1639 
1640 /* ARGSUSED */
1641 void
1642 otus_updateslot_cb(struct otus_softc *sc, void *arg)
1643 {
1644 	uint32_t slottime;
1645 
1646 	slottime = (sc->sc_ic.ic_flags & IEEE80211_F_SHSLOT) ?
1647 	    IEEE80211_DUR_DS_SHSLOT: IEEE80211_DUR_DS_SLOT;
1648 	otus_write(sc, AR_MAC_REG_SLOT_TIME, slottime << 10);
1649 	(void)otus_write_barrier(sc);
1650 }
1651 
1652 int
1653 otus_init_mac(struct otus_softc *sc)
1654 {
1655 	int error;
1656 
1657 	otus_write(sc, AR_MAC_REG_ACK_EXTENSION, 0x40);
1658 	otus_write(sc, AR_MAC_REG_RETRY_MAX, 0);
1659 	otus_write(sc, AR_MAC_REG_SNIFFER, 0x2000000);
1660 	otus_write(sc, AR_MAC_REG_RX_THRESHOLD, 0xc1f80);
1661 	otus_write(sc, AR_MAC_REG_RX_PE_DELAY, 0x70);
1662 	otus_write(sc, AR_MAC_REG_EIFS_AND_SIFS, 0xa144000);
1663 	otus_write(sc, AR_MAC_REG_SLOT_TIME, 9 << 10);
1664 	otus_write(sc, 0x1c3b2c, 0x19000000);
1665 	/* NAV protects ACK only (in TXOP). */
1666 	otus_write(sc, 0x1c3b38, 0x201);
1667 	/* Set beacon Tx power to 0x7. */
1668 	otus_write(sc, AR_MAC_REG_BCN_HT1, 0x8000170);
1669 	otus_write(sc, AR_MAC_REG_BACKOFF_PROTECT, 0x105);
1670 	otus_write(sc, 0x1c3b9c, 0x10000a);
1671 	/* Filter any control frames, BAR is bit 24. */
1672 	otus_write(sc, 0x1c368c, 0x0500ffff);
1673 	otus_write(sc, 0x1c3c40, 0x1);
1674 	otus_write(sc, AR_MAC_REG_BASIC_RATE, 0x150f);
1675 	otus_write(sc, AR_MAC_REG_MANDATORY_RATE, 0x150f);
1676 	otus_write(sc, AR_MAC_REG_RTS_CTS_RATE, 0x10b01bb);
1677 	otus_write(sc, 0x1c3694, 0x4003c1e);
1678 	/* Enable LED0 and LED1. */
1679 	otus_write(sc, 0x1d0100, 0x3);
1680 	otus_write(sc, 0x1d0104, 0x3);
1681 	/* Switch MAC to OTUS interface. */
1682 	otus_write(sc, 0x1c3600, 0x3);
1683 	otus_write(sc, 0x1c3c50, 0xffff);
1684 	otus_write(sc, 0x1c3680, 0xf00008);
1685 	/* Disable Rx timeout (workaround). */
1686 	otus_write(sc, 0x1c362c, 0);
1687 
1688 	/* Set USB Rx stream mode maximum frame number to 2. */
1689 	otus_write(sc, 0x1e1110, 0x4);
1690 	/* Set USB Rx stream mode timeout to 10us. */
1691 	otus_write(sc, 0x1e1114, 0x80);
1692 
1693 	/* Set clock frequency to 88/80MHz. */
1694 	otus_write(sc, 0x1d4008, 0x73);
1695 	/* Set WLAN DMA interrupt mode: generate intr per packet. */
1696 	otus_write(sc, 0x1c3d7c, 0x110011);
1697 	otus_write(sc, 0x1c3bb0, 0x4);
1698 	otus_write(sc, AR_MAC_REG_TXOP_NOT_ENOUGH_INDICATION, 0x141e0f48);
1699 
1700 	/* Disable HW decryption for now. */
1701 	otus_write(sc, 0x1c3678, 0x78);
1702 
1703 	if ((error = otus_write_barrier(sc)) != 0)
1704 		return error;
1705 
1706 	/* Set default EDCA parameters. */
1707 	otus_updateedca_cb(sc, NULL);
1708 
1709 	return 0;
1710 }
1711 
1712 /*
1713  * Return default value for PHY register based on current operating mode.
1714  */
1715 uint32_t
1716 otus_phy_get_def(struct otus_softc *sc, uint32_t reg)
1717 {
1718 	int i;
1719 
1720 	for (i = 0; i < nitems(ar5416_phy_regs); i++)
1721 		if (AR_PHY(ar5416_phy_regs[i]) == reg)
1722 			return sc->phy_vals[i];
1723 	return 0;	/* Register not found. */
1724 }
1725 
1726 /*
1727  * Update PHY's programming based on vendor-specific data stored in EEPROM.
1728  * This is for FEM-type devices only.
1729  */
1730 int
1731 otus_set_board_values(struct otus_softc *sc, struct ieee80211_channel *c)
1732 {
1733 	const struct ModalEepHeader *eep;
1734 	uint32_t tmp, offset;
1735 
1736 	if (IEEE80211_IS_CHAN_5GHZ(c))
1737 		eep = &sc->eeprom.modalHeader[0];
1738 	else
1739 		eep = &sc->eeprom.modalHeader[1];
1740 
1741 	/* Offset of chain 2. */
1742 	offset = 2 * 0x1000;
1743 
1744 	tmp = letoh32(eep->antCtrlCommon);
1745 	otus_write(sc, AR_PHY_SWITCH_COM, tmp);
1746 
1747 	tmp = letoh32(eep->antCtrlChain[0]);
1748 	otus_write(sc, AR_PHY_SWITCH_CHAIN_0, tmp);
1749 
1750 	tmp = letoh32(eep->antCtrlChain[1]);
1751 	otus_write(sc, AR_PHY_SWITCH_CHAIN_0 + offset, tmp);
1752 
1753 	if (1 /* sc->sc_sco == AR_SCO_SCN */) {
1754 		tmp = otus_phy_get_def(sc, AR_PHY_SETTLING);
1755 		tmp &= ~(0x7f << 7);
1756 		tmp |= (eep->switchSettling & 0x7f) << 7;
1757 		otus_write(sc, AR_PHY_SETTLING, tmp);
1758 	}
1759 
1760 	tmp = otus_phy_get_def(sc, AR_PHY_DESIRED_SZ);
1761 	tmp &= ~0xffff;
1762 	tmp |= eep->pgaDesiredSize << 8 | eep->adcDesiredSize;
1763 	otus_write(sc, AR_PHY_DESIRED_SZ, tmp);
1764 
1765 	tmp = eep->txEndToXpaOff << 24 | eep->txEndToXpaOff << 16 |
1766 	      eep->txFrameToXpaOn << 8 | eep->txFrameToXpaOn;
1767 	otus_write(sc, AR_PHY_RF_CTL4, tmp);
1768 
1769 	tmp = otus_phy_get_def(sc, AR_PHY_RF_CTL3);
1770 	tmp &= ~(0xff << 16);
1771 	tmp |= eep->txEndToRxOn << 16;
1772 	otus_write(sc, AR_PHY_RF_CTL3, tmp);
1773 
1774 	tmp = otus_phy_get_def(sc, AR_PHY_CCA);
1775 	tmp &= ~(0x7f << 12);
1776 	tmp |= (eep->thresh62 & 0x7f) << 12;
1777 	otus_write(sc, AR_PHY_CCA, tmp);
1778 
1779 	tmp = otus_phy_get_def(sc, AR_PHY_RXGAIN);
1780 	tmp &= ~(0x3f << 12);
1781 	tmp |= (eep->txRxAttenCh[0] & 0x3f) << 12;
1782 	otus_write(sc, AR_PHY_RXGAIN, tmp);
1783 
1784 	tmp = otus_phy_get_def(sc, AR_PHY_RXGAIN + offset);
1785 	tmp &= ~(0x3f << 12);
1786 	tmp |= (eep->txRxAttenCh[1] & 0x3f) << 12;
1787 	otus_write(sc, AR_PHY_RXGAIN + offset, tmp);
1788 
1789 	tmp = otus_phy_get_def(sc, AR_PHY_GAIN_2GHZ);
1790 	tmp &= ~(0x3f << 18);
1791 	tmp |= (eep->rxTxMarginCh[0] & 0x3f) << 18;
1792 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
1793 		tmp &= ~(0xf << 10);
1794 		tmp |= (eep->bswMargin[0] & 0xf) << 10;
1795 	}
1796 	otus_write(sc, AR_PHY_GAIN_2GHZ, tmp);
1797 
1798 	tmp = otus_phy_get_def(sc, AR_PHY_GAIN_2GHZ + offset);
1799 	tmp &= ~(0x3f << 18);
1800 	tmp |= (eep->rxTxMarginCh[1] & 0x3f) << 18;
1801 	otus_write(sc, AR_PHY_GAIN_2GHZ + offset, tmp);
1802 
1803 	tmp = otus_phy_get_def(sc, AR_PHY_TIMING_CTRL4);
1804 	tmp &= ~(0x3f << 5 | 0x1f);
1805 	tmp |= (eep->iqCalICh[0] & 0x3f) << 5 | (eep->iqCalQCh[0] & 0x1f);
1806 	otus_write(sc, AR_PHY_TIMING_CTRL4, tmp);
1807 
1808 	tmp = otus_phy_get_def(sc, AR_PHY_TIMING_CTRL4 + offset);
1809 	tmp &= ~(0x3f << 5 | 0x1f);
1810 	tmp |= (eep->iqCalICh[1] & 0x3f) << 5 | (eep->iqCalQCh[1] & 0x1f);
1811 	otus_write(sc, AR_PHY_TIMING_CTRL4 + offset, tmp);
1812 
1813 	tmp = otus_phy_get_def(sc, AR_PHY_TPCRG1);
1814 	tmp &= ~(0xf << 16);
1815 	tmp |= (eep->xpd & 0xf) << 16;
1816 	otus_write(sc, AR_PHY_TPCRG1, tmp);
1817 
1818 	return otus_write_barrier(sc);
1819 }
1820 
1821 int
1822 otus_program_phy(struct otus_softc *sc, struct ieee80211_channel *c)
1823 {
1824 	const uint32_t *vals;
1825 	int error, i;
1826 
1827 	/* Select PHY programming based on band and bandwidth. */
1828 	if (IEEE80211_IS_CHAN_2GHZ(c))
1829 		vals = ar5416_phy_vals_2ghz_20mhz;
1830 	else
1831 		vals = ar5416_phy_vals_5ghz_20mhz;
1832 	for (i = 0; i < nitems(ar5416_phy_regs); i++)
1833 		otus_write(sc, AR_PHY(ar5416_phy_regs[i]), vals[i]);
1834 	sc->phy_vals = vals;
1835 
1836 	if (sc->eeprom.baseEepHeader.deviceType == 0x80)	/* FEM */
1837 		if ((error = otus_set_board_values(sc, c)) != 0)
1838 			return error;
1839 
1840 	/* Initial Tx power settings. */
1841 	otus_write(sc, AR_PHY_POWER_TX_RATE_MAX, 0x7f);
1842 	otus_write(sc, AR_PHY_POWER_TX_RATE1, 0x3f3f3f3f);
1843 	otus_write(sc, AR_PHY_POWER_TX_RATE2, 0x3f3f3f3f);
1844 	otus_write(sc, AR_PHY_POWER_TX_RATE3, 0x3f3f3f3f);
1845 	otus_write(sc, AR_PHY_POWER_TX_RATE4, 0x3f3f3f3f);
1846 	otus_write(sc, AR_PHY_POWER_TX_RATE5, 0x3f3f3f3f);
1847 	otus_write(sc, AR_PHY_POWER_TX_RATE6, 0x3f3f3f3f);
1848 	otus_write(sc, AR_PHY_POWER_TX_RATE7, 0x3f3f3f3f);
1849 	otus_write(sc, AR_PHY_POWER_TX_RATE8, 0x3f3f3f3f);
1850 	otus_write(sc, AR_PHY_POWER_TX_RATE9, 0x3f3f3f3f);
1851 
1852 	if (IEEE80211_IS_CHAN_2GHZ(c))
1853 		otus_write(sc, 0x1d4014, 0x5163);
1854 	else
1855 		otus_write(sc, 0x1d4014, 0x5143);
1856 
1857 	return otus_write_barrier(sc);
1858 }
1859 
1860 static __inline uint8_t
1861 otus_reverse_bits(uint8_t v)
1862 {
1863 	v = ((v >> 1) & 0x55) | ((v & 0x55) << 1);
1864 	v = ((v >> 2) & 0x33) | ((v & 0x33) << 2);
1865 	v = ((v >> 4) & 0x0f) | ((v & 0x0f) << 4);
1866 	return v;
1867 }
1868 
1869 int
1870 otus_set_rf_bank4(struct otus_softc *sc, struct ieee80211_channel *c)
1871 {
1872 	uint8_t chansel, d0, d1;
1873 	uint16_t data;
1874 	int error;
1875 
1876 	d0 = 0;
1877 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
1878 		chansel = (c->ic_freq - 4800) / 5;
1879 		if (chansel & 1)
1880 			d0 |= AR_BANK4_AMODE_REFSEL(2);
1881 		else
1882 			d0 |= AR_BANK4_AMODE_REFSEL(1);
1883 	} else {
1884 		d0 |= AR_BANK4_AMODE_REFSEL(2);
1885 		if (c->ic_freq == 2484) {	/* CH 14 */
1886 			d0 |= AR_BANK4_BMODE_LF_SYNTH_FREQ;
1887 			chansel = 10 + (c->ic_freq - 2274) / 5;
1888 		} else
1889 			chansel = 16 + (c->ic_freq - 2272) / 5;
1890 		chansel <<= 2;
1891 	}
1892 	d0 |= AR_BANK4_ADDR(1) | AR_BANK4_CHUP;
1893 	d1 = otus_reverse_bits(chansel);
1894 
1895 	/* Write bits 0-4 of d0 and d1. */
1896 	data = (d1 & 0x1f) << 5 | (d0 & 0x1f);
1897 	otus_write(sc, AR_PHY(44), data);
1898 	/* Write bits 5-7 of d0 and d1. */
1899 	data = (d1 >> 5) << 5 | (d0 >> 5);
1900 	otus_write(sc, AR_PHY(58), data);
1901 
1902 	if ((error = otus_write_barrier(sc)) == 0)
1903 		usbd_delay_ms(sc->sc_udev, 10);
1904 	return error;
1905 }
1906 
1907 void
1908 otus_get_delta_slope(uint32_t coeff, uint32_t *exponent, uint32_t *mantissa)
1909 {
1910 #define COEFF_SCALE_SHIFT	24
1911 	uint32_t exp, man;
1912 
1913 	/* exponent = 14 - floor(log2(coeff)) */
1914 	for (exp = 31; exp > 0; exp--)
1915 		if (coeff & (1 << exp))
1916 			break;
1917 	KASSERT(exp != 0);
1918 	exp = 14 - (exp - COEFF_SCALE_SHIFT);
1919 
1920 	/* mantissa = floor(coeff * 2^exponent + 0.5) */
1921 	man = coeff + (1 << (COEFF_SCALE_SHIFT - exp - 1));
1922 
1923 	*mantissa = man >> (COEFF_SCALE_SHIFT - exp);
1924 	*exponent = exp - 16;
1925 #undef COEFF_SCALE_SHIFT
1926 }
1927 
1928 int
1929 otus_set_chan(struct otus_softc *sc, struct ieee80211_channel *c, int assoc)
1930 {
1931 	struct ieee80211com *ic = &sc->sc_ic;
1932 	struct ar_cmd_frequency cmd;
1933 	struct ar_rsp_frequency rsp;
1934 	const uint32_t *vals;
1935 	uint32_t coeff, exp, man, tmp;
1936 	uint8_t code;
1937 	int error, chan, i;
1938 
1939 	chan = ieee80211_chan2ieee(ic, c);
1940 	DPRINTF(("setting channel %d (%dMHz)\n", chan, c->ic_freq));
1941 
1942 	tmp = IEEE80211_IS_CHAN_2GHZ(c) ? 0x105 : 0x104;
1943 	otus_write(sc, AR_MAC_REG_DYNAMIC_SIFS_ACK, tmp);
1944 	if ((error = otus_write_barrier(sc)) != 0)
1945 		return error;
1946 
1947 	/* Disable BB Heavy Clip. */
1948 	otus_write(sc, AR_PHY_HEAVY_CLIP_ENABLE, 0x200);
1949 	if ((error = otus_write_barrier(sc)) != 0)
1950 		return error;
1951 
1952 	/* XXX Is that FREQ_START ? */
1953 	error = otus_cmd(sc, AR_CMD_FREQ_STRAT, NULL, 0, NULL);
1954 	if (error != 0)
1955 		return error;
1956 
1957 	/* Reprogram PHY and RF on channel band or bandwidth changes. */
1958 	if (sc->bb_reset || c->ic_flags != sc->sc_curchan->ic_flags) {
1959 		DPRINTF(("band switch\n"));
1960 
1961 		/* Cold/Warm reset BB/ADDA. */
1962 		otus_write(sc, 0x1d4004, sc->bb_reset ? 0x800 : 0x400);
1963 		if ((error = otus_write_barrier(sc)) != 0)
1964 			return error;
1965 		otus_write(sc, 0x1d4004, 0);
1966 		if ((error = otus_write_barrier(sc)) != 0)
1967 			return error;
1968 		sc->bb_reset = 0;
1969 
1970 		if ((error = otus_program_phy(sc, c)) != 0) {
1971 			printf("%s: could not program PHY\n",
1972 			    sc->sc_dev.dv_xname);
1973 			return error;
1974 		}
1975 
1976 		/* Select RF programming based on band. */
1977 		if (IEEE80211_IS_CHAN_5GHZ(c))
1978 			vals = ar5416_banks_vals_5ghz;
1979 		else
1980 			vals = ar5416_banks_vals_2ghz;
1981 		for (i = 0; i < nitems(ar5416_banks_regs); i++)
1982 			otus_write(sc, AR_PHY(ar5416_banks_regs[i]), vals[i]);
1983 		if ((error = otus_write_barrier(sc)) != 0) {
1984 			printf("%s: could not program RF\n",
1985 			    sc->sc_dev.dv_xname);
1986 			return error;
1987 		}
1988 		code = AR_CMD_RF_INIT;
1989 	} else {
1990 		code = AR_CMD_FREQUENCY;
1991 	}
1992 
1993 	if ((error = otus_set_rf_bank4(sc, c)) != 0)
1994 		return error;
1995 
1996 	tmp = (sc->txmask == 0x5) ? 0x340 : 0x240;
1997 	otus_write(sc, AR_PHY_TURBO, tmp);
1998 	if ((error = otus_write_barrier(sc)) != 0)
1999 		return error;
2000 
2001 	/* Send firmware command to set channel. */
2002 	cmd.freq = htole32((uint32_t)c->ic_freq * 1000);
2003 	cmd.dynht2040 = htole32(0);
2004 	cmd.htena = htole32(1);
2005 	/* Set Delta Slope (exponent and mantissa). */
2006 	coeff = (100 << 24) / c->ic_freq;
2007 	otus_get_delta_slope(coeff, &exp, &man);
2008 	cmd.dsc_exp = htole32(exp);
2009 	cmd.dsc_man = htole32(man);
2010 	DPRINTF(("ds coeff=%u exp=%u man=%u\n", coeff, exp, man));
2011 	/* For Short GI, coeff is 9/10 that of normal coeff. */
2012 	coeff = (9 * coeff) / 10;
2013 	otus_get_delta_slope(coeff, &exp, &man);
2014 	cmd.dsc_shgi_exp = htole32(exp);
2015 	cmd.dsc_shgi_man = htole32(man);
2016 	DPRINTF(("ds shgi coeff=%u exp=%u man=%u\n", coeff, exp, man));
2017 	/* Set wait time for AGC and noise calibration (100 or 200ms). */
2018 	cmd.check_loop_count = assoc ? htole32(2000) : htole32(1000);
2019 	DPRINTF(("%s\n", (code == AR_CMD_RF_INIT) ? "RF_INIT" : "FREQUENCY"));
2020 	error = otus_cmd(sc, code, &cmd, sizeof cmd, &rsp);
2021 	if (error != 0)
2022 		return error;
2023 	if ((rsp.status & htole32(AR_CAL_ERR_AGC | AR_CAL_ERR_NF_VAL)) != 0) {
2024 		DPRINTF(("status=0x%x\n", letoh32(rsp.status)));
2025 		/* Force cold reset on next channel. */
2026 		sc->bb_reset = 1;
2027 	}
2028 #ifdef OTUS_DEBUG
2029 	if (otus_debug) {
2030 		printf("calibration status=0x%x\n", letoh32(rsp.status));
2031 		for (i = 0; i < 2; i++) {	/* 2 Rx chains */
2032 			/* Sign-extend 9-bit NF values. */
2033 			printf("noisefloor chain %d=%d\n", i,
2034 			    (((int32_t)letoh32(rsp.nf[i])) << 4) >> 23);
2035 			printf("noisefloor ext chain %d=%d\n", i,
2036 			    ((int32_t)letoh32(rsp.nf_ext[i])) >> 23);
2037 		}
2038 	}
2039 #endif
2040 	sc->sc_curchan = c;
2041 	return 0;
2042 }
2043 
2044 #ifdef notyet
2045 int
2046 otus_set_key(struct ieee80211com *ic, struct ieee80211_node *ni,
2047     struct ieee80211_key *k)
2048 {
2049 	struct otus_softc *sc = ic->ic_softc;
2050 	struct otus_cmd_key cmd;
2051 
2052 	/* Defer setting of WEP keys until interface is brought up. */
2053 	if ((ic->ic_if.if_flags & (IFF_UP | IFF_RUNNING)) !=
2054 	    (IFF_UP | IFF_RUNNING))
2055 		return 0;
2056 
2057 	/* Do it in a process context. */
2058 	cmd.key = *k;
2059 	cmd.associd = (ni != NULL) ? ni->ni_associd : 0;
2060 	otus_do_async(sc, otus_set_key_cb, &cmd, sizeof cmd);
2061 	return 0;
2062 }
2063 
2064 void
2065 otus_set_key_cb(struct otus_softc *sc, void *arg)
2066 {
2067 	struct otus_cmd_key *cmd = arg;
2068 	struct ieee80211_key *k = &cmd->key;
2069 	struct ar_cmd_ekey key;
2070 	uint16_t cipher;
2071 	int error;
2072 
2073 	memset(&key, 0, sizeof key);
2074 	if (k->k_flags & IEEE80211_KEY_GROUP) {
2075 		key.uid = htole16(k->k_id);
2076 		IEEE80211_ADDR_COPY(key.macaddr, sc->sc_ic.ic_myaddr);
2077 		key.macaddr[0] |= 0x80;
2078 	} else {
2079 		key.uid = htole16(OTUS_UID(cmd->associd));
2080 		IEEE80211_ADDR_COPY(key.macaddr, ni->ni_macaddr);
2081 	}
2082 	key.kix = htole16(0);
2083 	/* Map net80211 cipher to hardware. */
2084 	switch (k->k_cipher) {
2085 	case IEEE80211_CIPHER_WEP40:
2086 		cipher = AR_CIPHER_WEP64;
2087 		break;
2088 	case IEEE80211_CIPHER_WEP104:
2089 		cipher = AR_CIPHER_WEP128;
2090 		break;
2091 	case IEEE80211_CIPHER_TKIP:
2092 		cipher = AR_CIPHER_TKIP;
2093 		break;
2094 	case IEEE80211_CIPHER_CCMP:
2095 		cipher = AR_CIPHER_AES;
2096 		break;
2097 	default:
2098 		return;
2099 	}
2100 	key.cipher = htole16(cipher);
2101 	memcpy(key.key, k->k_key, MIN(k->k_len, 16));
2102 	error = otus_cmd(sc, AR_CMD_EKEY, &key, sizeof key, NULL);
2103 	if (error != 0 || k->k_cipher != IEEE80211_CIPHER_TKIP)
2104 		return;
2105 
2106 	/* TKIP: set Tx/Rx MIC Key. */
2107 	key.kix = htole16(1);
2108 	memcpy(key.key, k->k_key + 16, 16);
2109 	(void)otus_cmd(sc, AR_CMD_EKEY, &key, sizeof key, NULL);
2110 }
2111 
2112 void
2113 otus_delete_key(struct ieee80211com *ic, struct ieee80211_node *ni,
2114     struct ieee80211_key *k)
2115 {
2116 	struct otus_softc *sc = ic->ic_softc;
2117 	struct otus_cmd_key cmd;
2118 
2119 	if (!(ic->ic_if.if_flags & IFF_RUNNING) ||
2120 	    ic->ic_state != IEEE80211_S_RUN)
2121 		return;	/* Nothing to do. */
2122 
2123 	/* Do it in a process context. */
2124 	cmd.key = *k;
2125 	cmd.associd = (ni != NULL) ? ni->ni_associd : 0;
2126 	otus_do_async(sc, otus_delete_key_cb, &cmd, sizeof cmd);
2127 }
2128 
2129 void
2130 otus_delete_key_cb(struct otus_softc *sc, void *arg)
2131 {
2132 	struct otus_cmd_key *cmd = arg;
2133 	struct ieee80211_key *k = &cmd->key;
2134 	uint32_t uid;
2135 
2136 	if (k->k_flags & IEEE80211_KEY_GROUP)
2137 		uid = htole32(k->k_id);
2138 	else
2139 		uid = htole32(OTUS_UID(cmd->associd));
2140 	(void)otus_cmd(sc, AR_CMD_DKEY, &uid, sizeof uid, NULL);
2141 }
2142 #endif
2143 
2144 void
2145 otus_calibrate_to(void *arg)
2146 {
2147 	struct otus_softc *sc = arg;
2148 	struct ieee80211com *ic = &sc->sc_ic;
2149 	struct ieee80211_node *ni;
2150 	int s;
2151 
2152 	if (usbd_is_dying(sc->sc_udev))
2153 		return;
2154 
2155 	usbd_ref_incr(sc->sc_udev);
2156 
2157 	s = splnet();
2158 	ni = ic->ic_bss;
2159 	ieee80211_amrr_choose(&sc->amrr, ni, &((struct otus_node *)ni)->amn);
2160 	splx(s);
2161 
2162 	if (!usbd_is_dying(sc->sc_udev))
2163 		timeout_add_sec(&sc->calib_to, 1);
2164 
2165 	usbd_ref_decr(sc->sc_udev);
2166 }
2167 
2168 int
2169 otus_set_bssid(struct otus_softc *sc, const uint8_t *bssid)
2170 {
2171 	otus_write(sc, AR_MAC_REG_BSSID_L,
2172 	    bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24);
2173 	otus_write(sc, AR_MAC_REG_BSSID_H,
2174 	    bssid[4] | bssid[5] << 8);
2175 	return otus_write_barrier(sc);
2176 }
2177 
2178 int
2179 otus_set_macaddr(struct otus_softc *sc, const uint8_t *addr)
2180 {
2181 	otus_write(sc, AR_MAC_REG_MAC_ADDR_L,
2182 	    addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24);
2183 	otus_write(sc, AR_MAC_REG_MAC_ADDR_H,
2184 	    addr[4] | addr[5] << 8);
2185 	return otus_write_barrier(sc);
2186 }
2187 
2188 /* Default single-LED. */
2189 void
2190 otus_led_newstate_type1(struct otus_softc *sc)
2191 {
2192 	/* TBD */
2193 }
2194 
2195 /* NETGEAR, dual-LED. */
2196 void
2197 otus_led_newstate_type2(struct otus_softc *sc)
2198 {
2199 	/* TBD */
2200 }
2201 
2202 /* NETGEAR, single-LED/3 colors (blue, red, purple.) */
2203 void
2204 otus_led_newstate_type3(struct otus_softc *sc)
2205 {
2206 	struct ieee80211com *ic = &sc->sc_ic;
2207 	uint32_t state = sc->led_state;
2208 
2209 	if (ic->ic_state == IEEE80211_S_INIT) {
2210 		state = 0;	/* LED off. */
2211 	} else if (ic->ic_state == IEEE80211_S_RUN) {
2212 		/* Associated, LED always on. */
2213 		if (IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan))
2214 			state = AR_LED0_ON;	/* 2GHz=>Red. */
2215 		else
2216 			state = AR_LED1_ON;	/* 5GHz=>Blue. */
2217 	} else {
2218 		/* Scanning, blink LED. */
2219 		state ^= AR_LED0_ON | AR_LED1_ON;
2220 		if (IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan))
2221 			state &= ~AR_LED1_ON;
2222 		else
2223 			state &= ~AR_LED0_ON;
2224 	}
2225 	if (state != sc->led_state) {
2226 		otus_write(sc, 0x1d0104, state);
2227 		if (otus_write_barrier(sc) == 0)
2228 			sc->led_state = state;
2229 	}
2230 }
2231 
2232 int
2233 otus_init(struct ifnet *ifp)
2234 {
2235 	struct otus_softc *sc = ifp->if_softc;
2236 	struct ieee80211com *ic = &sc->sc_ic;
2237 	int error;
2238 
2239 	/* Init host command ring. */
2240 	sc->cmdq.cur = sc->cmdq.next = sc->cmdq.queued = 0;
2241 
2242 	if ((error = otus_init_mac(sc)) != 0) {
2243 		printf("%s: could not initialize MAC\n", sc->sc_dev.dv_xname);
2244 		return error;
2245 	}
2246 
2247 	IEEE80211_ADDR_COPY(ic->ic_myaddr, LLADDR(ifp->if_sadl));
2248 	(void)otus_set_macaddr(sc, ic->ic_myaddr);
2249 
2250 	switch (ic->ic_opmode) {
2251 #ifdef notyet
2252 #ifndef IEEE80211_STA_ONLY
2253 	case IEEE80211_M_HOSTAP:
2254 		otus_write(sc, 0x1c3700, 0x0f0000a1);
2255 		otus_write(sc, 0x1c3c40, 0x1);
2256 		break;
2257 	case IEEE80211_M_IBSS:
2258 		otus_write(sc, 0x1c3700, 0x0f000000);
2259 		otus_write(sc, 0x1c3c40, 0x1);
2260 		break;
2261 #endif
2262 #endif
2263 	case IEEE80211_M_STA:
2264 		otus_write(sc, 0x1c3700, 0x0f000002);
2265 		otus_write(sc, 0x1c3c40, 0x1);
2266 		break;
2267 	default:
2268 		break;
2269 	}
2270 	otus_write(sc, AR_MAC_REG_SNIFFER,
2271 	    (ic->ic_opmode == IEEE80211_M_MONITOR) ? 0x2000001 : 0x2000000);
2272 	(void)otus_write_barrier(sc);
2273 
2274 	sc->bb_reset = 1;	/* Force cold reset. */
2275 	ic->ic_bss->ni_chan = ic->ic_ibss_chan;
2276 	if ((error = otus_set_chan(sc, ic->ic_ibss_chan, 0)) != 0) {
2277 		printf("%s: could not set channel\n", sc->sc_dev.dv_xname);
2278 		return error;
2279 	}
2280 
2281 	/* Start Rx. */
2282 	otus_write(sc, AR_MAC_REG_DMA_TRIGGER, AR_DMA_TRIGGER_RXQ);
2283 	(void)otus_write_barrier(sc);
2284 
2285 	ifp->if_flags |= IFF_RUNNING;
2286 	ifq_clr_oactive(&ifp->if_snd);
2287 
2288 	if (ic->ic_opmode == IEEE80211_M_MONITOR)
2289 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
2290 	else
2291 		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
2292 
2293 	return 0;
2294 }
2295 
2296 void
2297 otus_stop(struct ifnet *ifp)
2298 {
2299 	struct otus_softc *sc = ifp->if_softc;
2300 	struct ieee80211com *ic = &sc->sc_ic;
2301 	int s;
2302 
2303 	sc->sc_tx_timer = 0;
2304 	ifp->if_timer = 0;
2305 	ifp->if_flags &= ~IFF_RUNNING;
2306 	ifq_clr_oactive(&ifp->if_snd);
2307 
2308 	timeout_del(&sc->scan_to);
2309 	timeout_del(&sc->calib_to);
2310 
2311 	s = splusb();
2312 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
2313 	/* Wait for all queued asynchronous commands to complete. */
2314 	usb_wait_task(sc->sc_udev, &sc->sc_task);
2315 	splx(s);
2316 
2317 	/* Stop Rx. */
2318 	otus_write(sc, AR_MAC_REG_DMA_TRIGGER, 0);
2319 	(void)otus_write_barrier(sc);
2320 
2321 	sc->tx_queued = 0;
2322 }
2323