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