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