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