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