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