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