xref: /freebsd/sys/dev/otus/if_otus.c (revision 74ca7bf1d4c7173d5575ba168bc4b5f6d181ff5a)
1 /*	$OpenBSD: if_otus.c,v 1.49 2015/11/24 13:33:18 mpi Exp $	*/
2 
3 /*-
4  * Copyright (c) 2009 Damien Bergamini <damien.bergamini@free.fr>
5  * Copyright (c) 2015 Adrian Chadd <adrian@FreeBSD.org>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 /*
21  * Driver for Atheros AR9001U chipset.
22  */
23 
24 #include <sys/cdefs.h>
25 __FBSDID("$FreeBSD$");
26 
27 #include "opt_wlan.h"
28 
29 #include <sys/param.h>
30 #include <sys/endian.h>
31 #include <sys/sockio.h>
32 #include <sys/mbuf.h>
33 #include <sys/kernel.h>
34 #include <sys/malloc.h>
35 #include <sys/socket.h>
36 #include <sys/systm.h>
37 #include <sys/conf.h>
38 #include <sys/bus.h>
39 #include <sys/rman.h>
40 #include <sys/firmware.h>
41 #include <sys/module.h>
42 #include <sys/taskqueue.h>
43 
44 #include <machine/bus.h>
45 #include <machine/resource.h>
46 
47 #include <net/bpf.h>
48 #include <net/if.h>
49 #include <net/if_var.h>
50 #include <net/if_arp.h>
51 #include <net/if_dl.h>
52 #include <net/if_media.h>
53 
54 #include <netinet/in.h>
55 #include <netinet/in_systm.h>
56 #include <netinet/in_var.h>
57 #include <netinet/if_ether.h>
58 #include <netinet/ip.h>
59 
60 #include <net80211/ieee80211_var.h>
61 #include <net80211/ieee80211_regdomain.h>
62 #include <net80211/ieee80211_radiotap.h>
63 #include <net80211/ieee80211_ratectl.h>
64 #ifdef	IEEE80211_SUPPORT_SUPERG
65 #include <net80211/ieee80211_superg.h>
66 #endif
67 
68 #include <dev/usb/usb.h>
69 #include <dev/usb/usbdi.h>
70 #include "usbdevs.h"
71 
72 #define USB_DEBUG_VAR otus_debug
73 #include <dev/usb/usb_debug.h>
74 
75 #include "if_otusreg.h"
76 
77 static int otus_debug = 0;
78 static SYSCTL_NODE(_hw_usb, OID_AUTO, otus, CTLFLAG_RW, 0, "USB otus");
79 SYSCTL_INT(_hw_usb_otus, OID_AUTO, debug, CTLFLAG_RWTUN, &otus_debug, 0,
80     "Debug level");
81 #define	OTUS_DEBUG_XMIT		0x00000001
82 #define	OTUS_DEBUG_RECV		0x00000002
83 #define	OTUS_DEBUG_TXDONE	0x00000004
84 #define	OTUS_DEBUG_RXDONE	0x00000008
85 #define	OTUS_DEBUG_CMD		0x00000010
86 #define	OTUS_DEBUG_CMDDONE	0x00000020
87 #define	OTUS_DEBUG_RESET	0x00000040
88 #define	OTUS_DEBUG_STATE	0x00000080
89 #define	OTUS_DEBUG_CMDNOTIFY	0x00000100
90 #define	OTUS_DEBUG_REGIO	0x00000200
91 #define	OTUS_DEBUG_IRQ		0x00000400
92 #define	OTUS_DEBUG_TXCOMP	0x00000800
93 #define	OTUS_DEBUG_ANY		0xffffffff
94 
95 #define	OTUS_DPRINTF(sc, dm, ...) \
96 	do { \
97 		if ((dm == OTUS_DEBUG_ANY) || (dm & otus_debug)) \
98 			device_printf(sc->sc_dev, __VA_ARGS__); \
99 	} while (0)
100 
101 #define	OTUS_DEV(v, p) { USB_VPI(v, p, 0) }
102 static const STRUCT_USB_HOST_ID otus_devs[] = {
103 	OTUS_DEV(USB_VENDOR_ACCTON,		USB_PRODUCT_ACCTON_WN7512),
104 	OTUS_DEV(USB_VENDOR_ATHEROS2,		USB_PRODUCT_ATHEROS2_3CRUSBN275),
105 	OTUS_DEV(USB_VENDOR_ATHEROS2,		USB_PRODUCT_ATHEROS2_TG121N),
106 	OTUS_DEV(USB_VENDOR_ATHEROS2,		USB_PRODUCT_ATHEROS2_AR9170),
107 	OTUS_DEV(USB_VENDOR_ATHEROS2,		USB_PRODUCT_ATHEROS2_WN612),
108 	OTUS_DEV(USB_VENDOR_ATHEROS2,		USB_PRODUCT_ATHEROS2_WN821NV2),
109 	OTUS_DEV(USB_VENDOR_AVM,		USB_PRODUCT_AVM_FRITZWLAN),
110 	OTUS_DEV(USB_VENDOR_CACE,		USB_PRODUCT_CACE_AIRPCAPNX),
111 	OTUS_DEV(USB_VENDOR_DLINK2,		USB_PRODUCT_DLINK2_DWA130D1),
112 	OTUS_DEV(USB_VENDOR_DLINK2,		USB_PRODUCT_DLINK2_DWA160A1),
113 	OTUS_DEV(USB_VENDOR_DLINK2,		USB_PRODUCT_DLINK2_DWA160A2),
114 	OTUS_DEV(USB_VENDOR_IODATA,		USB_PRODUCT_IODATA_WNGDNUS2),
115 	OTUS_DEV(USB_VENDOR_NEC,		USB_PRODUCT_NEC_WL300NUG),
116 	OTUS_DEV(USB_VENDOR_NETGEAR,		USB_PRODUCT_NETGEAR_WN111V2),
117 	OTUS_DEV(USB_VENDOR_NETGEAR,		USB_PRODUCT_NETGEAR_WNA1000),
118 	OTUS_DEV(USB_VENDOR_NETGEAR,		USB_PRODUCT_NETGEAR_WNDA3100),
119 	OTUS_DEV(USB_VENDOR_PLANEX2,		USB_PRODUCT_PLANEX2_GW_US300),
120 	OTUS_DEV(USB_VENDOR_WISTRONNEWEB,	USB_PRODUCT_WISTRONNEWEB_O8494),
121 	OTUS_DEV(USB_VENDOR_WISTRONNEWEB,	USB_PRODUCT_WISTRONNEWEB_WNC0600),
122 	OTUS_DEV(USB_VENDOR_ZCOM,		USB_PRODUCT_ZCOM_UB81),
123 	OTUS_DEV(USB_VENDOR_ZCOM,		USB_PRODUCT_ZCOM_UB82),
124 	OTUS_DEV(USB_VENDOR_ZYDAS,		USB_PRODUCT_ZYDAS_ZD1221),
125 	OTUS_DEV(USB_VENDOR_ZYXEL,		USB_PRODUCT_ZYXEL_NWD271N),
126 };
127 
128 static device_probe_t otus_match;
129 static device_attach_t otus_attach;
130 static device_detach_t otus_detach;
131 
132 static int	otus_attachhook(struct otus_softc *);
133 void		otus_get_chanlist(struct otus_softc *);
134 static void	otus_getradiocaps(struct ieee80211com *, int, int *,
135 		    struct ieee80211_channel[]);
136 int		otus_load_firmware(struct otus_softc *, const char *,
137 		    uint32_t);
138 int		otus_open_pipes(struct otus_softc *);
139 void		otus_close_pipes(struct otus_softc *);
140 
141 static int	otus_alloc_tx_cmd_list(struct otus_softc *);
142 static void	otus_free_tx_cmd_list(struct otus_softc *);
143 
144 static int	otus_alloc_rx_list(struct otus_softc *);
145 static void	otus_free_rx_list(struct otus_softc *);
146 static int	otus_alloc_tx_list(struct otus_softc *);
147 static void	otus_free_tx_list(struct otus_softc *);
148 static void	otus_free_list(struct otus_softc *, struct otus_data [], int);
149 static struct otus_data *_otus_getbuf(struct otus_softc *);
150 static struct otus_data *otus_getbuf(struct otus_softc *);
151 static void	otus_freebuf(struct otus_softc *, struct otus_data *);
152 
153 static struct otus_tx_cmd *_otus_get_txcmd(struct otus_softc *);
154 static struct otus_tx_cmd *otus_get_txcmd(struct otus_softc *);
155 static void	otus_free_txcmd(struct otus_softc *, struct otus_tx_cmd *);
156 
157 void		otus_next_scan(void *, int);
158 static void	otus_tx_task(void *, int pending);
159 void		otus_do_async(struct otus_softc *,
160 		    void (*)(struct otus_softc *, void *), void *, int);
161 int		otus_newstate(struct ieee80211vap *, enum ieee80211_state,
162 		    int);
163 int		otus_cmd(struct otus_softc *, uint8_t, const void *, int,
164 		    void *, int);
165 void		otus_write(struct otus_softc *, uint32_t, uint32_t);
166 int		otus_write_barrier(struct otus_softc *);
167 static struct	ieee80211_node *otus_node_alloc(struct ieee80211vap *vap,
168 		    const uint8_t mac[IEEE80211_ADDR_LEN]);
169 int		otus_media_change(struct ifnet *);
170 int		otus_read_eeprom(struct otus_softc *);
171 void		otus_newassoc(struct ieee80211_node *, int);
172 void		otus_cmd_rxeof(struct otus_softc *, uint8_t *, int);
173 void		otus_sub_rxeof(struct otus_softc *, uint8_t *, int,
174 		    struct mbufq *);
175 static int	otus_tx(struct otus_softc *, struct ieee80211_node *,
176 		    struct mbuf *, struct otus_data *,
177 		    const struct ieee80211_bpf_params *);
178 int		otus_ioctl(struct ifnet *, u_long, caddr_t);
179 int		otus_set_multi(struct otus_softc *);
180 static int	otus_updateedca(struct ieee80211com *);
181 static void	otus_updateedca_locked(struct otus_softc *);
182 static void	otus_updateslot(struct otus_softc *);
183 static void	otus_set_operating_mode(struct otus_softc *sc);
184 static void	otus_set_rx_filter(struct otus_softc *sc);
185 int		otus_init_mac(struct otus_softc *);
186 uint32_t	otus_phy_get_def(struct otus_softc *, uint32_t);
187 int		otus_set_board_values(struct otus_softc *,
188 		    struct ieee80211_channel *);
189 int		otus_program_phy(struct otus_softc *,
190 		    struct ieee80211_channel *);
191 int		otus_set_rf_bank4(struct otus_softc *,
192 		    struct ieee80211_channel *);
193 void		otus_get_delta_slope(uint32_t, uint32_t *, uint32_t *);
194 static int	otus_set_chan(struct otus_softc *, struct ieee80211_channel *,
195 		    int);
196 int		otus_set_key(struct ieee80211com *, struct ieee80211_node *,
197 		    struct ieee80211_key *);
198 void		otus_set_key_cb(struct otus_softc *, void *);
199 void		otus_delete_key(struct ieee80211com *, struct ieee80211_node *,
200 		    struct ieee80211_key *);
201 void		otus_delete_key_cb(struct otus_softc *, void *);
202 void		otus_calibrate_to(void *, int);
203 int		otus_set_bssid(struct otus_softc *, const uint8_t *);
204 int		otus_set_macaddr(struct otus_softc *, const uint8_t *);
205 void		otus_led_newstate_type1(struct otus_softc *);
206 void		otus_led_newstate_type2(struct otus_softc *);
207 void		otus_led_newstate_type3(struct otus_softc *);
208 int		otus_init(struct otus_softc *sc);
209 void		otus_stop(struct otus_softc *sc);
210 
211 static device_method_t otus_methods[] = {
212 	DEVMETHOD(device_probe,		otus_match),
213 	DEVMETHOD(device_attach,	otus_attach),
214 	DEVMETHOD(device_detach,	otus_detach),
215 
216 	DEVMETHOD_END
217 };
218 
219 static driver_t otus_driver = {
220 	.name = "otus",
221 	.methods = otus_methods,
222 	.size = sizeof(struct otus_softc)
223 };
224 
225 static devclass_t otus_devclass;
226 
227 DRIVER_MODULE(otus, uhub, otus_driver, otus_devclass, NULL, 0);
228 MODULE_DEPEND(otus, wlan, 1, 1, 1);
229 MODULE_DEPEND(otus, usb, 1, 1, 1);
230 MODULE_DEPEND(otus, firmware, 1, 1, 1);
231 MODULE_VERSION(otus, 1);
232 
233 static usb_callback_t	otus_bulk_tx_callback;
234 static usb_callback_t	otus_bulk_rx_callback;
235 static usb_callback_t	otus_bulk_irq_callback;
236 static usb_callback_t	otus_bulk_cmd_callback;
237 
238 static const struct usb_config otus_config[OTUS_N_XFER] = {
239 	[OTUS_BULK_TX] = {
240 	.type = UE_BULK,
241 	.endpoint = UE_ADDR_ANY,
242 	.direction = UE_DIR_OUT,
243 	.bufsize = 0x200,
244 	.flags = {.pipe_bof = 1,.force_short_xfer = 1,},
245 	.callback = otus_bulk_tx_callback,
246 	.timeout = 5000,	/* ms */
247 	},
248 	[OTUS_BULK_RX] = {
249 	.type = UE_BULK,
250 	.endpoint = UE_ADDR_ANY,
251 	.direction = UE_DIR_IN,
252 	.bufsize = OTUS_RXBUFSZ,
253 	.flags = { .ext_buffer = 1, .pipe_bof = 1,.short_xfer_ok = 1,},
254 	.callback = otus_bulk_rx_callback,
255 	},
256 	[OTUS_BULK_IRQ] = {
257 	.type = UE_INTERRUPT,
258 	.endpoint = UE_ADDR_ANY,
259 	.direction = UE_DIR_IN,
260 	.bufsize = OTUS_MAX_CTRLSZ,
261 	.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
262 	.callback = otus_bulk_irq_callback,
263 	},
264 	[OTUS_BULK_CMD] = {
265 	.type = UE_INTERRUPT,
266 	.endpoint = UE_ADDR_ANY,
267 	.direction = UE_DIR_OUT,
268 	.bufsize = OTUS_MAX_CTRLSZ,
269 	.flags = {.pipe_bof = 1,.force_short_xfer = 1,},
270 	.callback = otus_bulk_cmd_callback,
271 	.timeout = 5000,	/* ms */
272 	},
273 };
274 
275 static int
276 otus_match(device_t self)
277 {
278 	struct usb_attach_arg *uaa = device_get_ivars(self);
279 
280 	if (uaa->usb_mode != USB_MODE_HOST ||
281 	    uaa->info.bIfaceIndex != 0 ||
282 	    uaa->info.bConfigIndex != 0)
283 	return (ENXIO);
284 
285 	return (usbd_lookup_id_by_uaa(otus_devs, sizeof(otus_devs), uaa));
286 }
287 
288 static int
289 otus_attach(device_t self)
290 {
291 	struct usb_attach_arg *uaa = device_get_ivars(self);
292 	struct otus_softc *sc = device_get_softc(self);
293 	int error;
294 	uint8_t iface_index;
295 
296 	device_set_usb_desc(self);
297 	sc->sc_udev = uaa->device;
298 	sc->sc_dev = self;
299 
300 	mtx_init(&sc->sc_mtx, device_get_nameunit(self), MTX_NETWORK_LOCK,
301 	    MTX_DEF);
302 
303 	TIMEOUT_TASK_INIT(taskqueue_thread, &sc->scan_to, 0, otus_next_scan, sc);
304 	TIMEOUT_TASK_INIT(taskqueue_thread, &sc->calib_to, 0, otus_calibrate_to, sc);
305 	TASK_INIT(&sc->tx_task, 0, otus_tx_task, sc);
306 	mbufq_init(&sc->sc_snd, ifqmaxlen);
307 
308 	iface_index = 0;
309 	error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer,
310 	    otus_config, OTUS_N_XFER, sc, &sc->sc_mtx);
311 	if (error) {
312 		device_printf(sc->sc_dev,
313 		    "could not allocate USB transfers, err=%s\n",
314 		    usbd_errstr(error));
315 		goto fail_usb;
316 	}
317 
318 	if ((error = otus_open_pipes(sc)) != 0) {
319 		device_printf(sc->sc_dev, "%s: could not open pipes\n",
320 		    __func__);
321 		goto fail;
322 	}
323 
324 	/* XXX check return status; fail out if appropriate */
325 	if (otus_attachhook(sc) != 0)
326 		goto fail;
327 
328 	return (0);
329 
330 fail:
331 	otus_close_pipes(sc);
332 fail_usb:
333 	mtx_destroy(&sc->sc_mtx);
334 	return (ENXIO);
335 }
336 
337 static int
338 otus_detach(device_t self)
339 {
340 	struct otus_softc *sc = device_get_softc(self);
341 	struct ieee80211com *ic = &sc->sc_ic;
342 
343 	otus_stop(sc);
344 
345 	usbd_transfer_unsetup(sc->sc_xfer, OTUS_N_XFER);
346 
347 	taskqueue_drain_timeout(taskqueue_thread, &sc->scan_to);
348 	taskqueue_drain_timeout(taskqueue_thread, &sc->calib_to);
349 	taskqueue_drain(taskqueue_thread, &sc->tx_task);
350 
351 	otus_close_pipes(sc);
352 #if 0
353 	/* Wait for all queued asynchronous commands to complete. */
354 	usb_rem_wait_task(sc->sc_udev, &sc->sc_task);
355 
356 	usbd_ref_wait(sc->sc_udev);
357 #endif
358 
359 	ieee80211_ifdetach(ic);
360 	mtx_destroy(&sc->sc_mtx);
361 	return 0;
362 }
363 
364 static void
365 otus_delay_ms(struct otus_softc *sc, int ms)
366 {
367 
368 	DELAY(1000 * ms);
369 }
370 
371 static struct ieee80211vap *
372 otus_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
373     enum ieee80211_opmode opmode, int flags,
374     const uint8_t bssid[IEEE80211_ADDR_LEN],
375     const uint8_t mac[IEEE80211_ADDR_LEN])
376 {
377 	struct otus_vap *uvp;
378 	struct ieee80211vap *vap;
379 
380 	if (!TAILQ_EMPTY(&ic->ic_vaps))	 /* only one at a time */
381 		return (NULL);
382 
383 	uvp =  malloc(sizeof(struct otus_vap), M_80211_VAP, M_WAITOK | M_ZERO);
384 	vap = &uvp->vap;
385 
386 	if (ieee80211_vap_setup(ic, vap, name, unit, opmode,
387 	    flags, bssid) != 0) {
388 		/* out of memory */
389 		free(uvp, M_80211_VAP);
390 		return (NULL);
391 	}
392 
393 	/* override state transition machine */
394 	uvp->newstate = vap->iv_newstate;
395 	vap->iv_newstate = otus_newstate;
396 
397 	/* XXX TODO: double-check */
398 	vap->iv_ampdu_density = IEEE80211_HTCAP_MPDUDENSITY_16;
399 	vap->iv_ampdu_rxmax = IEEE80211_HTCAP_MAXRXAMPDU_32K;
400 
401 	ieee80211_ratectl_init(vap);
402 
403 	/* complete setup */
404 	ieee80211_vap_attach(vap, ieee80211_media_change,
405 	    ieee80211_media_status, mac);
406 	ic->ic_opmode = opmode;
407 
408 	return (vap);
409 }
410 
411 static void
412 otus_vap_delete(struct ieee80211vap *vap)
413 {
414 	struct otus_vap *uvp = OTUS_VAP(vap);
415 
416 	ieee80211_ratectl_deinit(vap);
417 	ieee80211_vap_detach(vap);
418 	free(uvp, M_80211_VAP);
419 }
420 
421 static void
422 otus_parent(struct ieee80211com *ic)
423 {
424 	struct otus_softc *sc = ic->ic_softc;
425 	int startall = 0;
426 
427 	if (ic->ic_nrunning > 0) {
428 		if (!sc->sc_running) {
429 			otus_init(sc);
430 			startall = 1;
431 		} else {
432 			(void) otus_set_multi(sc);
433 		}
434 	} else if (sc->sc_running)
435 		otus_stop(sc);
436 
437 	if (startall)
438 		ieee80211_start_all(ic);
439 }
440 
441 static void
442 otus_drain_mbufq(struct otus_softc *sc)
443 {
444 	struct mbuf *m;
445 	struct ieee80211_node *ni;
446 
447 	OTUS_LOCK_ASSERT(sc);
448 	while ((m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
449 		ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
450 		m->m_pkthdr.rcvif = NULL;
451 		ieee80211_free_node(ni);
452 		m_freem(m);
453 	}
454 }
455 
456 static void
457 otus_tx_start(struct otus_softc *sc)
458 {
459 
460 	taskqueue_enqueue(taskqueue_thread, &sc->tx_task);
461 }
462 
463 static int
464 otus_transmit(struct ieee80211com *ic, struct mbuf *m)
465 {
466 	struct otus_softc *sc = ic->ic_softc;
467 	int error;
468 
469 	OTUS_LOCK(sc);
470 	if (! sc->sc_running) {
471 		OTUS_UNLOCK(sc);
472 		return (ENXIO);
473 	}
474 
475 	/* XXX TODO: handle fragments */
476 	error = mbufq_enqueue(&sc->sc_snd, m);
477 	if (error) {
478 		OTUS_DPRINTF(sc, OTUS_DEBUG_XMIT,
479 		    "%s: mbufq_enqueue failed: %d\n",
480 		    __func__,
481 		    error);
482 		OTUS_UNLOCK(sc);
483 		return (error);
484 	}
485 	OTUS_UNLOCK(sc);
486 
487 	/* Kick TX */
488 	otus_tx_start(sc);
489 
490 	return (0);
491 }
492 
493 static void
494 _otus_start(struct otus_softc *sc)
495 {
496 	struct ieee80211_node *ni;
497 	struct otus_data *bf;
498 	struct mbuf *m;
499 
500 	OTUS_LOCK_ASSERT(sc);
501 
502 	while ((m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
503 		bf = otus_getbuf(sc);
504 		if (bf == NULL) {
505 			OTUS_DPRINTF(sc, OTUS_DEBUG_XMIT,
506 			    "%s: failed to get buffer\n", __func__);
507 			mbufq_prepend(&sc->sc_snd, m);
508 			break;
509 		}
510 
511 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
512 		m->m_pkthdr.rcvif = NULL;
513 
514 		if (otus_tx(sc, ni, m, bf, NULL) != 0) {
515 			OTUS_DPRINTF(sc, OTUS_DEBUG_XMIT,
516 			    "%s: failed to transmit\n", __func__);
517 			if_inc_counter(ni->ni_vap->iv_ifp,
518 			    IFCOUNTER_OERRORS, 1);
519 			otus_freebuf(sc, bf);
520 			ieee80211_free_node(ni);
521 			m_freem(m);
522 			break;
523 		}
524 	}
525 }
526 
527 static void
528 otus_tx_task(void *arg, int pending)
529 {
530 	struct otus_softc *sc = arg;
531 
532 	OTUS_LOCK(sc);
533 	_otus_start(sc);
534 	OTUS_UNLOCK(sc);
535 }
536 
537 static int
538 otus_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
539     const struct ieee80211_bpf_params *params)
540 {
541 	struct ieee80211com *ic= ni->ni_ic;
542 	struct otus_softc *sc = ic->ic_softc;
543 	struct otus_data *bf = NULL;
544 	int error = 0;
545 
546 	/* Don't transmit if we're not running */
547 	OTUS_LOCK(sc);
548 	if (! sc->sc_running) {
549 		error = ENETDOWN;
550 		goto error;
551 	}
552 
553 	bf = otus_getbuf(sc);
554 	if (bf == NULL) {
555 		error = ENOBUFS;
556 		goto error;
557 	}
558 
559 	if (otus_tx(sc, ni, m, bf, params) != 0) {
560 		error = EIO;
561 		goto error;
562 	}
563 
564 	OTUS_UNLOCK(sc);
565 	return (0);
566 error:
567 	if (bf)
568 		otus_freebuf(sc, bf);
569 	OTUS_UNLOCK(sc);
570 	m_freem(m);
571 	return (ENXIO);
572 }
573 
574 static void
575 otus_update_chw(struct ieee80211com *ic)
576 {
577 
578 	printf("%s: TODO\n", __func__);
579 }
580 
581 static void
582 otus_set_channel(struct ieee80211com *ic)
583 {
584 	struct otus_softc *sc = ic->ic_softc;
585 	OTUS_DPRINTF(sc, OTUS_DEBUG_RESET, "%s: set channel: %d\n",
586 	    __func__,
587 	    ic->ic_curchan->ic_freq);
588 
589 	OTUS_LOCK(sc);
590 	(void) otus_set_chan(sc, ic->ic_curchan, 0);
591 	OTUS_UNLOCK(sc);
592 }
593 
594 static int
595 otus_ampdu_enable(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap)
596 {
597 
598 	/* For now, no A-MPDU TX support in the driver */
599 	return (0);
600 }
601 
602 static void
603 otus_scan_start(struct ieee80211com *ic)
604 {
605 
606 //	printf("%s: TODO\n", __func__);
607 }
608 
609 static void
610 otus_scan_end(struct ieee80211com *ic)
611 {
612 
613 //	printf("%s: TODO\n", __func__);
614 }
615 
616 static void
617 otus_update_mcast(struct ieee80211com *ic)
618 {
619 	struct otus_softc *sc = ic->ic_softc;
620 
621 	(void) otus_set_multi(sc);
622 }
623 
624 static int
625 otus_attachhook(struct otus_softc *sc)
626 {
627 	struct ieee80211com *ic = &sc->sc_ic;
628 	usb_device_request_t req;
629 	uint32_t in, out;
630 	int error;
631 
632 	/* Not locked */
633 	error = otus_load_firmware(sc, "otusfw_init", AR_FW_INIT_ADDR);
634 	if (error != 0) {
635 		device_printf(sc->sc_dev, "%s: could not load %s firmware\n",
636 		    __func__, "init");
637 		return (ENXIO);
638 	}
639 
640 	/* XXX not locked? */
641 	otus_delay_ms(sc, 1000);
642 
643 	/* Not locked */
644 	error = otus_load_firmware(sc, "otusfw_main", AR_FW_MAIN_ADDR);
645 	if (error != 0) {
646 		device_printf(sc->sc_dev, "%s: could not load %s firmware\n",
647 		    __func__, "main");
648 		return (ENXIO);
649 	}
650 
651 	OTUS_LOCK(sc);
652 
653 	/* Tell device that firmware transfer is complete. */
654 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
655 	req.bRequest = AR_FW_DOWNLOAD_COMPLETE;
656 	USETW(req.wValue, 0);
657 	USETW(req.wIndex, 0);
658 	USETW(req.wLength, 0);
659 	if (usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx, &req, NULL,
660 	    0, NULL, 250) != 0) {
661 		OTUS_UNLOCK(sc);
662 		device_printf(sc->sc_dev,
663 		    "%s: firmware initialization failed\n",
664 		    __func__);
665 		return (ENXIO);
666 	}
667 
668 	/* Send an ECHO command to check that everything is settled. */
669 	in = 0xbadc0ffe;
670 	if (otus_cmd(sc, AR_CMD_ECHO, &in, sizeof in, &out, sizeof(out)) != 0) {
671 		OTUS_UNLOCK(sc);
672 		device_printf(sc->sc_dev,
673 		    "%s: echo command failed\n", __func__);
674 		return (ENXIO);
675 	}
676 	if (in != out) {
677 		OTUS_UNLOCK(sc);
678 		device_printf(sc->sc_dev,
679 		    "%s: echo reply mismatch: 0x%08x!=0x%08x\n",
680 		    __func__, in, out);
681 		return (ENXIO);
682 	}
683 
684 	/* Read entire EEPROM. */
685 	if (otus_read_eeprom(sc) != 0) {
686 		OTUS_UNLOCK(sc);
687 		device_printf(sc->sc_dev,
688 		    "%s: could not read EEPROM\n",
689 		    __func__);
690 		return (ENXIO);
691 	}
692 
693 	OTUS_UNLOCK(sc);
694 
695 	sc->txmask = sc->eeprom.baseEepHeader.txMask;
696 	sc->rxmask = sc->eeprom.baseEepHeader.rxMask;
697 	sc->capflags = sc->eeprom.baseEepHeader.opCapFlags;
698 	IEEE80211_ADDR_COPY(ic->ic_macaddr, sc->eeprom.baseEepHeader.macAddr);
699 	sc->sc_led_newstate = otus_led_newstate_type3;	/* XXX */
700 
701 	device_printf(sc->sc_dev,
702 	    "MAC/BBP AR9170, RF AR%X, MIMO %dT%dR, address %s\n",
703 	    (sc->capflags & AR5416_OPFLAGS_11A) ?
704 		0x9104 : ((sc->txmask == 0x5) ? 0x9102 : 0x9101),
705 	    (sc->txmask == 0x5) ? 2 : 1, (sc->rxmask == 0x5) ? 2 : 1,
706 	    ether_sprintf(ic->ic_macaddr));
707 
708 	ic->ic_softc = sc;
709 	ic->ic_name = device_get_nameunit(sc->sc_dev);
710 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
711 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
712 
713 	/* Set device capabilities. */
714 	ic->ic_caps =
715 	    IEEE80211_C_STA |		/* station mode */
716 #if 0
717 	    IEEE80211_C_BGSCAN |	/* Background scan. */
718 #endif
719 	    IEEE80211_C_SHPREAMBLE |	/* Short preamble supported. */
720 	    IEEE80211_C_WME |		/* WME/QoS */
721 	    IEEE80211_C_SHSLOT |	/* Short slot time supported. */
722 	    IEEE80211_C_FF |		/* Atheros fast-frames supported. */
723 	    IEEE80211_C_MONITOR |
724 	    IEEE80211_C_WPA;		/* WPA/RSN. */
725 
726 	/* XXX TODO: 11n */
727 
728 #if 0
729 	if (sc->eeprom.baseEepHeader.opCapFlags & AR5416_OPFLAGS_11G) {
730 		/* Set supported .11b and .11g rates. */
731 		ic->ic_sup_rates[IEEE80211_MODE_11B] =
732 		    ieee80211_std_rateset_11b;
733 		ic->ic_sup_rates[IEEE80211_MODE_11G] =
734 		    ieee80211_std_rateset_11g;
735 	}
736 	if (sc->eeprom.baseEepHeader.opCapFlags & AR5416_OPFLAGS_11A) {
737 		/* Set supported .11a rates. */
738 		ic->ic_sup_rates[IEEE80211_MODE_11A] =
739 		    ieee80211_std_rateset_11a;
740 	}
741 #endif
742 
743 #if 0
744 	/* Build the list of supported channels. */
745 	otus_get_chanlist(sc);
746 #else
747 	otus_getradiocaps(ic, IEEE80211_CHAN_MAX, &ic->ic_nchans,
748 	    ic->ic_channels);
749 #endif
750 
751 	ieee80211_ifattach(ic);
752 	ic->ic_raw_xmit = otus_raw_xmit;
753 	ic->ic_scan_start = otus_scan_start;
754 	ic->ic_scan_end = otus_scan_end;
755 	ic->ic_set_channel = otus_set_channel;
756 	ic->ic_getradiocaps = otus_getradiocaps;
757 	ic->ic_vap_create = otus_vap_create;
758 	ic->ic_vap_delete = otus_vap_delete;
759 	ic->ic_update_mcast = otus_update_mcast;
760 	ic->ic_update_promisc = otus_update_mcast;
761 	ic->ic_parent = otus_parent;
762 	ic->ic_transmit = otus_transmit;
763 	ic->ic_update_chw = otus_update_chw;
764 	ic->ic_ampdu_enable = otus_ampdu_enable;
765 	ic->ic_wme.wme_update = otus_updateedca;
766 	ic->ic_newassoc = otus_newassoc;
767 	ic->ic_node_alloc = otus_node_alloc;
768 
769 #ifdef notyet
770 	ic->ic_set_key = otus_set_key;
771 	ic->ic_delete_key = otus_delete_key;
772 #endif
773 
774 	ieee80211_radiotap_attach(ic, &sc->sc_txtap.wt_ihdr,
775 	    sizeof(sc->sc_txtap), OTUS_TX_RADIOTAP_PRESENT,
776 	    &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
777 	    OTUS_RX_RADIOTAP_PRESENT);
778 
779 	return (0);
780 }
781 
782 void
783 otus_get_chanlist(struct otus_softc *sc)
784 {
785 	struct ieee80211com *ic = &sc->sc_ic;
786 	uint16_t domain;
787 	uint8_t chan;
788 	int i;
789 
790 	/* XXX regulatory domain. */
791 	domain = le16toh(sc->eeprom.baseEepHeader.regDmn[0]);
792 	OTUS_DPRINTF(sc, OTUS_DEBUG_RESET, "regdomain=0x%04x\n", domain);
793 
794 	if (sc->eeprom.baseEepHeader.opCapFlags & AR5416_OPFLAGS_11G) {
795 		for (i = 0; i < 14; i++) {
796 			chan = ar_chans[i];
797 			ic->ic_channels[chan].ic_freq =
798 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_2GHZ);
799 			ic->ic_channels[chan].ic_flags =
800 			    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
801 			    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
802 		}
803 	}
804 	if (sc->eeprom.baseEepHeader.opCapFlags & AR5416_OPFLAGS_11A) {
805 		for (i = 14; i < nitems(ar_chans); i++) {
806 			chan = ar_chans[i];
807 			ic->ic_channels[chan].ic_freq =
808 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_5GHZ);
809 			ic->ic_channels[chan].ic_flags = IEEE80211_CHAN_A;
810 		}
811 	}
812 }
813 
814 static void
815 otus_getradiocaps(struct ieee80211com *ic,
816     int maxchans, int *nchans, struct ieee80211_channel chans[])
817 {
818 	struct otus_softc *sc = ic->ic_softc;
819 	uint8_t bands[IEEE80211_MODE_BYTES];
820 
821 	/* Set supported .11b and .11g rates. */
822 	memset(bands, 0, sizeof(bands));
823 	if (sc->eeprom.baseEepHeader.opCapFlags & AR5416_OPFLAGS_11G) {
824 		setbit(bands, IEEE80211_MODE_11B);
825 		setbit(bands, IEEE80211_MODE_11G);
826 #if 0
827 		if (sc->sc_ht)
828 			setbit(bands, IEEE80211_MODE_11NG);
829 #endif
830 		ieee80211_add_channel_list_2ghz(chans, maxchans, nchans,
831 		    ar_chans, 14, bands, 0);
832 	}
833 	if (sc->eeprom.baseEepHeader.opCapFlags & AR5416_OPFLAGS_11A) {
834 		setbit(bands, IEEE80211_MODE_11A);
835 		ieee80211_add_channel_list_5ghz(chans, maxchans, nchans,
836                     &ar_chans[14], nitems(ar_chans) - 14, bands, 0);
837 	}
838 }
839 
840 int
841 otus_load_firmware(struct otus_softc *sc, const char *name, uint32_t addr)
842 {
843 	usb_device_request_t req;
844 	char *ptr;
845 	const struct firmware *fw;
846 	int mlen, error, size;
847 
848 	error = 0;
849 
850 	/* Read firmware image from the filesystem. */
851 	if ((fw = firmware_get(name)) == NULL) {
852 		device_printf(sc->sc_dev,
853 		    "%s: failed loadfirmware of file %s\n", __func__, name);
854 		return (ENXIO);
855 	}
856 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
857 	req.bRequest = AR_FW_DOWNLOAD;
858 	USETW(req.wIndex, 0);
859 
860 	OTUS_LOCK(sc);
861 
862 	/* XXX const */
863 	ptr = __DECONST(char *, fw->data);
864 	size = fw->datasize;
865 	addr >>= 8;
866 	while (size > 0) {
867 		mlen = MIN(size, 4096);
868 
869 		USETW(req.wValue, addr);
870 		USETW(req.wLength, mlen);
871 		if (usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx,
872 		    &req, ptr, 0, NULL, 250) != 0) {
873 			error = EIO;
874 			break;
875 		}
876 		addr += mlen >> 8;
877 		ptr  += mlen;
878 		size -= mlen;
879 	}
880 
881 	OTUS_UNLOCK(sc);
882 
883 	firmware_put(fw, FIRMWARE_UNLOAD);
884 	if (error != 0)
885 		device_printf(sc->sc_dev,
886 		    "%s: %s: error=%d\n", __func__, name, error);
887 	return error;
888 }
889 
890 int
891 otus_open_pipes(struct otus_softc *sc)
892 {
893 #if 0
894 	int isize, error;
895 	int i;
896 #endif
897 	int error;
898 
899 	OTUS_UNLOCK_ASSERT(sc);
900 
901 	if ((error = otus_alloc_tx_cmd_list(sc)) != 0) {
902 		device_printf(sc->sc_dev,
903 		    "%s: could not allocate command xfer\n",
904 		    __func__);
905 		goto fail;
906 	}
907 
908 	if ((error = otus_alloc_tx_list(sc)) != 0) {
909 		device_printf(sc->sc_dev, "%s: could not allocate Tx xfers\n",
910 		    __func__);
911 		goto fail;
912 	}
913 
914 	if ((error = otus_alloc_rx_list(sc)) != 0) {
915 		device_printf(sc->sc_dev, "%s: could not allocate Rx xfers\n",
916 		    __func__);
917 		goto fail;
918 	}
919 
920 	/* Enable RX transfers; needed for initial firmware messages */
921 	OTUS_LOCK(sc);
922 	usbd_transfer_start(sc->sc_xfer[OTUS_BULK_RX]);
923 	usbd_transfer_start(sc->sc_xfer[OTUS_BULK_IRQ]);
924 	OTUS_UNLOCK(sc);
925 	return 0;
926 
927 fail:	otus_close_pipes(sc);
928 	return error;
929 }
930 
931 void
932 otus_close_pipes(struct otus_softc *sc)
933 {
934 
935 	OTUS_LOCK(sc);
936 	otus_free_tx_cmd_list(sc);
937 	otus_free_tx_list(sc);
938 	otus_free_rx_list(sc);
939 	OTUS_UNLOCK(sc);
940 
941 	usbd_transfer_unsetup(sc->sc_xfer, OTUS_N_XFER);
942 }
943 
944 static void
945 otus_free_cmd_list(struct otus_softc *sc, struct otus_tx_cmd cmd[], int ndata)
946 {
947 	int i;
948 
949 	/* XXX TODO: someone has to have waken up waiters! */
950 	for (i = 0; i < ndata; i++) {
951 		struct otus_tx_cmd *dp = &cmd[i];
952 
953 		if (dp->buf != NULL) {
954 			free(dp->buf, M_USBDEV);
955 			dp->buf = NULL;
956 		}
957 	}
958 }
959 
960 static int
961 otus_alloc_cmd_list(struct otus_softc *sc, struct otus_tx_cmd cmd[],
962     int ndata, int maxsz)
963 {
964 	int i, error;
965 
966 	for (i = 0; i < ndata; i++) {
967 		struct otus_tx_cmd *dp = &cmd[i];
968 		dp->buf = malloc(maxsz, M_USBDEV, M_NOWAIT | M_ZERO);
969 		dp->odata = NULL;
970 		if (dp->buf == NULL) {
971 			device_printf(sc->sc_dev,
972 			    "could not allocate buffer\n");
973 			error = ENOMEM;
974 			goto fail;
975 		}
976 	}
977 
978 	return (0);
979 fail:
980 	otus_free_cmd_list(sc, cmd, ndata);
981 	return (error);
982 }
983 
984 static int
985 otus_alloc_tx_cmd_list(struct otus_softc *sc)
986 {
987 	int error, i;
988 
989 	error = otus_alloc_cmd_list(sc, sc->sc_cmd, OTUS_CMD_LIST_COUNT,
990 	    OTUS_MAX_TXCMDSZ);
991 	if (error != 0)
992 		return (error);
993 
994 	STAILQ_INIT(&sc->sc_cmd_active);
995 	STAILQ_INIT(&sc->sc_cmd_inactive);
996 	STAILQ_INIT(&sc->sc_cmd_pending);
997 	STAILQ_INIT(&sc->sc_cmd_waiting);
998 
999 	for (i = 0; i < OTUS_CMD_LIST_COUNT; i++)
1000 		STAILQ_INSERT_HEAD(&sc->sc_cmd_inactive, &sc->sc_cmd[i],
1001 		    next_cmd);
1002 
1003 	return (0);
1004 }
1005 
1006 static void
1007 otus_free_tx_cmd_list(struct otus_softc *sc)
1008 {
1009 
1010 	/*
1011 	 * XXX TODO: something needs to wake up any pending/sleeping
1012 	 * waiters!
1013 	 */
1014 	STAILQ_INIT(&sc->sc_cmd_active);
1015 	STAILQ_INIT(&sc->sc_cmd_inactive);
1016 	STAILQ_INIT(&sc->sc_cmd_pending);
1017 	STAILQ_INIT(&sc->sc_cmd_waiting);
1018 
1019 	otus_free_cmd_list(sc, sc->sc_cmd, OTUS_CMD_LIST_COUNT);
1020 }
1021 
1022 static int
1023 otus_alloc_list(struct otus_softc *sc, struct otus_data data[],
1024     int ndata, int maxsz)
1025 {
1026 	int i, error;
1027 
1028 	for (i = 0; i < ndata; i++) {
1029 		struct otus_data *dp = &data[i];
1030 		dp->sc = sc;
1031 		dp->m = NULL;
1032 		dp->buf = malloc(maxsz, M_USBDEV, M_NOWAIT | M_ZERO);
1033 		if (dp->buf == NULL) {
1034 			device_printf(sc->sc_dev,
1035 			    "could not allocate buffer\n");
1036 			error = ENOMEM;
1037 			goto fail;
1038 		}
1039 		dp->ni = NULL;
1040 	}
1041 
1042 	return (0);
1043 fail:
1044 	otus_free_list(sc, data, ndata);
1045 	return (error);
1046 }
1047 
1048 static int
1049 otus_alloc_rx_list(struct otus_softc *sc)
1050 {
1051 	int error, i;
1052 
1053 	error = otus_alloc_list(sc, sc->sc_rx, OTUS_RX_LIST_COUNT,
1054 	    OTUS_RXBUFSZ);
1055 	if (error != 0)
1056 		return (error);
1057 
1058 	STAILQ_INIT(&sc->sc_rx_active);
1059 	STAILQ_INIT(&sc->sc_rx_inactive);
1060 
1061 	for (i = 0; i < OTUS_RX_LIST_COUNT; i++)
1062 		STAILQ_INSERT_HEAD(&sc->sc_rx_inactive, &sc->sc_rx[i], next);
1063 
1064 	return (0);
1065 }
1066 
1067 static int
1068 otus_alloc_tx_list(struct otus_softc *sc)
1069 {
1070 	int error, i;
1071 
1072 	error = otus_alloc_list(sc, sc->sc_tx, OTUS_TX_LIST_COUNT,
1073 	    OTUS_TXBUFSZ);
1074 	if (error != 0)
1075 		return (error);
1076 
1077 	STAILQ_INIT(&sc->sc_tx_inactive);
1078 
1079 	for (i = 0; i != OTUS_N_XFER; i++) {
1080 		STAILQ_INIT(&sc->sc_tx_active[i]);
1081 		STAILQ_INIT(&sc->sc_tx_pending[i]);
1082 	}
1083 
1084 	for (i = 0; i < OTUS_TX_LIST_COUNT; i++) {
1085 		STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, &sc->sc_tx[i], next);
1086 	}
1087 
1088 	return (0);
1089 }
1090 
1091 static void
1092 otus_free_tx_list(struct otus_softc *sc)
1093 {
1094 	int i;
1095 
1096 	/* prevent further allocations from TX list(s) */
1097 	STAILQ_INIT(&sc->sc_tx_inactive);
1098 
1099 	for (i = 0; i != OTUS_N_XFER; i++) {
1100 		STAILQ_INIT(&sc->sc_tx_active[i]);
1101 		STAILQ_INIT(&sc->sc_tx_pending[i]);
1102 	}
1103 
1104 	otus_free_list(sc, sc->sc_tx, OTUS_TX_LIST_COUNT);
1105 }
1106 
1107 static void
1108 otus_free_rx_list(struct otus_softc *sc)
1109 {
1110 	/* prevent further allocations from RX list(s) */
1111 	STAILQ_INIT(&sc->sc_rx_inactive);
1112 	STAILQ_INIT(&sc->sc_rx_active);
1113 
1114 	otus_free_list(sc, sc->sc_rx, OTUS_RX_LIST_COUNT);
1115 }
1116 
1117 static void
1118 otus_free_list(struct otus_softc *sc, struct otus_data data[], int ndata)
1119 {
1120 	int i;
1121 
1122 	for (i = 0; i < ndata; i++) {
1123 		struct otus_data *dp = &data[i];
1124 
1125 		if (dp->buf != NULL) {
1126 			free(dp->buf, M_USBDEV);
1127 			dp->buf = NULL;
1128 		}
1129 		if (dp->ni != NULL) {
1130 			ieee80211_free_node(dp->ni);
1131 			dp->ni = NULL;
1132 		}
1133 	}
1134 }
1135 
1136 static struct otus_data *
1137 _otus_getbuf(struct otus_softc *sc)
1138 {
1139 	struct otus_data *bf;
1140 
1141 	bf = STAILQ_FIRST(&sc->sc_tx_inactive);
1142 	if (bf != NULL)
1143 		STAILQ_REMOVE_HEAD(&sc->sc_tx_inactive, next);
1144 	else
1145 		bf = NULL;
1146 	/* XXX bzero? */
1147 	return (bf);
1148 }
1149 
1150 static struct otus_data *
1151 otus_getbuf(struct otus_softc *sc)
1152 {
1153 	struct otus_data *bf;
1154 
1155 	OTUS_LOCK_ASSERT(sc);
1156 
1157 	bf = _otus_getbuf(sc);
1158 	return (bf);
1159 }
1160 
1161 static void
1162 otus_freebuf(struct otus_softc *sc, struct otus_data *bf)
1163 {
1164 
1165 	OTUS_LOCK_ASSERT(sc);
1166 	STAILQ_INSERT_TAIL(&sc->sc_tx_inactive, bf, next);
1167 }
1168 
1169 static struct otus_tx_cmd *
1170 _otus_get_txcmd(struct otus_softc *sc)
1171 {
1172 	struct otus_tx_cmd *bf;
1173 
1174 	bf = STAILQ_FIRST(&sc->sc_cmd_inactive);
1175 	if (bf != NULL)
1176 		STAILQ_REMOVE_HEAD(&sc->sc_cmd_inactive, next_cmd);
1177 	else
1178 		bf = NULL;
1179 	return (bf);
1180 }
1181 
1182 static struct otus_tx_cmd *
1183 otus_get_txcmd(struct otus_softc *sc)
1184 {
1185 	struct otus_tx_cmd *bf;
1186 
1187 	OTUS_LOCK_ASSERT(sc);
1188 
1189 	bf = _otus_get_txcmd(sc);
1190 	if (bf == NULL) {
1191 		device_printf(sc->sc_dev, "%s: no tx cmd buffers\n",
1192 		    __func__);
1193 	}
1194 	return (bf);
1195 }
1196 
1197 static void
1198 otus_free_txcmd(struct otus_softc *sc, struct otus_tx_cmd *bf)
1199 {
1200 
1201 	OTUS_LOCK_ASSERT(sc);
1202 	STAILQ_INSERT_TAIL(&sc->sc_cmd_inactive, bf, next_cmd);
1203 }
1204 
1205 void
1206 otus_next_scan(void *arg, int pending)
1207 {
1208 #if 0
1209 	struct otus_softc *sc = arg;
1210 
1211 	if (usbd_is_dying(sc->sc_udev))
1212 		return;
1213 
1214 	usbd_ref_incr(sc->sc_udev);
1215 
1216 	if (sc->sc_ic.ic_state == IEEE80211_S_SCAN)
1217 		ieee80211_next_scan(&sc->sc_ic.ic_if);
1218 
1219 	usbd_ref_decr(sc->sc_udev);
1220 #endif
1221 }
1222 
1223 int
1224 otus_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
1225 {
1226 	struct otus_vap *uvp = OTUS_VAP(vap);
1227 	struct ieee80211com *ic = vap->iv_ic;
1228 	struct otus_softc *sc = ic->ic_softc;
1229 	enum ieee80211_state ostate;
1230 
1231 	ostate = vap->iv_state;
1232 	OTUS_DPRINTF(sc, OTUS_DEBUG_STATE, "%s: %s -> %s\n", __func__,
1233 	    ieee80211_state_name[ostate],
1234 	    ieee80211_state_name[nstate]);
1235 
1236 	IEEE80211_UNLOCK(ic);
1237 
1238 	OTUS_LOCK(sc);
1239 
1240 	/* XXX TODO: more fleshing out! */
1241 
1242 	switch (nstate) {
1243 	case IEEE80211_S_INIT:
1244 		otus_set_operating_mode(sc);
1245 		otus_set_rx_filter(sc);
1246 		break;
1247 	case IEEE80211_S_RUN:
1248 		if (ic->ic_opmode == IEEE80211_M_STA) {
1249 			otus_updateslot(sc);
1250 			otus_set_operating_mode(sc);
1251 			otus_set_rx_filter(sc);
1252 
1253 			/* Start calibration timer. */
1254 			taskqueue_enqueue_timeout(taskqueue_thread,
1255 			    &sc->calib_to, hz);
1256 		}
1257 		break;
1258 	default:
1259 		break;
1260 	}
1261 
1262 	/* XXX TODO: calibration? */
1263 
1264 	sc->sc_led_newstate(sc);
1265 
1266 	OTUS_UNLOCK(sc);
1267 	IEEE80211_LOCK(ic);
1268 	return (uvp->newstate(vap, nstate, arg));
1269 }
1270 
1271 int
1272 otus_cmd(struct otus_softc *sc, uint8_t code, const void *idata, int ilen,
1273     void *odata, int odatalen)
1274 {
1275 	struct otus_tx_cmd *cmd;
1276 	struct ar_cmd_hdr *hdr;
1277 	int xferlen, error;
1278 
1279 	OTUS_LOCK_ASSERT(sc);
1280 
1281 	/* Always bulk-out a multiple of 4 bytes. */
1282 	xferlen = (sizeof (*hdr) + ilen + 3) & ~3;
1283 	if (xferlen > OTUS_MAX_TXCMDSZ) {
1284 		device_printf(sc->sc_dev, "%s: command (0x%02x) size (%d) > %d\n",
1285 		    __func__,
1286 		    code,
1287 		    xferlen,
1288 		    OTUS_MAX_TXCMDSZ);
1289 		return (EIO);
1290 	}
1291 
1292 	cmd = otus_get_txcmd(sc);
1293 	if (cmd == NULL) {
1294 		device_printf(sc->sc_dev, "%s: failed to get buf\n",
1295 		    __func__);
1296 		return (EIO);
1297 	}
1298 
1299 	hdr = (struct ar_cmd_hdr *)cmd->buf;
1300 	hdr->code  = code;
1301 	hdr->len   = ilen;
1302 	hdr->token = ++sc->token;	/* Don't care about endianness. */
1303 	cmd->token = hdr->token;
1304 	/* XXX TODO: check max cmd length? */
1305 	memcpy((uint8_t *)&hdr[1], idata, ilen);
1306 
1307 	OTUS_DPRINTF(sc, OTUS_DEBUG_CMD,
1308 	    "%s: sending command code=0x%02x len=%d token=%d\n",
1309 	    __func__, code, ilen, hdr->token);
1310 
1311 	cmd->odata = odata;
1312 	cmd->odatalen = odatalen;
1313 	cmd->buflen = xferlen;
1314 
1315 	/* Queue the command to the endpoint */
1316 	STAILQ_INSERT_TAIL(&sc->sc_cmd_pending, cmd, next_cmd);
1317 	usbd_transfer_start(sc->sc_xfer[OTUS_BULK_CMD]);
1318 
1319 	/* Sleep on the command; wait for it to complete */
1320 	error = msleep(cmd, &sc->sc_mtx, PCATCH, "otuscmd", hz);
1321 
1322 	/*
1323 	 * At this point we don't own cmd any longer; it'll be
1324 	 * freed by the cmd bulk path or the RX notification
1325 	 * path.  If the data is made available then it'll be copied
1326 	 * to the caller.  All that is left to do is communicate
1327 	 * status back to the caller.
1328 	 */
1329 	if (error != 0) {
1330 		device_printf(sc->sc_dev,
1331 		    "%s: timeout waiting for command 0x%02x reply\n",
1332 		    __func__, code);
1333 	}
1334 	return error;
1335 }
1336 
1337 void
1338 otus_write(struct otus_softc *sc, uint32_t reg, uint32_t val)
1339 {
1340 
1341 	OTUS_LOCK_ASSERT(sc);
1342 
1343 	sc->write_buf[sc->write_idx].reg = htole32(reg);
1344 	sc->write_buf[sc->write_idx].val = htole32(val);
1345 
1346 	if (++sc->write_idx > (AR_MAX_WRITE_IDX-1))
1347 		(void)otus_write_barrier(sc);
1348 }
1349 
1350 int
1351 otus_write_barrier(struct otus_softc *sc)
1352 {
1353 	int error;
1354 
1355 	OTUS_LOCK_ASSERT(sc);
1356 
1357 	if (sc->write_idx == 0)
1358 		return 0;	/* Nothing to flush. */
1359 
1360 	OTUS_DPRINTF(sc, OTUS_DEBUG_REGIO, "%s: called; %d updates\n",
1361 	    __func__,
1362 	    sc->write_idx);
1363 
1364 	error = otus_cmd(sc, AR_CMD_WREG, sc->write_buf,
1365 	    sizeof (sc->write_buf[0]) * sc->write_idx, NULL, 0);
1366 	sc->write_idx = 0;
1367 	return error;
1368 }
1369 
1370 static struct ieee80211_node *
1371 otus_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
1372 {
1373 
1374 	return malloc(sizeof (struct otus_node), M_80211_NODE,
1375 	    M_NOWAIT | M_ZERO);
1376 }
1377 
1378 #if 0
1379 int
1380 otus_media_change(struct ifnet *ifp)
1381 {
1382 	struct otus_softc *sc = ifp->if_softc;
1383 	struct ieee80211com *ic = &sc->sc_ic;
1384 	uint8_t rate, ridx;
1385 	int error;
1386 
1387 	error = ieee80211_media_change(ifp);
1388 	if (error != ENETRESET)
1389 		return error;
1390 
1391 	if (ic->ic_fixed_rate != -1) {
1392 		rate = ic->ic_sup_rates[ic->ic_curmode].
1393 		    rs_rates[ic->ic_fixed_rate] & IEEE80211_RATE_VAL;
1394 		for (ridx = 0; ridx <= OTUS_RIDX_MAX; ridx++)
1395 			if (otus_rates[ridx].rate == rate)
1396 				break;
1397 		sc->fixed_ridx = ridx;
1398 	}
1399 
1400 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
1401 		error = otus_init(sc);
1402 
1403 	return error;
1404 }
1405 #endif
1406 
1407 int
1408 otus_read_eeprom(struct otus_softc *sc)
1409 {
1410 	uint32_t regs[8], reg;
1411 	uint8_t *eep;
1412 	int i, j, error;
1413 
1414 	OTUS_LOCK_ASSERT(sc);
1415 
1416 	/* Read EEPROM by blocks of 32 bytes. */
1417 	eep = (uint8_t *)&sc->eeprom;
1418 	reg = AR_EEPROM_OFFSET;
1419 	for (i = 0; i < sizeof (sc->eeprom) / 32; i++) {
1420 		for (j = 0; j < 8; j++, reg += 4)
1421 			regs[j] = htole32(reg);
1422 		error = otus_cmd(sc, AR_CMD_RREG, regs, sizeof regs, eep, 32);
1423 		if (error != 0)
1424 			break;
1425 		eep += 32;
1426 	}
1427 	return error;
1428 }
1429 
1430 void
1431 otus_newassoc(struct ieee80211_node *ni, int isnew)
1432 {
1433 	struct ieee80211com *ic = ni->ni_ic;
1434 	struct otus_softc *sc = ic->ic_softc;
1435 	struct otus_node *on = OTUS_NODE(ni);
1436 
1437 	OTUS_DPRINTF(sc, OTUS_DEBUG_STATE, "new assoc isnew=%d addr=%s\n",
1438 	    isnew, ether_sprintf(ni->ni_macaddr));
1439 
1440 	on->tx_done = 0;
1441 	on->tx_err = 0;
1442 	on->tx_retries = 0;
1443 }
1444 
1445 static void
1446 otus_cmd_handle_response(struct otus_softc *sc, struct ar_cmd_hdr *hdr)
1447 {
1448 	struct otus_tx_cmd *cmd;
1449 
1450 	OTUS_LOCK_ASSERT(sc);
1451 
1452 	OTUS_DPRINTF(sc, OTUS_DEBUG_CMDDONE,
1453 	    "%s: received reply code=0x%02x len=%d token=%d\n",
1454 	    __func__,
1455 	    hdr->code, hdr->len, hdr->token);
1456 
1457 	/*
1458 	 * Walk the list, freeing items that aren't ours,
1459 	 * stopping when we hit our token.
1460 	 */
1461 	while ((cmd = STAILQ_FIRST(&sc->sc_cmd_waiting)) != NULL) {
1462 		STAILQ_REMOVE_HEAD(&sc->sc_cmd_waiting, next_cmd);
1463 		OTUS_DPRINTF(sc, OTUS_DEBUG_CMDDONE,
1464 		    "%s: cmd=%p; hdr.token=%d, cmd.token=%d\n",
1465 		    __func__,
1466 		    cmd,
1467 		    (int) hdr->token,
1468 		    (int) cmd->token);
1469 		if (hdr->token == cmd->token) {
1470 			/* Copy answer into caller's supplied buffer. */
1471 			if (cmd->odata != NULL) {
1472 				if (hdr->len != cmd->odatalen) {
1473 					device_printf(sc->sc_dev,
1474 					    "%s: code 0x%02x, len=%d, olen=%d\n",
1475 					    __func__,
1476 					    (int) hdr->code,
1477 					    (int) hdr->len,
1478 					    (int) cmd->odatalen);
1479 				}
1480 				memcpy(cmd->odata, &hdr[1],
1481 				    MIN(cmd->odatalen, hdr->len));
1482 			}
1483 			wakeup(cmd);
1484 		}
1485 
1486 		STAILQ_INSERT_TAIL(&sc->sc_cmd_inactive, cmd, next_cmd);
1487 	}
1488 }
1489 
1490 void
1491 otus_cmd_rxeof(struct otus_softc *sc, uint8_t *buf, int len)
1492 {
1493 	struct ieee80211com *ic = &sc->sc_ic;
1494 	struct ar_cmd_hdr *hdr;
1495 
1496 	OTUS_LOCK_ASSERT(sc);
1497 
1498 	if (__predict_false(len < sizeof (*hdr))) {
1499 		OTUS_DPRINTF(sc, OTUS_DEBUG_CMDDONE,
1500 		    "cmd too small %d\n", len);
1501 		return;
1502 	}
1503 	hdr = (struct ar_cmd_hdr *)buf;
1504 	if (__predict_false(sizeof (*hdr) + hdr->len > len ||
1505 	    sizeof (*hdr) + hdr->len > 64)) {
1506 		OTUS_DPRINTF(sc, OTUS_DEBUG_CMDDONE,
1507 		    "cmd too large %d\n", hdr->len);
1508 		return;
1509 	}
1510 
1511 	OTUS_DPRINTF(sc, OTUS_DEBUG_RXDONE,
1512 	    "%s: code=%.02x\n",
1513 	    __func__,
1514 	    hdr->code);
1515 
1516 	/*
1517 	 * This has to reach into the cmd queue "waiting for
1518 	 * an RX response" list, grab the head entry and check
1519 	 * if we need to wake anyone up.
1520 	 */
1521 	if ((hdr->code & 0xc0) != 0xc0) {
1522 		otus_cmd_handle_response(sc, hdr);
1523 		return;
1524 	}
1525 
1526 	/* Received unsolicited notification. */
1527 	switch (hdr->code & 0x3f) {
1528 	case AR_EVT_BEACON:
1529 		break;
1530 	case AR_EVT_TX_COMP:
1531 	{
1532 		struct ar_evt_tx_comp *tx = (struct ar_evt_tx_comp *)&hdr[1];
1533 		struct ieee80211_node *ni;
1534 
1535 		ni = ieee80211_find_node(&ic->ic_sta, tx->macaddr);
1536 		if (ni == NULL) {
1537 			device_printf(sc->sc_dev,
1538 			    "%s: txcomp on unknown node (%s)\n",
1539 			    __func__,
1540 			    ether_sprintf(tx->macaddr));
1541 			break;
1542 		}
1543 
1544 		OTUS_DPRINTF(sc, OTUS_DEBUG_TXCOMP,
1545 		    "tx completed %s status=%d phy=0x%x\n",
1546 		    ether_sprintf(tx->macaddr), le16toh(tx->status),
1547 		    le32toh(tx->phy));
1548 
1549 		switch (le16toh(tx->status)) {
1550 		case AR_TX_STATUS_COMP:
1551 #if 0
1552 			ackfailcnt = 0;
1553 			ieee80211_ratectl_tx_complete(ni->ni_vap, ni,
1554 			    IEEE80211_RATECTL_TX_SUCCESS, &ackfailcnt, NULL);
1555 #endif
1556 			/*
1557 			 * We don't get the above; only error notifications.
1558 			 * Sigh.  So, don't worry about this.
1559 			 */
1560 			break;
1561 		case AR_TX_STATUS_RETRY_COMP:
1562 			OTUS_NODE(ni)->tx_retries++;
1563 			break;
1564 		case AR_TX_STATUS_FAILED:
1565 			OTUS_NODE(ni)->tx_err++;
1566 			break;
1567 		}
1568 		ieee80211_free_node(ni);
1569 		break;
1570 	}
1571 	case AR_EVT_TBTT:
1572 		break;
1573 	case AR_EVT_DO_BB_RESET:
1574 		/*
1575 		 * This is "tell driver to reset baseband" from ar9170-fw.
1576 		 *
1577 		 * I'm not sure what we should do here, so I'm going to
1578 		 * fall through; it gets generated when RTSRetryCnt internally
1579 		 * reaches '5' - I guess the firmware authors thought that
1580 		 * meant that the BB may have gone deaf or something.
1581 		 */
1582 	default:
1583 		device_printf(sc->sc_dev,
1584 		    "%s: received notification code=0x%02x len=%d\n",
1585 		    __func__,
1586 		    hdr->code, hdr->len);
1587 	}
1588 }
1589 
1590 void
1591 otus_sub_rxeof(struct otus_softc *sc, uint8_t *buf, int len, struct mbufq *rxq)
1592 {
1593 	struct ieee80211com *ic = &sc->sc_ic;
1594 	struct ieee80211_rx_stats rxs;
1595 #if 0
1596 	struct ieee80211_node *ni;
1597 #endif
1598 	struct ar_rx_tail *tail;
1599 	struct ieee80211_frame *wh;
1600 	struct mbuf *m;
1601 	uint8_t *plcp;
1602 //	int s;
1603 	int mlen;
1604 
1605 	if (__predict_false(len < AR_PLCP_HDR_LEN)) {
1606 		OTUS_DPRINTF(sc, OTUS_DEBUG_RXDONE,
1607 		    "sub-xfer too short %d\n", len);
1608 		return;
1609 	}
1610 	plcp = buf;
1611 
1612 	/* All bits in the PLCP header are set to 1 for non-MPDU. */
1613 	if (memcmp(plcp, AR_PLCP_HDR_INTR, AR_PLCP_HDR_LEN) == 0) {
1614 		otus_cmd_rxeof(sc, plcp + AR_PLCP_HDR_LEN,
1615 		    len - AR_PLCP_HDR_LEN);
1616 		return;
1617 	}
1618 
1619 	/* Received MPDU. */
1620 	if (__predict_false(len < AR_PLCP_HDR_LEN + sizeof (*tail))) {
1621 		OTUS_DPRINTF(sc, OTUS_DEBUG_RXDONE, "MPDU too short %d\n", len);
1622 		counter_u64_add(ic->ic_ierrors, 1);
1623 		return;
1624 	}
1625 	tail = (struct ar_rx_tail *)(plcp + len - sizeof (*tail));
1626 
1627 	/* Discard error frames; don't discard BAD_RA (eg monitor mode); let net80211 do that */
1628 	if (__predict_false((tail->error & ~AR_RX_ERROR_BAD_RA) != 0)) {
1629 		OTUS_DPRINTF(sc, OTUS_DEBUG_RXDONE, "error frame 0x%02x\n", tail->error);
1630 		if (tail->error & AR_RX_ERROR_FCS) {
1631 			OTUS_DPRINTF(sc, OTUS_DEBUG_RXDONE, "bad FCS\n");
1632 		} else if (tail->error & AR_RX_ERROR_MMIC) {
1633 			/* Report Michael MIC failures to net80211. */
1634 #if 0
1635 			ieee80211_notify_michael_failure(ni->ni_vap, wh, keyidx);
1636 #endif
1637 			device_printf(sc->sc_dev, "%s: MIC failure\n", __func__);
1638 		}
1639 		counter_u64_add(ic->ic_ierrors, 1);
1640 		return;
1641 	}
1642 	/* Compute MPDU's length. */
1643 	mlen = len - AR_PLCP_HDR_LEN - sizeof (*tail);
1644 	/* Make sure there's room for an 802.11 header + FCS. */
1645 	if (__predict_false(mlen < IEEE80211_MIN_LEN)) {
1646 		counter_u64_add(ic->ic_ierrors, 1);
1647 		return;
1648 	}
1649 	mlen -= IEEE80211_CRC_LEN;	/* strip 802.11 FCS */
1650 
1651 	wh = (struct ieee80211_frame *)(plcp + AR_PLCP_HDR_LEN);
1652 
1653 	/*
1654 	 * TODO: I see > 2KiB buffers in this path; is it A-MSDU or something?
1655 	 */
1656 	m = m_get2(mlen, M_NOWAIT, MT_DATA, M_PKTHDR);
1657 	if (m == NULL) {
1658 		device_printf(sc->sc_dev, "%s: failed m_get2() (mlen=%d)\n", __func__, mlen);
1659 		counter_u64_add(ic->ic_ierrors, 1);
1660 		return;
1661 	}
1662 
1663 	/* Finalize mbuf. */
1664 	memcpy(mtod(m, uint8_t *), wh, mlen);
1665 	m->m_pkthdr.len = m->m_len = mlen;
1666 
1667 #if 0
1668 	if (__predict_false(sc->sc_drvbpf != NULL)) {
1669 		struct otus_rx_radiotap_header *tap = &sc->sc_rxtap;
1670 		struct mbuf mb;
1671 
1672 		tap->wr_flags = 0;
1673 		tap->wr_chan_freq = htole16(ic->ic_ibss_chan->ic_freq);
1674 		tap->wr_chan_flags = htole16(ic->ic_ibss_chan->ic_flags);
1675 		tap->wr_antsignal = tail->rssi;
1676 		tap->wr_rate = 2;	/* In case it can't be found below. */
1677 		switch (tail->status & AR_RX_STATUS_MT_MASK) {
1678 		case AR_RX_STATUS_MT_CCK:
1679 			switch (plcp[0]) {
1680 			case  10: tap->wr_rate =   2; break;
1681 			case  20: tap->wr_rate =   4; break;
1682 			case  55: tap->wr_rate =  11; break;
1683 			case 110: tap->wr_rate =  22; break;
1684 			}
1685 			if (tail->status & AR_RX_STATUS_SHPREAMBLE)
1686 				tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
1687 			break;
1688 		case AR_RX_STATUS_MT_OFDM:
1689 			switch (plcp[0] & 0xf) {
1690 			case 0xb: tap->wr_rate =  12; break;
1691 			case 0xf: tap->wr_rate =  18; break;
1692 			case 0xa: tap->wr_rate =  24; break;
1693 			case 0xe: tap->wr_rate =  36; break;
1694 			case 0x9: tap->wr_rate =  48; break;
1695 			case 0xd: tap->wr_rate =  72; break;
1696 			case 0x8: tap->wr_rate =  96; break;
1697 			case 0xc: tap->wr_rate = 108; break;
1698 			}
1699 			break;
1700 		}
1701 		mb.m_data = (caddr_t)tap;
1702 		mb.m_next = m;
1703 		mb.m_nextpkt = NULL;
1704 		mb.m_type = 0;
1705 		mb.m_flags = 0;
1706 		bpf_mtap(sc->sc_drvbpf, &mb, BPF_DIRECTION_IN);
1707 	}
1708 #endif
1709 
1710 	/* Add RSSI/NF to this mbuf */
1711 	bzero(&rxs, sizeof(rxs));
1712 	rxs.r_flags = IEEE80211_R_NF | IEEE80211_R_RSSI;
1713 	rxs.c_nf = sc->sc_nf[0];	/* XXX chain 0 != combined rssi/nf */
1714 	rxs.c_rssi = tail->rssi;
1715 	/* XXX TODO: add MIMO RSSI/NF as well */
1716 	if (ieee80211_add_rx_params(m, &rxs) == 0) {
1717 		counter_u64_add(ic->ic_ierrors, 1);
1718 		return;
1719 	}
1720 
1721 	/* XXX make a method */
1722 	STAILQ_INSERT_TAIL(&rxq->mq_head, m, m_stailqpkt);
1723 
1724 #if 0
1725 	OTUS_UNLOCK(sc);
1726 	ni = ieee80211_find_rxnode(ic, wh);
1727 	rxi.rxi_flags = 0;
1728 	rxi.rxi_rssi = tail->rssi;
1729 	rxi.rxi_tstamp = 0;	/* unused */
1730 	ieee80211_input(ifp, m, ni, &rxi);
1731 
1732 	/* Node is no longer needed. */
1733 	ieee80211_release_node(ic, ni);
1734 	OTUS_LOCK(sc);
1735 #endif
1736 }
1737 
1738 static void
1739 otus_rxeof(struct usb_xfer *xfer, struct otus_data *data, struct mbufq *rxq)
1740 {
1741 	struct otus_softc *sc = usbd_xfer_softc(xfer);
1742 	caddr_t buf = data->buf;
1743 	struct ar_rx_head *head;
1744 	uint16_t hlen;
1745 	int len;
1746 
1747 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
1748 
1749 	while (len >= sizeof (*head)) {
1750 		head = (struct ar_rx_head *)buf;
1751 		if (__predict_false(head->tag != htole16(AR_RX_HEAD_TAG))) {
1752 			OTUS_DPRINTF(sc, OTUS_DEBUG_RXDONE,
1753 			    "tag not valid 0x%x\n", le16toh(head->tag));
1754 			break;
1755 		}
1756 		hlen = le16toh(head->len);
1757 		if (__predict_false(sizeof (*head) + hlen > len)) {
1758 			OTUS_DPRINTF(sc, OTUS_DEBUG_RXDONE,
1759 			    "xfer too short %d/%d\n", len, hlen);
1760 			break;
1761 		}
1762 		/* Process sub-xfer. */
1763 		otus_sub_rxeof(sc, (uint8_t *)&head[1], hlen, rxq);
1764 
1765 		/* Next sub-xfer is aligned on a 32-bit boundary. */
1766 		hlen = (sizeof (*head) + hlen + 3) & ~3;
1767 		buf += hlen;
1768 		len -= hlen;
1769 	}
1770 }
1771 
1772 static void
1773 otus_bulk_rx_callback(struct usb_xfer *xfer, usb_error_t error)
1774 {
1775 	struct otus_softc *sc = usbd_xfer_softc(xfer);
1776 	struct ieee80211com *ic = &sc->sc_ic;
1777 	struct ieee80211_frame *wh;
1778 	struct ieee80211_node *ni;
1779 	struct mbuf *m;
1780 	struct mbufq scrx;
1781 	struct otus_data *data;
1782 
1783 	OTUS_LOCK_ASSERT(sc);
1784 
1785 	mbufq_init(&scrx, 1024);
1786 
1787 #if 0
1788 	device_printf(sc->sc_dev, "%s: called; state=%d; error=%d\n",
1789 	    __func__,
1790 	    USB_GET_STATE(xfer),
1791 	    error);
1792 #endif
1793 
1794 	switch (USB_GET_STATE(xfer)) {
1795 	case USB_ST_TRANSFERRED:
1796 		data = STAILQ_FIRST(&sc->sc_rx_active);
1797 		if (data == NULL)
1798 			goto tr_setup;
1799 		STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
1800 		otus_rxeof(xfer, data, &scrx);
1801 		STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
1802 		/* FALLTHROUGH */
1803 	case USB_ST_SETUP:
1804 tr_setup:
1805 		/*
1806 		 * XXX TODO: what if sc_rx isn't empty, but data
1807 		 * is empty?  Then we leak mbufs.
1808 		 */
1809 		data = STAILQ_FIRST(&sc->sc_rx_inactive);
1810 		if (data == NULL) {
1811 			//KASSERT(m == NULL, ("mbuf isn't NULL"));
1812 			return;
1813 		}
1814 		STAILQ_REMOVE_HEAD(&sc->sc_rx_inactive, next);
1815 		STAILQ_INSERT_TAIL(&sc->sc_rx_active, data, next);
1816 		usbd_xfer_set_frame_data(xfer, 0, data->buf,
1817 		    usbd_xfer_max_len(xfer));
1818 		usbd_transfer_submit(xfer);
1819 		/*
1820 		 * To avoid LOR we should unlock our private mutex here to call
1821 		 * ieee80211_input() because here is at the end of a USB
1822 		 * callback and safe to unlock.
1823 		 */
1824 		OTUS_UNLOCK(sc);
1825 		while ((m = mbufq_dequeue(&scrx)) != NULL) {
1826 			wh = mtod(m, struct ieee80211_frame *);
1827 			ni = ieee80211_find_rxnode(ic,
1828 			    (struct ieee80211_frame_min *)wh);
1829 			if (ni != NULL) {
1830 				if (ni->ni_flags & IEEE80211_NODE_HT)
1831 					m->m_flags |= M_AMPDU;
1832 				(void)ieee80211_input_mimo(ni, m);
1833 				ieee80211_free_node(ni);
1834 			} else
1835 				(void)ieee80211_input_mimo_all(ic, m);
1836 		}
1837 #ifdef	IEEE80211_SUPPORT_SUPERG
1838 		ieee80211_ff_age_all(ic, 100);
1839 #endif
1840 		OTUS_LOCK(sc);
1841 		break;
1842 	default:
1843 		/* needs it to the inactive queue due to a error. */
1844 		data = STAILQ_FIRST(&sc->sc_rx_active);
1845 		if (data != NULL) {
1846 			STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
1847 			STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
1848 		}
1849 		if (error != USB_ERR_CANCELLED) {
1850 			usbd_xfer_set_stall(xfer);
1851 			counter_u64_add(ic->ic_ierrors, 1);
1852 			goto tr_setup;
1853 		}
1854 		break;
1855 	}
1856 }
1857 
1858 static void
1859 otus_txeof(struct usb_xfer *xfer, struct otus_data *data)
1860 {
1861 	struct otus_softc *sc = usbd_xfer_softc(xfer);
1862 
1863 	OTUS_DPRINTF(sc, OTUS_DEBUG_TXDONE,
1864 	    "%s: called; data=%p\n", __func__, data);
1865 
1866 	OTUS_LOCK_ASSERT(sc);
1867 
1868 	if (sc->sc_tx_n_active == 0) {
1869 		device_printf(sc->sc_dev,
1870 		    "%s: completed but tx_active=0\n",
1871 		    __func__);
1872 	} else {
1873 		sc->sc_tx_n_active--;
1874 	}
1875 
1876 	if (data->m) {
1877 		/* XXX status? */
1878 		/* XXX we get TX status via the RX path.. */
1879 		ieee80211_tx_complete(data->ni, data->m, 0);
1880 		data->m = NULL;
1881 		data->ni = NULL;
1882 	}
1883 }
1884 
1885 static void
1886 otus_txcmdeof(struct usb_xfer *xfer, struct otus_tx_cmd *cmd)
1887 {
1888 	struct otus_softc *sc = usbd_xfer_softc(xfer);
1889 
1890 	OTUS_LOCK_ASSERT(sc);
1891 
1892 	OTUS_DPRINTF(sc, OTUS_DEBUG_CMDDONE,
1893 	    "%s: called; data=%p; odata=%p\n",
1894 	    __func__, cmd, cmd->odata);
1895 
1896 	/*
1897 	 * Non-response commands still need wakeup so the caller
1898 	 * knows it was submitted and completed OK; response commands should
1899 	 * wait until they're ACKed by the firmware with a response.
1900 	 */
1901 	if (cmd->odata) {
1902 		STAILQ_INSERT_TAIL(&sc->sc_cmd_waiting, cmd, next_cmd);
1903 	} else {
1904 		wakeup(cmd);
1905 		otus_free_txcmd(sc, cmd);
1906 	}
1907 }
1908 
1909 static void
1910 otus_bulk_tx_callback(struct usb_xfer *xfer, usb_error_t error)
1911 {
1912 	uint8_t which = OTUS_BULK_TX;
1913 	struct otus_softc *sc = usbd_xfer_softc(xfer);
1914 	struct ieee80211com *ic = &sc->sc_ic;
1915 	struct otus_data *data;
1916 
1917 	OTUS_LOCK_ASSERT(sc);
1918 
1919 	switch (USB_GET_STATE(xfer)) {
1920 	case USB_ST_TRANSFERRED:
1921 		data = STAILQ_FIRST(&sc->sc_tx_active[which]);
1922 		if (data == NULL)
1923 			goto tr_setup;
1924 		OTUS_DPRINTF(sc, OTUS_DEBUG_TXDONE,
1925 		    "%s: transfer done %p\n", __func__, data);
1926 		STAILQ_REMOVE_HEAD(&sc->sc_tx_active[which], next);
1927 		otus_txeof(xfer, data);
1928 		otus_freebuf(sc, data);
1929 		/* FALLTHROUGH */
1930 	case USB_ST_SETUP:
1931 tr_setup:
1932 		data = STAILQ_FIRST(&sc->sc_tx_pending[which]);
1933 		if (data == NULL) {
1934 			OTUS_DPRINTF(sc, OTUS_DEBUG_XMIT,
1935 			    "%s: empty pending queue sc %p\n", __func__, sc);
1936 			sc->sc_tx_n_active = 0;
1937 			goto finish;
1938 		}
1939 		STAILQ_REMOVE_HEAD(&sc->sc_tx_pending[which], next);
1940 		STAILQ_INSERT_TAIL(&sc->sc_tx_active[which], data, next);
1941 		usbd_xfer_set_frame_data(xfer, 0, data->buf, data->buflen);
1942 		OTUS_DPRINTF(sc, OTUS_DEBUG_XMIT,
1943 		    "%s: submitting transfer %p\n", __func__, data);
1944 		usbd_transfer_submit(xfer);
1945 		sc->sc_tx_n_active++;
1946 		break;
1947 	default:
1948 		data = STAILQ_FIRST(&sc->sc_tx_active[which]);
1949 		if (data != NULL) {
1950 			STAILQ_REMOVE_HEAD(&sc->sc_tx_active[which], next);
1951 			otus_txeof(xfer, data);
1952 			otus_freebuf(sc, data);
1953 		}
1954 		counter_u64_add(ic->ic_oerrors, 1);
1955 
1956 		if (error != USB_ERR_CANCELLED) {
1957 			usbd_xfer_set_stall(xfer);
1958 			goto tr_setup;
1959 		}
1960 		break;
1961 	}
1962 
1963 finish:
1964 #ifdef	IEEE80211_SUPPORT_SUPERG
1965 	/*
1966 	 * If the TX active queue drops below a certain
1967 	 * threshold, ensure we age fast-frames out so they're
1968 	 * transmitted.
1969 	 */
1970 	if (sc->sc_tx_n_active < 2) {
1971 		/* XXX ew - net80211 should defer this for us! */
1972 		OTUS_UNLOCK(sc);
1973 		ieee80211_ff_flush(ic, WME_AC_VO);
1974 		ieee80211_ff_flush(ic, WME_AC_VI);
1975 		ieee80211_ff_flush(ic, WME_AC_BE);
1976 		ieee80211_ff_flush(ic, WME_AC_BK);
1977 		OTUS_LOCK(sc);
1978 	}
1979 #endif
1980 	/* Kick TX */
1981 	otus_tx_start(sc);
1982 }
1983 
1984 static void
1985 otus_bulk_cmd_callback(struct usb_xfer *xfer, usb_error_t error)
1986 {
1987 	struct otus_softc *sc = usbd_xfer_softc(xfer);
1988 #if 0
1989 	struct ieee80211com *ic = &sc->sc_ic;
1990 #endif
1991 	struct otus_tx_cmd *cmd;
1992 
1993 	OTUS_LOCK_ASSERT(sc);
1994 
1995 	switch (USB_GET_STATE(xfer)) {
1996 	case USB_ST_TRANSFERRED:
1997 		cmd = STAILQ_FIRST(&sc->sc_cmd_active);
1998 		if (cmd == NULL)
1999 			goto tr_setup;
2000 		OTUS_DPRINTF(sc, OTUS_DEBUG_CMDDONE,
2001 		    "%s: transfer done %p\n", __func__, cmd);
2002 		STAILQ_REMOVE_HEAD(&sc->sc_cmd_active, next_cmd);
2003 		otus_txcmdeof(xfer, cmd);
2004 		/* FALLTHROUGH */
2005 	case USB_ST_SETUP:
2006 tr_setup:
2007 		cmd = STAILQ_FIRST(&sc->sc_cmd_pending);
2008 		if (cmd == NULL) {
2009 			OTUS_DPRINTF(sc, OTUS_DEBUG_CMD,
2010 			    "%s: empty pending queue sc %p\n", __func__, sc);
2011 			return;
2012 		}
2013 		STAILQ_REMOVE_HEAD(&sc->sc_cmd_pending, next_cmd);
2014 		STAILQ_INSERT_TAIL(&sc->sc_cmd_active, cmd, next_cmd);
2015 		usbd_xfer_set_frame_data(xfer, 0, cmd->buf, cmd->buflen);
2016 		OTUS_DPRINTF(sc, OTUS_DEBUG_CMD,
2017 		    "%s: submitting transfer %p; buf=%p, buflen=%d\n", __func__, cmd, cmd->buf, cmd->buflen);
2018 		usbd_transfer_submit(xfer);
2019 		break;
2020 	default:
2021 		cmd = STAILQ_FIRST(&sc->sc_cmd_active);
2022 		if (cmd != NULL) {
2023 			STAILQ_REMOVE_HEAD(&sc->sc_cmd_active, next_cmd);
2024 			otus_txcmdeof(xfer, cmd);
2025 		}
2026 
2027 		if (error != USB_ERR_CANCELLED) {
2028 			usbd_xfer_set_stall(xfer);
2029 			goto tr_setup;
2030 		}
2031 		break;
2032 	}
2033 }
2034 
2035 /*
2036  * This isn't used by carl9170; it however may be used by the
2037  * initial bootloader.
2038  */
2039 static void
2040 otus_bulk_irq_callback(struct usb_xfer *xfer, usb_error_t error)
2041 {
2042 	struct otus_softc *sc = usbd_xfer_softc(xfer);
2043 	int actlen;
2044 	int sumlen;
2045 
2046 	usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
2047 	OTUS_DPRINTF(sc, OTUS_DEBUG_IRQ,
2048 	    "%s: called; state=%d\n", __func__, USB_GET_STATE(xfer));
2049 
2050 	switch (USB_GET_STATE(xfer)) {
2051 	case USB_ST_TRANSFERRED:
2052 		/*
2053 		 * Read usb frame data, if any.
2054 		 * "actlen" has the total length for all frames
2055 		 * transferred.
2056 		 */
2057 		OTUS_DPRINTF(sc, OTUS_DEBUG_IRQ,
2058 		    "%s: comp; %d bytes\n",
2059 		    __func__,
2060 		    actlen);
2061 #if 0
2062 		pc = usbd_xfer_get_frame(xfer, 0);
2063 		otus_dump_usb_rx_page(sc, pc, actlen);
2064 #endif
2065 		/* XXX fallthrough */
2066 	case USB_ST_SETUP:
2067 		/*
2068 		 * Setup xfer frame lengths/count and data
2069 		 */
2070 		OTUS_DPRINTF(sc, OTUS_DEBUG_IRQ, "%s: setup\n", __func__);
2071 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
2072 		usbd_transfer_submit(xfer);
2073 		break;
2074 
2075 	default: /* Error */
2076 		/*
2077 		 * Print error message and clear stall
2078 		 * for example.
2079 		 */
2080 		OTUS_DPRINTF(sc, OTUS_DEBUG_IRQ, "%s: ERROR?\n", __func__);
2081 		break;
2082 	}
2083 }
2084 
2085 /*
2086  * Map net80211 rate to hw rate for otus MAC/PHY.
2087  */
2088 static uint8_t
2089 otus_rate_to_hw_rate(struct otus_softc *sc, uint8_t rate)
2090 {
2091 	int is_2ghz;
2092 
2093 	is_2ghz = !! (IEEE80211_IS_CHAN_2GHZ(sc->sc_ic.ic_curchan));
2094 
2095 	switch (rate) {
2096 	/* CCK */
2097 	case 2:
2098 		return (0x0);
2099 	case 4:
2100 		return (0x1);
2101 	case 11:
2102 		return (0x2);
2103 	case 22:
2104 		return (0x3);
2105 	/* OFDM */
2106 	case 12:
2107 		return (0xb);
2108 	case 18:
2109 		return (0xf);
2110 	case 24:
2111 		return (0xa);
2112 	case 36:
2113 		return (0xe);
2114 	case 48:
2115 		return (0x9);
2116 	case 72:
2117 		return (0xd);
2118 	case 96:
2119 		return (0x8);
2120 	case 108:
2121 		return (0xc);
2122 	default:
2123 		device_printf(sc->sc_dev, "%s: unknown rate '%d'\n",
2124 		    __func__, (int) rate);
2125 	case 0:
2126 		if (is_2ghz)
2127 			return (0x0);	/* 1MB CCK */
2128 		else
2129 			return (0xb);	/* 6MB OFDM */
2130 
2131 	/* XXX TODO: HT */
2132 	}
2133 }
2134 
2135 static int
2136 otus_hw_rate_is_ofdm(struct otus_softc *sc, uint8_t hw_rate)
2137 {
2138 
2139 	switch (hw_rate) {
2140 	case 0x0:
2141 	case 0x1:
2142 	case 0x2:
2143 	case 0x3:
2144 		return (0);
2145 	default:
2146 		return (1);
2147 	}
2148 }
2149 
2150 
2151 static void
2152 otus_tx_update_ratectl(struct otus_softc *sc, struct ieee80211_node *ni)
2153 {
2154 	struct ieee80211_ratectl_tx_stats *txs = &sc->sc_txs;
2155 	struct otus_node *on = OTUS_NODE(ni);
2156 
2157 	txs->flags = IEEE80211_RATECTL_TX_STATS_NODE |
2158 		     IEEE80211_RATECTL_TX_STATS_RETRIES;
2159 	txs->ni = ni;
2160 	txs->nframes = on->tx_done;
2161 	txs->nsuccess = on->tx_done - on->tx_err;
2162 	txs->nretries = on->tx_retries;
2163 
2164 	ieee80211_ratectl_tx_update(ni->ni_vap, txs);
2165 	on->tx_done = on->tx_err = on->tx_retries = 0;
2166 }
2167 
2168 /*
2169  * XXX TODO: support tx bpf parameters for configuration!
2170  *
2171  * Relevant pieces:
2172  *
2173  * ac = params->ibp_pri & 3;
2174  * rate = params->ibp_rate0;
2175  * params->ibp_flags & IEEE80211_BPF_NOACK
2176  * params->ibp_flags & IEEE80211_BPF_RTS
2177  * params->ibp_flags & IEEE80211_BPF_CTS
2178  * tx->rts_ntries = params->ibp_try1;
2179  * tx->data_ntries = params->ibp_try0;
2180  */
2181 static int
2182 otus_tx(struct otus_softc *sc, struct ieee80211_node *ni, struct mbuf *m,
2183     struct otus_data *data, const struct ieee80211_bpf_params *params)
2184 {
2185 	const struct ieee80211_txparam *tp = ni->ni_txparms;
2186 	struct ieee80211com *ic = &sc->sc_ic;
2187 	struct ieee80211vap *vap = ni->ni_vap;
2188 	struct ieee80211_frame *wh;
2189 	struct ieee80211_key *k;
2190 	struct ar_tx_head *head;
2191 	uint32_t phyctl;
2192 	uint16_t macctl, qos;
2193 	uint8_t qid, rate;
2194 	int hasqos, xferlen, type, ismcast;
2195 
2196 	wh = mtod(m, struct ieee80211_frame *);
2197 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
2198 		k = ieee80211_crypto_encap(ni, m);
2199 		if (k == NULL) {
2200 			device_printf(sc->sc_dev,
2201 			    "%s: m=%p: ieee80211_crypto_encap returns NULL\n",
2202 			    __func__,
2203 			    m);
2204 			return (ENOBUFS);
2205 		}
2206 		wh = mtod(m, struct ieee80211_frame *);
2207 	}
2208 
2209 	/* Calculate transfer length; ensure data buffer is large enough */
2210 	xferlen = sizeof (*head) + m->m_pkthdr.len;
2211 	if (xferlen > OTUS_TXBUFSZ) {
2212 		device_printf(sc->sc_dev,
2213 		    "%s: 802.11 TX frame is %d bytes, max %d bytes\n",
2214 		    __func__,
2215 		    xferlen,
2216 		    OTUS_TXBUFSZ);
2217 		return (ENOBUFS);
2218 	}
2219 
2220 	hasqos = !! IEEE80211_QOS_HAS_SEQ(wh);
2221 
2222 	if (hasqos) {
2223 		uint8_t tid;
2224 		qos = ((const struct ieee80211_qosframe *)wh)->i_qos[0];
2225 		tid = qos & IEEE80211_QOS_TID;
2226 		qid = TID_TO_WME_AC(tid);
2227 	} else {
2228 		qos = 0;
2229 		qid = WME_AC_BE;
2230 	}
2231 
2232 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2233 	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
2234 
2235 	/* Pickup a rate index. */
2236 	if (params != NULL)
2237 		rate = otus_rate_to_hw_rate(sc, params->ibp_rate0);
2238 	else if (!!(m->m_flags & M_EAPOL) || type != IEEE80211_FC0_TYPE_DATA)
2239 		rate = otus_rate_to_hw_rate(sc, tp->mgmtrate);
2240 	else if (ismcast)
2241 		rate = otus_rate_to_hw_rate(sc, tp->mcastrate);
2242 	else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
2243 		rate = otus_rate_to_hw_rate(sc, tp->ucastrate);
2244 	else {
2245 		(void) ieee80211_ratectl_rate(ni, NULL, 0);
2246 		rate = otus_rate_to_hw_rate(sc, ni->ni_txrate);
2247 	}
2248 
2249 	phyctl = 0;
2250 	macctl = AR_TX_MAC_BACKOFF | AR_TX_MAC_HW_DUR | AR_TX_MAC_QID(qid);
2251 
2252 	/*
2253 	 * XXX TODO: params for NOACK, ACK, RTS, CTS, etc
2254 	 */
2255 	if (ismcast ||
2256 	    (hasqos && ((qos & IEEE80211_QOS_ACKPOLICY) ==
2257 	     IEEE80211_QOS_ACKPOLICY_NOACK)))
2258 		macctl |= AR_TX_MAC_NOACK;
2259 
2260 	if (!ismcast) {
2261 		if (m->m_pkthdr.len + IEEE80211_CRC_LEN >= vap->iv_rtsthreshold)
2262 			macctl |= AR_TX_MAC_RTS;
2263 		else if (ic->ic_flags & IEEE80211_F_USEPROT) {
2264 			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
2265 				macctl |= AR_TX_MAC_CTS;
2266 			else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
2267 				macctl |= AR_TX_MAC_RTS;
2268 		}
2269 	}
2270 
2271 	phyctl |= AR_TX_PHY_MCS(rate);
2272 	if (otus_hw_rate_is_ofdm(sc, rate)) {
2273 		phyctl |= AR_TX_PHY_MT_OFDM;
2274 		/* Always use all tx antennas for now, just to be safe */
2275 		phyctl |= AR_TX_PHY_ANTMSK(sc->txmask);
2276 	} else {	/* CCK */
2277 		phyctl |= AR_TX_PHY_MT_CCK;
2278 		phyctl |= AR_TX_PHY_ANTMSK(sc->txmask);
2279 	}
2280 
2281 	/* Update net80211 with the current counters */
2282 	otus_tx_update_ratectl(sc, ni);
2283 
2284 	/* Update rate control stats for frames that are ACK'ed. */
2285 	if (!(macctl & AR_TX_MAC_NOACK))
2286 		OTUS_NODE(ni)->tx_done++;
2287 
2288 
2289 	/* Fill Tx descriptor. */
2290 	head = (struct ar_tx_head *)data->buf;
2291 	head->len = htole16(m->m_pkthdr.len + IEEE80211_CRC_LEN);
2292 	head->macctl = htole16(macctl);
2293 	head->phyctl = htole32(phyctl);
2294 
2295 	m_copydata(m, 0, m->m_pkthdr.len, (caddr_t)&head[1]);
2296 
2297 	data->buflen = xferlen;
2298 	data->ni = ni;
2299 	data->m = m;
2300 
2301 	OTUS_DPRINTF(sc, OTUS_DEBUG_XMIT,
2302 	    "%s: tx: m=%p; data=%p; len=%d mac=0x%04x phy=0x%08x rate=0x%02x, ni_txrate=%d\n",
2303 	    __func__, m, data, le16toh(head->len), macctl, phyctl,
2304 	    (int) rate, (int) ni->ni_txrate);
2305 
2306 	/* Submit transfer */
2307 	STAILQ_INSERT_TAIL(&sc->sc_tx_pending[OTUS_BULK_TX], data, next);
2308 	usbd_transfer_start(sc->sc_xfer[OTUS_BULK_TX]);
2309 
2310 	return 0;
2311 }
2312 
2313 int
2314 otus_set_multi(struct otus_softc *sc)
2315 {
2316 	uint32_t lo, hi;
2317 	struct ieee80211com *ic = &sc->sc_ic;
2318 	int r;
2319 
2320 	if (ic->ic_allmulti > 0 || ic->ic_promisc > 0 ||
2321 	    ic->ic_opmode == IEEE80211_M_MONITOR) {
2322 		lo = 0xffffffff;
2323 		hi = 0xffffffff;
2324 	} else {
2325 		struct ieee80211vap *vap;
2326 		struct ifnet *ifp;
2327 		struct ifmultiaddr *ifma;
2328 
2329 		lo = hi = 0;
2330 		TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
2331 			ifp = vap->iv_ifp;
2332 			if_maddr_rlock(ifp);
2333 			TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2334 				caddr_t dl;
2335 				uint32_t val;
2336 
2337 				dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
2338 				val = le32dec(dl + 4);
2339 				/* Get address byte 5 */
2340 				val = val & 0x0000ff00;
2341 				val = val >> 8;
2342 
2343 				/* As per below, shift it >> 2 to get only 6 bits */
2344 				val = val >> 2;
2345 				if (val < 32)
2346 					lo |= 1 << val;
2347 				else
2348 					hi |= 1 << (val - 32);
2349 			}
2350 			if_maddr_runlock(ifp);
2351 		}
2352 	}
2353 #if 0
2354 	/* XXX openbsd code */
2355 	while (enm != NULL) {
2356 		bit = enm->enm_addrlo[5] >> 2;
2357 		if (bit < 32)
2358 			lo |= 1 << bit;
2359 		else
2360 			hi |= 1 << (bit - 32);
2361 		ETHER_NEXT_MULTI(step, enm);
2362 	}
2363 #endif
2364 
2365 	hi |= 1U << 31;	/* Make sure the broadcast bit is set. */
2366 
2367 	OTUS_LOCK(sc);
2368 	otus_write(sc, AR_MAC_REG_GROUP_HASH_TBL_L, lo);
2369 	otus_write(sc, AR_MAC_REG_GROUP_HASH_TBL_H, hi);
2370 	r = otus_write_barrier(sc);
2371 	/* XXX operating mode? filter? */
2372 	OTUS_UNLOCK(sc);
2373 	return (r);
2374 }
2375 
2376 static int
2377 otus_updateedca(struct ieee80211com *ic)
2378 {
2379 	struct otus_softc *sc = ic->ic_softc;
2380 
2381 	OTUS_LOCK(sc);
2382 	/*
2383 	 * XXX TODO: take temporary copy of EDCA information
2384 	 * when scheduling this so we have a more time-correct view
2385 	 * of things.
2386 	 * XXX TODO: this can be done on the net80211 level
2387 	 */
2388 	otus_updateedca_locked(sc);
2389 	OTUS_UNLOCK(sc);
2390 	return (0);
2391 }
2392 
2393 static void
2394 otus_updateedca_locked(struct otus_softc *sc)
2395 {
2396 #define EXP2(val)	((1 << (val)) - 1)
2397 #define AIFS(val)	((val) * 9 + 10)
2398 	struct chanAccParams chp;
2399 	struct ieee80211com *ic = &sc->sc_ic;
2400 	const struct wmeParams *edca;
2401 
2402 	ieee80211_wme_ic_getparams(ic, &chp);
2403 
2404 	OTUS_LOCK_ASSERT(sc);
2405 
2406 	edca = chp.cap_wmeParams;
2407 
2408 	/* Set CWmin/CWmax values. */
2409 	otus_write(sc, AR_MAC_REG_AC0_CW,
2410 	    EXP2(edca[WME_AC_BE].wmep_logcwmax) << 16 |
2411 	    EXP2(edca[WME_AC_BE].wmep_logcwmin));
2412 	otus_write(sc, AR_MAC_REG_AC1_CW,
2413 	    EXP2(edca[WME_AC_BK].wmep_logcwmax) << 16 |
2414 	    EXP2(edca[WME_AC_BK].wmep_logcwmin));
2415 	otus_write(sc, AR_MAC_REG_AC2_CW,
2416 	    EXP2(edca[WME_AC_VI].wmep_logcwmax) << 16 |
2417 	    EXP2(edca[WME_AC_VI].wmep_logcwmin));
2418 	otus_write(sc, AR_MAC_REG_AC3_CW,
2419 	    EXP2(edca[WME_AC_VO].wmep_logcwmax) << 16 |
2420 	    EXP2(edca[WME_AC_VO].wmep_logcwmin));
2421 	otus_write(sc, AR_MAC_REG_AC4_CW,		/* Special TXQ. */
2422 	    EXP2(edca[WME_AC_VO].wmep_logcwmax) << 16 |
2423 	    EXP2(edca[WME_AC_VO].wmep_logcwmin));
2424 
2425 	/* Set AIFSN values. */
2426 	otus_write(sc, AR_MAC_REG_AC1_AC0_AIFS,
2427 	    AIFS(edca[WME_AC_VI].wmep_aifsn) << 24 |
2428 	    AIFS(edca[WME_AC_BK].wmep_aifsn) << 12 |
2429 	    AIFS(edca[WME_AC_BE].wmep_aifsn));
2430 	otus_write(sc, AR_MAC_REG_AC3_AC2_AIFS,
2431 	    AIFS(edca[WME_AC_VO].wmep_aifsn) << 16 |	/* Special TXQ. */
2432 	    AIFS(edca[WME_AC_VO].wmep_aifsn) <<  4 |
2433 	    AIFS(edca[WME_AC_VI].wmep_aifsn) >>  8);
2434 
2435 	/* Set TXOP limit. */
2436 	otus_write(sc, AR_MAC_REG_AC1_AC0_TXOP,
2437 	    edca[WME_AC_BK].wmep_txopLimit << 16 |
2438 	    edca[WME_AC_BE].wmep_txopLimit);
2439 	otus_write(sc, AR_MAC_REG_AC3_AC2_TXOP,
2440 	    edca[WME_AC_VO].wmep_txopLimit << 16 |
2441 	    edca[WME_AC_VI].wmep_txopLimit);
2442 
2443 	/* XXX ACK policy? */
2444 
2445 	(void)otus_write_barrier(sc);
2446 
2447 #undef AIFS
2448 #undef EXP2
2449 }
2450 
2451 static void
2452 otus_updateslot(struct otus_softc *sc)
2453 {
2454 	struct ieee80211com *ic = &sc->sc_ic;
2455 	uint32_t slottime;
2456 
2457 	OTUS_LOCK_ASSERT(sc);
2458 
2459 	slottime = IEEE80211_GET_SLOTTIME(ic);
2460 	otus_write(sc, AR_MAC_REG_SLOT_TIME, slottime << 10);
2461 	(void)otus_write_barrier(sc);
2462 }
2463 
2464 int
2465 otus_init_mac(struct otus_softc *sc)
2466 {
2467 	int error;
2468 
2469 	OTUS_LOCK_ASSERT(sc);
2470 
2471 	otus_write(sc, AR_MAC_REG_ACK_EXTENSION, 0x40);
2472 	otus_write(sc, AR_MAC_REG_RETRY_MAX, 0);
2473 	otus_write(sc, AR_MAC_REG_RX_THRESHOLD, 0xc1f80);
2474 	otus_write(sc, AR_MAC_REG_RX_PE_DELAY, 0x70);
2475 	otus_write(sc, AR_MAC_REG_EIFS_AND_SIFS, 0xa144000);
2476 	otus_write(sc, AR_MAC_REG_SLOT_TIME, 9 << 10);
2477 	otus_write(sc, AR_MAC_REG_TID_CFACK_CFEND_RATE, 0x19000000);
2478 	/* NAV protects ACK only (in TXOP). */
2479 	otus_write(sc, AR_MAC_REG_TXOP_DURATION, 0x201);
2480 	/* Set beacon Tx power to 0x7. */
2481 	otus_write(sc, AR_MAC_REG_BCN_HT1, 0x8000170);
2482 	otus_write(sc, AR_MAC_REG_BACKOFF_PROTECT, 0x105);
2483 	otus_write(sc, AR_MAC_REG_AMPDU_FACTOR, 0x10000a);
2484 
2485 	otus_set_rx_filter(sc);
2486 
2487 	otus_write(sc, AR_MAC_REG_BASIC_RATE, 0x150f);
2488 	otus_write(sc, AR_MAC_REG_MANDATORY_RATE, 0x150f);
2489 	otus_write(sc, AR_MAC_REG_RTS_CTS_RATE, 0x10b01bb);
2490 	otus_write(sc, AR_MAC_REG_ACK_TPC, 0x4003c1e);
2491 
2492 	/* Enable LED0 and LED1. */
2493 	otus_write(sc, AR_GPIO_REG_PORT_TYPE, 0x3);
2494 	otus_write(sc, AR_GPIO_REG_PORT_DATA, 0x3);
2495 	/* Switch MAC to OTUS interface. */
2496 	otus_write(sc, 0x1c3600, 0x3);
2497 	otus_write(sc, AR_MAC_REG_AMPDU_RX_THRESH, 0xffff);
2498 	otus_write(sc, AR_MAC_REG_MISC_680, 0xf00008);
2499 	/* Disable Rx timeout (workaround). */
2500 	otus_write(sc, AR_MAC_REG_RX_TIMEOUT, 0);
2501 
2502 	/* Set USB Rx stream mode maximum frame number to 2. */
2503 	otus_write(sc, 0x1e1110, 0x4);
2504 	/* Set USB Rx stream mode timeout to 10us. */
2505 	otus_write(sc, 0x1e1114, 0x80);
2506 
2507 	/* Set clock frequency to 88/80MHz. */
2508 	otus_write(sc, AR_PWR_REG_CLOCK_SEL, 0x73);
2509 	/* Set WLAN DMA interrupt mode: generate intr per packet. */
2510 	otus_write(sc, AR_MAC_REG_TXRX_MPI, 0x110011);
2511 	otus_write(sc, AR_MAC_REG_FCS_SELECT, 0x4);
2512 	otus_write(sc, AR_MAC_REG_TXOP_NOT_ENOUGH_INDICATION, 0x141e0f48);
2513 
2514 	/* Disable HW decryption for now. */
2515 	otus_write(sc, AR_MAC_REG_ENCRYPTION, 0x78);
2516 
2517 	if ((error = otus_write_barrier(sc)) != 0)
2518 		return error;
2519 
2520 	/* Set default EDCA parameters. */
2521 	otus_updateedca_locked(sc);
2522 
2523 	return 0;
2524 }
2525 
2526 /*
2527  * Return default value for PHY register based on current operating mode.
2528  */
2529 uint32_t
2530 otus_phy_get_def(struct otus_softc *sc, uint32_t reg)
2531 {
2532 	int i;
2533 
2534 	for (i = 0; i < nitems(ar5416_phy_regs); i++)
2535 		if (AR_PHY(ar5416_phy_regs[i]) == reg)
2536 			return sc->phy_vals[i];
2537 	return 0;	/* Register not found. */
2538 }
2539 
2540 /*
2541  * Update PHY's programming based on vendor-specific data stored in EEPROM.
2542  * This is for FEM-type devices only.
2543  */
2544 int
2545 otus_set_board_values(struct otus_softc *sc, struct ieee80211_channel *c)
2546 {
2547 	const struct ModalEepHeader *eep;
2548 	uint32_t tmp, offset;
2549 
2550 	if (IEEE80211_IS_CHAN_5GHZ(c))
2551 		eep = &sc->eeprom.modalHeader[0];
2552 	else
2553 		eep = &sc->eeprom.modalHeader[1];
2554 
2555 	/* Offset of chain 2. */
2556 	offset = 2 * 0x1000;
2557 
2558 	tmp = le32toh(eep->antCtrlCommon);
2559 	otus_write(sc, AR_PHY_SWITCH_COM, tmp);
2560 
2561 	tmp = le32toh(eep->antCtrlChain[0]);
2562 	otus_write(sc, AR_PHY_SWITCH_CHAIN_0, tmp);
2563 
2564 	tmp = le32toh(eep->antCtrlChain[1]);
2565 	otus_write(sc, AR_PHY_SWITCH_CHAIN_0 + offset, tmp);
2566 
2567 	if (1 /* sc->sc_sco == AR_SCO_SCN */) {
2568 		tmp = otus_phy_get_def(sc, AR_PHY_SETTLING);
2569 		tmp &= ~(0x7f << 7);
2570 		tmp |= (eep->switchSettling & 0x7f) << 7;
2571 		otus_write(sc, AR_PHY_SETTLING, tmp);
2572 	}
2573 
2574 	tmp = otus_phy_get_def(sc, AR_PHY_DESIRED_SZ);
2575 	tmp &= ~0xffff;
2576 	tmp |= eep->pgaDesiredSize << 8 | eep->adcDesiredSize;
2577 	otus_write(sc, AR_PHY_DESIRED_SZ, tmp);
2578 
2579 	tmp = eep->txEndToXpaOff << 24 | eep->txEndToXpaOff << 16 |
2580 	      eep->txFrameToXpaOn << 8 | eep->txFrameToXpaOn;
2581 	otus_write(sc, AR_PHY_RF_CTL4, tmp);
2582 
2583 	tmp = otus_phy_get_def(sc, AR_PHY_RF_CTL3);
2584 	tmp &= ~(0xff << 16);
2585 	tmp |= eep->txEndToRxOn << 16;
2586 	otus_write(sc, AR_PHY_RF_CTL3, tmp);
2587 
2588 	tmp = otus_phy_get_def(sc, AR_PHY_CCA);
2589 	tmp &= ~(0x7f << 12);
2590 	tmp |= (eep->thresh62 & 0x7f) << 12;
2591 	otus_write(sc, AR_PHY_CCA, tmp);
2592 
2593 	tmp = otus_phy_get_def(sc, AR_PHY_RXGAIN);
2594 	tmp &= ~(0x3f << 12);
2595 	tmp |= (eep->txRxAttenCh[0] & 0x3f) << 12;
2596 	otus_write(sc, AR_PHY_RXGAIN, tmp);
2597 
2598 	tmp = otus_phy_get_def(sc, AR_PHY_RXGAIN + offset);
2599 	tmp &= ~(0x3f << 12);
2600 	tmp |= (eep->txRxAttenCh[1] & 0x3f) << 12;
2601 	otus_write(sc, AR_PHY_RXGAIN + offset, tmp);
2602 
2603 	tmp = otus_phy_get_def(sc, AR_PHY_GAIN_2GHZ);
2604 	tmp &= ~(0x3f << 18);
2605 	tmp |= (eep->rxTxMarginCh[0] & 0x3f) << 18;
2606 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
2607 		tmp &= ~(0xf << 10);
2608 		tmp |= (eep->bswMargin[0] & 0xf) << 10;
2609 	}
2610 	otus_write(sc, AR_PHY_GAIN_2GHZ, tmp);
2611 
2612 	tmp = otus_phy_get_def(sc, AR_PHY_GAIN_2GHZ + offset);
2613 	tmp &= ~(0x3f << 18);
2614 	tmp |= (eep->rxTxMarginCh[1] & 0x3f) << 18;
2615 	otus_write(sc, AR_PHY_GAIN_2GHZ + offset, tmp);
2616 
2617 	tmp = otus_phy_get_def(sc, AR_PHY_TIMING_CTRL4);
2618 	tmp &= ~(0x3f << 5 | 0x1f);
2619 	tmp |= (eep->iqCalICh[0] & 0x3f) << 5 | (eep->iqCalQCh[0] & 0x1f);
2620 	otus_write(sc, AR_PHY_TIMING_CTRL4, tmp);
2621 
2622 	tmp = otus_phy_get_def(sc, AR_PHY_TIMING_CTRL4 + offset);
2623 	tmp &= ~(0x3f << 5 | 0x1f);
2624 	tmp |= (eep->iqCalICh[1] & 0x3f) << 5 | (eep->iqCalQCh[1] & 0x1f);
2625 	otus_write(sc, AR_PHY_TIMING_CTRL4 + offset, tmp);
2626 
2627 	tmp = otus_phy_get_def(sc, AR_PHY_TPCRG1);
2628 	tmp &= ~(0xf << 16);
2629 	tmp |= (eep->xpd & 0xf) << 16;
2630 	otus_write(sc, AR_PHY_TPCRG1, tmp);
2631 
2632 	return otus_write_barrier(sc);
2633 }
2634 
2635 int
2636 otus_program_phy(struct otus_softc *sc, struct ieee80211_channel *c)
2637 {
2638 	const uint32_t *vals;
2639 	int error, i;
2640 
2641 	/* Select PHY programming based on band and bandwidth. */
2642 	if (IEEE80211_IS_CHAN_2GHZ(c))
2643 		vals = ar5416_phy_vals_2ghz_20mhz;
2644 	else
2645 		vals = ar5416_phy_vals_5ghz_20mhz;
2646 	for (i = 0; i < nitems(ar5416_phy_regs); i++)
2647 		otus_write(sc, AR_PHY(ar5416_phy_regs[i]), vals[i]);
2648 	sc->phy_vals = vals;
2649 
2650 	if (sc->eeprom.baseEepHeader.deviceType == 0x80)	/* FEM */
2651 		if ((error = otus_set_board_values(sc, c)) != 0)
2652 			return error;
2653 
2654 	/* Initial Tx power settings. */
2655 	otus_write(sc, AR_PHY_POWER_TX_RATE_MAX, 0x7f);
2656 	otus_write(sc, AR_PHY_POWER_TX_RATE1, 0x3f3f3f3f);
2657 	otus_write(sc, AR_PHY_POWER_TX_RATE2, 0x3f3f3f3f);
2658 	otus_write(sc, AR_PHY_POWER_TX_RATE3, 0x3f3f3f3f);
2659 	otus_write(sc, AR_PHY_POWER_TX_RATE4, 0x3f3f3f3f);
2660 	otus_write(sc, AR_PHY_POWER_TX_RATE5, 0x3f3f3f3f);
2661 	otus_write(sc, AR_PHY_POWER_TX_RATE6, 0x3f3f3f3f);
2662 	otus_write(sc, AR_PHY_POWER_TX_RATE7, 0x3f3f3f3f);
2663 	otus_write(sc, AR_PHY_POWER_TX_RATE8, 0x3f3f3f3f);
2664 	otus_write(sc, AR_PHY_POWER_TX_RATE9, 0x3f3f3f3f);
2665 
2666 	if (IEEE80211_IS_CHAN_2GHZ(c))
2667 		otus_write(sc, AR_PWR_REG_PLL_ADDAC, 0x5163);
2668 	else
2669 		otus_write(sc, AR_PWR_REG_PLL_ADDAC, 0x5143);
2670 
2671 	return otus_write_barrier(sc);
2672 }
2673 
2674 static __inline uint8_t
2675 otus_reverse_bits(uint8_t v)
2676 {
2677 	v = ((v >> 1) & 0x55) | ((v & 0x55) << 1);
2678 	v = ((v >> 2) & 0x33) | ((v & 0x33) << 2);
2679 	v = ((v >> 4) & 0x0f) | ((v & 0x0f) << 4);
2680 	return v;
2681 }
2682 
2683 int
2684 otus_set_rf_bank4(struct otus_softc *sc, struct ieee80211_channel *c)
2685 {
2686 	uint8_t chansel, d0, d1;
2687 	uint16_t data;
2688 	int error;
2689 
2690 	OTUS_LOCK_ASSERT(sc);
2691 
2692 	d0 = 0;
2693 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
2694 		chansel = (c->ic_freq - 4800) / 5;
2695 		if (chansel & 1)
2696 			d0 |= AR_BANK4_AMODE_REFSEL(2);
2697 		else
2698 			d0 |= AR_BANK4_AMODE_REFSEL(1);
2699 	} else {
2700 		d0 |= AR_BANK4_AMODE_REFSEL(2);
2701 		if (c->ic_freq == 2484) {	/* CH 14 */
2702 			d0 |= AR_BANK4_BMODE_LF_SYNTH_FREQ;
2703 			chansel = 10 + (c->ic_freq - 2274) / 5;
2704 		} else
2705 			chansel = 16 + (c->ic_freq - 2272) / 5;
2706 		chansel <<= 2;
2707 	}
2708 	d0 |= AR_BANK4_ADDR(1) | AR_BANK4_CHUP;
2709 	d1 = otus_reverse_bits(chansel);
2710 
2711 	/* Write bits 0-4 of d0 and d1. */
2712 	data = (d1 & 0x1f) << 5 | (d0 & 0x1f);
2713 	otus_write(sc, AR_PHY(44), data);
2714 	/* Write bits 5-7 of d0 and d1. */
2715 	data = (d1 >> 5) << 5 | (d0 >> 5);
2716 	otus_write(sc, AR_PHY(58), data);
2717 
2718 	if ((error = otus_write_barrier(sc)) == 0)
2719 		otus_delay_ms(sc, 10);
2720 	return error;
2721 }
2722 
2723 void
2724 otus_get_delta_slope(uint32_t coeff, uint32_t *exponent, uint32_t *mantissa)
2725 {
2726 #define COEFF_SCALE_SHIFT	24
2727 	uint32_t exp, man;
2728 
2729 	/* exponent = 14 - floor(log2(coeff)) */
2730 	for (exp = 31; exp > 0; exp--)
2731 		if (coeff & (1 << exp))
2732 			break;
2733 	KASSERT(exp != 0, ("exp"));
2734 	exp = 14 - (exp - COEFF_SCALE_SHIFT);
2735 
2736 	/* mantissa = floor(coeff * 2^exponent + 0.5) */
2737 	man = coeff + (1 << (COEFF_SCALE_SHIFT - exp - 1));
2738 
2739 	*mantissa = man >> (COEFF_SCALE_SHIFT - exp);
2740 	*exponent = exp - 16;
2741 #undef COEFF_SCALE_SHIFT
2742 }
2743 
2744 static int
2745 otus_set_chan(struct otus_softc *sc, struct ieee80211_channel *c, int assoc)
2746 {
2747 	struct ieee80211com *ic = &sc->sc_ic;
2748 	struct ar_cmd_frequency cmd;
2749 	struct ar_rsp_frequency rsp;
2750 	const uint32_t *vals;
2751 	uint32_t coeff, exp, man, tmp;
2752 	uint8_t code;
2753 	int error, chan, i;
2754 
2755 	error = 0;
2756 	chan = ieee80211_chan2ieee(ic, c);
2757 
2758 	OTUS_DPRINTF(sc, OTUS_DEBUG_RESET,
2759 	    "setting channel %d (%dMHz)\n", chan, c->ic_freq);
2760 
2761 	tmp = IEEE80211_IS_CHAN_2GHZ(c) ? 0x105 : 0x104;
2762 	otus_write(sc, AR_MAC_REG_DYNAMIC_SIFS_ACK, tmp);
2763 	if ((error = otus_write_barrier(sc)) != 0)
2764 		goto finish;
2765 
2766 	/* Disable BB Heavy Clip. */
2767 	otus_write(sc, AR_PHY_HEAVY_CLIP_ENABLE, 0x200);
2768 	if ((error = otus_write_barrier(sc)) != 0)
2769 		goto finish;
2770 
2771 	/* XXX Is that FREQ_START ? */
2772 	error = otus_cmd(sc, AR_CMD_FREQ_STRAT, NULL, 0, NULL, 0);
2773 	if (error != 0)
2774 		goto finish;
2775 
2776 	/* Reprogram PHY and RF on channel band or bandwidth changes. */
2777 	if (sc->bb_reset || c->ic_flags != sc->sc_curchan->ic_flags) {
2778 		OTUS_DPRINTF(sc, OTUS_DEBUG_RESET, "band switch\n");
2779 
2780 		/* Cold/Warm reset BB/ADDA. */
2781 		otus_write(sc, AR_PWR_REG_RESET, sc->bb_reset ? 0x800 : 0x400);
2782 		if ((error = otus_write_barrier(sc)) != 0)
2783 			goto finish;
2784 		otus_write(sc, AR_PWR_REG_RESET, 0);
2785 		if ((error = otus_write_barrier(sc)) != 0)
2786 			goto finish;
2787 		sc->bb_reset = 0;
2788 
2789 		if ((error = otus_program_phy(sc, c)) != 0) {
2790 			device_printf(sc->sc_dev,
2791 			    "%s: could not program PHY\n",
2792 			    __func__);
2793 			goto finish;
2794 		}
2795 
2796 		/* Select RF programming based on band. */
2797 		if (IEEE80211_IS_CHAN_5GHZ(c))
2798 			vals = ar5416_banks_vals_5ghz;
2799 		else
2800 			vals = ar5416_banks_vals_2ghz;
2801 		for (i = 0; i < nitems(ar5416_banks_regs); i++)
2802 			otus_write(sc, AR_PHY(ar5416_banks_regs[i]), vals[i]);
2803 		if ((error = otus_write_barrier(sc)) != 0) {
2804 			device_printf(sc->sc_dev,
2805 			    "%s: could not program RF\n",
2806 			    __func__);
2807 			goto finish;
2808 		}
2809 		code = AR_CMD_RF_INIT;
2810 	} else {
2811 		code = AR_CMD_FREQUENCY;
2812 	}
2813 
2814 	if ((error = otus_set_rf_bank4(sc, c)) != 0)
2815 		goto finish;
2816 
2817 	tmp = (sc->txmask == 0x5) ? 0x340 : 0x240;
2818 	otus_write(sc, AR_PHY_TURBO, tmp);
2819 	if ((error = otus_write_barrier(sc)) != 0)
2820 		goto finish;
2821 
2822 	/* Send firmware command to set channel. */
2823 	cmd.freq = htole32((uint32_t)c->ic_freq * 1000);
2824 	cmd.dynht2040 = htole32(0);
2825 	cmd.htena = htole32(1);
2826 	/* Set Delta Slope (exponent and mantissa). */
2827 	coeff = (100 << 24) / c->ic_freq;
2828 	otus_get_delta_slope(coeff, &exp, &man);
2829 	cmd.dsc_exp = htole32(exp);
2830 	cmd.dsc_man = htole32(man);
2831 	OTUS_DPRINTF(sc, OTUS_DEBUG_RESET,
2832 	    "ds coeff=%u exp=%u man=%u\n", coeff, exp, man);
2833 	/* For Short GI, coeff is 9/10 that of normal coeff. */
2834 	coeff = (9 * coeff) / 10;
2835 	otus_get_delta_slope(coeff, &exp, &man);
2836 	cmd.dsc_shgi_exp = htole32(exp);
2837 	cmd.dsc_shgi_man = htole32(man);
2838 	OTUS_DPRINTF(sc, OTUS_DEBUG_RESET,
2839 	    "ds shgi coeff=%u exp=%u man=%u\n", coeff, exp, man);
2840 	/* Set wait time for AGC and noise calibration (100 or 200ms). */
2841 	cmd.check_loop_count = assoc ? htole32(2000) : htole32(1000);
2842 	OTUS_DPRINTF(sc, OTUS_DEBUG_RESET,
2843 	    "%s\n", (code == AR_CMD_RF_INIT) ? "RF_INIT" : "FREQUENCY");
2844 	error = otus_cmd(sc, code, &cmd, sizeof cmd, &rsp, sizeof(rsp));
2845 	if (error != 0)
2846 		goto finish;
2847 	if ((rsp.status & htole32(AR_CAL_ERR_AGC | AR_CAL_ERR_NF_VAL)) != 0) {
2848 		OTUS_DPRINTF(sc, OTUS_DEBUG_RESET,
2849 		    "status=0x%x\n", le32toh(rsp.status));
2850 		/* Force cold reset on next channel. */
2851 		sc->bb_reset = 1;
2852 	}
2853 #ifdef USB_DEBUG
2854 	if (otus_debug & OTUS_DEBUG_RESET) {
2855 		device_printf(sc->sc_dev, "calibration status=0x%x\n",
2856 		    le32toh(rsp.status));
2857 		for (i = 0; i < 2; i++) {	/* 2 Rx chains */
2858 			/* Sign-extend 9-bit NF values. */
2859 			device_printf(sc->sc_dev,
2860 			    "noisefloor chain %d=%d\n", i,
2861 			    (((int32_t)le32toh(rsp.nf[i])) << 4) >> 23);
2862 			device_printf(sc->sc_dev,
2863 			    "noisefloor ext chain %d=%d\n", i,
2864 			    ((int32_t)le32toh(rsp.nf_ext[i])) >> 23);
2865 		}
2866 	}
2867 #endif
2868 	for (i = 0; i < OTUS_NUM_CHAINS; i++) {
2869 		sc->sc_nf[i] = ((((int32_t)le32toh(rsp.nf[i])) << 4) >> 23);
2870 	}
2871 	sc->sc_curchan = c;
2872 finish:
2873 	return (error);
2874 }
2875 
2876 #ifdef notyet
2877 int
2878 otus_set_key(struct ieee80211com *ic, struct ieee80211_node *ni,
2879     struct ieee80211_key *k)
2880 {
2881 	struct otus_softc *sc = ic->ic_softc;
2882 	struct otus_cmd_key cmd;
2883 
2884 	/* Defer setting of WEP keys until interface is brought up. */
2885 	if ((ic->ic_if.if_flags & (IFF_UP | IFF_RUNNING)) !=
2886 	    (IFF_UP | IFF_RUNNING))
2887 		return 0;
2888 
2889 	/* Do it in a process context. */
2890 	cmd.key = *k;
2891 	cmd.associd = (ni != NULL) ? ni->ni_associd : 0;
2892 	otus_do_async(sc, otus_set_key_cb, &cmd, sizeof cmd);
2893 	return 0;
2894 }
2895 
2896 void
2897 otus_set_key_cb(struct otus_softc *sc, void *arg)
2898 {
2899 	struct otus_cmd_key *cmd = arg;
2900 	struct ieee80211_key *k = &cmd->key;
2901 	struct ar_cmd_ekey key;
2902 	uint16_t cipher;
2903 	int error;
2904 
2905 	memset(&key, 0, sizeof key);
2906 	if (k->k_flags & IEEE80211_KEY_GROUP) {
2907 		key.uid = htole16(k->k_id);
2908 		IEEE80211_ADDR_COPY(key.macaddr, sc->sc_ic.ic_myaddr);
2909 		key.macaddr[0] |= 0x80;
2910 	} else {
2911 		key.uid = htole16(OTUS_UID(cmd->associd));
2912 		IEEE80211_ADDR_COPY(key.macaddr, ni->ni_macaddr);
2913 	}
2914 	key.kix = htole16(0);
2915 	/* Map net80211 cipher to hardware. */
2916 	switch (k->k_cipher) {
2917 	case IEEE80211_CIPHER_WEP40:
2918 		cipher = AR_CIPHER_WEP64;
2919 		break;
2920 	case IEEE80211_CIPHER_WEP104:
2921 		cipher = AR_CIPHER_WEP128;
2922 		break;
2923 	case IEEE80211_CIPHER_TKIP:
2924 		cipher = AR_CIPHER_TKIP;
2925 		break;
2926 	case IEEE80211_CIPHER_CCMP:
2927 		cipher = AR_CIPHER_AES;
2928 		break;
2929 	default:
2930 		return;
2931 	}
2932 	key.cipher = htole16(cipher);
2933 	memcpy(key.key, k->k_key, MIN(k->k_len, 16));
2934 	error = otus_cmd(sc, AR_CMD_EKEY, &key, sizeof key, NULL, 0);
2935 	if (error != 0 || k->k_cipher != IEEE80211_CIPHER_TKIP)
2936 		return;
2937 
2938 	/* TKIP: set Tx/Rx MIC Key. */
2939 	key.kix = htole16(1);
2940 	memcpy(key.key, k->k_key + 16, 16);
2941 	(void)otus_cmd(sc, AR_CMD_EKEY, &key, sizeof key, NULL, 0);
2942 }
2943 
2944 void
2945 otus_delete_key(struct ieee80211com *ic, struct ieee80211_node *ni,
2946     struct ieee80211_key *k)
2947 {
2948 	struct otus_softc *sc = ic->ic_softc;
2949 	struct otus_cmd_key cmd;
2950 
2951 	if (!(ic->ic_if.if_flags & IFF_RUNNING) ||
2952 	    ic->ic_state != IEEE80211_S_RUN)
2953 		return;	/* Nothing to do. */
2954 
2955 	/* Do it in a process context. */
2956 	cmd.key = *k;
2957 	cmd.associd = (ni != NULL) ? ni->ni_associd : 0;
2958 	otus_do_async(sc, otus_delete_key_cb, &cmd, sizeof cmd);
2959 }
2960 
2961 void
2962 otus_delete_key_cb(struct otus_softc *sc, void *arg)
2963 {
2964 	struct otus_cmd_key *cmd = arg;
2965 	struct ieee80211_key *k = &cmd->key;
2966 	uint32_t uid;
2967 
2968 	if (k->k_flags & IEEE80211_KEY_GROUP)
2969 		uid = htole32(k->k_id);
2970 	else
2971 		uid = htole32(OTUS_UID(cmd->associd));
2972 	(void)otus_cmd(sc, AR_CMD_DKEY, &uid, sizeof uid, NULL, 0);
2973 }
2974 #endif
2975 
2976 /*
2977  * XXX TODO: check if we have to be doing any calibration in the host
2978  * or whether it's purely a firmware thing.
2979  */
2980 void
2981 otus_calibrate_to(void *arg, int pending)
2982 {
2983 #if 0
2984 	struct otus_softc *sc = arg;
2985 
2986 	device_printf(sc->sc_dev, "%s: called\n", __func__);
2987 	struct ieee80211com *ic = &sc->sc_ic;
2988 	struct ieee80211_node *ni;
2989 	int s;
2990 
2991 	if (usbd_is_dying(sc->sc_udev))
2992 		return;
2993 
2994 	usbd_ref_incr(sc->sc_udev);
2995 
2996 	s = splnet();
2997 	ni = ic->ic_bss;
2998 	ieee80211_amrr_choose(&sc->amrr, ni, &((struct otus_node *)ni)->amn);
2999 	splx(s);
3000 
3001 	if (!usbd_is_dying(sc->sc_udev))
3002 		timeout_add_sec(&sc->calib_to, 1);
3003 
3004 	usbd_ref_decr(sc->sc_udev);
3005 #endif
3006 }
3007 
3008 int
3009 otus_set_bssid(struct otus_softc *sc, const uint8_t *bssid)
3010 {
3011 
3012 	OTUS_LOCK_ASSERT(sc);
3013 
3014 	otus_write(sc, AR_MAC_REG_BSSID_L,
3015 	    bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24);
3016 	otus_write(sc, AR_MAC_REG_BSSID_H,
3017 	    bssid[4] | bssid[5] << 8);
3018 	return otus_write_barrier(sc);
3019 }
3020 
3021 int
3022 otus_set_macaddr(struct otus_softc *sc, const uint8_t *addr)
3023 {
3024 	OTUS_LOCK_ASSERT(sc);
3025 
3026 	otus_write(sc, AR_MAC_REG_MAC_ADDR_L,
3027 	    addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24);
3028 	otus_write(sc, AR_MAC_REG_MAC_ADDR_H,
3029 	    addr[4] | addr[5] << 8);
3030 	return otus_write_barrier(sc);
3031 }
3032 
3033 /* Default single-LED. */
3034 void
3035 otus_led_newstate_type1(struct otus_softc *sc)
3036 {
3037 	/* TBD */
3038 	device_printf(sc->sc_dev, "%s: TODO\n", __func__);
3039 }
3040 
3041 /* NETGEAR, dual-LED. */
3042 void
3043 otus_led_newstate_type2(struct otus_softc *sc)
3044 {
3045 	/* TBD */
3046 	device_printf(sc->sc_dev, "%s: TODO\n", __func__);
3047 }
3048 
3049 /* NETGEAR, single-LED/3 colors (blue, red, purple.) */
3050 void
3051 otus_led_newstate_type3(struct otus_softc *sc)
3052 {
3053 #if 0
3054 	struct ieee80211com *ic = &sc->sc_ic;
3055 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3056 
3057 	uint32_t state = sc->led_state;
3058 
3059 	OTUS_LOCK_ASSERT(sc);
3060 
3061 	if (!vap) {
3062 		state = 0;	/* led off */
3063 	} else if (vap->iv_state == IEEE80211_S_INIT) {
3064 		state = 0;	/* LED off. */
3065 	} else if (vap->iv_state == IEEE80211_S_RUN) {
3066 		/* Associated, LED always on. */
3067 		if (IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan))
3068 			state = AR_LED0_ON;	/* 2GHz=>Red. */
3069 		else
3070 			state = AR_LED1_ON;	/* 5GHz=>Blue. */
3071 	} else {
3072 		/* Scanning, blink LED. */
3073 		state ^= AR_LED0_ON | AR_LED1_ON;
3074 		if (IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan))
3075 			state &= ~AR_LED1_ON;
3076 		else
3077 			state &= ~AR_LED0_ON;
3078 	}
3079 	if (state != sc->led_state) {
3080 		otus_write(sc, AR_GPIO_REG_PORT_DATA, state);
3081 		if (otus_write_barrier(sc) == 0)
3082 			sc->led_state = state;
3083 	}
3084 #endif
3085 }
3086 
3087 static uint8_t zero_macaddr[IEEE80211_ADDR_LEN] = { 0,0,0,0,0,0 };
3088 
3089 /*
3090  * Set up operating mode, MAC/BSS address and RX filter.
3091  */
3092 static void
3093 otus_set_operating_mode(struct otus_softc *sc)
3094 {
3095 	struct ieee80211com *ic = &sc->sc_ic;
3096 	struct ieee80211vap *vap;
3097 	uint32_t cam_mode = AR_MAC_CAM_DEFAULTS;
3098 	uint32_t rx_ctrl = AR_MAC_RX_CTRL_DEAGG | AR_MAC_RX_CTRL_SHORT_FILTER;
3099 	uint32_t sniffer = AR_MAC_SNIFFER_DEFAULTS;
3100 	uint32_t enc_mode = 0x78; /* XXX */
3101 	const uint8_t *macaddr;
3102 	uint8_t bssid[IEEE80211_ADDR_LEN];
3103 	struct ieee80211_node *ni;
3104 
3105 	OTUS_LOCK_ASSERT(sc);
3106 
3107 	/*
3108 	 * If we're in sniffer mode or we don't have a MAC
3109 	 * address assigned, ensure it gets reset to all-zero.
3110 	 */
3111 	IEEE80211_ADDR_COPY(bssid, zero_macaddr);
3112 	vap = TAILQ_FIRST(&ic->ic_vaps);
3113 	macaddr = ic->ic_macaddr;
3114 
3115 	switch (ic->ic_opmode) {
3116 	case IEEE80211_M_STA:
3117 		if (vap) {
3118 			ni = ieee80211_ref_node(vap->iv_bss);
3119 			IEEE80211_ADDR_COPY(bssid, ni->ni_bssid);
3120 			ieee80211_free_node(ni);
3121 		}
3122 		cam_mode |= AR_MAC_CAM_STA;
3123 		rx_ctrl |= AR_MAC_RX_CTRL_PASS_TO_HOST;
3124 		break;
3125 	case IEEE80211_M_MONITOR:
3126 		/*
3127 		 * Note: monitor mode ends up causing the MAC to
3128 		 * generate ACK frames for everything it sees.
3129 		 * So don't do that; instead just put it in STA mode
3130 		 * and disable RX filters.
3131 		 */
3132 	default:
3133 		cam_mode |= AR_MAC_CAM_STA;
3134 		rx_ctrl |= AR_MAC_RX_CTRL_PASS_TO_HOST;
3135 		break;
3136 	}
3137 
3138 	/*
3139 	 * TODO: if/when we do hardware encryption, ensure it's
3140 	 * disabled if the NIC is in monitor mode.
3141 	 */
3142 	otus_write(sc, AR_MAC_REG_SNIFFER, sniffer);
3143 	otus_write(sc, AR_MAC_REG_CAM_MODE, cam_mode);
3144 	otus_write(sc, AR_MAC_REG_ENCRYPTION, enc_mode);
3145 	otus_write(sc, AR_MAC_REG_RX_CONTROL, rx_ctrl);
3146 	otus_set_macaddr(sc, macaddr);
3147 	otus_set_bssid(sc, bssid);
3148 	/* XXX barrier? */
3149 }
3150 
3151 static void
3152 otus_set_rx_filter(struct otus_softc *sc)
3153 {
3154 //	struct ieee80211com *ic = &sc->sc_ic;
3155 
3156 	OTUS_LOCK_ASSERT(sc);
3157 
3158 #if 0
3159 	if (ic->ic_allmulti > 0 || ic->ic_promisc > 0 ||
3160 	    ic->ic_opmode == IEEE80211_M_MONITOR) {
3161 		otus_write(sc, AR_MAC_REG_FRAMETYPE_FILTER, 0xff00ffff);
3162 	} else {
3163 #endif
3164 		/* Filter any control frames, BAR is bit 24. */
3165 		otus_write(sc, AR_MAC_REG_FRAMETYPE_FILTER, 0x0500ffff);
3166 #if 0
3167 	}
3168 #endif
3169 }
3170 
3171 int
3172 otus_init(struct otus_softc *sc)
3173 {
3174 	struct ieee80211com *ic = &sc->sc_ic;
3175 	int error;
3176 
3177 	OTUS_UNLOCK_ASSERT(sc);
3178 
3179 	OTUS_LOCK(sc);
3180 
3181 	/* Drain any pending TX frames */
3182 	otus_drain_mbufq(sc);
3183 
3184 	/* Init MAC */
3185 	if ((error = otus_init_mac(sc)) != 0) {
3186 		OTUS_UNLOCK(sc);
3187 		device_printf(sc->sc_dev,
3188 		    "%s: could not initialize MAC\n", __func__);
3189 		return error;
3190 	}
3191 
3192 	otus_set_operating_mode(sc);
3193 	otus_set_rx_filter(sc);
3194 	(void) otus_set_operating_mode(sc);
3195 
3196 	sc->bb_reset = 1;	/* Force cold reset. */
3197 
3198 	if ((error = otus_set_chan(sc, ic->ic_curchan, 0)) != 0) {
3199 		OTUS_UNLOCK(sc);
3200 		device_printf(sc->sc_dev,
3201 		    "%s: could not set channel\n", __func__);
3202 		return error;
3203 	}
3204 
3205 	/* Start Rx. */
3206 	otus_write(sc, AR_MAC_REG_DMA_TRIGGER, 0x100);
3207 	(void)otus_write_barrier(sc);
3208 
3209 	sc->sc_running = 1;
3210 
3211 	OTUS_UNLOCK(sc);
3212 	return 0;
3213 }
3214 
3215 void
3216 otus_stop(struct otus_softc *sc)
3217 {
3218 #if 0
3219 	int s;
3220 #endif
3221 
3222 	OTUS_UNLOCK_ASSERT(sc);
3223 
3224 	OTUS_LOCK(sc);
3225 	sc->sc_running = 0;
3226 	sc->sc_tx_timer = 0;
3227 	OTUS_UNLOCK(sc);
3228 
3229 	taskqueue_drain_timeout(taskqueue_thread, &sc->scan_to);
3230 	taskqueue_drain_timeout(taskqueue_thread, &sc->calib_to);
3231 	taskqueue_drain(taskqueue_thread, &sc->tx_task);
3232 
3233 	OTUS_LOCK(sc);
3234 	sc->sc_running = 0;
3235 	/* Stop Rx. */
3236 	otus_write(sc, AR_MAC_REG_DMA_TRIGGER, 0);
3237 	(void)otus_write_barrier(sc);
3238 
3239 	/* Drain any pending TX frames */
3240 	otus_drain_mbufq(sc);
3241 
3242 	OTUS_UNLOCK(sc);
3243 }
3244