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