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