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