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