xref: /openbsd-src/sys/dev/usb/if_athn_usb.c (revision 1a8dbaac879b9f3335ad7fb25429ce63ac1d6bac)
1 /*	$OpenBSD: if_athn_usb.c,v 1.58 2020/07/13 08:31:32 stsp Exp $	*/
2 
3 /*-
4  * Copyright (c) 2011 Damien Bergamini <damien.bergamini@free.fr>
5  * Copyright (c) 2018 Stefan Sperling <stsp@openbsd.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  * USB front-end for Atheros AR9271 and AR7010 chipsets.
22  */
23 
24 #include "bpfilter.h"
25 
26 #include <sys/param.h>
27 #include <sys/sockio.h>
28 #include <sys/mbuf.h>
29 #include <sys/kernel.h>
30 #include <sys/socket.h>
31 #include <sys/systm.h>
32 #include <sys/timeout.h>
33 #include <sys/conf.h>
34 #include <sys/device.h>
35 #include <sys/endian.h>
36 
37 #include <machine/bus.h>
38 #include <machine/intr.h>
39 
40 #if NBPFILTER > 0
41 #include <net/bpf.h>
42 #endif
43 #include <net/if.h>
44 #include <net/if_dl.h>
45 #include <net/if_media.h>
46 
47 #include <netinet/in.h>
48 #include <netinet/if_ether.h>
49 
50 #include <net80211/ieee80211_var.h>
51 #include <net80211/ieee80211_amrr.h>
52 #include <net80211/ieee80211_mira.h>
53 #include <net80211/ieee80211_radiotap.h>
54 
55 #include <dev/ic/athnreg.h>
56 #include <dev/ic/ar5008reg.h>
57 #include <dev/ic/athnvar.h>
58 
59 #include <dev/usb/usb.h>
60 #include <dev/usb/usbdi.h>
61 #include <dev/usb/usbdi_util.h>
62 #include <dev/usb/usbdevs.h>
63 
64 #include <dev/usb/if_athn_usb.h>
65 
66 static const struct athn_usb_type {
67 	struct usb_devno	devno;
68 	u_int			flags;
69 } athn_usb_devs[] = {
70 	{{ USB_VENDOR_ACCTON, USB_PRODUCT_ACCTON_AR9280 },
71 	   ATHN_USB_FLAG_AR7010 },
72 	{{ USB_VENDOR_ACTIONTEC, USB_PRODUCT_ACTIONTEC_AR9287 },
73 	   ATHN_USB_FLAG_AR7010 },
74 	{{ USB_VENDOR_ATHEROS2, USB_PRODUCT_ATHEROS2_AR9271_1 }},
75 	{{ USB_VENDOR_ATHEROS2, USB_PRODUCT_ATHEROS2_AR9271_2 }},
76 	{{ USB_VENDOR_ATHEROS2, USB_PRODUCT_ATHEROS2_AR9271_3 }},
77 	{{ USB_VENDOR_ATHEROS2, USB_PRODUCT_ATHEROS2_AR9280 },
78 	   ATHN_USB_FLAG_AR7010 },
79 	{{ USB_VENDOR_ATHEROS2, USB_PRODUCT_ATHEROS2_AR9287 },
80 	   ATHN_USB_FLAG_AR7010 },
81 	{{ USB_VENDOR_AZUREWAVE, USB_PRODUCT_AZUREWAVE_AR9271_1 }},
82 	{{ USB_VENDOR_AZUREWAVE, USB_PRODUCT_AZUREWAVE_AR9271_2 }},
83 	{{ USB_VENDOR_AZUREWAVE, USB_PRODUCT_AZUREWAVE_AR9271_3 }},
84 	{{ USB_VENDOR_AZUREWAVE, USB_PRODUCT_AZUREWAVE_AR9271_4 }},
85 	{{ USB_VENDOR_AZUREWAVE, USB_PRODUCT_AZUREWAVE_AR9271_5 }},
86 	{{ USB_VENDOR_AZUREWAVE, USB_PRODUCT_AZUREWAVE_AR9271_6 }},
87 	{{ USB_VENDOR_DLINK2, USB_PRODUCT_DLINK2_AR9271 }},
88 	{{ USB_VENDOR_LITEON, USB_PRODUCT_LITEON_AR9271 }},
89 	{{ USB_VENDOR_NETGEAR, USB_PRODUCT_NETGEAR_WNA1100 }},
90 	{{ USB_VENDOR_NETGEAR, USB_PRODUCT_NETGEAR_WNDA3200 },
91 	   ATHN_USB_FLAG_AR7010 },
92 	{{ USB_VENDOR_PANASONIC, USB_PRODUCT_PANASONIC_N5HBZ0000055 },
93 	   ATHN_USB_FLAG_AR7010 },
94 	{{ USB_VENDOR_VIA, USB_PRODUCT_VIA_AR9271 }}
95 };
96 #define athn_usb_lookup(v, p)	\
97 	((const struct athn_usb_type *)usb_lookup(athn_usb_devs, v, p))
98 
99 int		athn_usb_match(struct device *, void *, void *);
100 void		athn_usb_attach(struct device *, struct device *, void *);
101 int		athn_usb_detach(struct device *, int);
102 void		athn_usb_attachhook(struct device *);
103 int		athn_usb_open_pipes(struct athn_usb_softc *);
104 void		athn_usb_close_pipes(struct athn_usb_softc *);
105 int		athn_usb_alloc_rx_list(struct athn_usb_softc *);
106 void		athn_usb_free_rx_list(struct athn_usb_softc *);
107 int		athn_usb_alloc_tx_list(struct athn_usb_softc *);
108 void		athn_usb_free_tx_list(struct athn_usb_softc *);
109 int		athn_usb_alloc_tx_cmd(struct athn_usb_softc *);
110 void		athn_usb_free_tx_cmd(struct athn_usb_softc *);
111 void		athn_usb_task(void *);
112 void		athn_usb_do_async(struct athn_usb_softc *,
113 		    void (*)(struct athn_usb_softc *, void *), void *, int);
114 void		athn_usb_wait_async(struct athn_usb_softc *);
115 int		athn_usb_load_firmware(struct athn_usb_softc *);
116 int		athn_usb_htc_msg(struct athn_usb_softc *, uint16_t, void *,
117 		    int);
118 int		athn_usb_htc_setup(struct athn_usb_softc *);
119 int		athn_usb_htc_connect_svc(struct athn_usb_softc *, uint16_t,
120 		    uint8_t, uint8_t, uint8_t *);
121 int		athn_usb_wmi_xcmd(struct athn_usb_softc *, uint16_t, void *,
122 		    int, void *);
123 int		athn_usb_read_rom(struct athn_softc *);
124 uint32_t	athn_usb_read(struct athn_softc *, uint32_t);
125 void		athn_usb_write(struct athn_softc *, uint32_t, uint32_t);
126 void		athn_usb_write_barrier(struct athn_softc *);
127 int		athn_usb_media_change(struct ifnet *);
128 void		athn_usb_next_scan(void *);
129 int		athn_usb_newstate(struct ieee80211com *, enum ieee80211_state,
130 		    int);
131 void		athn_usb_newstate_cb(struct athn_usb_softc *, void *);
132 void		athn_usb_newassoc(struct ieee80211com *,
133 		    struct ieee80211_node *, int);
134 void		athn_usb_newassoc_cb(struct athn_usb_softc *, void *);
135 struct ieee80211_node *athn_usb_node_alloc(struct ieee80211com *);
136 void		athn_usb_count_active_sta(void *, struct ieee80211_node *);
137 void		athn_usb_newauth_cb(struct athn_usb_softc *, void *);
138 int		athn_usb_newauth(struct ieee80211com *,
139 		    struct ieee80211_node *, int, uint16_t);
140 void		athn_usb_node_free(struct ieee80211com *,
141 		    struct ieee80211_node *);
142 void		athn_usb_node_free_cb(struct athn_usb_softc *, void *);
143 int		athn_usb_ampdu_tx_start(struct ieee80211com *,
144 		    struct ieee80211_node *, uint8_t);
145 void		athn_usb_ampdu_tx_start_cb(struct athn_usb_softc *, void *);
146 void		athn_usb_ampdu_tx_stop(struct ieee80211com *,
147 		    struct ieee80211_node *, uint8_t);
148 void		athn_usb_ampdu_tx_stop_cb(struct athn_usb_softc *, void *);
149 void		athn_usb_clean_nodes(void *, struct ieee80211_node *);
150 int		athn_usb_create_node(struct athn_usb_softc *,
151 		    struct ieee80211_node *);
152 int		athn_usb_node_set_rates(struct athn_usb_softc *,
153 		    struct ieee80211_node *);
154 int		athn_usb_remove_node(struct athn_usb_softc *,
155 		    struct ieee80211_node *);
156 void		athn_usb_rx_enable(struct athn_softc *);
157 int		athn_set_chan(struct athn_softc *, struct ieee80211_channel *,
158 		    struct ieee80211_channel *);
159 int		athn_usb_switch_chan(struct athn_softc *,
160 		    struct ieee80211_channel *, struct ieee80211_channel *);
161 void		athn_usb_updateedca(struct ieee80211com *);
162 void		athn_usb_updateedca_cb(struct athn_usb_softc *, void *);
163 void		athn_usb_updateslot(struct ieee80211com *);
164 void		athn_usb_updateslot_cb(struct athn_usb_softc *, void *);
165 int		athn_usb_set_key(struct ieee80211com *,
166 		    struct ieee80211_node *, struct ieee80211_key *);
167 void		athn_usb_set_key_cb(struct athn_usb_softc *, void *);
168 void		athn_usb_delete_key(struct ieee80211com *,
169 		    struct ieee80211_node *, struct ieee80211_key *);
170 void		athn_usb_delete_key_cb(struct athn_usb_softc *, void *);
171 void		athn_usb_bcneof(struct usbd_xfer *, void *,
172 		    usbd_status);
173 void		athn_usb_swba(struct athn_usb_softc *);
174 void		athn_usb_tx_status(void *, struct ieee80211_node *);
175 void		athn_usb_rx_wmi_ctrl(struct athn_usb_softc *, uint8_t *, int);
176 void		athn_usb_intr(struct usbd_xfer *, void *,
177 		    usbd_status);
178 void		athn_usb_rx_radiotap(struct athn_softc *, struct mbuf *,
179 		    struct ar_rx_status *);
180 void		athn_usb_rx_frame(struct athn_usb_softc *, struct mbuf *,
181 		    struct mbuf_list *);
182 void		athn_usb_rxeof(struct usbd_xfer *, void *,
183 		    usbd_status);
184 void		athn_usb_txeof(struct usbd_xfer *, void *,
185 		    usbd_status);
186 int		athn_usb_tx(struct athn_softc *, struct mbuf *,
187 		    struct ieee80211_node *);
188 void		athn_usb_start(struct ifnet *);
189 void		athn_usb_watchdog(struct ifnet *);
190 int		athn_usb_ioctl(struct ifnet *, u_long, caddr_t);
191 int		athn_usb_init(struct ifnet *);
192 void		athn_usb_stop(struct ifnet *);
193 void		ar9271_load_ani(struct athn_softc *);
194 int		ar5008_ccmp_decap(struct athn_softc *, struct mbuf *,
195 		    struct ieee80211_node *);
196 int		ar5008_ccmp_encap(struct mbuf *, u_int, struct ieee80211_key *);
197 
198 /* Shortcut. */
199 #define athn_usb_wmi_cmd(sc, cmd_id)	\
200 	athn_usb_wmi_xcmd(sc, cmd_id, NULL, 0, NULL)
201 
202 /* Extern functions. */
203 void		athn_led_init(struct athn_softc *);
204 void		athn_set_led(struct athn_softc *, int);
205 void		athn_btcoex_init(struct athn_softc *);
206 void		athn_set_rxfilter(struct athn_softc *, uint32_t);
207 int		athn_reset(struct athn_softc *, int);
208 void		athn_init_pll(struct athn_softc *,
209 		    const struct ieee80211_channel *);
210 int		athn_set_power_awake(struct athn_softc *);
211 void		athn_set_power_sleep(struct athn_softc *);
212 void		athn_reset_key(struct athn_softc *, int);
213 int		athn_set_key(struct ieee80211com *, struct ieee80211_node *,
214 		    struct ieee80211_key *);
215 void		athn_delete_key(struct ieee80211com *, struct ieee80211_node *,
216 		    struct ieee80211_key *);
217 void		athn_rx_start(struct athn_softc *);
218 void		athn_set_sta_timers(struct athn_softc *);
219 void		athn_set_hostap_timers(struct athn_softc *);
220 void		athn_set_opmode(struct athn_softc *);
221 void		athn_set_bss(struct athn_softc *, struct ieee80211_node *);
222 int		athn_hw_reset(struct athn_softc *, struct ieee80211_channel *,
223 		    struct ieee80211_channel *, int);
224 void		athn_updateedca(struct ieee80211com *);
225 void		athn_updateslot(struct ieee80211com *);
226 
227 const struct cfattach athn_usb_ca = {
228 	sizeof(struct athn_usb_softc),
229 	athn_usb_match,
230 	athn_usb_attach,
231 	athn_usb_detach
232 };
233 
234 int
235 athn_usb_match(struct device *parent, void *match, void *aux)
236 {
237 	struct usb_attach_arg *uaa = aux;
238 
239 	if (uaa->iface == NULL || uaa->configno != 1)
240 		return (UMATCH_NONE);
241 
242 	return ((athn_usb_lookup(uaa->vendor, uaa->product) != NULL) ?
243 	    UMATCH_VENDOR_PRODUCT_CONF_IFACE : UMATCH_NONE);
244 }
245 
246 void
247 athn_usb_attach(struct device *parent, struct device *self, void *aux)
248 {
249 	struct athn_usb_softc *usc = (struct athn_usb_softc *)self;
250 	struct athn_softc *sc = &usc->sc_sc;
251 	struct usb_attach_arg *uaa = aux;
252 
253 	usc->sc_udev = uaa->device;
254 	usc->sc_iface = uaa->iface;
255 
256 	usc->flags = athn_usb_lookup(uaa->vendor, uaa->product)->flags;
257 	sc->flags |= ATHN_FLAG_USB;
258 #ifdef notyet
259 	/* Check if it is a combo WiFi+Bluetooth (WB193) device. */
260 	if (strncmp(product, "wb193", 5) == 0)
261 		sc->flags |= ATHN_FLAG_BTCOEX3WIRE;
262 #endif
263 
264 	sc->ops.read = athn_usb_read;
265 	sc->ops.write = athn_usb_write;
266 	sc->ops.write_barrier = athn_usb_write_barrier;
267 
268 	usb_init_task(&usc->sc_task, athn_usb_task, sc, USB_TASK_TYPE_GENERIC);
269 
270 	if (athn_usb_open_pipes(usc) != 0)
271 		return;
272 
273 	/* Allocate xfer for firmware commands. */
274 	if (athn_usb_alloc_tx_cmd(usc) != 0)
275 		return;
276 
277 	config_mountroot(self, athn_usb_attachhook);
278 }
279 
280 int
281 athn_usb_detach(struct device *self, int flags)
282 {
283 	struct athn_usb_softc *usc = (struct athn_usb_softc *)self;
284 	struct athn_softc *sc = &usc->sc_sc;
285 
286 	if (usc->sc_athn_attached)
287 		athn_detach(sc);
288 
289 	/* Wait for all async commands to complete. */
290 	athn_usb_wait_async(usc);
291 
292 	usbd_ref_wait(usc->sc_udev);
293 
294 	/* Abort and close Tx/Rx pipes. */
295 	athn_usb_close_pipes(usc);
296 
297 	/* Free Tx/Rx buffers. */
298 	athn_usb_free_tx_cmd(usc);
299 	athn_usb_free_tx_list(usc);
300 	athn_usb_free_rx_list(usc);
301 
302 	return (0);
303 }
304 
305 void
306 athn_usb_attachhook(struct device *self)
307 {
308 	struct athn_usb_softc *usc = (struct athn_usb_softc *)self;
309 	struct athn_softc *sc = &usc->sc_sc;
310 	struct athn_ops *ops = &sc->ops;
311 	struct ieee80211com *ic = &sc->sc_ic;
312 	struct ifnet *ifp = &ic->ic_if;
313 	int s, i, error;
314 
315 	/* Load firmware. */
316 	error = athn_usb_load_firmware(usc);
317 	if (error != 0) {
318 		printf("%s: could not load firmware\n", sc->sc_dev.dv_xname);
319 		return;
320 	}
321 
322 	/* Setup the host transport communication interface. */
323 	error = athn_usb_htc_setup(usc);
324 	if (error != 0)
325 		return;
326 
327 	/* We're now ready to attach the bus agnostic driver. */
328 	s = splnet();
329 	error = athn_attach(sc);
330 	if (error != 0) {
331 		splx(s);
332 		return;
333 	}
334 	usc->sc_athn_attached = 1;
335 	/* Override some operations for USB. */
336 	ifp->if_ioctl = athn_usb_ioctl;
337 	ifp->if_start = athn_usb_start;
338 	ifp->if_watchdog = athn_usb_watchdog;
339 	ic->ic_node_alloc = athn_usb_node_alloc;
340 	ic->ic_newauth = athn_usb_newauth;
341 	ic->ic_newassoc = athn_usb_newassoc;
342 #ifndef IEEE80211_STA_ONLY
343 	usc->sc_node_free = ic->ic_node_free;
344 	ic->ic_node_free = athn_usb_node_free;
345 #endif
346 	ic->ic_updateslot = athn_usb_updateslot;
347 	ic->ic_updateedca = athn_usb_updateedca;
348 	ic->ic_set_key = athn_usb_set_key;
349 	ic->ic_delete_key = athn_usb_delete_key;
350 #ifdef notyet
351 	ic->ic_ampdu_tx_start = athn_usb_ampdu_tx_start;
352 	ic->ic_ampdu_tx_stop = athn_usb_ampdu_tx_stop;
353 #endif
354 	ic->ic_newstate = athn_usb_newstate;
355 	ic->ic_media.ifm_change = athn_usb_media_change;
356 	timeout_set(&sc->scan_to, athn_usb_next_scan, usc);
357 
358 	ops->rx_enable = athn_usb_rx_enable;
359 	splx(s);
360 
361 	/* Reset HW key cache entries. */
362 	for (i = 0; i < sc->kc_entries; i++)
363 		athn_reset_key(sc, i);
364 
365 	ops->enable_antenna_diversity(sc);
366 
367 #ifdef ATHN_BT_COEXISTENCE
368 	/* Configure bluetooth coexistence for combo chips. */
369 	if (sc->flags & ATHN_FLAG_BTCOEX)
370 		athn_btcoex_init(sc);
371 #endif
372 	/* Configure LED. */
373 	athn_led_init(sc);
374 }
375 
376 int
377 athn_usb_open_pipes(struct athn_usb_softc *usc)
378 {
379 	usb_endpoint_descriptor_t *ed;
380 	int isize, error;
381 
382 	error = usbd_open_pipe(usc->sc_iface, AR_PIPE_TX_DATA, 0,
383 	    &usc->tx_data_pipe);
384 	if (error != 0) {
385 		printf("%s: could not open Tx bulk pipe\n",
386 		    usc->usb_dev.dv_xname);
387 		goto fail;
388 	}
389 
390 	error = usbd_open_pipe(usc->sc_iface, AR_PIPE_RX_DATA, 0,
391 	    &usc->rx_data_pipe);
392 	if (error != 0) {
393 		printf("%s: could not open Rx bulk pipe\n",
394 		    usc->usb_dev.dv_xname);
395 		goto fail;
396 	}
397 
398 	ed = usbd_get_endpoint_descriptor(usc->sc_iface, AR_PIPE_RX_INTR);
399 	if (ed == NULL) {
400 		printf("%s: could not retrieve Rx intr pipe descriptor\n",
401 		    usc->usb_dev.dv_xname);
402 		goto fail;
403 	}
404 	isize = UGETW(ed->wMaxPacketSize);
405 	if (isize == 0) {
406 		printf("%s: invalid Rx intr pipe descriptor\n",
407 		    usc->usb_dev.dv_xname);
408 		goto fail;
409 	}
410 	usc->ibuf = malloc(isize, M_USBDEV, M_NOWAIT);
411 	if (usc->ibuf == NULL) {
412 		printf("%s: could not allocate Rx intr buffer\n",
413 		    usc->usb_dev.dv_xname);
414 		goto fail;
415 	}
416 	usc->ibuflen = isize;
417 	error = usbd_open_pipe_intr(usc->sc_iface, AR_PIPE_RX_INTR,
418 	    USBD_SHORT_XFER_OK, &usc->rx_intr_pipe, usc, usc->ibuf, isize,
419 	    athn_usb_intr, USBD_DEFAULT_INTERVAL);
420 	if (error != 0) {
421 		printf("%s: could not open Rx intr pipe\n",
422 		    usc->usb_dev.dv_xname);
423 		goto fail;
424 	}
425 
426 	error = usbd_open_pipe(usc->sc_iface, AR_PIPE_TX_INTR, 0,
427 	    &usc->tx_intr_pipe);
428 	if (error != 0) {
429 		printf("%s: could not open Tx intr pipe\n",
430 		    usc->usb_dev.dv_xname);
431 		goto fail;
432 	}
433  fail:
434 	if (error != 0)
435 		athn_usb_close_pipes(usc);
436 	return (error);
437 }
438 
439 void
440 athn_usb_close_pipes(struct athn_usb_softc *usc)
441 {
442 	if (usc->tx_data_pipe != NULL) {
443 		usbd_close_pipe(usc->tx_data_pipe);
444 		usc->tx_data_pipe = NULL;
445 	}
446 	if (usc->rx_data_pipe != NULL) {
447 		usbd_close_pipe(usc->rx_data_pipe);
448 		usc->rx_data_pipe = NULL;
449 	}
450 	if (usc->tx_intr_pipe != NULL) {
451 		usbd_close_pipe(usc->tx_intr_pipe);
452 		usc->tx_intr_pipe = NULL;
453 	}
454 	if (usc->rx_intr_pipe != NULL) {
455 		usbd_close_pipe(usc->rx_intr_pipe);
456 		usc->rx_intr_pipe = NULL;
457 	}
458 	if (usc->ibuf != NULL) {
459 		free(usc->ibuf, M_USBDEV, usc->ibuflen);
460 		usc->ibuf = NULL;
461 	}
462 }
463 
464 int
465 athn_usb_alloc_rx_list(struct athn_usb_softc *usc)
466 {
467 	struct athn_usb_rx_data *data;
468 	int i, error = 0;
469 
470 	for (i = 0; i < ATHN_USB_RX_LIST_COUNT; i++) {
471 		data = &usc->rx_data[i];
472 
473 		data->sc = usc;	/* Backpointer for callbacks. */
474 
475 		data->xfer = usbd_alloc_xfer(usc->sc_udev);
476 		if (data->xfer == NULL) {
477 			printf("%s: could not allocate xfer\n",
478 			    usc->usb_dev.dv_xname);
479 			error = ENOMEM;
480 			break;
481 		}
482 		data->buf = usbd_alloc_buffer(data->xfer, ATHN_USB_RXBUFSZ);
483 		if (data->buf == NULL) {
484 			printf("%s: could not allocate xfer buffer\n",
485 			    usc->usb_dev.dv_xname);
486 			error = ENOMEM;
487 			break;
488 		}
489 	}
490 	if (error != 0)
491 		athn_usb_free_rx_list(usc);
492 	return (error);
493 }
494 
495 void
496 athn_usb_free_rx_list(struct athn_usb_softc *usc)
497 {
498 	int i;
499 
500 	/* NB: Caller must abort pipe first. */
501 	for (i = 0; i < ATHN_USB_RX_LIST_COUNT; i++) {
502 		if (usc->rx_data[i].xfer != NULL)
503 			usbd_free_xfer(usc->rx_data[i].xfer);
504 		usc->rx_data[i].xfer = NULL;
505 	}
506 }
507 
508 int
509 athn_usb_alloc_tx_list(struct athn_usb_softc *usc)
510 {
511 	struct athn_usb_tx_data *data;
512 	int i, error = 0;
513 
514 	TAILQ_INIT(&usc->tx_free_list);
515 	for (i = 0; i < ATHN_USB_TX_LIST_COUNT; i++) {
516 		data = &usc->tx_data[i];
517 
518 		data->sc = usc;	/* Backpointer for callbacks. */
519 
520 		data->xfer = usbd_alloc_xfer(usc->sc_udev);
521 		if (data->xfer == NULL) {
522 			printf("%s: could not allocate xfer\n",
523 			    usc->usb_dev.dv_xname);
524 			error = ENOMEM;
525 			break;
526 		}
527 		data->buf = usbd_alloc_buffer(data->xfer, ATHN_USB_TXBUFSZ);
528 		if (data->buf == NULL) {
529 			printf("%s: could not allocate xfer buffer\n",
530 			    usc->usb_dev.dv_xname);
531 			error = ENOMEM;
532 			break;
533 		}
534 		/* Append this Tx buffer to our free list. */
535 		TAILQ_INSERT_TAIL(&usc->tx_free_list, data, next);
536 	}
537 	if (error != 0)
538 		athn_usb_free_tx_list(usc);
539 	return (error);
540 }
541 
542 void
543 athn_usb_free_tx_list(struct athn_usb_softc *usc)
544 {
545 	int i;
546 
547 	/* NB: Caller must abort pipe first. */
548 	for (i = 0; i < ATHN_USB_TX_LIST_COUNT; i++) {
549 		if (usc->tx_data[i].xfer != NULL)
550 			usbd_free_xfer(usc->tx_data[i].xfer);
551 		usc->tx_data[i].xfer = NULL;
552 	}
553 }
554 
555 int
556 athn_usb_alloc_tx_cmd(struct athn_usb_softc *usc)
557 {
558 	struct athn_usb_tx_data *data = &usc->tx_cmd;
559 
560 	data->sc = usc;	/* Backpointer for callbacks. */
561 
562 	data->xfer = usbd_alloc_xfer(usc->sc_udev);
563 	if (data->xfer == NULL) {
564 		printf("%s: could not allocate xfer\n",
565 		    usc->usb_dev.dv_xname);
566 		return (ENOMEM);
567 	}
568 	data->buf = usbd_alloc_buffer(data->xfer, ATHN_USB_TXCMDSZ);
569 	if (data->buf == NULL) {
570 		printf("%s: could not allocate xfer buffer\n",
571 		    usc->usb_dev.dv_xname);
572 		return (ENOMEM);
573 	}
574 	return (0);
575 }
576 
577 void
578 athn_usb_free_tx_cmd(struct athn_usb_softc *usc)
579 {
580 	if (usc->tx_cmd.xfer != NULL)
581 		usbd_free_xfer(usc->tx_cmd.xfer);
582 	usc->tx_cmd.xfer = NULL;
583 }
584 
585 void
586 athn_usb_task(void *arg)
587 {
588 	struct athn_usb_softc *usc = arg;
589 	struct athn_usb_host_cmd_ring *ring = &usc->cmdq;
590 	struct athn_usb_host_cmd *cmd;
591 	int s;
592 
593 	/* Process host commands. */
594 	s = splusb();
595 	while (ring->next != ring->cur) {
596 		cmd = &ring->cmd[ring->next];
597 		splx(s);
598 		/* Invoke callback. */
599 		cmd->cb(usc, cmd->data);
600 		s = splusb();
601 		ring->queued--;
602 		ring->next = (ring->next + 1) % ATHN_USB_HOST_CMD_RING_COUNT;
603 	}
604 	splx(s);
605 }
606 
607 void
608 athn_usb_do_async(struct athn_usb_softc *usc,
609     void (*cb)(struct athn_usb_softc *, void *), void *arg, int len)
610 {
611 	struct athn_usb_host_cmd_ring *ring = &usc->cmdq;
612 	struct athn_usb_host_cmd *cmd;
613 	int s;
614 
615 	if (ring->queued == ATHN_USB_HOST_CMD_RING_COUNT) {
616 		printf("%s: host cmd queue overrun\n", usc->usb_dev.dv_xname);
617 		return;	/* XXX */
618 	}
619 
620 	s = splusb();
621 	cmd = &ring->cmd[ring->cur];
622 	cmd->cb = cb;
623 	KASSERT(len <= sizeof(cmd->data));
624 	memcpy(cmd->data, arg, len);
625 	ring->cur = (ring->cur + 1) % ATHN_USB_HOST_CMD_RING_COUNT;
626 
627 	/* If there is no pending command already, schedule a task. */
628 	if (++ring->queued == 1)
629 		usb_add_task(usc->sc_udev, &usc->sc_task);
630 	splx(s);
631 }
632 
633 void
634 athn_usb_wait_async(struct athn_usb_softc *usc)
635 {
636 	/* Wait for all queued asynchronous commands to complete. */
637 	usb_wait_task(usc->sc_udev, &usc->sc_task);
638 }
639 
640 int
641 athn_usb_load_firmware(struct athn_usb_softc *usc)
642 {
643 	usb_device_descriptor_t *dd;
644 	usb_device_request_t req;
645 	const char *name;
646 	u_char *fw, *ptr;
647 	size_t fwsize, size;
648 	uint32_t addr;
649 	int s, mlen, error;
650 
651 	/* Determine which firmware image to load. */
652 	if (usc->flags & ATHN_USB_FLAG_AR7010) {
653 		dd = usbd_get_device_descriptor(usc->sc_udev);
654 		name = "athn-open-ar7010";
655 	} else
656 		name = "athn-open-ar9271";
657 	/* Read firmware image from the filesystem. */
658 	if ((error = loadfirmware(name, &fw, &fwsize)) != 0) {
659 		printf("%s: failed loadfirmware of file %s (error %d)\n",
660 		    usc->usb_dev.dv_xname, name, error);
661 		return (error);
662 	}
663 	/* Load firmware image. */
664 	ptr = fw;
665 	addr = AR9271_FIRMWARE >> 8;
666 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
667 	req.bRequest = AR_FW_DOWNLOAD;
668 	USETW(req.wIndex, 0);
669 	size = fwsize;
670 	while (size > 0) {
671 		mlen = MIN(size, 4096);
672 
673 		USETW(req.wValue, addr);
674 		USETW(req.wLength, mlen);
675 		error = usbd_do_request(usc->sc_udev, &req, ptr);
676 		if (error != 0) {
677 			free(fw, M_DEVBUF, fwsize);
678 			return (error);
679 		}
680 		addr += mlen >> 8;
681 		ptr  += mlen;
682 		size -= mlen;
683 	}
684 	free(fw, M_DEVBUF, fwsize);
685 
686 	/* Start firmware. */
687 	if (usc->flags & ATHN_USB_FLAG_AR7010)
688 		addr = AR7010_FIRMWARE_TEXT >> 8;
689 	else
690 		addr = AR9271_FIRMWARE_TEXT >> 8;
691 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
692 	req.bRequest = AR_FW_DOWNLOAD_COMP;
693 	USETW(req.wIndex, 0);
694 	USETW(req.wValue, addr);
695 	USETW(req.wLength, 0);
696 	s = splusb();
697 	usc->wait_msg_id = AR_HTC_MSG_READY;
698 	error = usbd_do_request(usc->sc_udev, &req, NULL);
699 	/* Wait at most 1 second for firmware to boot. */
700 	if (error == 0 && usc->wait_msg_id != 0)
701 		error = tsleep_nsec(&usc->wait_msg_id, 0, "athnfw",
702 		    SEC_TO_NSEC(1));
703 	usc->wait_msg_id = 0;
704 	splx(s);
705 	return (error);
706 }
707 
708 int
709 athn_usb_htc_msg(struct athn_usb_softc *usc, uint16_t msg_id, void *buf,
710     int len)
711 {
712 	struct athn_usb_tx_data *data = &usc->tx_cmd;
713 	struct ar_htc_frame_hdr *htc;
714 	struct ar_htc_msg_hdr *msg;
715 
716 	htc = (struct ar_htc_frame_hdr *)data->buf;
717 	memset(htc, 0, sizeof(*htc));
718 	htc->endpoint_id = 0;
719 	htc->payload_len = htobe16(sizeof(*msg) + len);
720 
721 	msg = (struct ar_htc_msg_hdr *)&htc[1];
722 	msg->msg_id = htobe16(msg_id);
723 
724 	memcpy(&msg[1], buf, len);
725 
726 	usbd_setup_xfer(data->xfer, usc->tx_intr_pipe, NULL, data->buf,
727 	    sizeof(*htc) + sizeof(*msg) + len,
728 	    USBD_SHORT_XFER_OK | USBD_NO_COPY | USBD_SYNCHRONOUS,
729 	    ATHN_USB_CMD_TIMEOUT, NULL);
730 	return (usbd_transfer(data->xfer));
731 }
732 
733 int
734 athn_usb_htc_setup(struct athn_usb_softc *usc)
735 {
736 	struct ar_htc_msg_config_pipe cfg;
737 	int s, error;
738 
739 	/*
740 	 * Connect WMI services to USB pipes.
741 	 */
742 	error = athn_usb_htc_connect_svc(usc, AR_SVC_WMI_CONTROL,
743 	    AR_PIPE_TX_INTR, AR_PIPE_RX_INTR, &usc->ep_ctrl);
744 	if (error != 0)
745 		return (error);
746 	error = athn_usb_htc_connect_svc(usc, AR_SVC_WMI_BEACON,
747 	    AR_PIPE_TX_DATA, AR_PIPE_RX_DATA, &usc->ep_bcn);
748 	if (error != 0)
749 		return (error);
750 	error = athn_usb_htc_connect_svc(usc, AR_SVC_WMI_CAB,
751 	    AR_PIPE_TX_DATA, AR_PIPE_RX_DATA, &usc->ep_cab);
752 	if (error != 0)
753 		return (error);
754 	error = athn_usb_htc_connect_svc(usc, AR_SVC_WMI_UAPSD,
755 	    AR_PIPE_TX_DATA, AR_PIPE_RX_DATA, &usc->ep_uapsd);
756 	if (error != 0)
757 		return (error);
758 	error = athn_usb_htc_connect_svc(usc, AR_SVC_WMI_MGMT,
759 	    AR_PIPE_TX_DATA, AR_PIPE_RX_DATA, &usc->ep_mgmt);
760 	if (error != 0)
761 		return (error);
762 	error = athn_usb_htc_connect_svc(usc, AR_SVC_WMI_DATA_BE,
763 	    AR_PIPE_TX_DATA, AR_PIPE_RX_DATA, &usc->ep_data[EDCA_AC_BE]);
764 	if (error != 0)
765 		return (error);
766 	error = athn_usb_htc_connect_svc(usc, AR_SVC_WMI_DATA_BK,
767 	    AR_PIPE_TX_DATA, AR_PIPE_RX_DATA, &usc->ep_data[EDCA_AC_BK]);
768 	if (error != 0)
769 		return (error);
770 	error = athn_usb_htc_connect_svc(usc, AR_SVC_WMI_DATA_VI,
771 	    AR_PIPE_TX_DATA, AR_PIPE_RX_DATA, &usc->ep_data[EDCA_AC_VI]);
772 	if (error != 0)
773 		return (error);
774 	error = athn_usb_htc_connect_svc(usc, AR_SVC_WMI_DATA_VO,
775 	    AR_PIPE_TX_DATA, AR_PIPE_RX_DATA, &usc->ep_data[EDCA_AC_VO]);
776 	if (error != 0)
777 		return (error);
778 
779 	/* Set credits for WLAN Tx pipe. */
780 	memset(&cfg, 0, sizeof(cfg));
781 	cfg.pipe_id = UE_GET_ADDR(AR_PIPE_TX_DATA);
782 	cfg.credits = (usc->flags & ATHN_USB_FLAG_AR7010) ? 45 : 33;
783 	s = splusb();
784 	usc->wait_msg_id = AR_HTC_MSG_CONF_PIPE_RSP;
785 	error = athn_usb_htc_msg(usc, AR_HTC_MSG_CONF_PIPE, &cfg, sizeof(cfg));
786 	if (error == 0 && usc->wait_msg_id != 0)
787 		error = tsleep_nsec(&usc->wait_msg_id, 0, "athnhtc",
788 		    SEC_TO_NSEC(1));
789 	usc->wait_msg_id = 0;
790 	splx(s);
791 	if (error != 0) {
792 		printf("%s: could not configure pipe\n",
793 		    usc->usb_dev.dv_xname);
794 		return (error);
795 	}
796 
797 	error = athn_usb_htc_msg(usc, AR_HTC_MSG_SETUP_COMPLETE, NULL, 0);
798 	if (error != 0) {
799 		printf("%s: could not complete setup\n",
800 		    usc->usb_dev.dv_xname);
801 		return (error);
802 	}
803 	return (0);
804 }
805 
806 int
807 athn_usb_htc_connect_svc(struct athn_usb_softc *usc, uint16_t svc_id,
808     uint8_t ul_pipe, uint8_t dl_pipe, uint8_t *endpoint_id)
809 {
810 	struct ar_htc_msg_conn_svc msg;
811 	struct ar_htc_msg_conn_svc_rsp rsp;
812 	int s, error;
813 
814 	memset(&msg, 0, sizeof(msg));
815 	msg.svc_id = htobe16(svc_id);
816 	msg.dl_pipeid = UE_GET_ADDR(dl_pipe);
817 	msg.ul_pipeid = UE_GET_ADDR(ul_pipe);
818 	s = splusb();
819 	usc->msg_conn_svc_rsp = &rsp;
820 	usc->wait_msg_id = AR_HTC_MSG_CONN_SVC_RSP;
821 	error = athn_usb_htc_msg(usc, AR_HTC_MSG_CONN_SVC, &msg, sizeof(msg));
822 	/* Wait at most 1 second for response. */
823 	if (error == 0 && usc->wait_msg_id != 0)
824 		error = tsleep_nsec(&usc->wait_msg_id, 0, "athnhtc",
825 		    SEC_TO_NSEC(1));
826 	usc->wait_msg_id = 0;
827 	splx(s);
828 	if (error != 0) {
829 		printf("%s: error waiting for service %d connection\n",
830 		    usc->usb_dev.dv_xname, svc_id);
831 		return (error);
832 	}
833 	if (rsp.status != AR_HTC_SVC_SUCCESS) {
834 		printf("%s: service %d connection failed, error %d\n",
835 		    usc->usb_dev.dv_xname, svc_id, rsp.status);
836 		return (EIO);
837 	}
838 	DPRINTF(("service %d successfully connected to endpoint %d\n",
839 	    svc_id, rsp.endpoint_id));
840 
841 	/* Return endpoint id. */
842 	*endpoint_id = rsp.endpoint_id;
843 	return (0);
844 }
845 
846 int
847 athn_usb_wmi_xcmd(struct athn_usb_softc *usc, uint16_t cmd_id, void *ibuf,
848     int ilen, void *obuf)
849 {
850 	struct athn_usb_tx_data *data = &usc->tx_cmd;
851 	struct ar_htc_frame_hdr *htc;
852 	struct ar_wmi_cmd_hdr *wmi;
853 	int s, error;
854 
855 	if (usbd_is_dying(usc->sc_udev))
856 		return ENXIO;
857 
858 	s = splusb();
859 	while (usc->wait_cmd_id) {
860 		/*
861 		 * The previous USB transfer is not done yet. We can't use
862 		 * data->xfer until it is done or we'll cause major confusion
863 		 * in the USB stack.
864 		 */
865 		tsleep_nsec(&usc->wait_cmd_id, 0, "athnwmx",
866 		    MSEC_TO_NSEC(ATHN_USB_CMD_TIMEOUT));
867 		if (usbd_is_dying(usc->sc_udev)) {
868 			splx(s);
869 			return ENXIO;
870 		}
871 	}
872 	splx(s);
873 
874 	htc = (struct ar_htc_frame_hdr *)data->buf;
875 	memset(htc, 0, sizeof(*htc));
876 	htc->endpoint_id = usc->ep_ctrl;
877 	htc->payload_len = htobe16(sizeof(*wmi) + ilen);
878 
879 	wmi = (struct ar_wmi_cmd_hdr *)&htc[1];
880 	wmi->cmd_id = htobe16(cmd_id);
881 	usc->wmi_seq_no++;
882 	wmi->seq_no = htobe16(usc->wmi_seq_no);
883 
884 	memcpy(&wmi[1], ibuf, ilen);
885 
886 	usbd_setup_xfer(data->xfer, usc->tx_intr_pipe, NULL, data->buf,
887 	    sizeof(*htc) + sizeof(*wmi) + ilen,
888 	    USBD_SHORT_XFER_OK | USBD_NO_COPY, ATHN_USB_CMD_TIMEOUT,
889 	    NULL);
890 	s = splusb();
891 	error = usbd_transfer(data->xfer);
892 	if (__predict_false(error != USBD_IN_PROGRESS && error != 0)) {
893 		splx(s);
894 		return (error);
895 	}
896 	usc->obuf = obuf;
897 	usc->wait_cmd_id = cmd_id;
898 	/*
899 	 * Wait for WMI command complete interrupt. In case it does not fire
900 	 * wait until the USB transfer times out to avoid racing the transfer.
901 	 */
902 	error = tsleep_nsec(&usc->wait_cmd_id, 0, "athnwmi",
903 	    MSEC_TO_NSEC(ATHN_USB_CMD_TIMEOUT));
904 	if (error) {
905 		if (error == EWOULDBLOCK) {
906 			printf("%s: firmware command 0x%x timed out\n",
907 			    usc->usb_dev.dv_xname, cmd_id);
908 			error = ETIMEDOUT;
909 		}
910 	}
911 
912 	/*
913 	 * Both the WMI command and transfer are done or have timed out.
914 	 * Allow other threads to enter this function and use data->xfer.
915 	 */
916 	usc->wait_cmd_id = 0;
917 	wakeup(&usc->wait_cmd_id);
918 
919 	splx(s);
920 	return (error);
921 }
922 
923 int
924 athn_usb_read_rom(struct athn_softc *sc)
925 {
926 	struct athn_usb_softc *usc = (struct athn_usb_softc *)sc;
927 	uint32_t addrs[8], vals[8], addr;
928 	uint16_t *eep;
929 	int i, j, error;
930 
931 	/* Read EEPROM by blocks of 16 bytes. */
932 	eep = sc->eep;
933 	addr = AR_EEPROM_OFFSET(sc->eep_base);
934 	for (i = 0; i < sc->eep_size / 16; i++) {
935 		for (j = 0; j < 8; j++, addr += 4)
936 			addrs[j] = htobe32(addr);
937 		error = athn_usb_wmi_xcmd(usc, AR_WMI_CMD_REG_READ,
938 		    addrs, sizeof(addrs), vals);
939 		if (error != 0)
940 			break;
941 		for (j = 0; j < 8; j++)
942 			*eep++ = betoh32(vals[j]);
943 	}
944 	return (error);
945 }
946 
947 uint32_t
948 athn_usb_read(struct athn_softc *sc, uint32_t addr)
949 {
950 	struct athn_usb_softc *usc = (struct athn_usb_softc *)sc;
951 	uint32_t val;
952 	int error;
953 
954 	/* Flush pending writes for strict consistency. */
955 	athn_usb_write_barrier(sc);
956 
957 	addr = htobe32(addr);
958 	error = athn_usb_wmi_xcmd(usc, AR_WMI_CMD_REG_READ,
959 	    &addr, sizeof(addr), &val);
960 	if (error != 0)
961 		return (0xdeadbeef);
962 	return (betoh32(val));
963 }
964 
965 void
966 athn_usb_write(struct athn_softc *sc, uint32_t addr, uint32_t val)
967 {
968 	struct athn_usb_softc *usc = (struct athn_usb_softc *)sc;
969 
970 	usc->wbuf[usc->wcount].addr = htobe32(addr);
971 	usc->wbuf[usc->wcount].val  = htobe32(val);
972 	if (++usc->wcount == AR_MAX_WRITE_COUNT)
973 		athn_usb_write_barrier(sc);
974 }
975 
976 void
977 athn_usb_write_barrier(struct athn_softc *sc)
978 {
979 	struct athn_usb_softc *usc = (struct athn_usb_softc *)sc;
980 
981 	if (usc->wcount == 0)
982 		return;	/* Nothing to write. */
983 
984 	(void)athn_usb_wmi_xcmd(usc, AR_WMI_CMD_REG_WRITE,
985 	    usc->wbuf, usc->wcount * sizeof(usc->wbuf[0]), NULL);
986 	usc->wcount = 0;	/* Always flush buffer. */
987 }
988 
989 int
990 athn_usb_media_change(struct ifnet *ifp)
991 {
992 	struct athn_usb_softc *usc = (struct athn_usb_softc *)ifp->if_softc;
993 	int error;
994 
995 	if (usbd_is_dying(usc->sc_udev))
996 		return ENXIO;
997 
998 	error = ieee80211_media_change(ifp);
999 	if (error != ENETRESET)
1000 		return (error);
1001 
1002 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
1003 	    (IFF_UP | IFF_RUNNING)) {
1004 		athn_usb_stop(ifp);
1005 		error = athn_usb_init(ifp);
1006 	}
1007 	return (error);
1008 }
1009 
1010 void
1011 athn_usb_next_scan(void *arg)
1012 {
1013 	struct athn_usb_softc *usc = arg;
1014 	struct athn_softc *sc = &usc->sc_sc;
1015 	struct ieee80211com *ic = &sc->sc_ic;
1016 	int s;
1017 
1018 	if (usbd_is_dying(usc->sc_udev))
1019 		return;
1020 
1021 	usbd_ref_incr(usc->sc_udev);
1022 
1023 	s = splnet();
1024 	if (ic->ic_state == IEEE80211_S_SCAN)
1025 		ieee80211_next_scan(&ic->ic_if);
1026 	splx(s);
1027 
1028 	usbd_ref_decr(usc->sc_udev);
1029 }
1030 
1031 int
1032 athn_usb_newstate(struct ieee80211com *ic, enum ieee80211_state nstate,
1033     int arg)
1034 {
1035 	struct athn_usb_softc *usc = ic->ic_softc;
1036 	struct athn_usb_cmd_newstate cmd;
1037 
1038 	/* Do it in a process context. */
1039 	cmd.state = nstate;
1040 	cmd.arg = arg;
1041 	athn_usb_do_async(usc, athn_usb_newstate_cb, &cmd, sizeof(cmd));
1042 	return (0);
1043 }
1044 
1045 void
1046 athn_usb_newstate_cb(struct athn_usb_softc *usc, void *arg)
1047 {
1048 	struct athn_usb_cmd_newstate *cmd = arg;
1049 	struct athn_softc *sc = &usc->sc_sc;
1050 	struct ieee80211com *ic = &sc->sc_ic;
1051 	enum ieee80211_state ostate;
1052 	uint32_t reg, imask;
1053 	int s, error;
1054 
1055 	timeout_del(&sc->calib_to);
1056 
1057 	s = splnet();
1058 	ostate = ic->ic_state;
1059 
1060 	if (ostate == IEEE80211_S_RUN && ic->ic_opmode == IEEE80211_M_STA) {
1061 		athn_usb_remove_node(usc, ic->ic_bss);
1062 		reg = AR_READ(sc, AR_RX_FILTER);
1063 		reg = (reg & ~AR_RX_FILTER_MYBEACON) |
1064 		    AR_RX_FILTER_BEACON;
1065 		AR_WRITE(sc, AR_RX_FILTER, reg);
1066 		AR_WRITE_BARRIER(sc);
1067 	}
1068 	switch (cmd->state) {
1069 	case IEEE80211_S_INIT:
1070 		athn_set_led(sc, 0);
1071 		break;
1072 	case IEEE80211_S_SCAN:
1073 		/* Make the LED blink while scanning. */
1074 		athn_set_led(sc, !sc->led_state);
1075 		error = athn_usb_switch_chan(sc, ic->ic_bss->ni_chan, NULL);
1076 		if (error)
1077 			printf("%s: could not switch to channel %d\n",
1078 			    usc->usb_dev.dv_xname,
1079 			    ieee80211_chan2ieee(ic, ic->ic_bss->ni_chan));
1080 		if (!usbd_is_dying(usc->sc_udev))
1081 			timeout_add_msec(&sc->scan_to, 200);
1082 		break;
1083 	case IEEE80211_S_AUTH:
1084 		athn_set_led(sc, 0);
1085 		error = athn_usb_switch_chan(sc, ic->ic_bss->ni_chan, NULL);
1086 		if (error)
1087 			printf("%s: could not switch to channel %d\n",
1088 			    usc->usb_dev.dv_xname,
1089 			    ieee80211_chan2ieee(ic, ic->ic_bss->ni_chan));
1090 		break;
1091 	case IEEE80211_S_ASSOC:
1092 		break;
1093 	case IEEE80211_S_RUN:
1094 		athn_set_led(sc, 1);
1095 
1096 		if (ic->ic_opmode == IEEE80211_M_MONITOR)
1097 			break;
1098 
1099 		if (ic->ic_opmode == IEEE80211_M_STA) {
1100 			/* Create node entry for our BSS */
1101 			error = athn_usb_create_node(usc, ic->ic_bss);
1102 			if (error)
1103 				printf("%s: could not update firmware station "
1104 				    "table\n", usc->usb_dev.dv_xname);
1105 		}
1106 		athn_set_bss(sc, ic->ic_bss);
1107 		athn_usb_wmi_cmd(usc, AR_WMI_CMD_DISABLE_INTR);
1108 #ifndef IEEE80211_STA_ONLY
1109 		if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
1110 			athn_usb_switch_chan(sc, ic->ic_bss->ni_chan, NULL);
1111 			athn_set_hostap_timers(sc);
1112 			/* Enable software beacon alert interrupts. */
1113 			imask = htobe32(AR_IMR_SWBA);
1114 		} else
1115 #endif
1116 		{
1117 			athn_set_sta_timers(sc);
1118 			/* Enable beacon miss interrupts. */
1119 			imask = htobe32(AR_IMR_BMISS);
1120 
1121 			/* Stop receiving beacons from other BSS. */
1122 			reg = AR_READ(sc, AR_RX_FILTER);
1123 			reg = (reg & ~AR_RX_FILTER_BEACON) |
1124 			    AR_RX_FILTER_MYBEACON;
1125 			AR_WRITE(sc, AR_RX_FILTER, reg);
1126 			AR_WRITE_BARRIER(sc);
1127 		}
1128 		athn_usb_wmi_xcmd(usc, AR_WMI_CMD_ENABLE_INTR,
1129 		    &imask, sizeof(imask), NULL);
1130 		break;
1131 	}
1132 	(void)sc->sc_newstate(ic, cmd->state, cmd->arg);
1133 	splx(s);
1134 }
1135 
1136 void
1137 athn_usb_newassoc(struct ieee80211com *ic, struct ieee80211_node *ni,
1138     int isnew)
1139 {
1140 #ifndef IEEE80211_STA_ONLY
1141 	struct athn_usb_softc *usc = ic->ic_softc;
1142 
1143 	if (ic->ic_opmode != IEEE80211_M_HOSTAP &&
1144 	    ic->ic_state != IEEE80211_S_RUN)
1145 		return;
1146 
1147 	/* Update the node's supported rates in a process context. */
1148 	ieee80211_ref_node(ni);
1149 	athn_usb_do_async(usc, athn_usb_newassoc_cb, &ni, sizeof(ni));
1150 #endif
1151 }
1152 
1153 #ifndef IEEE80211_STA_ONLY
1154 void
1155 athn_usb_newassoc_cb(struct athn_usb_softc *usc, void *arg)
1156 {
1157 	struct ieee80211com *ic = &usc->sc_sc.sc_ic;
1158 	struct ieee80211_node *ni = *(void **)arg;
1159 	struct athn_node *an = (struct athn_node *)ni;
1160 	int s;
1161 
1162 	if (ic->ic_state != IEEE80211_S_RUN)
1163 		return;
1164 
1165 	s = splnet();
1166 	/* NB: Node may have left before we got scheduled. */
1167 	if (an->sta_index != 0)
1168 		(void)athn_usb_node_set_rates(usc, ni);
1169 	ieee80211_release_node(ic, ni);
1170 	splx(s);
1171 }
1172 #endif
1173 
1174 struct ieee80211_node *
1175 athn_usb_node_alloc(struct ieee80211com *ic)
1176 {
1177 	struct athn_node *an;
1178 
1179 	an = malloc(sizeof(struct athn_node), M_DEVBUF, M_NOWAIT | M_ZERO);
1180 	return (struct ieee80211_node *)an;
1181 }
1182 
1183 
1184 #ifndef IEEE80211_STA_ONLY
1185 void
1186 athn_usb_count_active_sta(void *arg, struct ieee80211_node *ni)
1187 {
1188 	int *nsta = arg;
1189 	struct athn_node *an = (struct athn_node *)ni;
1190 
1191 	if (an->sta_index == 0)
1192 		return;
1193 
1194 	if ((ni->ni_state == IEEE80211_STA_AUTH ||
1195 	    ni->ni_state == IEEE80211_STA_ASSOC) &&
1196 	    ni->ni_inact < IEEE80211_INACT_MAX)
1197 		(*nsta)++;
1198 }
1199 
1200 struct athn_usb_newauth_cb_arg {
1201 	struct ieee80211_node *ni;
1202 	uint16_t seq;
1203 };
1204 
1205 void
1206 athn_usb_newauth_cb(struct athn_usb_softc *usc, void *arg)
1207 {
1208 	struct ieee80211com *ic = &usc->sc_sc.sc_ic;
1209 	struct athn_usb_newauth_cb_arg *a = arg;
1210 	struct ieee80211_node *ni = a->ni;
1211 	uint16_t seq = a->seq;
1212 	struct athn_node *an = (struct athn_node *)ni;
1213 	int s, error = 0;
1214 
1215 	if (ic->ic_state != IEEE80211_S_RUN)
1216 		return;
1217 
1218 	s = splnet();
1219 	if (an->sta_index == 0) {
1220 		error = athn_usb_create_node(usc, ni);
1221 		if (error)
1222 			printf("%s: could not add station %s to firmware "
1223 			    "table\n", usc->usb_dev.dv_xname,
1224 			    ether_sprintf(ni->ni_macaddr));
1225 	}
1226 	if (error == 0)
1227 		ieee80211_auth_open_confirm(ic, ni, seq);
1228 	ieee80211_unref_node(&ni);
1229 	splx(s);
1230 }
1231 #endif
1232 
1233 int
1234 athn_usb_newauth(struct ieee80211com *ic, struct ieee80211_node *ni,
1235     int isnew, uint16_t seq)
1236 {
1237 #ifndef IEEE80211_STA_ONLY
1238 	struct athn_usb_softc *usc = ic->ic_softc;
1239 	struct ifnet *ifp = &ic->ic_if;
1240 	struct athn_node *an = (struct athn_node *)ni;
1241 	int nsta;
1242 	struct athn_usb_newauth_cb_arg arg;
1243 
1244 	if (ic->ic_opmode != IEEE80211_M_HOSTAP)
1245 		return 0;
1246 
1247 	if (!isnew && an->sta_index != 0) /* already in firmware table */
1248 		return 0;
1249 
1250 	/* Check if we have room in the firmware table. */
1251 	nsta = 1; /* Account for default node. */
1252 	ieee80211_iterate_nodes(ic, athn_usb_count_active_sta, &nsta);
1253 	if (nsta >= AR_USB_MAX_STA) {
1254 		if (ifp->if_flags & IFF_DEBUG)
1255 			printf("%s: cannot authenticate station %s: firmware "
1256 			    "table is full\n", usc->usb_dev.dv_xname,
1257 			    ether_sprintf(ni->ni_macaddr));
1258 		return ENOSPC;
1259 	}
1260 
1261 	/*
1262 	 * In a process context, try to add this node to the
1263 	 * firmware table and confirm the AUTH request.
1264 	 */
1265 	arg.ni = ieee80211_ref_node(ni);
1266 	arg.seq = seq;
1267 	athn_usb_do_async(usc, athn_usb_newauth_cb, &arg, sizeof(arg));
1268 	return EBUSY;
1269 #else
1270 	return 0;
1271 #endif /* IEEE80211_STA_ONLY */
1272 }
1273 
1274 #ifndef IEEE80211_STA_ONLY
1275 void
1276 athn_usb_node_free(struct ieee80211com *ic, struct ieee80211_node *ni)
1277 {
1278 	struct athn_usb_softc *usc = ic->ic_softc;
1279 	struct athn_node *an = (struct athn_node *)ni;
1280 
1281 	/*
1282 	 * Remove the node from the firmware table in a process context.
1283 	 * Pass an index rather than the pointer which we will free.
1284 	 */
1285 	if (an->sta_index != 0)
1286 		athn_usb_do_async(usc, athn_usb_node_free_cb,
1287 		    &an->sta_index, sizeof(an->sta_index));
1288 	usc->sc_node_free(ic, ni);
1289 }
1290 
1291 void
1292 athn_usb_node_free_cb(struct athn_usb_softc *usc, void *arg)
1293 {
1294 	struct ieee80211com *ic = &usc->sc_sc.sc_ic;
1295 	struct ifnet *ifp = &ic->ic_if;
1296 	uint8_t sta_index = *(uint8_t *)arg;
1297 	int error;
1298 
1299 	error = athn_usb_wmi_xcmd(usc, AR_WMI_CMD_NODE_REMOVE,
1300 	    &sta_index, sizeof(sta_index), NULL);
1301 	if (error) {
1302 		printf("%s: could not remove station %u from firmware table\n",
1303 		    usc->usb_dev.dv_xname, sta_index);
1304 		return;
1305 	}
1306 	usc->free_node_slots |= (1 << sta_index);
1307 	if (ifp->if_flags & IFF_DEBUG)
1308 		printf("%s: station %u removed from firmware table\n",
1309 		    usc->usb_dev.dv_xname, sta_index);
1310 }
1311 #endif /* IEEE80211_STA_ONLY */
1312 
1313 int
1314 athn_usb_ampdu_tx_start(struct ieee80211com *ic, struct ieee80211_node *ni,
1315     uint8_t tid)
1316 {
1317 	struct athn_usb_softc *usc = ic->ic_softc;
1318 	struct athn_node *an = (struct athn_node *)ni;
1319 	struct athn_usb_aggr_cmd cmd;
1320 
1321 	/* Do it in a process context. */
1322 	cmd.sta_index = an->sta_index;
1323 	cmd.tid = tid;
1324 	athn_usb_do_async(usc, athn_usb_ampdu_tx_start_cb, &cmd, sizeof(cmd));
1325 	return (0);
1326 }
1327 
1328 void
1329 athn_usb_ampdu_tx_start_cb(struct athn_usb_softc *usc, void *arg)
1330 {
1331 	struct athn_usb_aggr_cmd *cmd = arg;
1332 	struct ar_htc_target_aggr aggr;
1333 
1334 	memset(&aggr, 0, sizeof(aggr));
1335 	aggr.sta_index = cmd->sta_index;
1336 	aggr.tidno = cmd->tid;
1337 	aggr.aggr_enable = 1;
1338 	(void)athn_usb_wmi_xcmd(usc, AR_WMI_CMD_TX_AGGR_ENABLE,
1339 	    &aggr, sizeof(aggr), NULL);
1340 }
1341 
1342 void
1343 athn_usb_ampdu_tx_stop(struct ieee80211com *ic, struct ieee80211_node *ni,
1344     uint8_t tid)
1345 {
1346 	struct athn_usb_softc *usc = ic->ic_softc;
1347 	struct athn_node *an = (struct athn_node *)ni;
1348 	struct athn_usb_aggr_cmd cmd;
1349 
1350 	/* Do it in a process context. */
1351 	cmd.sta_index = an->sta_index;
1352 	cmd.tid = tid;
1353 	athn_usb_do_async(usc, athn_usb_ampdu_tx_stop_cb, &cmd, sizeof(cmd));
1354 }
1355 
1356 void
1357 athn_usb_ampdu_tx_stop_cb(struct athn_usb_softc *usc, void *arg)
1358 {
1359 	struct athn_usb_aggr_cmd *cmd = arg;
1360 	struct ar_htc_target_aggr aggr;
1361 
1362 	memset(&aggr, 0, sizeof(aggr));
1363 	aggr.sta_index = cmd->sta_index;
1364 	aggr.tidno = cmd->tid;
1365 	aggr.aggr_enable = 0;
1366 	(void)athn_usb_wmi_xcmd(usc, AR_WMI_CMD_TX_AGGR_ENABLE,
1367 	    &aggr, sizeof(aggr), NULL);
1368 }
1369 
1370 #ifndef IEEE80211_STA_ONLY
1371 /* Try to find a node we can evict to make room in the firmware table. */
1372 void
1373 athn_usb_clean_nodes(void *arg, struct ieee80211_node *ni)
1374 {
1375 	struct athn_usb_softc *usc = arg;
1376 	struct ieee80211com *ic = &usc->sc_sc.sc_ic;
1377 	struct athn_node *an = (struct athn_node *)ni;
1378 
1379 	/*
1380 	 * Don't remove the default node (used for management frames).
1381 	 * Nodes which are not in the firmware table also have index zero.
1382 	 */
1383 	if (an->sta_index == 0)
1384 		return;
1385 
1386 	/* Remove non-associated nodes. */
1387 	if (ni->ni_state != IEEE80211_STA_AUTH &&
1388 	    ni->ni_state != IEEE80211_STA_ASSOC) {
1389 		athn_usb_remove_node(usc, ni);
1390 		return;
1391 	}
1392 
1393 	/*
1394 	 * Kick off inactive associated nodes. This won't help
1395 	 * immediately but will help if the new STA retries later.
1396 	 */
1397 	if (ni->ni_inact >= IEEE80211_INACT_MAX) {
1398 		IEEE80211_SEND_MGMT(ic, ni, IEEE80211_FC0_SUBTYPE_DEAUTH,
1399 		    IEEE80211_REASON_AUTH_EXPIRE);
1400 		ieee80211_node_leave(ic, ni);
1401 	}
1402 }
1403 #endif
1404 
1405 int
1406 athn_usb_create_node(struct athn_usb_softc *usc, struct ieee80211_node *ni)
1407 {
1408 	struct athn_node *an = (struct athn_node *)ni;
1409 	struct ar_htc_target_sta sta;
1410 	int error, sta_index;
1411 #ifndef IEEE80211_STA_ONLY
1412 	struct ieee80211com *ic = &usc->sc_sc.sc_ic;
1413 	struct ifnet *ifp = &ic->ic_if;
1414 
1415 	/* Firmware cannot handle more than 8 STAs. Try to make room first. */
1416 	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1417 		ieee80211_iterate_nodes(ic, athn_usb_clean_nodes, usc);
1418 #endif
1419 	if (usc->free_node_slots == 0x00)
1420 		return ENOBUFS;
1421 
1422 	sta_index = ffs(usc->free_node_slots) - 1;
1423 	if (sta_index < 0 || sta_index >= AR_USB_MAX_STA)
1424 		return ENOSPC;
1425 
1426 	/* Create node entry on target. */
1427 	memset(&sta, 0, sizeof(sta));
1428 	IEEE80211_ADDR_COPY(sta.macaddr, ni->ni_macaddr);
1429 	IEEE80211_ADDR_COPY(sta.bssid, ni->ni_bssid);
1430 	sta.sta_index = sta_index;
1431 	sta.maxampdu = 0xffff;
1432 	if (ni->ni_flags & IEEE80211_NODE_HT)
1433 		sta.flags |= htobe16(AR_HTC_STA_HT);
1434 	error = athn_usb_wmi_xcmd(usc, AR_WMI_CMD_NODE_CREATE,
1435 	    &sta, sizeof(sta), NULL);
1436 	if (error != 0)
1437 		return (error);
1438 	an->sta_index = sta_index;
1439 	usc->free_node_slots &= ~(1 << an->sta_index);
1440 
1441 #ifndef IEEE80211_STA_ONLY
1442 	if (ifp->if_flags & IFF_DEBUG)
1443 		printf("%s: station %u (%s) added to firmware table\n",
1444 		    usc->usb_dev.dv_xname, sta_index,
1445 		    ether_sprintf(ni->ni_macaddr));
1446 #endif
1447 	return athn_usb_node_set_rates(usc, ni);
1448 }
1449 
1450 int
1451 athn_usb_node_set_rates(struct athn_usb_softc *usc, struct ieee80211_node *ni)
1452 {
1453 	struct athn_node *an = (struct athn_node *)ni;
1454 	struct ar_htc_target_rate rate;
1455 	int i, j;
1456 
1457 	/* Setup supported rates. */
1458 	memset(&rate, 0, sizeof(rate));
1459 	rate.sta_index = an->sta_index;
1460 	rate.isnew = 1;
1461 	rate.lg_rates.rs_nrates = ni->ni_rates.rs_nrates;
1462 	memcpy(rate.lg_rates.rs_rates, ni->ni_rates.rs_rates,
1463 	    ni->ni_rates.rs_nrates);
1464 	if (ni->ni_flags & IEEE80211_NODE_HT) {
1465 		rate.capflags |= htobe32(AR_RC_HT_FLAG);
1466 		/* Setup HT rates. */
1467 		for (i = 0, j = 0; i < IEEE80211_HT_NUM_MCS; i++) {
1468 			if (!isset(ni->ni_rxmcs, i))
1469 				continue;
1470 			if (j >= AR_HTC_RATE_MAX)
1471 				break;
1472 			rate.ht_rates.rs_rates[j++] = i;
1473 		}
1474 		rate.ht_rates.rs_nrates = j;
1475 
1476 		if (ni->ni_rxmcs[1]) /* dual-stream MIMO rates */
1477 			rate.capflags |= htobe32(AR_RC_DS_FLAG);
1478 #ifdef notyet
1479 		if (ni->ni_htcaps & IEEE80211_HTCAP_CBW20_40)
1480 			rate.capflags |= htobe32(AR_RC_40_FLAG);
1481 		if (ni->ni_htcaps & IEEE80211_HTCAP_SGI40)
1482 			rate.capflags |= htobe32(AR_RC_SGI_FLAG);
1483 		if (ni->ni_htcaps & IEEE80211_HTCAP_SGI20)
1484 			rate.capflags |= htobe32(AR_RC_SGI_FLAG);
1485 #endif
1486 	}
1487 
1488 	return athn_usb_wmi_xcmd(usc, AR_WMI_CMD_RC_RATE_UPDATE,
1489 	    &rate, sizeof(rate), NULL);
1490 }
1491 
1492 int
1493 athn_usb_remove_node(struct athn_usb_softc *usc, struct ieee80211_node *ni)
1494 {
1495 	struct athn_node *an = (struct athn_node *)ni;
1496 	int error;
1497 #ifndef IEEE80211_STA_ONLY
1498 	struct ieee80211com *ic = &usc->sc_sc.sc_ic;
1499 	struct ifnet *ifp = &ic->ic_if;
1500 #endif
1501 
1502 	error = athn_usb_wmi_xcmd(usc, AR_WMI_CMD_NODE_REMOVE,
1503 	    &an->sta_index, sizeof(an->sta_index), NULL);
1504 	if (error) {
1505 		printf("%s: could not remove station %u (%s) from "
1506 		    "firmware table\n", usc->usb_dev.dv_xname, an->sta_index,
1507 		    ether_sprintf(ni->ni_macaddr));
1508 		return error;
1509 	}
1510 
1511 #ifndef IEEE80211_STA_ONLY
1512 	if (ifp->if_flags & IFF_DEBUG)
1513 		printf("%s: station %u (%s) removed from firmware table\n",
1514 		    usc->usb_dev.dv_xname, an->sta_index,
1515 		    ether_sprintf(ni->ni_macaddr));
1516 #endif
1517 
1518 	usc->free_node_slots |= (1 << an->sta_index);
1519 	an->sta_index = 0;
1520 	return 0;
1521 }
1522 
1523 void
1524 athn_usb_rx_enable(struct athn_softc *sc)
1525 {
1526 	AR_WRITE(sc, AR_CR, AR_CR_RXE);
1527 	AR_WRITE_BARRIER(sc);
1528 }
1529 
1530 int
1531 athn_usb_switch_chan(struct athn_softc *sc, struct ieee80211_channel *c,
1532     struct ieee80211_channel *extc)
1533 {
1534 	struct athn_usb_softc *usc = (struct athn_usb_softc *)sc;
1535 	uint16_t mode;
1536 	int error;
1537 
1538 	/* Disable interrupts. */
1539 	error = athn_usb_wmi_cmd(usc, AR_WMI_CMD_DISABLE_INTR);
1540 	if (error != 0)
1541 		goto reset;
1542 	/* Stop all Tx queues. */
1543 	error = athn_usb_wmi_cmd(usc, AR_WMI_CMD_DRAIN_TXQ_ALL);
1544 	if (error != 0)
1545 		goto reset;
1546 	/* Stop Rx. */
1547 	error = athn_usb_wmi_cmd(usc, AR_WMI_CMD_STOP_RECV);
1548 	if (error != 0)
1549 		goto reset;
1550 
1551 	/* If band or bandwidth changes, we need to do a full reset. */
1552 	if (c->ic_flags != sc->curchan->ic_flags ||
1553 	    ((extc != NULL) ^ (sc->curchanext != NULL))) {
1554 		DPRINTFN(2, ("channel band switch\n"));
1555 		goto reset;
1556 	}
1557 
1558 	error = athn_set_chan(sc, c, extc);
1559 	if (AR_SREV_9271(sc) && error == 0)
1560 		ar9271_load_ani(sc);
1561 	if (error != 0) {
1562  reset:		/* Error found, try a full reset. */
1563 		DPRINTFN(3, ("needs a full reset\n"));
1564 		error = athn_hw_reset(sc, c, extc, 0);
1565 		if (error != 0)	/* Hopeless case. */
1566 			return (error);
1567 
1568 		error = athn_set_chan(sc, c, extc);
1569 		if (AR_SREV_9271(sc) && error == 0)
1570 			ar9271_load_ani(sc);
1571 		if (error != 0)
1572 			return (error);
1573 	}
1574 
1575 	sc->ops.set_txpower(sc, c, extc);
1576 
1577 	error = athn_usb_wmi_cmd(usc, AR_WMI_CMD_START_RECV);
1578 	if (error != 0)
1579 		return (error);
1580 	athn_rx_start(sc);
1581 
1582 	mode = htobe16(IEEE80211_IS_CHAN_2GHZ(c) ?
1583 	    AR_HTC_MODE_11NG : AR_HTC_MODE_11NA);
1584 	error = athn_usb_wmi_xcmd(usc, AR_WMI_CMD_SET_MODE,
1585 	    &mode, sizeof(mode), NULL);
1586 	if (error != 0)
1587 		return (error);
1588 
1589 	/* Re-enable interrupts. */
1590 	error = athn_usb_wmi_cmd(usc, AR_WMI_CMD_ENABLE_INTR);
1591 	return (error);
1592 }
1593 
1594 void
1595 athn_usb_updateedca(struct ieee80211com *ic)
1596 {
1597 	struct athn_usb_softc *usc = ic->ic_softc;
1598 
1599 	/* Do it in a process context. */
1600 	athn_usb_do_async(usc, athn_usb_updateedca_cb, NULL, 0);
1601 }
1602 
1603 void
1604 athn_usb_updateedca_cb(struct athn_usb_softc *usc, void *arg)
1605 {
1606 	int s;
1607 
1608 	s = splnet();
1609 	athn_updateedca(&usc->sc_sc.sc_ic);
1610 	splx(s);
1611 }
1612 
1613 void
1614 athn_usb_updateslot(struct ieee80211com *ic)
1615 {
1616 	struct athn_usb_softc *usc = ic->ic_softc;
1617 
1618 	return;	/* XXX */
1619 	/* Do it in a process context. */
1620 	athn_usb_do_async(usc, athn_usb_updateslot_cb, NULL, 0);
1621 }
1622 
1623 void
1624 athn_usb_updateslot_cb(struct athn_usb_softc *usc, void *arg)
1625 {
1626 	int s;
1627 
1628 	s = splnet();
1629 	athn_updateslot(&usc->sc_sc.sc_ic);
1630 	splx(s);
1631 }
1632 
1633 int
1634 athn_usb_set_key(struct ieee80211com *ic, struct ieee80211_node *ni,
1635     struct ieee80211_key *k)
1636 {
1637 	struct athn_usb_softc *usc = ic->ic_softc;
1638 	struct athn_usb_cmd_key cmd;
1639 
1640 	/* Defer setting of WEP keys until interface is brought up. */
1641 	if ((ic->ic_if.if_flags & (IFF_UP | IFF_RUNNING)) !=
1642 	    (IFF_UP | IFF_RUNNING))
1643 		return (0);
1644 
1645 	/* Do it in a process context. */
1646 	cmd.ni = (ni != NULL) ? ieee80211_ref_node(ni) : NULL;
1647 	cmd.key = k;
1648 	athn_usb_do_async(usc, athn_usb_set_key_cb, &cmd, sizeof(cmd));
1649 	return (0);
1650 }
1651 
1652 void
1653 athn_usb_set_key_cb(struct athn_usb_softc *usc, void *arg)
1654 {
1655 	struct ieee80211com *ic = &usc->sc_sc.sc_ic;
1656 	struct athn_usb_cmd_key *cmd = arg;
1657 	int s;
1658 
1659 	s = splnet();
1660 	athn_usb_write_barrier(&usc->sc_sc);
1661 	athn_set_key(ic, cmd->ni, cmd->key);
1662 	if (cmd->ni != NULL)
1663 		ieee80211_release_node(ic, cmd->ni);
1664 	splx(s);
1665 }
1666 
1667 void
1668 athn_usb_delete_key(struct ieee80211com *ic, struct ieee80211_node *ni,
1669     struct ieee80211_key *k)
1670 {
1671 	struct athn_usb_softc *usc = ic->ic_softc;
1672 	struct athn_usb_cmd_key cmd;
1673 
1674 	if (!(ic->ic_if.if_flags & IFF_RUNNING) ||
1675 	    ic->ic_state != IEEE80211_S_RUN)
1676 		return;	/* Nothing to do. */
1677 
1678 	/* Do it in a process context. */
1679 	cmd.ni = (ni != NULL) ? ieee80211_ref_node(ni) : NULL;
1680 	cmd.key = k;
1681 	athn_usb_do_async(usc, athn_usb_delete_key_cb, &cmd, sizeof(cmd));
1682 }
1683 
1684 void
1685 athn_usb_delete_key_cb(struct athn_usb_softc *usc, void *arg)
1686 {
1687 	struct ieee80211com *ic = &usc->sc_sc.sc_ic;
1688 	struct athn_usb_cmd_key *cmd = arg;
1689 	int s;
1690 
1691 	s = splnet();
1692 	athn_delete_key(ic, cmd->ni, cmd->key);
1693 	if (cmd->ni != NULL)
1694 		ieee80211_release_node(ic, cmd->ni);
1695 	splx(s);
1696 }
1697 
1698 #ifndef IEEE80211_STA_ONLY
1699 void
1700 athn_usb_bcneof(struct usbd_xfer *xfer, void *priv,
1701     usbd_status status)
1702 {
1703 	struct athn_usb_tx_data *data = priv;
1704 	struct athn_usb_softc *usc = data->sc;
1705 
1706 	if (__predict_false(status == USBD_STALLED))
1707 		usbd_clear_endpoint_stall_async(usc->tx_data_pipe);
1708 	usc->tx_bcn = data;
1709 }
1710 
1711 /*
1712  * Process Software Beacon Alert interrupts.
1713  */
1714 void
1715 athn_usb_swba(struct athn_usb_softc *usc)
1716 {
1717 	struct athn_softc *sc = &usc->sc_sc;
1718 	struct ieee80211com *ic = &sc->sc_ic;
1719 	struct athn_usb_tx_data *data;
1720 	struct ieee80211_frame *wh;
1721 	struct ar_stream_hdr *hdr;
1722 	struct ar_htc_frame_hdr *htc;
1723 	struct ar_tx_bcn *bcn;
1724 	struct mbuf *m;
1725 	int error;
1726 
1727 	if (ic->ic_dtim_count == 0)
1728 		ic->ic_dtim_count = ic->ic_dtim_period - 1;
1729 	else
1730 		ic->ic_dtim_count--;
1731 
1732 	/* Make sure previous beacon has been sent. */
1733 	if (usc->tx_bcn == NULL)
1734 		return;
1735 	data = usc->tx_bcn;
1736 
1737 	/* Get new beacon. */
1738 	m = ieee80211_beacon_alloc(ic, ic->ic_bss);
1739 	if (__predict_false(m == NULL))
1740 		return;
1741 	/* Assign sequence number. */
1742 	wh = mtod(m, struct ieee80211_frame *);
1743 	*(uint16_t *)&wh->i_seq[0] =
1744 	    htole16(ic->ic_bss->ni_txseq << IEEE80211_SEQ_SEQ_SHIFT);
1745 	ic->ic_bss->ni_txseq++;
1746 
1747 	hdr = (struct ar_stream_hdr *)data->buf;
1748 	hdr->tag = htole16(AR_USB_TX_STREAM_TAG);
1749 	hdr->len = htole16(sizeof(*htc) + sizeof(*bcn) + m->m_pkthdr.len);
1750 
1751 	htc = (struct ar_htc_frame_hdr *)&hdr[1];
1752 	memset(htc, 0, sizeof(*htc));
1753 	htc->endpoint_id = usc->ep_bcn;
1754 	htc->payload_len = htobe16(sizeof(*bcn) + m->m_pkthdr.len);
1755 
1756 	bcn = (struct ar_tx_bcn *)&htc[1];
1757 	memset(bcn, 0, sizeof(*bcn));
1758 	bcn->vif_idx = 0;
1759 
1760 	m_copydata(m, 0, m->m_pkthdr.len, (caddr_t)&bcn[1]);
1761 
1762 	usbd_setup_xfer(data->xfer, usc->tx_data_pipe, data, data->buf,
1763 	    sizeof(*hdr) + sizeof(*htc) + sizeof(*bcn) + m->m_pkthdr.len,
1764 	    USBD_SHORT_XFER_OK | USBD_NO_COPY, ATHN_USB_TX_TIMEOUT,
1765 	    athn_usb_bcneof);
1766 
1767 	m_freem(m);
1768 	usc->tx_bcn = NULL;
1769 	error = usbd_transfer(data->xfer);
1770 	if (__predict_false(error != USBD_IN_PROGRESS && error != 0))
1771 		usc->tx_bcn = data;
1772 }
1773 #endif
1774 
1775 /* Update current transmit rate for a node based on firmware Tx status. */
1776 void
1777 athn_usb_tx_status(void *arg, struct ieee80211_node *ni)
1778 {
1779 	struct ar_wmi_evt_txstatus *ts = arg;
1780 	struct athn_node *an = (struct athn_node *)ni;
1781 	uint8_t rate_index = (ts->rate & AR_HTC_TXSTAT_RATE);
1782 
1783 	if (an->sta_index != ts->cookie) /* Tx report for a different node */
1784 		return;
1785 
1786 	if (ts->flags & AR_HTC_TXSTAT_MCS) {
1787 		if (isset(ni->ni_rxmcs, rate_index))
1788 			ni->ni_txmcs = rate_index;
1789 	} else if (rate_index < ni->ni_rates.rs_nrates)
1790 		ni->ni_txrate = rate_index;
1791 }
1792 
1793 void
1794 athn_usb_rx_wmi_ctrl(struct athn_usb_softc *usc, uint8_t *buf, int len)
1795 {
1796 	struct ar_wmi_cmd_hdr *wmi;
1797 	uint16_t cmd_id;
1798 
1799 	if (__predict_false(len < sizeof(*wmi)))
1800 		return;
1801 	wmi = (struct ar_wmi_cmd_hdr *)buf;
1802 	cmd_id = betoh16(wmi->cmd_id);
1803 
1804 	if (!(cmd_id & AR_WMI_EVT_FLAG)) {
1805 		if (usc->wait_cmd_id != cmd_id)
1806 			return;	/* Unexpected reply. */
1807 		if (usc->obuf != NULL) {
1808 			/* Copy answer into caller supplied buffer. */
1809 			memcpy(usc->obuf, &wmi[1], len - sizeof(*wmi));
1810 		}
1811 		/* Notify caller of completion. */
1812 		wakeup(&usc->wait_cmd_id);
1813 		return;
1814 	}
1815 	switch (cmd_id & 0xfff) {
1816 #ifndef IEEE80211_STA_ONLY
1817 	case AR_WMI_EVT_SWBA:
1818 		athn_usb_swba(usc);
1819 		break;
1820 #endif
1821 	case AR_WMI_EVT_TXSTATUS: {
1822 		struct ar_wmi_evt_txstatus_list *tsl;
1823 		int i;
1824 
1825 		tsl = (struct ar_wmi_evt_txstatus_list *)&wmi[1];
1826 		for (i = 0; i < tsl->count && i < nitems(tsl->ts); i++) {
1827 			struct ieee80211com *ic = &usc->sc_sc.sc_ic;
1828 			struct athn_node *an = (struct athn_node *)ic->ic_bss;
1829 			struct ar_wmi_evt_txstatus *ts = &tsl->ts[i];
1830 			uint8_t qid;
1831 
1832 			/* Skip the node we use to send management frames. */
1833 			if (ts->cookie == 0)
1834 				continue;
1835 
1836 			/* Skip Tx reports for non-data frame endpoints. */
1837 			qid = (ts->rate & AR_HTC_TXSTAT_EPID) >>
1838 				AR_HTC_TXSTAT_EPID_SHIFT;
1839 			if (qid != usc->ep_data[EDCA_AC_BE] &&
1840 			    qid != usc->ep_data[EDCA_AC_BK] &&
1841 			    qid != usc->ep_data[EDCA_AC_VI] &&
1842 			    qid != usc->ep_data[EDCA_AC_VO])
1843 				continue;
1844 
1845 			if (ts->cookie == an->sta_index)
1846 				athn_usb_tx_status(ts, ic->ic_bss);
1847 			else
1848 				ieee80211_iterate_nodes(ic, athn_usb_tx_status,
1849 				    ts);
1850 		}
1851 		break;
1852 	}
1853 	case AR_WMI_EVT_FATAL:
1854 		printf("%s: fatal firmware error\n", usc->usb_dev.dv_xname);
1855 		break;
1856 	default:
1857 		DPRINTF(("WMI event %d ignored\n", cmd_id));
1858 		break;
1859 	}
1860 }
1861 
1862 void
1863 athn_usb_intr(struct usbd_xfer *xfer, void *priv,
1864     usbd_status status)
1865 {
1866 	struct athn_usb_softc *usc = priv;
1867 	struct ar_htc_frame_hdr *htc;
1868 	struct ar_htc_msg_hdr *msg;
1869 	uint8_t *buf = usc->ibuf;
1870 	uint16_t msg_id;
1871 	int len;
1872 
1873 	if (__predict_false(status != USBD_NORMAL_COMPLETION)) {
1874 		DPRINTF(("intr status=%d\n", status));
1875 		if (status == USBD_STALLED)
1876 			usbd_clear_endpoint_stall_async(usc->rx_intr_pipe);
1877 		else if (status == USBD_IOERROR) {
1878 			/*
1879 			 * The device has gone away. If async commands are
1880 			 * pending or running ensure the device dies ASAP
1881 			 * and any blocked processes are woken up.
1882 			 */
1883 			if (usc->cmdq.queued > 0)
1884 				usbd_deactivate(usc->sc_udev);
1885 		}
1886 		return;
1887 	}
1888 	usbd_get_xfer_status(xfer, NULL, NULL, &len, NULL);
1889 
1890 	/* Skip watchdog pattern if present. */
1891 	if (len >= 4 && *(uint32_t *)buf == htobe32(0x00c60000)) {
1892 		buf += 4;
1893 		len -= 4;
1894 	}
1895 	if (__predict_false(len < sizeof(*htc)))
1896 		return;
1897 	htc = (struct ar_htc_frame_hdr *)buf;
1898 	/* Skip HTC header. */
1899 	buf += sizeof(*htc);
1900 	len -= sizeof(*htc);
1901 
1902 	if (htc->endpoint_id != 0) {
1903 		if (__predict_false(htc->endpoint_id != usc->ep_ctrl))
1904 			return;
1905 		/* Remove trailer if present. */
1906 		if (htc->flags & AR_HTC_FLAG_TRAILER) {
1907 			if (__predict_false(len < htc->control[0]))
1908 				return;
1909 			len -= htc->control[0];
1910 		}
1911 		athn_usb_rx_wmi_ctrl(usc, buf, len);
1912 		return;
1913 	}
1914 	/* Endpoint 0 carries HTC messages. */
1915 	if (__predict_false(len < sizeof(*msg)))
1916 		return;
1917 	msg = (struct ar_htc_msg_hdr *)buf;
1918 	msg_id = betoh16(msg->msg_id);
1919 	DPRINTF(("Rx HTC message %d\n", msg_id));
1920 	switch (msg_id) {
1921 	case AR_HTC_MSG_READY:
1922 		if (usc->wait_msg_id != msg_id)
1923 			break;
1924 		usc->wait_msg_id = 0;
1925 		wakeup(&usc->wait_msg_id);
1926 		break;
1927 	case AR_HTC_MSG_CONN_SVC_RSP:
1928 		if (usc->wait_msg_id != msg_id)
1929 			break;
1930 		if (usc->msg_conn_svc_rsp != NULL) {
1931 			memcpy(usc->msg_conn_svc_rsp, &msg[1],
1932 			    sizeof(struct ar_htc_msg_conn_svc_rsp));
1933 		}
1934 		usc->wait_msg_id = 0;
1935 		wakeup(&usc->wait_msg_id);
1936 		break;
1937 	case AR_HTC_MSG_CONF_PIPE_RSP:
1938 		if (usc->wait_msg_id != msg_id)
1939 			break;
1940 		usc->wait_msg_id = 0;
1941 		wakeup(&usc->wait_msg_id);
1942 		break;
1943 	default:
1944 		DPRINTF(("HTC message %d ignored\n", msg_id));
1945 		break;
1946 	}
1947 }
1948 
1949 #if NBPFILTER > 0
1950 void
1951 athn_usb_rx_radiotap(struct athn_softc *sc, struct mbuf *m,
1952     struct ar_rx_status *rs)
1953 {
1954 #define IEEE80211_RADIOTAP_F_SHORTGI	0x80	/* XXX from FBSD */
1955 
1956 	struct athn_rx_radiotap_header *tap = &sc->sc_rxtap;
1957 	struct ieee80211com *ic = &sc->sc_ic;
1958 	struct mbuf mb;
1959 	uint8_t rate;
1960 
1961 	tap->wr_flags = IEEE80211_RADIOTAP_F_FCS;
1962 	tap->wr_tsft = htole64(betoh64(rs->rs_tstamp));
1963 	tap->wr_chan_freq = htole16(ic->ic_bss->ni_chan->ic_freq);
1964 	tap->wr_chan_flags = htole16(ic->ic_bss->ni_chan->ic_flags);
1965 	tap->wr_dbm_antsignal = rs->rs_rssi;
1966 	/* XXX noise. */
1967 	tap->wr_antenna = rs->rs_antenna;
1968 	tap->wr_rate = 0;	/* In case it can't be found below. */
1969 	rate = rs->rs_rate;
1970 	if (rate & 0x80) {		/* HT. */
1971 		/* Bit 7 set means HT MCS instead of rate. */
1972 		tap->wr_rate = rate;
1973 		if (!(rs->rs_flags & AR_RXS_FLAG_GI))
1974 			tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTGI;
1975 
1976 	} else if (rate & 0x10) {	/* CCK. */
1977 		if (rate & 0x04)
1978 			tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
1979 		switch (rate & ~0x14) {
1980 		case 0xb: tap->wr_rate =   2; break;
1981 		case 0xa: tap->wr_rate =   4; break;
1982 		case 0x9: tap->wr_rate =  11; break;
1983 		case 0x8: tap->wr_rate =  22; break;
1984 		}
1985 	} else {			/* OFDM. */
1986 		switch (rate) {
1987 		case 0xb: tap->wr_rate =  12; break;
1988 		case 0xf: tap->wr_rate =  18; break;
1989 		case 0xa: tap->wr_rate =  24; break;
1990 		case 0xe: tap->wr_rate =  36; break;
1991 		case 0x9: tap->wr_rate =  48; break;
1992 		case 0xd: tap->wr_rate =  72; break;
1993 		case 0x8: tap->wr_rate =  96; break;
1994 		case 0xc: tap->wr_rate = 108; break;
1995 		}
1996 	}
1997 	mb.m_data = (caddr_t)tap;
1998 	mb.m_len = sc->sc_rxtap_len;
1999 	mb.m_next = m;
2000 	mb.m_nextpkt = NULL;
2001 	mb.m_type = 0;
2002 	mb.m_flags = 0;
2003 	bpf_mtap(sc->sc_drvbpf, &mb, BPF_DIRECTION_IN);
2004 }
2005 #endif
2006 
2007 void
2008 athn_usb_rx_frame(struct athn_usb_softc *usc, struct mbuf *m,
2009     struct mbuf_list *ml)
2010 {
2011 	struct athn_softc *sc = &usc->sc_sc;
2012 	struct ieee80211com *ic = &sc->sc_ic;
2013 	struct ifnet *ifp = &ic->ic_if;
2014 	struct ieee80211_frame *wh;
2015 	struct ieee80211_node *ni;
2016 	struct ieee80211_rxinfo rxi;
2017 	struct ar_htc_frame_hdr *htc;
2018 	struct ar_rx_status *rs;
2019 	uint16_t datalen;
2020 	int s;
2021 
2022 	if (__predict_false(m->m_len < sizeof(*htc)))
2023 		goto skip;
2024 	htc = mtod(m, struct ar_htc_frame_hdr *);
2025 	if (__predict_false(htc->endpoint_id == 0)) {
2026 		DPRINTF(("bad endpoint %d\n", htc->endpoint_id));
2027 		goto skip;
2028 	}
2029 	if (htc->flags & AR_HTC_FLAG_TRAILER) {
2030 		if (m->m_len < htc->control[0])
2031 			goto skip;
2032 		m_adj(m, -(int)htc->control[0]);
2033 	}
2034 	m_adj(m, sizeof(*htc));	/* Strip HTC header. */
2035 
2036 	if (__predict_false(m->m_len < sizeof(*rs)))
2037 		goto skip;
2038 	rs = mtod(m, struct ar_rx_status *);
2039 
2040 	/* Make sure that payload fits. */
2041 	datalen = betoh16(rs->rs_datalen);
2042 	if (__predict_false(m->m_len < sizeof(*rs) + datalen))
2043 		goto skip;
2044 
2045 	if (__predict_false(datalen < sizeof(*wh) + IEEE80211_CRC_LEN))
2046 		goto skip;
2047 
2048 	if (rs->rs_status != 0) {
2049 		if (rs->rs_status & AR_RXS_RXERR_DECRYPT)
2050 			ic->ic_stats.is_ccmp_dec_errs++;
2051 		ifp->if_ierrors++;
2052 		goto skip;
2053 	}
2054 	m_adj(m, sizeof(*rs));	/* Strip Rx status. */
2055 
2056 	s = splnet();
2057 
2058 	/* Grab a reference to the source node. */
2059 	wh = mtod(m, struct ieee80211_frame *);
2060 	ni = ieee80211_find_rxnode(ic, wh);
2061 
2062 	/* Remove any HW padding after the 802.11 header. */
2063 	if (!(wh->i_fc[0] & IEEE80211_FC0_TYPE_CTL)) {
2064 		u_int hdrlen = ieee80211_get_hdrlen(wh);
2065 		if (hdrlen & 3) {
2066 			memmove((caddr_t)wh + 2, wh, hdrlen);
2067 			m_adj(m, 2);
2068 		}
2069 		wh = mtod(m, struct ieee80211_frame *);
2070 	}
2071 #if NBPFILTER > 0
2072 	if (__predict_false(sc->sc_drvbpf != NULL))
2073 		athn_usb_rx_radiotap(sc, m, rs);
2074 #endif
2075 	/* Trim 802.11 FCS after radiotap. */
2076 	m_adj(m, -IEEE80211_CRC_LEN);
2077 
2078 	/* Send the frame to the 802.11 layer. */
2079 	rxi.rxi_flags = 0;
2080 	rxi.rxi_rssi = rs->rs_rssi + AR_USB_DEFAULT_NF;
2081 	rxi.rxi_tstamp = betoh64(rs->rs_tstamp);
2082 	if (!(wh->i_fc[0] & IEEE80211_FC0_TYPE_CTL) &&
2083 	    (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) &&
2084 	    (ic->ic_flags & IEEE80211_F_RSNON) &&
2085 	    (ni->ni_flags & IEEE80211_NODE_RXPROT) &&
2086 	    (ni->ni_rsncipher == IEEE80211_CIPHER_CCMP ||
2087 	    (IEEE80211_IS_MULTICAST(wh->i_addr1) &&
2088 	    ni->ni_rsngroupcipher == IEEE80211_CIPHER_CCMP))) {
2089 		if (ar5008_ccmp_decap(sc, m, ni) != 0) {
2090 			ifp->if_ierrors++;
2091 			ieee80211_release_node(ic, ni);
2092 			splx(s);
2093 			goto skip;
2094 		}
2095 		rxi.rxi_flags |= IEEE80211_RXI_HWDEC;
2096 	}
2097 	ieee80211_inputm(ifp, m, ni, &rxi, ml);
2098 
2099 	/* Node is no longer needed. */
2100 	ieee80211_release_node(ic, ni);
2101 	splx(s);
2102 	return;
2103  skip:
2104 	m_freem(m);
2105 }
2106 
2107 void
2108 athn_usb_rxeof(struct usbd_xfer *xfer, void *priv,
2109     usbd_status status)
2110 {
2111 	struct mbuf_list ml = MBUF_LIST_INITIALIZER();
2112 	struct athn_usb_rx_data *data = priv;
2113 	struct athn_usb_softc *usc = data->sc;
2114 	struct athn_softc *sc = &usc->sc_sc;
2115 	struct ifnet *ifp = &sc->sc_ic.ic_if;
2116 	struct athn_usb_rx_stream *stream = &usc->rx_stream;
2117 	uint8_t *buf = data->buf;
2118 	struct ar_stream_hdr *hdr;
2119 	struct mbuf *m;
2120 	uint16_t pktlen;
2121 	int off, len;
2122 
2123 	if (__predict_false(status != USBD_NORMAL_COMPLETION)) {
2124 		DPRINTF(("RX status=%d\n", status));
2125 		if (status == USBD_STALLED)
2126 			usbd_clear_endpoint_stall_async(usc->rx_data_pipe);
2127 		if (status != USBD_CANCELLED)
2128 			goto resubmit;
2129 		return;
2130 	}
2131 	usbd_get_xfer_status(xfer, NULL, NULL, &len, NULL);
2132 
2133 	if (stream->left > 0) {
2134 		if (len >= stream->left) {
2135 			/* We have all our pktlen bytes now. */
2136 			if (__predict_true(stream->m != NULL)) {
2137 				memcpy(mtod(stream->m, uint8_t *) +
2138 				    stream->moff, buf, stream->left);
2139 				athn_usb_rx_frame(usc, stream->m, &ml);
2140 				stream->m = NULL;
2141 			}
2142 			/* Next header is 32-bit aligned. */
2143 			off = (stream->left + 3) & ~3;
2144 			buf += off;
2145 			len -= off;
2146 			stream->left = 0;
2147 		} else {
2148 			/* Still need more bytes, save what we have. */
2149 			if (__predict_true(stream->m != NULL)) {
2150 				memcpy(mtod(stream->m, uint8_t *) +
2151 				    stream->moff, buf, len);
2152 				stream->moff += len;
2153 			}
2154 			stream->left -= len;
2155 			goto resubmit;
2156 		}
2157 	}
2158 	KASSERT(stream->left == 0);
2159 	while (len >= sizeof(*hdr)) {
2160 		hdr = (struct ar_stream_hdr *)buf;
2161 		if (hdr->tag != htole16(AR_USB_RX_STREAM_TAG)) {
2162 			DPRINTF(("invalid tag 0x%x\n", hdr->tag));
2163 			break;
2164 		}
2165 		pktlen = letoh16(hdr->len);
2166 		buf += sizeof(*hdr);
2167 		len -= sizeof(*hdr);
2168 
2169 		if (__predict_true(pktlen <= MCLBYTES)) {
2170 			/* Allocate an mbuf to store the next pktlen bytes. */
2171 			MGETHDR(m, M_DONTWAIT, MT_DATA);
2172 			if (__predict_true(m != NULL)) {
2173 				m->m_pkthdr.len = m->m_len = pktlen;
2174 				if (pktlen > MHLEN) {
2175 					MCLGET(m, M_DONTWAIT);
2176 					if (!(m->m_flags & M_EXT)) {
2177 						m_free(m);
2178 						m = NULL;
2179 					}
2180 				}
2181 			}
2182 		} else	/* Drop frames larger than MCLBYTES. */
2183 			m = NULL;
2184 
2185 		if (m == NULL)
2186 			ifp->if_ierrors++;
2187 
2188 		/*
2189 		 * NB: m can be NULL, in which case the next pktlen bytes
2190 		 * will be discarded from the Rx stream.
2191 		 */
2192 		if (pktlen > len) {
2193 			/* Need more bytes, save what we have. */
2194 			stream->m = m;	/* NB: m can be NULL. */
2195 			if (__predict_true(stream->m != NULL)) {
2196 				memcpy(mtod(stream->m, uint8_t *), buf, len);
2197 				stream->moff = len;
2198 			}
2199 			stream->left = pktlen - len;
2200 			goto resubmit;
2201 		}
2202 		if (__predict_true(m != NULL)) {
2203 			/* We have all the pktlen bytes in this xfer. */
2204 			memcpy(mtod(m, uint8_t *), buf, pktlen);
2205 			athn_usb_rx_frame(usc, m, &ml);
2206 		}
2207 
2208 		/* Next header is 32-bit aligned. */
2209 		off = (pktlen + 3) & ~3;
2210 		buf += off;
2211 		len -= off;
2212 	}
2213 	if_input(ifp, &ml);
2214 
2215  resubmit:
2216 	/* Setup a new transfer. */
2217 	usbd_setup_xfer(xfer, usc->rx_data_pipe, data, data->buf,
2218 	    ATHN_USB_RXBUFSZ, USBD_SHORT_XFER_OK | USBD_NO_COPY,
2219 	    USBD_NO_TIMEOUT, athn_usb_rxeof);
2220 	(void)usbd_transfer(xfer);
2221 }
2222 
2223 void
2224 athn_usb_txeof(struct usbd_xfer *xfer, void *priv,
2225     usbd_status status)
2226 {
2227 	struct athn_usb_tx_data *data = priv;
2228 	struct athn_usb_softc *usc = data->sc;
2229 	struct athn_softc *sc = &usc->sc_sc;
2230 	struct ifnet *ifp = &sc->sc_ic.ic_if;
2231 	int s;
2232 
2233 	s = splnet();
2234 	/* Put this Tx buffer back to our free list. */
2235 	TAILQ_INSERT_TAIL(&usc->tx_free_list, data, next);
2236 
2237 	if (__predict_false(status != USBD_NORMAL_COMPLETION)) {
2238 		DPRINTF(("TX status=%d\n", status));
2239 		if (status == USBD_STALLED)
2240 			usbd_clear_endpoint_stall_async(usc->tx_data_pipe);
2241 		ifp->if_oerrors++;
2242 		splx(s);
2243 		/* XXX Why return? */
2244 		return;
2245 	}
2246 	sc->sc_tx_timer = 0;
2247 
2248 	/* We just released a Tx buffer, notify Tx. */
2249 	if (ifq_is_oactive(&ifp->if_snd)) {
2250 		ifq_clr_oactive(&ifp->if_snd);
2251 		ifp->if_start(ifp);
2252 	}
2253 	splx(s);
2254 }
2255 
2256 int
2257 athn_usb_tx(struct athn_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
2258 {
2259 	struct athn_usb_softc *usc = (struct athn_usb_softc *)sc;
2260 	struct athn_node *an = (struct athn_node *)ni;
2261 	struct ieee80211com *ic = &sc->sc_ic;
2262 	struct ieee80211_frame *wh;
2263 	struct ieee80211_key *k = NULL;
2264 	struct athn_usb_tx_data *data;
2265 	struct ar_stream_hdr *hdr;
2266 	struct ar_htc_frame_hdr *htc;
2267 	struct ar_tx_frame *txf;
2268 	struct ar_tx_mgmt *txm;
2269 	uint8_t *frm;
2270 	uint16_t qos;
2271 	uint8_t qid, tid = 0;
2272 	int hasqos, xferlen, error;
2273 
2274 	wh = mtod(m, struct ieee80211_frame *);
2275 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
2276 		k = ieee80211_get_txkey(ic, wh, ni);
2277 		if (k->k_cipher == IEEE80211_CIPHER_CCMP) {
2278 			u_int hdrlen = ieee80211_get_hdrlen(wh);
2279 			if (ar5008_ccmp_encap(m, hdrlen, k) != 0)
2280 				return (ENOBUFS);
2281 		} else {
2282 			if ((m = ieee80211_encrypt(ic, m, k)) == NULL)
2283 				return (ENOBUFS);
2284 			k = NULL; /* skip hardware crypto further below */
2285 		}
2286 		wh = mtod(m, struct ieee80211_frame *);
2287 	}
2288 	if ((hasqos = ieee80211_has_qos(wh))) {
2289 		qos = ieee80211_get_qos(wh);
2290 		tid = qos & IEEE80211_QOS_TID;
2291 		qid = ieee80211_up_to_ac(ic, tid);
2292 	} else
2293 		qid = EDCA_AC_BE;
2294 
2295 	/* Grab a Tx buffer from our free list. */
2296 	data = TAILQ_FIRST(&usc->tx_free_list);
2297 	TAILQ_REMOVE(&usc->tx_free_list, data, next);
2298 
2299 #if NBPFILTER > 0
2300 	/* XXX Change radiotap Tx header for USB (no txrate). */
2301 	if (__predict_false(sc->sc_drvbpf != NULL)) {
2302 		struct athn_tx_radiotap_header *tap = &sc->sc_txtap;
2303 		struct mbuf mb;
2304 
2305 		tap->wt_flags = 0;
2306 		tap->wt_chan_freq = htole16(ic->ic_bss->ni_chan->ic_freq);
2307 		tap->wt_chan_flags = htole16(ic->ic_bss->ni_chan->ic_flags);
2308 		mb.m_data = (caddr_t)tap;
2309 		mb.m_len = sc->sc_txtap_len;
2310 		mb.m_next = m;
2311 		mb.m_nextpkt = NULL;
2312 		mb.m_type = 0;
2313 		mb.m_flags = 0;
2314 		bpf_mtap(sc->sc_drvbpf, &mb, BPF_DIRECTION_OUT);
2315 	}
2316 #endif
2317 
2318 	/* NB: We don't take advantage of USB Tx stream mode for now. */
2319 	hdr = (struct ar_stream_hdr *)data->buf;
2320 	hdr->tag = htole16(AR_USB_TX_STREAM_TAG);
2321 
2322 	htc = (struct ar_htc_frame_hdr *)&hdr[1];
2323 	memset(htc, 0, sizeof(*htc));
2324 	if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
2325 	    IEEE80211_FC0_TYPE_DATA) {
2326 		htc->endpoint_id = usc->ep_data[qid];
2327 
2328 		txf = (struct ar_tx_frame *)&htc[1];
2329 		memset(txf, 0, sizeof(*txf));
2330 		txf->data_type = AR_HTC_NORMAL;
2331 		txf->node_idx = an->sta_index;
2332 		txf->vif_idx = 0;
2333 		txf->tid = tid;
2334 		if (m->m_pkthdr.len + IEEE80211_CRC_LEN > ic->ic_rtsthreshold)
2335 			txf->flags |= htobe32(AR_HTC_TX_RTSCTS);
2336 		else if (ic->ic_flags & IEEE80211_F_USEPROT) {
2337 			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
2338 				txf->flags |= htobe32(AR_HTC_TX_CTSONLY);
2339 			else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
2340 				txf->flags |= htobe32(AR_HTC_TX_RTSCTS);
2341 		}
2342 
2343 		if (k != NULL) {
2344 			/* Map 802.11 cipher to hardware encryption type. */
2345 			if (k->k_cipher == IEEE80211_CIPHER_CCMP) {
2346 				txf->key_type = AR_ENCR_TYPE_AES;
2347 			} else
2348 				panic("unsupported cipher");
2349 			/*
2350 			 * NB: The key cache entry index is stored in the key
2351 			 * private field when the key is installed.
2352 			 */
2353 			txf->key_idx = (uintptr_t)k->k_priv;
2354 		} else
2355 			txf->key_idx = 0xff;
2356 
2357 		txf->cookie = an->sta_index;
2358 		frm = (uint8_t *)&txf[1];
2359 	} else {
2360 		htc->endpoint_id = usc->ep_mgmt;
2361 
2362 		txm = (struct ar_tx_mgmt *)&htc[1];
2363 		memset(txm, 0, sizeof(*txm));
2364 		txm->node_idx = an->sta_index;
2365 		txm->vif_idx = 0;
2366 		txm->key_idx = 0xff;
2367 		txm->cookie = an->sta_index;
2368 		frm = (uint8_t *)&txm[1];
2369 	}
2370 	/* Copy payload. */
2371 	m_copydata(m, 0, m->m_pkthdr.len, (caddr_t)frm);
2372 	frm += m->m_pkthdr.len;
2373 	m_freem(m);
2374 
2375 	/* Finalize headers. */
2376 	htc->payload_len = htobe16(frm - (uint8_t *)&htc[1]);
2377 	hdr->len = htole16(frm - (uint8_t *)&hdr[1]);
2378 	xferlen = frm - data->buf;
2379 
2380 	usbd_setup_xfer(data->xfer, usc->tx_data_pipe, data, data->buf,
2381 	    xferlen, USBD_FORCE_SHORT_XFER | USBD_NO_COPY, ATHN_USB_TX_TIMEOUT,
2382 	    athn_usb_txeof);
2383 	error = usbd_transfer(data->xfer);
2384 	if (__predict_false(error != USBD_IN_PROGRESS && error != 0)) {
2385 		/* Put this Tx buffer back to our free list. */
2386 		TAILQ_INSERT_TAIL(&usc->tx_free_list, data, next);
2387 		return (error);
2388 	}
2389 	ieee80211_release_node(ic, ni);
2390 	return (0);
2391 }
2392 
2393 void
2394 athn_usb_start(struct ifnet *ifp)
2395 {
2396 	struct athn_softc *sc = ifp->if_softc;
2397 	struct athn_usb_softc *usc = (struct athn_usb_softc *)sc;
2398 	struct ieee80211com *ic = &sc->sc_ic;
2399 	struct ieee80211_node *ni;
2400 	struct mbuf *m;
2401 
2402 	if (!(ifp->if_flags & IFF_RUNNING) || ifq_is_oactive(&ifp->if_snd))
2403 		return;
2404 
2405 	for (;;) {
2406 		if (TAILQ_EMPTY(&usc->tx_free_list)) {
2407 			ifq_set_oactive(&ifp->if_snd);
2408 			break;
2409 		}
2410 		/* Send pending management frames first. */
2411 		m = mq_dequeue(&ic->ic_mgtq);
2412 		if (m != NULL) {
2413 			ni = m->m_pkthdr.ph_cookie;
2414 			goto sendit;
2415 		}
2416 		if (ic->ic_state != IEEE80211_S_RUN)
2417 			break;
2418 
2419 		/* Encapsulate and send data frames. */
2420 		m = ifq_dequeue(&ifp->if_snd);
2421 		if (m == NULL)
2422 			break;
2423 #if NBPFILTER > 0
2424 		if (ifp->if_bpf != NULL)
2425 			bpf_mtap(ifp->if_bpf, m, BPF_DIRECTION_OUT);
2426 #endif
2427 		if ((m = ieee80211_encap(ifp, m, &ni)) == NULL)
2428 			continue;
2429  sendit:
2430 #if NBPFILTER > 0
2431 		if (ic->ic_rawbpf != NULL)
2432 			bpf_mtap(ic->ic_rawbpf, m, BPF_DIRECTION_OUT);
2433 #endif
2434 		if (athn_usb_tx(sc, m, ni) != 0) {
2435 			ieee80211_release_node(ic, ni);
2436 			ifp->if_oerrors++;
2437 			continue;
2438 		}
2439 
2440 		sc->sc_tx_timer = 5;
2441 		ifp->if_timer = 1;
2442 	}
2443 }
2444 
2445 void
2446 athn_usb_watchdog(struct ifnet *ifp)
2447 {
2448 	struct athn_softc *sc = ifp->if_softc;
2449 
2450 	ifp->if_timer = 0;
2451 
2452 	if (sc->sc_tx_timer > 0) {
2453 		if (--sc->sc_tx_timer == 0) {
2454 			printf("%s: device timeout\n", sc->sc_dev.dv_xname);
2455 			/* athn_usb_init(ifp); XXX needs a process context! */
2456 			ifp->if_oerrors++;
2457 			return;
2458 		}
2459 		ifp->if_timer = 1;
2460 	}
2461 	ieee80211_watchdog(ifp);
2462 }
2463 
2464 int
2465 athn_usb_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
2466 {
2467 	struct athn_softc *sc = ifp->if_softc;
2468 	struct athn_usb_softc *usc = (struct athn_usb_softc *)sc;
2469 	struct ieee80211com *ic = &sc->sc_ic;
2470 	int s, error = 0;
2471 
2472 	if (usbd_is_dying(usc->sc_udev))
2473 		return ENXIO;
2474 
2475 	usbd_ref_incr(usc->sc_udev);
2476 
2477 	s = splnet();
2478 
2479 	switch (cmd) {
2480 	case SIOCSIFADDR:
2481 		ifp->if_flags |= IFF_UP;
2482 		/* FALLTHROUGH */
2483 	case SIOCSIFFLAGS:
2484 		if (ifp->if_flags & IFF_UP) {
2485 			if (!(ifp->if_flags & IFF_RUNNING))
2486 				error = athn_usb_init(ifp);
2487 		} else {
2488 			if (ifp->if_flags & IFF_RUNNING)
2489 				athn_usb_stop(ifp);
2490 		}
2491 		break;
2492 	case SIOCS80211CHANNEL:
2493 		error = ieee80211_ioctl(ifp, cmd, data);
2494 		if (error == ENETRESET &&
2495 		    ic->ic_opmode == IEEE80211_M_MONITOR) {
2496 			if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
2497 			    (IFF_UP | IFF_RUNNING)) {
2498 				athn_usb_switch_chan(sc, ic->ic_ibss_chan,
2499 				    NULL);
2500 			}
2501 			error = 0;
2502 		}
2503 		break;
2504 	default:
2505 		error = ieee80211_ioctl(ifp, cmd, data);
2506 	}
2507 
2508 	if (error == ENETRESET) {
2509 		error = 0;
2510 		if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
2511 		    (IFF_UP | IFF_RUNNING)) {
2512 			athn_usb_stop(ifp);
2513 			error = athn_usb_init(ifp);
2514 		}
2515 	}
2516 	splx(s);
2517 
2518 	usbd_ref_decr(usc->sc_udev);
2519 
2520 	return (error);
2521 }
2522 
2523 int
2524 athn_usb_init(struct ifnet *ifp)
2525 {
2526 	struct athn_softc *sc = ifp->if_softc;
2527 	struct athn_usb_softc *usc = (struct athn_usb_softc *)sc;
2528 	struct athn_ops *ops = &sc->ops;
2529 	struct ieee80211com *ic = &sc->sc_ic;
2530 	struct ieee80211_channel *c, *extc;
2531 	struct athn_usb_rx_data *data;
2532 	struct ar_htc_target_vif hvif;
2533 	struct ar_htc_target_sta sta;
2534 	struct ar_htc_cap_target hic;
2535 	uint16_t mode;
2536 	int i, error;
2537 
2538 	/* Init host async commands ring. */
2539 	usc->cmdq.cur = usc->cmdq.next = usc->cmdq.queued = 0;
2540 
2541 	/* Allocate Tx/Rx buffers. */
2542 	error = athn_usb_alloc_rx_list(usc);
2543 	if (error != 0)
2544 		goto fail;
2545 	error = athn_usb_alloc_tx_list(usc);
2546 	if (error != 0)
2547 		goto fail;
2548 	/* Steal one buffer for beacons. */
2549 	usc->tx_bcn = TAILQ_FIRST(&usc->tx_free_list);
2550 	TAILQ_REMOVE(&usc->tx_free_list, usc->tx_bcn, next);
2551 
2552 	c = ic->ic_bss->ni_chan = ic->ic_ibss_chan;
2553 	extc = NULL;
2554 
2555 	/* In case a new MAC address has been configured. */
2556 	IEEE80211_ADDR_COPY(ic->ic_myaddr, LLADDR(ifp->if_sadl));
2557 
2558 	error = athn_set_power_awake(sc);
2559 	if (error != 0)
2560 		goto fail;
2561 
2562 	error = athn_usb_wmi_cmd(usc, AR_WMI_CMD_FLUSH_RECV);
2563 	if (error != 0)
2564 		goto fail;
2565 
2566 	error = athn_hw_reset(sc, c, extc, 1);
2567 	if (error != 0)
2568 		goto fail;
2569 
2570 	ops->set_txpower(sc, c, extc);
2571 
2572 	mode = htobe16(IEEE80211_IS_CHAN_2GHZ(c) ?
2573 	    AR_HTC_MODE_11NG : AR_HTC_MODE_11NA);
2574 	error = athn_usb_wmi_xcmd(usc, AR_WMI_CMD_SET_MODE,
2575 	    &mode, sizeof(mode), NULL);
2576 	if (error != 0)
2577 		goto fail;
2578 
2579 	error = athn_usb_wmi_cmd(usc, AR_WMI_CMD_ATH_INIT);
2580 	if (error != 0)
2581 		goto fail;
2582 
2583 	error = athn_usb_wmi_cmd(usc, AR_WMI_CMD_START_RECV);
2584 	if (error != 0)
2585 		goto fail;
2586 
2587 	athn_rx_start(sc);
2588 
2589 	/* Create main interface on target. */
2590 	memset(&hvif, 0, sizeof(hvif));
2591 	hvif.index = 0;
2592 	IEEE80211_ADDR_COPY(hvif.myaddr, ic->ic_myaddr);
2593 	switch (ic->ic_opmode) {
2594 	case IEEE80211_M_STA:
2595 		hvif.opmode = htobe32(AR_HTC_M_STA);
2596 		break;
2597 	case IEEE80211_M_MONITOR:
2598 		hvif.opmode = htobe32(AR_HTC_M_MONITOR);
2599 		break;
2600 #ifndef IEEE80211_STA_ONLY
2601 	case IEEE80211_M_IBSS:
2602 		hvif.opmode = htobe32(AR_HTC_M_IBSS);
2603 		break;
2604 	case IEEE80211_M_AHDEMO:
2605 		hvif.opmode = htobe32(AR_HTC_M_AHDEMO);
2606 		break;
2607 	case IEEE80211_M_HOSTAP:
2608 		hvif.opmode = htobe32(AR_HTC_M_HOSTAP);
2609 		break;
2610 #endif
2611 	}
2612 	hvif.rtsthreshold = htobe16(ic->ic_rtsthreshold);
2613 	DPRINTF(("creating VAP\n"));
2614 	error = athn_usb_wmi_xcmd(usc, AR_WMI_CMD_VAP_CREATE,
2615 	    &hvif, sizeof(hvif), NULL);
2616 	if (error != 0)
2617 		goto fail;
2618 
2619 	/* Create a fake node to send management frames before assoc. */
2620 	memset(&sta, 0, sizeof(sta));
2621 	IEEE80211_ADDR_COPY(sta.macaddr, ic->ic_myaddr);
2622 	sta.sta_index = 0;
2623 	sta.is_vif_sta = 1;
2624 	sta.vif_index = hvif.index;
2625 	sta.maxampdu = 0xffff;
2626 	DPRINTF(("creating default node\n"));
2627 	error = athn_usb_wmi_xcmd(usc, AR_WMI_CMD_NODE_CREATE,
2628 	    &sta, sizeof(sta), NULL);
2629 	if (error != 0)
2630 		goto fail;
2631 	usc->free_node_slots = ~(1 << sta.sta_index);
2632 
2633 	/* Update target capabilities. */
2634 	memset(&hic, 0, sizeof(hic));
2635 	hic.ampdu_limit = htobe32(0x0000ffff);
2636 	hic.ampdu_subframes = 20;
2637 	hic.txchainmask = sc->txchainmask;
2638 	DPRINTF(("updating target configuration\n"));
2639 	error = athn_usb_wmi_xcmd(usc, AR_WMI_CMD_TARGET_IC_UPDATE,
2640 	    &hic, sizeof(hic), NULL);
2641 	if (error != 0)
2642 		goto fail;
2643 
2644 	/* Queue Rx xfers. */
2645 	for (i = 0; i < ATHN_USB_RX_LIST_COUNT; i++) {
2646 		data = &usc->rx_data[i];
2647 
2648 		usbd_setup_xfer(data->xfer, usc->rx_data_pipe, data, data->buf,
2649 		    ATHN_USB_RXBUFSZ, USBD_SHORT_XFER_OK | USBD_NO_COPY,
2650 		    USBD_NO_TIMEOUT, athn_usb_rxeof);
2651 		error = usbd_transfer(data->xfer);
2652 		if (error != 0 && error != USBD_IN_PROGRESS)
2653 			goto fail;
2654 	}
2655 	/* We're ready to go. */
2656 	ifp->if_flags |= IFF_RUNNING;
2657 	ifq_clr_oactive(&ifp->if_snd);
2658 
2659 #ifdef notyet
2660 	if (ic->ic_flags & IEEE80211_F_WEPON) {
2661 		/* Install WEP keys. */
2662 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
2663 			athn_usb_set_key(ic, NULL, &ic->ic_nw_keys[i]);
2664 	}
2665 #endif
2666 	if (ic->ic_opmode == IEEE80211_M_MONITOR)
2667 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
2668 	else
2669 		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
2670 	athn_usb_wait_async(usc);
2671 	return (0);
2672  fail:
2673 	athn_usb_stop(ifp);
2674 	return (error);
2675 }
2676 
2677 void
2678 athn_usb_stop(struct ifnet *ifp)
2679 {
2680 	struct athn_softc *sc = ifp->if_softc;
2681 	struct athn_usb_softc *usc = (struct athn_usb_softc *)sc;
2682 	struct ieee80211com *ic = &sc->sc_ic;
2683 	struct ar_htc_target_vif hvif;
2684 	uint8_t sta_index;
2685 	int s;
2686 
2687 	sc->sc_tx_timer = 0;
2688 	ifp->if_timer = 0;
2689 	ifp->if_flags &= ~IFF_RUNNING;
2690 	ifq_clr_oactive(&ifp->if_snd);
2691 
2692 	s = splusb();
2693 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
2694 
2695 	/* Wait for all async commands to complete. */
2696 	athn_usb_wait_async(usc);
2697 
2698 	timeout_del(&sc->scan_to);
2699 	timeout_del(&sc->calib_to);
2700 
2701 	/* Remove all non-default nodes. */
2702 	for (sta_index = 1; sta_index < AR_USB_MAX_STA; sta_index++) {
2703 		if (usc->free_node_slots & (1 << sta_index))
2704 			continue;
2705 		(void)athn_usb_wmi_xcmd(usc, AR_WMI_CMD_NODE_REMOVE,
2706 		    &sta_index, sizeof(sta_index), NULL);
2707 	}
2708 
2709 	/* Remove main interface. This also invalidates our default node. */
2710 	memset(&hvif, 0, sizeof(hvif));
2711 	hvif.index = 0;
2712 	IEEE80211_ADDR_COPY(hvif.myaddr, ic->ic_myaddr);
2713 	(void)athn_usb_wmi_xcmd(usc, AR_WMI_CMD_VAP_REMOVE,
2714 	    &hvif, sizeof(hvif), NULL);
2715 
2716 	usc->free_node_slots = 0xff;
2717 
2718 	(void)athn_usb_wmi_cmd(usc, AR_WMI_CMD_DISABLE_INTR);
2719 	(void)athn_usb_wmi_cmd(usc, AR_WMI_CMD_DRAIN_TXQ_ALL);
2720 	(void)athn_usb_wmi_cmd(usc, AR_WMI_CMD_STOP_RECV);
2721 
2722 	athn_reset(sc, 0);
2723 	athn_init_pll(sc, NULL);
2724 	athn_set_power_awake(sc);
2725 	athn_reset(sc, 1);
2726 	athn_init_pll(sc, NULL);
2727 	athn_set_power_sleep(sc);
2728 
2729 	/* Abort Tx/Rx. */
2730 	usbd_abort_pipe(usc->tx_data_pipe);
2731 	usbd_abort_pipe(usc->rx_data_pipe);
2732 
2733 	/* Free Tx/Rx buffers. */
2734 	athn_usb_free_tx_list(usc);
2735 	athn_usb_free_rx_list(usc);
2736 	splx(s);
2737 
2738 	/* Flush Rx stream. */
2739 	m_freem(usc->rx_stream.m);
2740 	usc->rx_stream.m = NULL;
2741 	usc->rx_stream.left = 0;
2742 }
2743