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