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