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