xref: /freebsd/sys/net80211/ieee80211_proto.c (revision 94a82666846d62cdff7d78f78d428df35412e50d)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2001 Atsushi Onoe
5  * Copyright (c) 2002-2008 Sam Leffler, Errno Consulting
6  * Copyright (c) 2012 IEEE
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 /*
34  * IEEE 802.11 protocol support.
35  */
36 
37 #include "opt_inet.h"
38 #include "opt_wlan.h"
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
43 #include <sys/malloc.h>
44 
45 #include <sys/socket.h>
46 #include <sys/sockio.h>
47 
48 #include <net/if.h>
49 #include <net/if_var.h>
50 #include <net/if_media.h>
51 #include <net/ethernet.h>		/* XXX for ether_sprintf */
52 
53 #include <net80211/ieee80211_var.h>
54 #include <net80211/ieee80211_adhoc.h>
55 #include <net80211/ieee80211_sta.h>
56 #include <net80211/ieee80211_hostap.h>
57 #include <net80211/ieee80211_wds.h>
58 #ifdef IEEE80211_SUPPORT_MESH
59 #include <net80211/ieee80211_mesh.h>
60 #endif
61 #include <net80211/ieee80211_monitor.h>
62 #include <net80211/ieee80211_input.h>
63 
64 /* XXX tunables */
65 #define	AGGRESSIVE_MODE_SWITCH_HYSTERESIS	3	/* pkts / 100ms */
66 #define	HIGH_PRI_SWITCH_THRESH			10	/* pkts / 100ms */
67 
68 const char *mgt_subtype_name[] = {
69 	"assoc_req",	"assoc_resp",	"reassoc_req",	"reassoc_resp",
70 	"probe_req",	"probe_resp",	"timing_adv",	"reserved#7",
71 	"beacon",	"atim",		"disassoc",	"auth",
72 	"deauth",	"action",	"action_noack",	"reserved#15"
73 };
74 const char *ctl_subtype_name[] = {
75 	"reserved#0",	"reserved#1",	"reserved#2",	"reserved#3",
76 	"reserved#4",	"reserved#5",	"reserved#6",	"control_wrap",
77 	"bar",		"ba",		"ps_poll",	"rts",
78 	"cts",		"ack",		"cf_end",	"cf_end_ack"
79 };
80 const char *ieee80211_opmode_name[IEEE80211_OPMODE_MAX] = {
81 	"IBSS",		/* IEEE80211_M_IBSS */
82 	"STA",		/* IEEE80211_M_STA */
83 	"WDS",		/* IEEE80211_M_WDS */
84 	"AHDEMO",	/* IEEE80211_M_AHDEMO */
85 	"HOSTAP",	/* IEEE80211_M_HOSTAP */
86 	"MONITOR",	/* IEEE80211_M_MONITOR */
87 	"MBSS"		/* IEEE80211_M_MBSS */
88 };
89 const char *ieee80211_state_name[IEEE80211_S_MAX] = {
90 	"INIT",		/* IEEE80211_S_INIT */
91 	"SCAN",		/* IEEE80211_S_SCAN */
92 	"AUTH",		/* IEEE80211_S_AUTH */
93 	"ASSOC",	/* IEEE80211_S_ASSOC */
94 	"CAC",		/* IEEE80211_S_CAC */
95 	"RUN",		/* IEEE80211_S_RUN */
96 	"CSA",		/* IEEE80211_S_CSA */
97 	"SLEEP",	/* IEEE80211_S_SLEEP */
98 };
99 const char *ieee80211_wme_acnames[] = {
100 	"WME_AC_BE",
101 	"WME_AC_BK",
102 	"WME_AC_VI",
103 	"WME_AC_VO",
104 	"WME_UPSD",
105 };
106 
107 
108 /*
109  * Reason code descriptions were (mostly) obtained from
110  * IEEE Std 802.11-2012, pp. 442-445 Table 8-36.
111  */
112 const char *
113 ieee80211_reason_to_string(uint16_t reason)
114 {
115 	switch (reason) {
116 	case IEEE80211_REASON_UNSPECIFIED:
117 		return ("unspecified");
118 	case IEEE80211_REASON_AUTH_EXPIRE:
119 		return ("previous authentication is expired");
120 	case IEEE80211_REASON_AUTH_LEAVE:
121 		return ("sending STA is leaving/has left IBSS or ESS");
122 	case IEEE80211_REASON_ASSOC_EXPIRE:
123 		return ("disassociated due to inactivity");
124 	case IEEE80211_REASON_ASSOC_TOOMANY:
125 		return ("too many associated STAs");
126 	case IEEE80211_REASON_NOT_AUTHED:
127 		return ("class 2 frame received from nonauthenticated STA");
128 	case IEEE80211_REASON_NOT_ASSOCED:
129 		return ("class 3 frame received from nonassociated STA");
130 	case IEEE80211_REASON_ASSOC_LEAVE:
131 		return ("sending STA is leaving/has left BSS");
132 	case IEEE80211_REASON_ASSOC_NOT_AUTHED:
133 		return ("STA requesting (re)association is not authenticated");
134 	case IEEE80211_REASON_DISASSOC_PWRCAP_BAD:
135 		return ("information in the Power Capability element is "
136 			"unacceptable");
137 	case IEEE80211_REASON_DISASSOC_SUPCHAN_BAD:
138 		return ("information in the Supported Channels element is "
139 			"unacceptable");
140 	case IEEE80211_REASON_IE_INVALID:
141 		return ("invalid element");
142 	case IEEE80211_REASON_MIC_FAILURE:
143 		return ("MIC failure");
144 	case IEEE80211_REASON_4WAY_HANDSHAKE_TIMEOUT:
145 		return ("4-Way handshake timeout");
146 	case IEEE80211_REASON_GROUP_KEY_UPDATE_TIMEOUT:
147 		return ("group key update timeout");
148 	case IEEE80211_REASON_IE_IN_4WAY_DIFFERS:
149 		return ("element in 4-Way handshake different from "
150 			"(re)association request/probe response/beacon frame");
151 	case IEEE80211_REASON_GROUP_CIPHER_INVALID:
152 		return ("invalid group cipher");
153 	case IEEE80211_REASON_PAIRWISE_CIPHER_INVALID:
154 		return ("invalid pairwise cipher");
155 	case IEEE80211_REASON_AKMP_INVALID:
156 		return ("invalid AKMP");
157 	case IEEE80211_REASON_UNSUPP_RSN_IE_VERSION:
158 		return ("unsupported version in RSN IE");
159 	case IEEE80211_REASON_INVALID_RSN_IE_CAP:
160 		return ("invalid capabilities in RSN IE");
161 	case IEEE80211_REASON_802_1X_AUTH_FAILED:
162 		return ("IEEE 802.1X authentication failed");
163 	case IEEE80211_REASON_CIPHER_SUITE_REJECTED:
164 		return ("cipher suite rejected because of the security "
165 			"policy");
166 	case IEEE80211_REASON_UNSPECIFIED_QOS:
167 		return ("unspecified (QoS-related)");
168 	case IEEE80211_REASON_INSUFFICIENT_BW:
169 		return ("QoS AP lacks sufficient bandwidth for this QoS STA");
170 	case IEEE80211_REASON_TOOMANY_FRAMES:
171 		return ("too many frames need to be acknowledged");
172 	case IEEE80211_REASON_OUTSIDE_TXOP:
173 		return ("STA is transmitting outside the limits of its TXOPs");
174 	case IEEE80211_REASON_LEAVING_QBSS:
175 		return ("requested from peer STA (the STA is "
176 			"resetting/leaving the BSS)");
177 	case IEEE80211_REASON_BAD_MECHANISM:
178 		return ("requested from peer STA (it does not want to use "
179 			"the mechanism)");
180 	case IEEE80211_REASON_SETUP_NEEDED:
181 		return ("requested from peer STA (setup is required for the "
182 			"used mechanism)");
183 	case IEEE80211_REASON_TIMEOUT:
184 		return ("requested from peer STA (timeout)");
185 	case IEEE80211_REASON_PEER_LINK_CANCELED:
186 		return ("SME cancels the mesh peering instance (not related "
187 			"to the maximum number of peer mesh STAs)");
188 	case IEEE80211_REASON_MESH_MAX_PEERS:
189 		return ("maximum number of peer mesh STAs was reached");
190 	case IEEE80211_REASON_MESH_CPVIOLATION:
191 		return ("the received information violates the Mesh "
192 			"Configuration policy configured in the mesh STA "
193 			"profile");
194 	case IEEE80211_REASON_MESH_CLOSE_RCVD:
195 		return ("the mesh STA has received a Mesh Peering Close "
196 			"message requesting to close the mesh peering");
197 	case IEEE80211_REASON_MESH_MAX_RETRIES:
198 		return ("the mesh STA has resent dot11MeshMaxRetries Mesh "
199 			"Peering Open messages, without receiving a Mesh "
200 			"Peering Confirm message");
201 	case IEEE80211_REASON_MESH_CONFIRM_TIMEOUT:
202 		return ("the confirmTimer for the mesh peering instance times "
203 			"out");
204 	case IEEE80211_REASON_MESH_INVALID_GTK:
205 		return ("the mesh STA fails to unwrap the GTK or the values "
206 			"in the wrapped contents do not match");
207 	case IEEE80211_REASON_MESH_INCONS_PARAMS:
208 		return ("the mesh STA receives inconsistent information about "
209 			"the mesh parameters between Mesh Peering Management "
210 			"frames");
211 	case IEEE80211_REASON_MESH_INVALID_SECURITY:
212 		return ("the mesh STA fails the authenticated mesh peering "
213 			"exchange because due to failure in selecting "
214 			"pairwise/group ciphersuite");
215 	case IEEE80211_REASON_MESH_PERR_NO_PROXY:
216 		return ("the mesh STA does not have proxy information for "
217 			"this external destination");
218 	case IEEE80211_REASON_MESH_PERR_NO_FI:
219 		return ("the mesh STA does not have forwarding information "
220 			"for this destination");
221 	case IEEE80211_REASON_MESH_PERR_DEST_UNREACH:
222 		return ("the mesh STA determines that the link to the next "
223 			"hop of an active path in its forwarding information "
224 			"is no longer usable");
225 	case IEEE80211_REASON_MESH_MAC_ALRDY_EXISTS_MBSS:
226 		return ("the MAC address of the STA already exists in the "
227 			"mesh BSS");
228 	case IEEE80211_REASON_MESH_CHAN_SWITCH_REG:
229 		return ("the mesh STA performs channel switch to meet "
230 			"regulatory requirements");
231 	case IEEE80211_REASON_MESH_CHAN_SWITCH_UNSPEC:
232 		return ("the mesh STA performs channel switch with "
233 			"unspecified reason");
234 	default:
235 		return ("reserved/unknown");
236 	}
237 }
238 
239 static void beacon_miss(void *, int);
240 static void beacon_swmiss(void *, int);
241 static void parent_updown(void *, int);
242 static void update_mcast(void *, int);
243 static void update_promisc(void *, int);
244 static void update_channel(void *, int);
245 static void update_chw(void *, int);
246 static void vap_update_wme(void *, int);
247 static void vap_update_slot(void *, int);
248 static void restart_vaps(void *, int);
249 static void ieee80211_newstate_cb(void *, int);
250 
251 static int
252 null_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
253 	const struct ieee80211_bpf_params *params)
254 {
255 
256 	ic_printf(ni->ni_ic, "missing ic_raw_xmit callback, drop frame\n");
257 	m_freem(m);
258 	return ENETDOWN;
259 }
260 
261 void
262 ieee80211_proto_attach(struct ieee80211com *ic)
263 {
264 	uint8_t hdrlen;
265 
266 	/* override the 802.3 setting */
267 	hdrlen = ic->ic_headroom
268 		+ sizeof(struct ieee80211_qosframe_addr4)
269 		+ IEEE80211_WEP_IVLEN + IEEE80211_WEP_KIDLEN
270 		+ IEEE80211_WEP_EXTIVLEN;
271 	/* XXX no way to recalculate on ifdetach */
272 	if (ALIGN(hdrlen) > max_linkhdr) {
273 		/* XXX sanity check... */
274 		max_linkhdr = ALIGN(hdrlen);
275 		max_hdr = max_linkhdr + max_protohdr;
276 		max_datalen = MHLEN - max_hdr;
277 	}
278 	ic->ic_protmode = IEEE80211_PROT_CTSONLY;
279 
280 	TASK_INIT(&ic->ic_parent_task, 0, parent_updown, ic);
281 	TASK_INIT(&ic->ic_mcast_task, 0, update_mcast, ic);
282 	TASK_INIT(&ic->ic_promisc_task, 0, update_promisc, ic);
283 	TASK_INIT(&ic->ic_chan_task, 0, update_channel, ic);
284 	TASK_INIT(&ic->ic_bmiss_task, 0, beacon_miss, ic);
285 	TASK_INIT(&ic->ic_chw_task, 0, update_chw, ic);
286 	TASK_INIT(&ic->ic_restart_task, 0, restart_vaps, ic);
287 
288 	ic->ic_wme.wme_hipri_switch_hysteresis =
289 		AGGRESSIVE_MODE_SWITCH_HYSTERESIS;
290 
291 	/* initialize management frame handlers */
292 	ic->ic_send_mgmt = ieee80211_send_mgmt;
293 	ic->ic_raw_xmit = null_raw_xmit;
294 
295 	ieee80211_adhoc_attach(ic);
296 	ieee80211_sta_attach(ic);
297 	ieee80211_wds_attach(ic);
298 	ieee80211_hostap_attach(ic);
299 #ifdef IEEE80211_SUPPORT_MESH
300 	ieee80211_mesh_attach(ic);
301 #endif
302 	ieee80211_monitor_attach(ic);
303 }
304 
305 void
306 ieee80211_proto_detach(struct ieee80211com *ic)
307 {
308 	ieee80211_monitor_detach(ic);
309 #ifdef IEEE80211_SUPPORT_MESH
310 	ieee80211_mesh_detach(ic);
311 #endif
312 	ieee80211_hostap_detach(ic);
313 	ieee80211_wds_detach(ic);
314 	ieee80211_adhoc_detach(ic);
315 	ieee80211_sta_detach(ic);
316 }
317 
318 static void
319 null_update_beacon(struct ieee80211vap *vap, int item)
320 {
321 }
322 
323 void
324 ieee80211_proto_vattach(struct ieee80211vap *vap)
325 {
326 	struct ieee80211com *ic = vap->iv_ic;
327 	struct ifnet *ifp = vap->iv_ifp;
328 	int i;
329 
330 	/* override the 802.3 setting */
331 	ifp->if_hdrlen = ic->ic_headroom
332                 + sizeof(struct ieee80211_qosframe_addr4)
333                 + IEEE80211_WEP_IVLEN + IEEE80211_WEP_KIDLEN
334                 + IEEE80211_WEP_EXTIVLEN;
335 
336 	vap->iv_rtsthreshold = IEEE80211_RTS_DEFAULT;
337 	vap->iv_fragthreshold = IEEE80211_FRAG_DEFAULT;
338 	vap->iv_bmiss_max = IEEE80211_BMISS_MAX;
339 	callout_init_mtx(&vap->iv_swbmiss, IEEE80211_LOCK_OBJ(ic), 0);
340 	callout_init(&vap->iv_mgtsend, 1);
341 	TASK_INIT(&vap->iv_nstate_task, 0, ieee80211_newstate_cb, vap);
342 	TASK_INIT(&vap->iv_swbmiss_task, 0, beacon_swmiss, vap);
343 	TASK_INIT(&vap->iv_wme_task, 0, vap_update_wme, vap);
344 	TASK_INIT(&vap->iv_slot_task, 0, vap_update_slot, vap);
345 	/*
346 	 * Install default tx rate handling: no fixed rate, lowest
347 	 * supported rate for mgmt and multicast frames.  Default
348 	 * max retry count.  These settings can be changed by the
349 	 * driver and/or user applications.
350 	 */
351 	for (i = IEEE80211_MODE_11A; i < IEEE80211_MODE_MAX; i++) {
352 		if (isclr(ic->ic_modecaps, i))
353 			continue;
354 
355 		const struct ieee80211_rateset *rs = &ic->ic_sup_rates[i];
356 
357 		vap->iv_txparms[i].ucastrate = IEEE80211_FIXED_RATE_NONE;
358 
359 		/*
360 		 * Setting the management rate to MCS 0 assumes that the
361 		 * BSS Basic rate set is empty and the BSS Basic MCS set
362 		 * is not.
363 		 *
364 		 * Since we're not checking this, default to the lowest
365 		 * defined rate for this mode.
366 		 *
367 		 * At least one 11n AP (DLINK DIR-825) is reported to drop
368 		 * some MCS management traffic (eg BA response frames.)
369 		 *
370 		 * See also: 9.6.0 of the 802.11n-2009 specification.
371 		 */
372 #ifdef	NOTYET
373 		if (i == IEEE80211_MODE_11NA || i == IEEE80211_MODE_11NG) {
374 			vap->iv_txparms[i].mgmtrate = 0 | IEEE80211_RATE_MCS;
375 			vap->iv_txparms[i].mcastrate = 0 | IEEE80211_RATE_MCS;
376 		} else {
377 			vap->iv_txparms[i].mgmtrate =
378 			    rs->rs_rates[0] & IEEE80211_RATE_VAL;
379 			vap->iv_txparms[i].mcastrate =
380 			    rs->rs_rates[0] & IEEE80211_RATE_VAL;
381 		}
382 #endif
383 		vap->iv_txparms[i].mgmtrate = rs->rs_rates[0] & IEEE80211_RATE_VAL;
384 		vap->iv_txparms[i].mcastrate = rs->rs_rates[0] & IEEE80211_RATE_VAL;
385 		vap->iv_txparms[i].maxretry = IEEE80211_TXMAX_DEFAULT;
386 	}
387 	vap->iv_roaming = IEEE80211_ROAMING_AUTO;
388 
389 	vap->iv_update_beacon = null_update_beacon;
390 	vap->iv_deliver_data = ieee80211_deliver_data;
391 
392 	/* attach support for operating mode */
393 	ic->ic_vattach[vap->iv_opmode](vap);
394 }
395 
396 void
397 ieee80211_proto_vdetach(struct ieee80211vap *vap)
398 {
399 #define	FREEAPPIE(ie) do { \
400 	if (ie != NULL) \
401 		IEEE80211_FREE(ie, M_80211_NODE_IE); \
402 } while (0)
403 	/*
404 	 * Detach operating mode module.
405 	 */
406 	if (vap->iv_opdetach != NULL)
407 		vap->iv_opdetach(vap);
408 	/*
409 	 * This should not be needed as we detach when reseting
410 	 * the state but be conservative here since the
411 	 * authenticator may do things like spawn kernel threads.
412 	 */
413 	if (vap->iv_auth->ia_detach != NULL)
414 		vap->iv_auth->ia_detach(vap);
415 	/*
416 	 * Detach any ACL'ator.
417 	 */
418 	if (vap->iv_acl != NULL)
419 		vap->iv_acl->iac_detach(vap);
420 
421 	FREEAPPIE(vap->iv_appie_beacon);
422 	FREEAPPIE(vap->iv_appie_probereq);
423 	FREEAPPIE(vap->iv_appie_proberesp);
424 	FREEAPPIE(vap->iv_appie_assocreq);
425 	FREEAPPIE(vap->iv_appie_assocresp);
426 	FREEAPPIE(vap->iv_appie_wpa);
427 #undef FREEAPPIE
428 }
429 
430 /*
431  * Simple-minded authenticator module support.
432  */
433 
434 #define	IEEE80211_AUTH_MAX	(IEEE80211_AUTH_WPA+1)
435 /* XXX well-known names */
436 static const char *auth_modnames[IEEE80211_AUTH_MAX] = {
437 	"wlan_internal",	/* IEEE80211_AUTH_NONE */
438 	"wlan_internal",	/* IEEE80211_AUTH_OPEN */
439 	"wlan_internal",	/* IEEE80211_AUTH_SHARED */
440 	"wlan_xauth",		/* IEEE80211_AUTH_8021X	 */
441 	"wlan_internal",	/* IEEE80211_AUTH_AUTO */
442 	"wlan_xauth",		/* IEEE80211_AUTH_WPA */
443 };
444 static const struct ieee80211_authenticator *authenticators[IEEE80211_AUTH_MAX];
445 
446 static const struct ieee80211_authenticator auth_internal = {
447 	.ia_name		= "wlan_internal",
448 	.ia_attach		= NULL,
449 	.ia_detach		= NULL,
450 	.ia_node_join		= NULL,
451 	.ia_node_leave		= NULL,
452 };
453 
454 /*
455  * Setup internal authenticators once; they are never unregistered.
456  */
457 static void
458 ieee80211_auth_setup(void)
459 {
460 	ieee80211_authenticator_register(IEEE80211_AUTH_OPEN, &auth_internal);
461 	ieee80211_authenticator_register(IEEE80211_AUTH_SHARED, &auth_internal);
462 	ieee80211_authenticator_register(IEEE80211_AUTH_AUTO, &auth_internal);
463 }
464 SYSINIT(wlan_auth, SI_SUB_DRIVERS, SI_ORDER_FIRST, ieee80211_auth_setup, NULL);
465 
466 const struct ieee80211_authenticator *
467 ieee80211_authenticator_get(int auth)
468 {
469 	if (auth >= IEEE80211_AUTH_MAX)
470 		return NULL;
471 	if (authenticators[auth] == NULL)
472 		ieee80211_load_module(auth_modnames[auth]);
473 	return authenticators[auth];
474 }
475 
476 void
477 ieee80211_authenticator_register(int type,
478 	const struct ieee80211_authenticator *auth)
479 {
480 	if (type >= IEEE80211_AUTH_MAX)
481 		return;
482 	authenticators[type] = auth;
483 }
484 
485 void
486 ieee80211_authenticator_unregister(int type)
487 {
488 
489 	if (type >= IEEE80211_AUTH_MAX)
490 		return;
491 	authenticators[type] = NULL;
492 }
493 
494 /*
495  * Very simple-minded ACL module support.
496  */
497 /* XXX just one for now */
498 static	const struct ieee80211_aclator *acl = NULL;
499 
500 void
501 ieee80211_aclator_register(const struct ieee80211_aclator *iac)
502 {
503 	printf("wlan: %s acl policy registered\n", iac->iac_name);
504 	acl = iac;
505 }
506 
507 void
508 ieee80211_aclator_unregister(const struct ieee80211_aclator *iac)
509 {
510 	if (acl == iac)
511 		acl = NULL;
512 	printf("wlan: %s acl policy unregistered\n", iac->iac_name);
513 }
514 
515 const struct ieee80211_aclator *
516 ieee80211_aclator_get(const char *name)
517 {
518 	if (acl == NULL)
519 		ieee80211_load_module("wlan_acl");
520 	return acl != NULL && strcmp(acl->iac_name, name) == 0 ? acl : NULL;
521 }
522 
523 void
524 ieee80211_print_essid(const uint8_t *essid, int len)
525 {
526 	const uint8_t *p;
527 	int i;
528 
529 	if (len > IEEE80211_NWID_LEN)
530 		len = IEEE80211_NWID_LEN;
531 	/* determine printable or not */
532 	for (i = 0, p = essid; i < len; i++, p++) {
533 		if (*p < ' ' || *p > 0x7e)
534 			break;
535 	}
536 	if (i == len) {
537 		printf("\"");
538 		for (i = 0, p = essid; i < len; i++, p++)
539 			printf("%c", *p);
540 		printf("\"");
541 	} else {
542 		printf("0x");
543 		for (i = 0, p = essid; i < len; i++, p++)
544 			printf("%02x", *p);
545 	}
546 }
547 
548 void
549 ieee80211_dump_pkt(struct ieee80211com *ic,
550 	const uint8_t *buf, int len, int rate, int rssi)
551 {
552 	const struct ieee80211_frame *wh;
553 	int i;
554 
555 	wh = (const struct ieee80211_frame *)buf;
556 	switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
557 	case IEEE80211_FC1_DIR_NODS:
558 		printf("NODS %s", ether_sprintf(wh->i_addr2));
559 		printf("->%s", ether_sprintf(wh->i_addr1));
560 		printf("(%s)", ether_sprintf(wh->i_addr3));
561 		break;
562 	case IEEE80211_FC1_DIR_TODS:
563 		printf("TODS %s", ether_sprintf(wh->i_addr2));
564 		printf("->%s", ether_sprintf(wh->i_addr3));
565 		printf("(%s)", ether_sprintf(wh->i_addr1));
566 		break;
567 	case IEEE80211_FC1_DIR_FROMDS:
568 		printf("FRDS %s", ether_sprintf(wh->i_addr3));
569 		printf("->%s", ether_sprintf(wh->i_addr1));
570 		printf("(%s)", ether_sprintf(wh->i_addr2));
571 		break;
572 	case IEEE80211_FC1_DIR_DSTODS:
573 		printf("DSDS %s", ether_sprintf((const uint8_t *)&wh[1]));
574 		printf("->%s", ether_sprintf(wh->i_addr3));
575 		printf("(%s", ether_sprintf(wh->i_addr2));
576 		printf("->%s)", ether_sprintf(wh->i_addr1));
577 		break;
578 	}
579 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
580 	case IEEE80211_FC0_TYPE_DATA:
581 		printf(" data");
582 		break;
583 	case IEEE80211_FC0_TYPE_MGT:
584 		printf(" %s", ieee80211_mgt_subtype_name(wh->i_fc[0]));
585 		break;
586 	default:
587 		printf(" type#%d", wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK);
588 		break;
589 	}
590 	if (IEEE80211_QOS_HAS_SEQ(wh)) {
591 		const struct ieee80211_qosframe *qwh =
592 			(const struct ieee80211_qosframe *)buf;
593 		printf(" QoS [TID %u%s]", qwh->i_qos[0] & IEEE80211_QOS_TID,
594 			qwh->i_qos[0] & IEEE80211_QOS_ACKPOLICY ? " ACM" : "");
595 	}
596 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
597 		int off;
598 
599 		off = ieee80211_anyhdrspace(ic, wh);
600 		printf(" WEP [IV %.02x %.02x %.02x",
601 			buf[off+0], buf[off+1], buf[off+2]);
602 		if (buf[off+IEEE80211_WEP_IVLEN] & IEEE80211_WEP_EXTIV)
603 			printf(" %.02x %.02x %.02x",
604 				buf[off+4], buf[off+5], buf[off+6]);
605 		printf(" KID %u]", buf[off+IEEE80211_WEP_IVLEN] >> 6);
606 	}
607 	if (rate >= 0)
608 		printf(" %dM", rate / 2);
609 	if (rssi >= 0)
610 		printf(" +%d", rssi);
611 	printf("\n");
612 	if (len > 0) {
613 		for (i = 0; i < len; i++) {
614 			if ((i & 1) == 0)
615 				printf(" ");
616 			printf("%02x", buf[i]);
617 		}
618 		printf("\n");
619 	}
620 }
621 
622 static __inline int
623 findrix(const struct ieee80211_rateset *rs, int r)
624 {
625 	int i;
626 
627 	for (i = 0; i < rs->rs_nrates; i++)
628 		if ((rs->rs_rates[i] & IEEE80211_RATE_VAL) == r)
629 			return i;
630 	return -1;
631 }
632 
633 int
634 ieee80211_fix_rate(struct ieee80211_node *ni,
635 	struct ieee80211_rateset *nrs, int flags)
636 {
637 	struct ieee80211vap *vap = ni->ni_vap;
638 	struct ieee80211com *ic = ni->ni_ic;
639 	int i, j, rix, error;
640 	int okrate, badrate, fixedrate, ucastrate;
641 	const struct ieee80211_rateset *srs;
642 	uint8_t r;
643 
644 	error = 0;
645 	okrate = badrate = 0;
646 	ucastrate = vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)].ucastrate;
647 	if (ucastrate != IEEE80211_FIXED_RATE_NONE) {
648 		/*
649 		 * Workaround awkwardness with fixed rate.  We are called
650 		 * to check both the legacy rate set and the HT rate set
651 		 * but we must apply any legacy fixed rate check only to the
652 		 * legacy rate set and vice versa.  We cannot tell what type
653 		 * of rate set we've been given (legacy or HT) but we can
654 		 * distinguish the fixed rate type (MCS have 0x80 set).
655 		 * So to deal with this the caller communicates whether to
656 		 * check MCS or legacy rate using the flags and we use the
657 		 * type of any fixed rate to avoid applying an MCS to a
658 		 * legacy rate and vice versa.
659 		 */
660 		if (ucastrate & 0x80) {
661 			if (flags & IEEE80211_F_DOFRATE)
662 				flags &= ~IEEE80211_F_DOFRATE;
663 		} else if ((ucastrate & 0x80) == 0) {
664 			if (flags & IEEE80211_F_DOFMCS)
665 				flags &= ~IEEE80211_F_DOFMCS;
666 		}
667 		/* NB: required to make MCS match below work */
668 		ucastrate &= IEEE80211_RATE_VAL;
669 	}
670 	fixedrate = IEEE80211_FIXED_RATE_NONE;
671 	/*
672 	 * XXX we are called to process both MCS and legacy rates;
673 	 * we must use the appropriate basic rate set or chaos will
674 	 * ensue; for now callers that want MCS must supply
675 	 * IEEE80211_F_DOBRS; at some point we'll need to split this
676 	 * function so there are two variants, one for MCS and one
677 	 * for legacy rates.
678 	 */
679 	if (flags & IEEE80211_F_DOBRS)
680 		srs = (const struct ieee80211_rateset *)
681 		    ieee80211_get_suphtrates(ic, ni->ni_chan);
682 	else
683 		srs = ieee80211_get_suprates(ic, ni->ni_chan);
684 	for (i = 0; i < nrs->rs_nrates; ) {
685 		if (flags & IEEE80211_F_DOSORT) {
686 			/*
687 			 * Sort rates.
688 			 */
689 			for (j = i + 1; j < nrs->rs_nrates; j++) {
690 				if (IEEE80211_RV(nrs->rs_rates[i]) >
691 				    IEEE80211_RV(nrs->rs_rates[j])) {
692 					r = nrs->rs_rates[i];
693 					nrs->rs_rates[i] = nrs->rs_rates[j];
694 					nrs->rs_rates[j] = r;
695 				}
696 			}
697 		}
698 		r = nrs->rs_rates[i] & IEEE80211_RATE_VAL;
699 		badrate = r;
700 		/*
701 		 * Check for fixed rate.
702 		 */
703 		if (r == ucastrate)
704 			fixedrate = r;
705 		/*
706 		 * Check against supported rates.
707 		 */
708 		rix = findrix(srs, r);
709 		if (flags & IEEE80211_F_DONEGO) {
710 			if (rix < 0) {
711 				/*
712 				 * A rate in the node's rate set is not
713 				 * supported.  If this is a basic rate and we
714 				 * are operating as a STA then this is an error.
715 				 * Otherwise we just discard/ignore the rate.
716 				 */
717 				if ((flags & IEEE80211_F_JOIN) &&
718 				    (nrs->rs_rates[i] & IEEE80211_RATE_BASIC))
719 					error++;
720 			} else if ((flags & IEEE80211_F_JOIN) == 0) {
721 				/*
722 				 * Overwrite with the supported rate
723 				 * value so any basic rate bit is set.
724 				 */
725 				nrs->rs_rates[i] = srs->rs_rates[rix];
726 			}
727 		}
728 		if ((flags & IEEE80211_F_DODEL) && rix < 0) {
729 			/*
730 			 * Delete unacceptable rates.
731 			 */
732 			nrs->rs_nrates--;
733 			for (j = i; j < nrs->rs_nrates; j++)
734 				nrs->rs_rates[j] = nrs->rs_rates[j + 1];
735 			nrs->rs_rates[j] = 0;
736 			continue;
737 		}
738 		if (rix >= 0)
739 			okrate = nrs->rs_rates[i];
740 		i++;
741 	}
742 	if (okrate == 0 || error != 0 ||
743 	    ((flags & (IEEE80211_F_DOFRATE|IEEE80211_F_DOFMCS)) &&
744 	     fixedrate != ucastrate)) {
745 		IEEE80211_NOTE(vap, IEEE80211_MSG_XRATE | IEEE80211_MSG_11N, ni,
746 		    "%s: flags 0x%x okrate %d error %d fixedrate 0x%x "
747 		    "ucastrate %x\n", __func__, fixedrate, ucastrate, flags);
748 		return badrate | IEEE80211_RATE_BASIC;
749 	} else
750 		return IEEE80211_RV(okrate);
751 }
752 
753 /*
754  * Reset 11g-related state.
755  *
756  * This is for per-VAP ERP/11g state.
757  *
758  * Eventually everything in ieee80211_reset_erp() will be
759  * per-VAP and in here.
760  */
761 void
762 ieee80211_vap_reset_erp(struct ieee80211vap *vap)
763 {
764 	struct ieee80211com *ic = vap->iv_ic;
765 
766 	/*
767 	 * Short slot time is enabled only when operating in 11g
768 	 * and not in an IBSS.  We must also honor whether or not
769 	 * the driver is capable of doing it.
770 	 */
771 	ieee80211_vap_set_shortslottime(vap,
772 		IEEE80211_IS_CHAN_A(ic->ic_curchan) ||
773 		IEEE80211_IS_CHAN_HT(ic->ic_curchan) ||
774 		(IEEE80211_IS_CHAN_ANYG(ic->ic_curchan) &&
775 		vap->iv_opmode == IEEE80211_M_HOSTAP &&
776 		(ic->ic_caps & IEEE80211_C_SHSLOT)));
777 }
778 
779 /*
780  * Reset 11g-related state.
781  */
782 void
783 ieee80211_reset_erp(struct ieee80211com *ic)
784 {
785 	ic->ic_flags &= ~IEEE80211_F_USEPROT;
786 	ic->ic_nonerpsta = 0;
787 	ic->ic_longslotsta = 0;
788 	/*
789 	 * Set short preamble and ERP barker-preamble flags.
790 	 */
791 	if (IEEE80211_IS_CHAN_A(ic->ic_curchan) ||
792 	    (ic->ic_caps & IEEE80211_C_SHPREAMBLE)) {
793 		ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
794 		ic->ic_flags &= ~IEEE80211_F_USEBARKER;
795 	} else {
796 		ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
797 		ic->ic_flags |= IEEE80211_F_USEBARKER;
798 	}
799 }
800 
801 /*
802  * Deferred slot time update.
803  *
804  * For per-VAP slot time configuration, call the VAP
805  * method if the VAP requires it.  Otherwise, just call the
806  * older global method.
807  *
808  * If the per-VAP method is called then it's expected that
809  * the driver/firmware will take care of turning the per-VAP
810  * flags into slot time configuration.
811  *
812  * If the per-VAP method is not called then the global flags will be
813  * flipped into sync with the VAPs; ic_flags IEEE80211_F_SHSLOT will
814  * be set only if all of the vaps will have it set.
815  */
816 static void
817 vap_update_slot(void *arg, int npending)
818 {
819 	struct ieee80211vap *vap = arg;
820 	struct ieee80211com *ic = vap->iv_ic;
821 	struct ieee80211vap *iv;
822 	int num_shslot = 0, num_lgslot = 0;
823 
824 	/*
825 	 * Per-VAP path - we've already had the flags updated;
826 	 * so just notify the driver and move on.
827 	 */
828 	if (vap->iv_updateslot != NULL) {
829 		vap->iv_updateslot(vap);
830 		return;
831 	}
832 
833 	/*
834 	 * Iterate over all of the VAP flags to update the
835 	 * global flag.
836 	 *
837 	 * If all vaps have short slot enabled then flip on
838 	 * short slot.  If any vap has it disabled then
839 	 * we leave it globally disabled.  This should provide
840 	 * correct behaviour in a multi-BSS scenario where
841 	 * at least one VAP has short slot disabled for some
842 	 * reason.
843 	 */
844 	IEEE80211_LOCK(ic);
845 	TAILQ_FOREACH(iv, &ic->ic_vaps, iv_next) {
846 		if (iv->iv_flags & IEEE80211_F_SHSLOT)
847 			num_shslot++;
848 		else
849 			num_lgslot++;
850 	}
851 	IEEE80211_UNLOCK(ic);
852 
853 	/*
854 	 * It looks backwards but - if the number of short slot VAPs
855 	 * is zero then we're not short slot.  Else, we have one
856 	 * or more short slot VAPs and we're checking to see if ANY
857 	 * of them have short slot disabled.
858 	 */
859 	if (num_shslot == 0)
860 		ic->ic_flags &= ~IEEE80211_F_SHSLOT;
861 	else if (num_lgslot == 0)
862 		ic->ic_flags |= IEEE80211_F_SHSLOT;
863 
864 	/*
865 	 * Call the driver with our new global slot time flags.
866 	 */
867 	if (ic->ic_updateslot != NULL)
868 		ic->ic_updateslot(ic);
869 }
870 
871 /*
872  * Set the short slot time state and notify the driver.
873  *
874  * This is the per-VAP slot time state.
875  */
876 void
877 ieee80211_vap_set_shortslottime(struct ieee80211vap *vap, int onoff)
878 {
879 	struct ieee80211com *ic = vap->iv_ic;
880 
881 	/*
882 	 * Only modify the per-VAP slot time.
883 	 */
884 	if (onoff)
885 		vap->iv_flags |= IEEE80211_F_SHSLOT;
886 	else
887 		vap->iv_flags &= ~IEEE80211_F_SHSLOT;
888 
889 	/* schedule the deferred slot flag update and update */
890 	ieee80211_runtask(ic, &vap->iv_slot_task);
891 }
892 
893 /*
894  * Check if the specified rate set supports ERP.
895  * NB: the rate set is assumed to be sorted.
896  */
897 int
898 ieee80211_iserp_rateset(const struct ieee80211_rateset *rs)
899 {
900 	static const int rates[] = { 2, 4, 11, 22, 12, 24, 48 };
901 	int i, j;
902 
903 	if (rs->rs_nrates < nitems(rates))
904 		return 0;
905 	for (i = 0; i < nitems(rates); i++) {
906 		for (j = 0; j < rs->rs_nrates; j++) {
907 			int r = rs->rs_rates[j] & IEEE80211_RATE_VAL;
908 			if (rates[i] == r)
909 				goto next;
910 			if (r > rates[i])
911 				return 0;
912 		}
913 		return 0;
914 	next:
915 		;
916 	}
917 	return 1;
918 }
919 
920 /*
921  * Mark the basic rates for the rate table based on the
922  * operating mode.  For real 11g we mark all the 11b rates
923  * and 6, 12, and 24 OFDM.  For 11b compatibility we mark only
924  * 11b rates.  There's also a pseudo 11a-mode used to mark only
925  * the basic OFDM rates.
926  */
927 static void
928 setbasicrates(struct ieee80211_rateset *rs,
929     enum ieee80211_phymode mode, int add)
930 {
931 	static const struct ieee80211_rateset basic[IEEE80211_MODE_MAX] = {
932 	    [IEEE80211_MODE_11A]	= { 3, { 12, 24, 48 } },
933 	    [IEEE80211_MODE_11B]	= { 2, { 2, 4 } },
934 					    /* NB: mixed b/g */
935 	    [IEEE80211_MODE_11G]	= { 4, { 2, 4, 11, 22 } },
936 	    [IEEE80211_MODE_TURBO_A]	= { 3, { 12, 24, 48 } },
937 	    [IEEE80211_MODE_TURBO_G]	= { 4, { 2, 4, 11, 22 } },
938 	    [IEEE80211_MODE_STURBO_A]	= { 3, { 12, 24, 48 } },
939 	    [IEEE80211_MODE_HALF]	= { 3, { 6, 12, 24 } },
940 	    [IEEE80211_MODE_QUARTER]	= { 3, { 3, 6, 12 } },
941 	    [IEEE80211_MODE_11NA]	= { 3, { 12, 24, 48 } },
942 					    /* NB: mixed b/g */
943 	    [IEEE80211_MODE_11NG]	= { 4, { 2, 4, 11, 22 } },
944 					    /* NB: mixed b/g */
945 	    [IEEE80211_MODE_VHT_2GHZ]	= { 4, { 2, 4, 11, 22 } },
946 	    [IEEE80211_MODE_VHT_5GHZ]	= { 3, { 12, 24, 48 } },
947 	};
948 	int i, j;
949 
950 	for (i = 0; i < rs->rs_nrates; i++) {
951 		if (!add)
952 			rs->rs_rates[i] &= IEEE80211_RATE_VAL;
953 		for (j = 0; j < basic[mode].rs_nrates; j++)
954 			if (basic[mode].rs_rates[j] == rs->rs_rates[i]) {
955 				rs->rs_rates[i] |= IEEE80211_RATE_BASIC;
956 				break;
957 			}
958 	}
959 }
960 
961 /*
962  * Set the basic rates in a rate set.
963  */
964 void
965 ieee80211_setbasicrates(struct ieee80211_rateset *rs,
966     enum ieee80211_phymode mode)
967 {
968 	setbasicrates(rs, mode, 0);
969 }
970 
971 /*
972  * Add basic rates to a rate set.
973  */
974 void
975 ieee80211_addbasicrates(struct ieee80211_rateset *rs,
976     enum ieee80211_phymode mode)
977 {
978 	setbasicrates(rs, mode, 1);
979 }
980 
981 /*
982  * WME protocol support.
983  *
984  * The default 11a/b/g/n parameters come from the WiFi Alliance WMM
985  * System Interopability Test Plan (v1.4, Appendix F) and the 802.11n
986  * Draft 2.0 Test Plan (Appendix D).
987  *
988  * Static/Dynamic Turbo mode settings come from Atheros.
989  */
990 typedef struct phyParamType {
991 	uint8_t		aifsn;
992 	uint8_t		logcwmin;
993 	uint8_t		logcwmax;
994 	uint16_t	txopLimit;
995 	uint8_t 	acm;
996 } paramType;
997 
998 static const struct phyParamType phyParamForAC_BE[IEEE80211_MODE_MAX] = {
999 	[IEEE80211_MODE_AUTO]	= { 3, 4,  6,  0, 0 },
1000 	[IEEE80211_MODE_11A]	= { 3, 4,  6,  0, 0 },
1001 	[IEEE80211_MODE_11B]	= { 3, 4,  6,  0, 0 },
1002 	[IEEE80211_MODE_11G]	= { 3, 4,  6,  0, 0 },
1003 	[IEEE80211_MODE_FH]	= { 3, 4,  6,  0, 0 },
1004 	[IEEE80211_MODE_TURBO_A]= { 2, 3,  5,  0, 0 },
1005 	[IEEE80211_MODE_TURBO_G]= { 2, 3,  5,  0, 0 },
1006 	[IEEE80211_MODE_STURBO_A]={ 2, 3,  5,  0, 0 },
1007 	[IEEE80211_MODE_HALF]	= { 3, 4,  6,  0, 0 },
1008 	[IEEE80211_MODE_QUARTER]= { 3, 4,  6,  0, 0 },
1009 	[IEEE80211_MODE_11NA]	= { 3, 4,  6,  0, 0 },
1010 	[IEEE80211_MODE_11NG]	= { 3, 4,  6,  0, 0 },
1011 	[IEEE80211_MODE_VHT_2GHZ]	= { 3, 4,  6,  0, 0 },
1012 	[IEEE80211_MODE_VHT_5GHZ]	= { 3, 4,  6,  0, 0 },
1013 };
1014 static const struct phyParamType phyParamForAC_BK[IEEE80211_MODE_MAX] = {
1015 	[IEEE80211_MODE_AUTO]	= { 7, 4, 10,  0, 0 },
1016 	[IEEE80211_MODE_11A]	= { 7, 4, 10,  0, 0 },
1017 	[IEEE80211_MODE_11B]	= { 7, 4, 10,  0, 0 },
1018 	[IEEE80211_MODE_11G]	= { 7, 4, 10,  0, 0 },
1019 	[IEEE80211_MODE_FH]	= { 7, 4, 10,  0, 0 },
1020 	[IEEE80211_MODE_TURBO_A]= { 7, 3, 10,  0, 0 },
1021 	[IEEE80211_MODE_TURBO_G]= { 7, 3, 10,  0, 0 },
1022 	[IEEE80211_MODE_STURBO_A]={ 7, 3, 10,  0, 0 },
1023 	[IEEE80211_MODE_HALF]	= { 7, 4, 10,  0, 0 },
1024 	[IEEE80211_MODE_QUARTER]= { 7, 4, 10,  0, 0 },
1025 	[IEEE80211_MODE_11NA]	= { 7, 4, 10,  0, 0 },
1026 	[IEEE80211_MODE_11NG]	= { 7, 4, 10,  0, 0 },
1027 	[IEEE80211_MODE_VHT_2GHZ]	= { 7, 4, 10,  0, 0 },
1028 	[IEEE80211_MODE_VHT_5GHZ]	= { 7, 4, 10,  0, 0 },
1029 };
1030 static const struct phyParamType phyParamForAC_VI[IEEE80211_MODE_MAX] = {
1031 	[IEEE80211_MODE_AUTO]	= { 1, 3, 4,  94, 0 },
1032 	[IEEE80211_MODE_11A]	= { 1, 3, 4,  94, 0 },
1033 	[IEEE80211_MODE_11B]	= { 1, 3, 4, 188, 0 },
1034 	[IEEE80211_MODE_11G]	= { 1, 3, 4,  94, 0 },
1035 	[IEEE80211_MODE_FH]	= { 1, 3, 4, 188, 0 },
1036 	[IEEE80211_MODE_TURBO_A]= { 1, 2, 3,  94, 0 },
1037 	[IEEE80211_MODE_TURBO_G]= { 1, 2, 3,  94, 0 },
1038 	[IEEE80211_MODE_STURBO_A]={ 1, 2, 3,  94, 0 },
1039 	[IEEE80211_MODE_HALF]	= { 1, 3, 4,  94, 0 },
1040 	[IEEE80211_MODE_QUARTER]= { 1, 3, 4,  94, 0 },
1041 	[IEEE80211_MODE_11NA]	= { 1, 3, 4,  94, 0 },
1042 	[IEEE80211_MODE_11NG]	= { 1, 3, 4,  94, 0 },
1043 	[IEEE80211_MODE_VHT_2GHZ]	= { 1, 3, 4,  94, 0 },
1044 	[IEEE80211_MODE_VHT_5GHZ]	= { 1, 3, 4,  94, 0 },
1045 };
1046 static const struct phyParamType phyParamForAC_VO[IEEE80211_MODE_MAX] = {
1047 	[IEEE80211_MODE_AUTO]	= { 1, 2, 3,  47, 0 },
1048 	[IEEE80211_MODE_11A]	= { 1, 2, 3,  47, 0 },
1049 	[IEEE80211_MODE_11B]	= { 1, 2, 3, 102, 0 },
1050 	[IEEE80211_MODE_11G]	= { 1, 2, 3,  47, 0 },
1051 	[IEEE80211_MODE_FH]	= { 1, 2, 3, 102, 0 },
1052 	[IEEE80211_MODE_TURBO_A]= { 1, 2, 2,  47, 0 },
1053 	[IEEE80211_MODE_TURBO_G]= { 1, 2, 2,  47, 0 },
1054 	[IEEE80211_MODE_STURBO_A]={ 1, 2, 2,  47, 0 },
1055 	[IEEE80211_MODE_HALF]	= { 1, 2, 3,  47, 0 },
1056 	[IEEE80211_MODE_QUARTER]= { 1, 2, 3,  47, 0 },
1057 	[IEEE80211_MODE_11NA]	= { 1, 2, 3,  47, 0 },
1058 	[IEEE80211_MODE_11NG]	= { 1, 2, 3,  47, 0 },
1059 	[IEEE80211_MODE_VHT_2GHZ]	= { 1, 2, 3,  47, 0 },
1060 	[IEEE80211_MODE_VHT_5GHZ]	= { 1, 2, 3,  47, 0 },
1061 };
1062 
1063 static const struct phyParamType bssPhyParamForAC_BE[IEEE80211_MODE_MAX] = {
1064 	[IEEE80211_MODE_AUTO]	= { 3, 4, 10,  0, 0 },
1065 	[IEEE80211_MODE_11A]	= { 3, 4, 10,  0, 0 },
1066 	[IEEE80211_MODE_11B]	= { 3, 4, 10,  0, 0 },
1067 	[IEEE80211_MODE_11G]	= { 3, 4, 10,  0, 0 },
1068 	[IEEE80211_MODE_FH]	= { 3, 4, 10,  0, 0 },
1069 	[IEEE80211_MODE_TURBO_A]= { 2, 3, 10,  0, 0 },
1070 	[IEEE80211_MODE_TURBO_G]= { 2, 3, 10,  0, 0 },
1071 	[IEEE80211_MODE_STURBO_A]={ 2, 3, 10,  0, 0 },
1072 	[IEEE80211_MODE_HALF]	= { 3, 4, 10,  0, 0 },
1073 	[IEEE80211_MODE_QUARTER]= { 3, 4, 10,  0, 0 },
1074 	[IEEE80211_MODE_11NA]	= { 3, 4, 10,  0, 0 },
1075 	[IEEE80211_MODE_11NG]	= { 3, 4, 10,  0, 0 },
1076 };
1077 static const struct phyParamType bssPhyParamForAC_VI[IEEE80211_MODE_MAX] = {
1078 	[IEEE80211_MODE_AUTO]	= { 2, 3, 4,  94, 0 },
1079 	[IEEE80211_MODE_11A]	= { 2, 3, 4,  94, 0 },
1080 	[IEEE80211_MODE_11B]	= { 2, 3, 4, 188, 0 },
1081 	[IEEE80211_MODE_11G]	= { 2, 3, 4,  94, 0 },
1082 	[IEEE80211_MODE_FH]	= { 2, 3, 4, 188, 0 },
1083 	[IEEE80211_MODE_TURBO_A]= { 2, 2, 3,  94, 0 },
1084 	[IEEE80211_MODE_TURBO_G]= { 2, 2, 3,  94, 0 },
1085 	[IEEE80211_MODE_STURBO_A]={ 2, 2, 3,  94, 0 },
1086 	[IEEE80211_MODE_HALF]	= { 2, 3, 4,  94, 0 },
1087 	[IEEE80211_MODE_QUARTER]= { 2, 3, 4,  94, 0 },
1088 	[IEEE80211_MODE_11NA]	= { 2, 3, 4,  94, 0 },
1089 	[IEEE80211_MODE_11NG]	= { 2, 3, 4,  94, 0 },
1090 };
1091 static const struct phyParamType bssPhyParamForAC_VO[IEEE80211_MODE_MAX] = {
1092 	[IEEE80211_MODE_AUTO]	= { 2, 2, 3,  47, 0 },
1093 	[IEEE80211_MODE_11A]	= { 2, 2, 3,  47, 0 },
1094 	[IEEE80211_MODE_11B]	= { 2, 2, 3, 102, 0 },
1095 	[IEEE80211_MODE_11G]	= { 2, 2, 3,  47, 0 },
1096 	[IEEE80211_MODE_FH]	= { 2, 2, 3, 102, 0 },
1097 	[IEEE80211_MODE_TURBO_A]= { 1, 2, 2,  47, 0 },
1098 	[IEEE80211_MODE_TURBO_G]= { 1, 2, 2,  47, 0 },
1099 	[IEEE80211_MODE_STURBO_A]={ 1, 2, 2,  47, 0 },
1100 	[IEEE80211_MODE_HALF]	= { 2, 2, 3,  47, 0 },
1101 	[IEEE80211_MODE_QUARTER]= { 2, 2, 3,  47, 0 },
1102 	[IEEE80211_MODE_11NA]	= { 2, 2, 3,  47, 0 },
1103 	[IEEE80211_MODE_11NG]	= { 2, 2, 3,  47, 0 },
1104 };
1105 
1106 static void
1107 _setifsparams(struct wmeParams *wmep, const paramType *phy)
1108 {
1109 	wmep->wmep_aifsn = phy->aifsn;
1110 	wmep->wmep_logcwmin = phy->logcwmin;
1111 	wmep->wmep_logcwmax = phy->logcwmax;
1112 	wmep->wmep_txopLimit = phy->txopLimit;
1113 }
1114 
1115 static void
1116 setwmeparams(struct ieee80211vap *vap, const char *type, int ac,
1117 	struct wmeParams *wmep, const paramType *phy)
1118 {
1119 	wmep->wmep_acm = phy->acm;
1120 	_setifsparams(wmep, phy);
1121 
1122 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
1123 	    "set %s (%s) [acm %u aifsn %u logcwmin %u logcwmax %u txop %u]\n",
1124 	    ieee80211_wme_acnames[ac], type,
1125 	    wmep->wmep_acm, wmep->wmep_aifsn, wmep->wmep_logcwmin,
1126 	    wmep->wmep_logcwmax, wmep->wmep_txopLimit);
1127 }
1128 
1129 static void
1130 ieee80211_wme_initparams_locked(struct ieee80211vap *vap)
1131 {
1132 	struct ieee80211com *ic = vap->iv_ic;
1133 	struct ieee80211_wme_state *wme = &ic->ic_wme;
1134 	const paramType *pPhyParam, *pBssPhyParam;
1135 	struct wmeParams *wmep;
1136 	enum ieee80211_phymode mode;
1137 	int i;
1138 
1139 	IEEE80211_LOCK_ASSERT(ic);
1140 
1141 	if ((ic->ic_caps & IEEE80211_C_WME) == 0 || ic->ic_nrunning > 1)
1142 		return;
1143 
1144 	/*
1145 	 * Clear the wme cap_info field so a qoscount from a previous
1146 	 * vap doesn't confuse later code which only parses the beacon
1147 	 * field and updates hardware when said field changes.
1148 	 * Otherwise the hardware is programmed with defaults, not what
1149 	 * the beacon actually announces.
1150 	 *
1151 	 * Note that we can't ever have 0xff as an actual value;
1152 	 * the only valid values are 0..15.
1153 	 */
1154 	wme->wme_wmeChanParams.cap_info = 0xfe;
1155 
1156 	/*
1157 	 * Select mode; we can be called early in which case we
1158 	 * always use auto mode.  We know we'll be called when
1159 	 * entering the RUN state with bsschan setup properly
1160 	 * so state will eventually get set correctly
1161 	 */
1162 	if (ic->ic_bsschan != IEEE80211_CHAN_ANYC)
1163 		mode = ieee80211_chan2mode(ic->ic_bsschan);
1164 	else
1165 		mode = IEEE80211_MODE_AUTO;
1166 	for (i = 0; i < WME_NUM_AC; i++) {
1167 		switch (i) {
1168 		case WME_AC_BK:
1169 			pPhyParam = &phyParamForAC_BK[mode];
1170 			pBssPhyParam = &phyParamForAC_BK[mode];
1171 			break;
1172 		case WME_AC_VI:
1173 			pPhyParam = &phyParamForAC_VI[mode];
1174 			pBssPhyParam = &bssPhyParamForAC_VI[mode];
1175 			break;
1176 		case WME_AC_VO:
1177 			pPhyParam = &phyParamForAC_VO[mode];
1178 			pBssPhyParam = &bssPhyParamForAC_VO[mode];
1179 			break;
1180 		case WME_AC_BE:
1181 		default:
1182 			pPhyParam = &phyParamForAC_BE[mode];
1183 			pBssPhyParam = &bssPhyParamForAC_BE[mode];
1184 			break;
1185 		}
1186 		wmep = &wme->wme_wmeChanParams.cap_wmeParams[i];
1187 		if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
1188 			setwmeparams(vap, "chan", i, wmep, pPhyParam);
1189 		} else {
1190 			setwmeparams(vap, "chan", i, wmep, pBssPhyParam);
1191 		}
1192 		wmep = &wme->wme_wmeBssChanParams.cap_wmeParams[i];
1193 		setwmeparams(vap, "bss ", i, wmep, pBssPhyParam);
1194 	}
1195 	/* NB: check ic_bss to avoid NULL deref on initial attach */
1196 	if (vap->iv_bss != NULL) {
1197 		/*
1198 		 * Calculate aggressive mode switching threshold based
1199 		 * on beacon interval.  This doesn't need locking since
1200 		 * we're only called before entering the RUN state at
1201 		 * which point we start sending beacon frames.
1202 		 */
1203 		wme->wme_hipri_switch_thresh =
1204 			(HIGH_PRI_SWITCH_THRESH * vap->iv_bss->ni_intval) / 100;
1205 		wme->wme_flags &= ~WME_F_AGGRMODE;
1206 		ieee80211_wme_updateparams(vap);
1207 	}
1208 }
1209 
1210 void
1211 ieee80211_wme_initparams(struct ieee80211vap *vap)
1212 {
1213 	struct ieee80211com *ic = vap->iv_ic;
1214 
1215 	IEEE80211_LOCK(ic);
1216 	ieee80211_wme_initparams_locked(vap);
1217 	IEEE80211_UNLOCK(ic);
1218 }
1219 
1220 /*
1221  * Update WME parameters for ourself and the BSS.
1222  */
1223 void
1224 ieee80211_wme_updateparams_locked(struct ieee80211vap *vap)
1225 {
1226 	static const paramType aggrParam[IEEE80211_MODE_MAX] = {
1227 	    [IEEE80211_MODE_AUTO]	= { 2, 4, 10, 64, 0 },
1228 	    [IEEE80211_MODE_11A]	= { 2, 4, 10, 64, 0 },
1229 	    [IEEE80211_MODE_11B]	= { 2, 5, 10, 64, 0 },
1230 	    [IEEE80211_MODE_11G]	= { 2, 4, 10, 64, 0 },
1231 	    [IEEE80211_MODE_FH]		= { 2, 5, 10, 64, 0 },
1232 	    [IEEE80211_MODE_TURBO_A]	= { 1, 3, 10, 64, 0 },
1233 	    [IEEE80211_MODE_TURBO_G]	= { 1, 3, 10, 64, 0 },
1234 	    [IEEE80211_MODE_STURBO_A]	= { 1, 3, 10, 64, 0 },
1235 	    [IEEE80211_MODE_HALF]	= { 2, 4, 10, 64, 0 },
1236 	    [IEEE80211_MODE_QUARTER]	= { 2, 4, 10, 64, 0 },
1237 	    [IEEE80211_MODE_11NA]	= { 2, 4, 10, 64, 0 },	/* XXXcheck*/
1238 	    [IEEE80211_MODE_11NG]	= { 2, 4, 10, 64, 0 },	/* XXXcheck*/
1239 	    [IEEE80211_MODE_VHT_2GHZ]	= { 2, 4, 10, 64, 0 },	/* XXXcheck*/
1240 	    [IEEE80211_MODE_VHT_5GHZ]	= { 2, 4, 10, 64, 0 },	/* XXXcheck*/
1241 	};
1242 	struct ieee80211com *ic = vap->iv_ic;
1243 	struct ieee80211_wme_state *wme = &ic->ic_wme;
1244 	const struct wmeParams *wmep;
1245 	struct wmeParams *chanp, *bssp;
1246 	enum ieee80211_phymode mode;
1247 	int i;
1248 	int do_aggrmode = 0;
1249 
1250        	/*
1251 	 * Set up the channel access parameters for the physical
1252 	 * device.  First populate the configured settings.
1253 	 */
1254 	for (i = 0; i < WME_NUM_AC; i++) {
1255 		chanp = &wme->wme_chanParams.cap_wmeParams[i];
1256 		wmep = &wme->wme_wmeChanParams.cap_wmeParams[i];
1257 		chanp->wmep_aifsn = wmep->wmep_aifsn;
1258 		chanp->wmep_logcwmin = wmep->wmep_logcwmin;
1259 		chanp->wmep_logcwmax = wmep->wmep_logcwmax;
1260 		chanp->wmep_txopLimit = wmep->wmep_txopLimit;
1261 
1262 		chanp = &wme->wme_bssChanParams.cap_wmeParams[i];
1263 		wmep = &wme->wme_wmeBssChanParams.cap_wmeParams[i];
1264 		chanp->wmep_aifsn = wmep->wmep_aifsn;
1265 		chanp->wmep_logcwmin = wmep->wmep_logcwmin;
1266 		chanp->wmep_logcwmax = wmep->wmep_logcwmax;
1267 		chanp->wmep_txopLimit = wmep->wmep_txopLimit;
1268 	}
1269 
1270 	/*
1271 	 * Select mode; we can be called early in which case we
1272 	 * always use auto mode.  We know we'll be called when
1273 	 * entering the RUN state with bsschan setup properly
1274 	 * so state will eventually get set correctly
1275 	 */
1276 	if (ic->ic_bsschan != IEEE80211_CHAN_ANYC)
1277 		mode = ieee80211_chan2mode(ic->ic_bsschan);
1278 	else
1279 		mode = IEEE80211_MODE_AUTO;
1280 
1281 	/*
1282 	 * This implements aggressive mode as found in certain
1283 	 * vendors' AP's.  When there is significant high
1284 	 * priority (VI/VO) traffic in the BSS throttle back BE
1285 	 * traffic by using conservative parameters.  Otherwise
1286 	 * BE uses aggressive params to optimize performance of
1287 	 * legacy/non-QoS traffic.
1288 	 */
1289 
1290 	/* Hostap? Only if aggressive mode is enabled */
1291         if (vap->iv_opmode == IEEE80211_M_HOSTAP &&
1292 	     (wme->wme_flags & WME_F_AGGRMODE) != 0)
1293 		do_aggrmode = 1;
1294 
1295 	/*
1296 	 * Station? Only if we're in a non-QoS BSS.
1297 	 */
1298 	else if ((vap->iv_opmode == IEEE80211_M_STA &&
1299 	     (vap->iv_bss->ni_flags & IEEE80211_NODE_QOS) == 0))
1300 		do_aggrmode = 1;
1301 
1302 	/*
1303 	 * IBSS? Only if we we have WME enabled.
1304 	 */
1305 	else if ((vap->iv_opmode == IEEE80211_M_IBSS) &&
1306 	    (vap->iv_flags & IEEE80211_F_WME))
1307 		do_aggrmode = 1;
1308 
1309 	/*
1310 	 * If WME is disabled on this VAP, default to aggressive mode
1311 	 * regardless of the configuration.
1312 	 */
1313 	if ((vap->iv_flags & IEEE80211_F_WME) == 0)
1314 		do_aggrmode = 1;
1315 
1316 	/* XXX WDS? */
1317 
1318 	/* XXX MBSS? */
1319 
1320 	if (do_aggrmode) {
1321 		chanp = &wme->wme_chanParams.cap_wmeParams[WME_AC_BE];
1322 		bssp = &wme->wme_bssChanParams.cap_wmeParams[WME_AC_BE];
1323 
1324 		chanp->wmep_aifsn = bssp->wmep_aifsn = aggrParam[mode].aifsn;
1325 		chanp->wmep_logcwmin = bssp->wmep_logcwmin =
1326 		    aggrParam[mode].logcwmin;
1327 		chanp->wmep_logcwmax = bssp->wmep_logcwmax =
1328 		    aggrParam[mode].logcwmax;
1329 		chanp->wmep_txopLimit = bssp->wmep_txopLimit =
1330 		    (vap->iv_flags & IEEE80211_F_BURST) ?
1331 			aggrParam[mode].txopLimit : 0;
1332 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
1333 		    "update %s (chan+bss) [acm %u aifsn %u logcwmin %u "
1334 		    "logcwmax %u txop %u]\n", ieee80211_wme_acnames[WME_AC_BE],
1335 		    chanp->wmep_acm, chanp->wmep_aifsn, chanp->wmep_logcwmin,
1336 		    chanp->wmep_logcwmax, chanp->wmep_txopLimit);
1337 	}
1338 
1339 
1340 	/*
1341 	 * Change the contention window based on the number of associated
1342 	 * stations.  If the number of associated stations is 1 and
1343 	 * aggressive mode is enabled, lower the contention window even
1344 	 * further.
1345 	 */
1346 	if (vap->iv_opmode == IEEE80211_M_HOSTAP &&
1347 	    ic->ic_sta_assoc < 2 && (wme->wme_flags & WME_F_AGGRMODE) != 0) {
1348 		static const uint8_t logCwMin[IEEE80211_MODE_MAX] = {
1349 		    [IEEE80211_MODE_AUTO]	= 3,
1350 		    [IEEE80211_MODE_11A]	= 3,
1351 		    [IEEE80211_MODE_11B]	= 4,
1352 		    [IEEE80211_MODE_11G]	= 3,
1353 		    [IEEE80211_MODE_FH]		= 4,
1354 		    [IEEE80211_MODE_TURBO_A]	= 3,
1355 		    [IEEE80211_MODE_TURBO_G]	= 3,
1356 		    [IEEE80211_MODE_STURBO_A]	= 3,
1357 		    [IEEE80211_MODE_HALF]	= 3,
1358 		    [IEEE80211_MODE_QUARTER]	= 3,
1359 		    [IEEE80211_MODE_11NA]	= 3,
1360 		    [IEEE80211_MODE_11NG]	= 3,
1361 		    [IEEE80211_MODE_VHT_2GHZ]	= 3,
1362 		    [IEEE80211_MODE_VHT_5GHZ]	= 3,
1363 		};
1364 		chanp = &wme->wme_chanParams.cap_wmeParams[WME_AC_BE];
1365 		bssp = &wme->wme_bssChanParams.cap_wmeParams[WME_AC_BE];
1366 
1367 		chanp->wmep_logcwmin = bssp->wmep_logcwmin = logCwMin[mode];
1368 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
1369 		    "update %s (chan+bss) logcwmin %u\n",
1370 		    ieee80211_wme_acnames[WME_AC_BE], chanp->wmep_logcwmin);
1371 	}
1372 
1373 	/*
1374 	 * Arrange for the beacon update.
1375 	 *
1376 	 * XXX what about MBSS, WDS?
1377 	 */
1378 	if (vap->iv_opmode == IEEE80211_M_HOSTAP
1379 	    || vap->iv_opmode == IEEE80211_M_IBSS) {
1380 		/*
1381 		 * Arrange for a beacon update and bump the parameter
1382 		 * set number so associated stations load the new values.
1383 		 */
1384 		wme->wme_bssChanParams.cap_info =
1385 			(wme->wme_bssChanParams.cap_info+1) & WME_QOSINFO_COUNT;
1386 		ieee80211_beacon_notify(vap, IEEE80211_BEACON_WME);
1387 	}
1388 
1389 	/* schedule the deferred WME update */
1390 	ieee80211_runtask(ic, &vap->iv_wme_task);
1391 
1392 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
1393 	    "%s: WME params updated, cap_info 0x%x\n", __func__,
1394 	    vap->iv_opmode == IEEE80211_M_STA ?
1395 		wme->wme_wmeChanParams.cap_info :
1396 		wme->wme_bssChanParams.cap_info);
1397 }
1398 
1399 void
1400 ieee80211_wme_updateparams(struct ieee80211vap *vap)
1401 {
1402 	struct ieee80211com *ic = vap->iv_ic;
1403 
1404 	if (ic->ic_caps & IEEE80211_C_WME) {
1405 		IEEE80211_LOCK(ic);
1406 		ieee80211_wme_updateparams_locked(vap);
1407 		IEEE80211_UNLOCK(ic);
1408 	}
1409 }
1410 
1411 /*
1412  * Fetch the WME parameters for the given VAP.
1413  *
1414  * When net80211 grows p2p, etc support, this may return different
1415  * parameters for each VAP.
1416  */
1417 void
1418 ieee80211_wme_vap_getparams(struct ieee80211vap *vap, struct chanAccParams *wp)
1419 {
1420 
1421 	memcpy(wp, &vap->iv_ic->ic_wme.wme_chanParams, sizeof(*wp));
1422 }
1423 
1424 /*
1425  * For NICs which only support one set of WME paramaters (ie, softmac NICs)
1426  * there may be different VAP WME parameters but only one is "active".
1427  * This returns the "NIC" WME parameters for the currently active
1428  * context.
1429  */
1430 void
1431 ieee80211_wme_ic_getparams(struct ieee80211com *ic, struct chanAccParams *wp)
1432 {
1433 
1434 	memcpy(wp, &ic->ic_wme.wme_chanParams, sizeof(*wp));
1435 }
1436 
1437 /*
1438  * Return whether to use QoS on a given WME queue.
1439  *
1440  * This is intended to be called from the transmit path of softmac drivers
1441  * which are setting NoAck bits in transmit descriptors.
1442  *
1443  * Ideally this would be set in some transmit field before the packet is
1444  * queued to the driver but net80211 isn't quite there yet.
1445  */
1446 int
1447 ieee80211_wme_vap_ac_is_noack(struct ieee80211vap *vap, int ac)
1448 {
1449 	/* Bounds/sanity check */
1450 	if (ac < 0 || ac >= WME_NUM_AC)
1451 		return (0);
1452 
1453 	/* Again, there's only one global context for now */
1454 	return (!! vap->iv_ic->ic_wme.wme_chanParams.cap_wmeParams[ac].wmep_noackPolicy);
1455 }
1456 
1457 static void
1458 parent_updown(void *arg, int npending)
1459 {
1460 	struct ieee80211com *ic = arg;
1461 
1462 	ic->ic_parent(ic);
1463 }
1464 
1465 static void
1466 update_mcast(void *arg, int npending)
1467 {
1468 	struct ieee80211com *ic = arg;
1469 
1470 	ic->ic_update_mcast(ic);
1471 }
1472 
1473 static void
1474 update_promisc(void *arg, int npending)
1475 {
1476 	struct ieee80211com *ic = arg;
1477 
1478 	ic->ic_update_promisc(ic);
1479 }
1480 
1481 static void
1482 update_channel(void *arg, int npending)
1483 {
1484 	struct ieee80211com *ic = arg;
1485 
1486 	ic->ic_set_channel(ic);
1487 	ieee80211_radiotap_chan_change(ic);
1488 }
1489 
1490 static void
1491 update_chw(void *arg, int npending)
1492 {
1493 	struct ieee80211com *ic = arg;
1494 
1495 	/*
1496 	 * XXX should we defer the channel width _config_ update until now?
1497 	 */
1498 	ic->ic_update_chw(ic);
1499 }
1500 
1501 /*
1502  * Deferred WME update.
1503  *
1504  * In preparation for per-VAP WME configuration, call the VAP
1505  * method if the VAP requires it.  Otherwise, just call the
1506  * older global method.  There isn't a per-VAP WME configuration
1507  * just yet so for now just use the global configuration.
1508  */
1509 static void
1510 vap_update_wme(void *arg, int npending)
1511 {
1512 	struct ieee80211vap *vap = arg;
1513 	struct ieee80211com *ic = vap->iv_ic;
1514 
1515 	if (vap->iv_wme_update != NULL)
1516 		vap->iv_wme_update(vap,
1517 		    ic->ic_wme.wme_chanParams.cap_wmeParams);
1518 	else
1519 		ic->ic_wme.wme_update(ic);
1520 }
1521 
1522 static void
1523 restart_vaps(void *arg, int npending)
1524 {
1525 	struct ieee80211com *ic = arg;
1526 
1527 	ieee80211_suspend_all(ic);
1528 	ieee80211_resume_all(ic);
1529 }
1530 
1531 /*
1532  * Block until the parent is in a known state.  This is
1533  * used after any operations that dispatch a task (e.g.
1534  * to auto-configure the parent device up/down).
1535  */
1536 void
1537 ieee80211_waitfor_parent(struct ieee80211com *ic)
1538 {
1539 	taskqueue_block(ic->ic_tq);
1540 	ieee80211_draintask(ic, &ic->ic_parent_task);
1541 	ieee80211_draintask(ic, &ic->ic_mcast_task);
1542 	ieee80211_draintask(ic, &ic->ic_promisc_task);
1543 	ieee80211_draintask(ic, &ic->ic_chan_task);
1544 	ieee80211_draintask(ic, &ic->ic_bmiss_task);
1545 	ieee80211_draintask(ic, &ic->ic_chw_task);
1546 	taskqueue_unblock(ic->ic_tq);
1547 }
1548 
1549 /*
1550  * Check to see whether the current channel needs reset.
1551  *
1552  * Some devices don't handle being given an invalid channel
1553  * in their operating mode very well (eg wpi(4) will throw a
1554  * firmware exception.)
1555  *
1556  * Return 0 if we're ok, 1 if the channel needs to be reset.
1557  *
1558  * See PR kern/202502.
1559  */
1560 static int
1561 ieee80211_start_check_reset_chan(struct ieee80211vap *vap)
1562 {
1563 	struct ieee80211com *ic = vap->iv_ic;
1564 
1565 	if ((vap->iv_opmode == IEEE80211_M_IBSS &&
1566 	     IEEE80211_IS_CHAN_NOADHOC(ic->ic_curchan)) ||
1567 	    (vap->iv_opmode == IEEE80211_M_HOSTAP &&
1568 	     IEEE80211_IS_CHAN_NOHOSTAP(ic->ic_curchan)))
1569 		return (1);
1570 	return (0);
1571 }
1572 
1573 /*
1574  * Reset the curchan to a known good state.
1575  */
1576 static void
1577 ieee80211_start_reset_chan(struct ieee80211vap *vap)
1578 {
1579 	struct ieee80211com *ic = vap->iv_ic;
1580 
1581 	ic->ic_curchan = &ic->ic_channels[0];
1582 }
1583 
1584 /*
1585  * Start a vap running.  If this is the first vap to be
1586  * set running on the underlying device then we
1587  * automatically bring the device up.
1588  */
1589 void
1590 ieee80211_start_locked(struct ieee80211vap *vap)
1591 {
1592 	struct ifnet *ifp = vap->iv_ifp;
1593 	struct ieee80211com *ic = vap->iv_ic;
1594 
1595 	IEEE80211_LOCK_ASSERT(ic);
1596 
1597 	IEEE80211_DPRINTF(vap,
1598 		IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1599 		"start running, %d vaps running\n", ic->ic_nrunning);
1600 
1601 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1602 		/*
1603 		 * Mark us running.  Note that it's ok to do this first;
1604 		 * if we need to bring the parent device up we defer that
1605 		 * to avoid dropping the com lock.  We expect the device
1606 		 * to respond to being marked up by calling back into us
1607 		 * through ieee80211_start_all at which point we'll come
1608 		 * back in here and complete the work.
1609 		 */
1610 		ifp->if_drv_flags |= IFF_DRV_RUNNING;
1611 		ieee80211_notify_ifnet_change(vap);
1612 
1613 		/*
1614 		 * We are not running; if this we are the first vap
1615 		 * to be brought up auto-up the parent if necessary.
1616 		 */
1617 		if (ic->ic_nrunning++ == 0) {
1618 
1619 			/* reset the channel to a known good channel */
1620 			if (ieee80211_start_check_reset_chan(vap))
1621 				ieee80211_start_reset_chan(vap);
1622 
1623 			IEEE80211_DPRINTF(vap,
1624 			    IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1625 			    "%s: up parent %s\n", __func__, ic->ic_name);
1626 			ieee80211_runtask(ic, &ic->ic_parent_task);
1627 			return;
1628 		}
1629 	}
1630 	/*
1631 	 * If the parent is up and running, then kick the
1632 	 * 802.11 state machine as appropriate.
1633 	 */
1634 	if (vap->iv_roaming != IEEE80211_ROAMING_MANUAL) {
1635 		if (vap->iv_opmode == IEEE80211_M_STA) {
1636 #if 0
1637 			/* XXX bypasses scan too easily; disable for now */
1638 			/*
1639 			 * Try to be intelligent about clocking the state
1640 			 * machine.  If we're currently in RUN state then
1641 			 * we should be able to apply any new state/parameters
1642 			 * simply by re-associating.  Otherwise we need to
1643 			 * re-scan to select an appropriate ap.
1644 			 */
1645 			if (vap->iv_state >= IEEE80211_S_RUN)
1646 				ieee80211_new_state_locked(vap,
1647 				    IEEE80211_S_ASSOC, 1);
1648 			else
1649 #endif
1650 				ieee80211_new_state_locked(vap,
1651 				    IEEE80211_S_SCAN, 0);
1652 		} else {
1653 			/*
1654 			 * For monitor+wds mode there's nothing to do but
1655 			 * start running.  Otherwise if this is the first
1656 			 * vap to be brought up, start a scan which may be
1657 			 * preempted if the station is locked to a particular
1658 			 * channel.
1659 			 */
1660 			vap->iv_flags_ext |= IEEE80211_FEXT_REINIT;
1661 			if (vap->iv_opmode == IEEE80211_M_MONITOR ||
1662 			    vap->iv_opmode == IEEE80211_M_WDS)
1663 				ieee80211_new_state_locked(vap,
1664 				    IEEE80211_S_RUN, -1);
1665 			else
1666 				ieee80211_new_state_locked(vap,
1667 				    IEEE80211_S_SCAN, 0);
1668 		}
1669 	}
1670 }
1671 
1672 /*
1673  * Start a single vap.
1674  */
1675 void
1676 ieee80211_init(void *arg)
1677 {
1678 	struct ieee80211vap *vap = arg;
1679 
1680 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1681 	    "%s\n", __func__);
1682 
1683 	IEEE80211_LOCK(vap->iv_ic);
1684 	ieee80211_start_locked(vap);
1685 	IEEE80211_UNLOCK(vap->iv_ic);
1686 }
1687 
1688 /*
1689  * Start all runnable vap's on a device.
1690  */
1691 void
1692 ieee80211_start_all(struct ieee80211com *ic)
1693 {
1694 	struct ieee80211vap *vap;
1695 
1696 	IEEE80211_LOCK(ic);
1697 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1698 		struct ifnet *ifp = vap->iv_ifp;
1699 		if (IFNET_IS_UP_RUNNING(ifp))	/* NB: avoid recursion */
1700 			ieee80211_start_locked(vap);
1701 	}
1702 	IEEE80211_UNLOCK(ic);
1703 }
1704 
1705 /*
1706  * Stop a vap.  We force it down using the state machine
1707  * then mark it's ifnet not running.  If this is the last
1708  * vap running on the underlying device then we close it
1709  * too to insure it will be properly initialized when the
1710  * next vap is brought up.
1711  */
1712 void
1713 ieee80211_stop_locked(struct ieee80211vap *vap)
1714 {
1715 	struct ieee80211com *ic = vap->iv_ic;
1716 	struct ifnet *ifp = vap->iv_ifp;
1717 
1718 	IEEE80211_LOCK_ASSERT(ic);
1719 
1720 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1721 	    "stop running, %d vaps running\n", ic->ic_nrunning);
1722 
1723 	ieee80211_new_state_locked(vap, IEEE80211_S_INIT, -1);
1724 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1725 		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;	/* mark us stopped */
1726 		ieee80211_notify_ifnet_change(vap);
1727 		if (--ic->ic_nrunning == 0) {
1728 			IEEE80211_DPRINTF(vap,
1729 			    IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1730 			    "down parent %s\n", ic->ic_name);
1731 			ieee80211_runtask(ic, &ic->ic_parent_task);
1732 		}
1733 	}
1734 }
1735 
1736 void
1737 ieee80211_stop(struct ieee80211vap *vap)
1738 {
1739 	struct ieee80211com *ic = vap->iv_ic;
1740 
1741 	IEEE80211_LOCK(ic);
1742 	ieee80211_stop_locked(vap);
1743 	IEEE80211_UNLOCK(ic);
1744 }
1745 
1746 /*
1747  * Stop all vap's running on a device.
1748  */
1749 void
1750 ieee80211_stop_all(struct ieee80211com *ic)
1751 {
1752 	struct ieee80211vap *vap;
1753 
1754 	IEEE80211_LOCK(ic);
1755 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1756 		struct ifnet *ifp = vap->iv_ifp;
1757 		if (IFNET_IS_UP_RUNNING(ifp))	/* NB: avoid recursion */
1758 			ieee80211_stop_locked(vap);
1759 	}
1760 	IEEE80211_UNLOCK(ic);
1761 
1762 	ieee80211_waitfor_parent(ic);
1763 }
1764 
1765 /*
1766  * Stop all vap's running on a device and arrange
1767  * for those that were running to be resumed.
1768  */
1769 void
1770 ieee80211_suspend_all(struct ieee80211com *ic)
1771 {
1772 	struct ieee80211vap *vap;
1773 
1774 	IEEE80211_LOCK(ic);
1775 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1776 		struct ifnet *ifp = vap->iv_ifp;
1777 		if (IFNET_IS_UP_RUNNING(ifp)) {	/* NB: avoid recursion */
1778 			vap->iv_flags_ext |= IEEE80211_FEXT_RESUME;
1779 			ieee80211_stop_locked(vap);
1780 		}
1781 	}
1782 	IEEE80211_UNLOCK(ic);
1783 
1784 	ieee80211_waitfor_parent(ic);
1785 }
1786 
1787 /*
1788  * Start all vap's marked for resume.
1789  */
1790 void
1791 ieee80211_resume_all(struct ieee80211com *ic)
1792 {
1793 	struct ieee80211vap *vap;
1794 
1795 	IEEE80211_LOCK(ic);
1796 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1797 		struct ifnet *ifp = vap->iv_ifp;
1798 		if (!IFNET_IS_UP_RUNNING(ifp) &&
1799 		    (vap->iv_flags_ext & IEEE80211_FEXT_RESUME)) {
1800 			vap->iv_flags_ext &= ~IEEE80211_FEXT_RESUME;
1801 			ieee80211_start_locked(vap);
1802 		}
1803 	}
1804 	IEEE80211_UNLOCK(ic);
1805 }
1806 
1807 /*
1808  * Restart all vap's running on a device.
1809  */
1810 void
1811 ieee80211_restart_all(struct ieee80211com *ic)
1812 {
1813 	/*
1814 	 * NB: do not use ieee80211_runtask here, we will
1815 	 * block & drain net80211 taskqueue.
1816 	 */
1817 	taskqueue_enqueue(taskqueue_thread, &ic->ic_restart_task);
1818 }
1819 
1820 void
1821 ieee80211_beacon_miss(struct ieee80211com *ic)
1822 {
1823 	IEEE80211_LOCK(ic);
1824 	if ((ic->ic_flags & IEEE80211_F_SCAN) == 0) {
1825 		/* Process in a taskq, the handler may reenter the driver */
1826 		ieee80211_runtask(ic, &ic->ic_bmiss_task);
1827 	}
1828 	IEEE80211_UNLOCK(ic);
1829 }
1830 
1831 static void
1832 beacon_miss(void *arg, int npending)
1833 {
1834 	struct ieee80211com *ic = arg;
1835 	struct ieee80211vap *vap;
1836 
1837 	IEEE80211_LOCK(ic);
1838 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1839 		/*
1840 		 * We only pass events through for sta vap's in RUN+ state;
1841 		 * may be too restrictive but for now this saves all the
1842 		 * handlers duplicating these checks.
1843 		 */
1844 		if (vap->iv_opmode == IEEE80211_M_STA &&
1845 		    vap->iv_state >= IEEE80211_S_RUN &&
1846 		    vap->iv_bmiss != NULL)
1847 			vap->iv_bmiss(vap);
1848 	}
1849 	IEEE80211_UNLOCK(ic);
1850 }
1851 
1852 static void
1853 beacon_swmiss(void *arg, int npending)
1854 {
1855 	struct ieee80211vap *vap = arg;
1856 	struct ieee80211com *ic = vap->iv_ic;
1857 
1858 	IEEE80211_LOCK(ic);
1859 	if (vap->iv_state >= IEEE80211_S_RUN) {
1860 		/* XXX Call multiple times if npending > zero? */
1861 		vap->iv_bmiss(vap);
1862 	}
1863 	IEEE80211_UNLOCK(ic);
1864 }
1865 
1866 /*
1867  * Software beacon miss handling.  Check if any beacons
1868  * were received in the last period.  If not post a
1869  * beacon miss; otherwise reset the counter.
1870  */
1871 void
1872 ieee80211_swbmiss(void *arg)
1873 {
1874 	struct ieee80211vap *vap = arg;
1875 	struct ieee80211com *ic = vap->iv_ic;
1876 
1877 	IEEE80211_LOCK_ASSERT(ic);
1878 
1879 	KASSERT(vap->iv_state >= IEEE80211_S_RUN,
1880 	    ("wrong state %d", vap->iv_state));
1881 
1882 	if (ic->ic_flags & IEEE80211_F_SCAN) {
1883 		/*
1884 		 * If scanning just ignore and reset state.  If we get a
1885 		 * bmiss after coming out of scan because we haven't had
1886 		 * time to receive a beacon then we should probe the AP
1887 		 * before posting a real bmiss (unless iv_bmiss_max has
1888 		 * been artifiically lowered).  A cleaner solution might
1889 		 * be to disable the timer on scan start/end but to handle
1890 		 * case of multiple sta vap's we'd need to disable the
1891 		 * timers of all affected vap's.
1892 		 */
1893 		vap->iv_swbmiss_count = 0;
1894 	} else if (vap->iv_swbmiss_count == 0) {
1895 		if (vap->iv_bmiss != NULL)
1896 			ieee80211_runtask(ic, &vap->iv_swbmiss_task);
1897 	} else
1898 		vap->iv_swbmiss_count = 0;
1899 	callout_reset(&vap->iv_swbmiss, vap->iv_swbmiss_period,
1900 		ieee80211_swbmiss, vap);
1901 }
1902 
1903 /*
1904  * Start an 802.11h channel switch.  We record the parameters,
1905  * mark the operation pending, notify each vap through the
1906  * beacon update mechanism so it can update the beacon frame
1907  * contents, and then switch vap's to CSA state to block outbound
1908  * traffic.  Devices that handle CSA directly can use the state
1909  * switch to do the right thing so long as they call
1910  * ieee80211_csa_completeswitch when it's time to complete the
1911  * channel change.  Devices that depend on the net80211 layer can
1912  * use ieee80211_beacon_update to handle the countdown and the
1913  * channel switch.
1914  */
1915 void
1916 ieee80211_csa_startswitch(struct ieee80211com *ic,
1917 	struct ieee80211_channel *c, int mode, int count)
1918 {
1919 	struct ieee80211vap *vap;
1920 
1921 	IEEE80211_LOCK_ASSERT(ic);
1922 
1923 	ic->ic_csa_newchan = c;
1924 	ic->ic_csa_mode = mode;
1925 	ic->ic_csa_count = count;
1926 	ic->ic_flags |= IEEE80211_F_CSAPENDING;
1927 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1928 		if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
1929 		    vap->iv_opmode == IEEE80211_M_IBSS ||
1930 		    vap->iv_opmode == IEEE80211_M_MBSS)
1931 			ieee80211_beacon_notify(vap, IEEE80211_BEACON_CSA);
1932 		/* switch to CSA state to block outbound traffic */
1933 		if (vap->iv_state == IEEE80211_S_RUN)
1934 			ieee80211_new_state_locked(vap, IEEE80211_S_CSA, 0);
1935 	}
1936 	ieee80211_notify_csa(ic, c, mode, count);
1937 }
1938 
1939 /*
1940  * Complete the channel switch by transitioning all CSA VAPs to RUN.
1941  * This is called by both the completion and cancellation functions
1942  * so each VAP is placed back in the RUN state and can thus transmit.
1943  */
1944 static void
1945 csa_completeswitch(struct ieee80211com *ic)
1946 {
1947 	struct ieee80211vap *vap;
1948 
1949 	ic->ic_csa_newchan = NULL;
1950 	ic->ic_flags &= ~IEEE80211_F_CSAPENDING;
1951 
1952 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
1953 		if (vap->iv_state == IEEE80211_S_CSA)
1954 			ieee80211_new_state_locked(vap, IEEE80211_S_RUN, 0);
1955 }
1956 
1957 /*
1958  * Complete an 802.11h channel switch started by ieee80211_csa_startswitch.
1959  * We clear state and move all vap's in CSA state to RUN state
1960  * so they can again transmit.
1961  *
1962  * Although this may not be completely correct, update the BSS channel
1963  * for each VAP to the newly configured channel. The setcurchan sets
1964  * the current operating channel for the interface (so the radio does
1965  * switch over) but the VAP BSS isn't updated, leading to incorrectly
1966  * reported information via ioctl.
1967  */
1968 void
1969 ieee80211_csa_completeswitch(struct ieee80211com *ic)
1970 {
1971 	struct ieee80211vap *vap;
1972 
1973 	IEEE80211_LOCK_ASSERT(ic);
1974 
1975 	KASSERT(ic->ic_flags & IEEE80211_F_CSAPENDING, ("csa not pending"));
1976 
1977 	ieee80211_setcurchan(ic, ic->ic_csa_newchan);
1978 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
1979 		if (vap->iv_state == IEEE80211_S_CSA)
1980 			vap->iv_bss->ni_chan = ic->ic_curchan;
1981 
1982 	csa_completeswitch(ic);
1983 }
1984 
1985 /*
1986  * Cancel an 802.11h channel switch started by ieee80211_csa_startswitch.
1987  * We clear state and move all vap's in CSA state to RUN state
1988  * so they can again transmit.
1989  */
1990 void
1991 ieee80211_csa_cancelswitch(struct ieee80211com *ic)
1992 {
1993 	IEEE80211_LOCK_ASSERT(ic);
1994 
1995 	csa_completeswitch(ic);
1996 }
1997 
1998 /*
1999  * Complete a DFS CAC started by ieee80211_dfs_cac_start.
2000  * We clear state and move all vap's in CAC state to RUN state.
2001  */
2002 void
2003 ieee80211_cac_completeswitch(struct ieee80211vap *vap0)
2004 {
2005 	struct ieee80211com *ic = vap0->iv_ic;
2006 	struct ieee80211vap *vap;
2007 
2008 	IEEE80211_LOCK(ic);
2009 	/*
2010 	 * Complete CAC state change for lead vap first; then
2011 	 * clock all the other vap's waiting.
2012 	 */
2013 	KASSERT(vap0->iv_state == IEEE80211_S_CAC,
2014 	    ("wrong state %d", vap0->iv_state));
2015 	ieee80211_new_state_locked(vap0, IEEE80211_S_RUN, 0);
2016 
2017 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
2018 		if (vap->iv_state == IEEE80211_S_CAC && vap != vap0)
2019 			ieee80211_new_state_locked(vap, IEEE80211_S_RUN, 0);
2020 	IEEE80211_UNLOCK(ic);
2021 }
2022 
2023 /*
2024  * Force all vap's other than the specified vap to the INIT state
2025  * and mark them as waiting for a scan to complete.  These vaps
2026  * will be brought up when the scan completes and the scanning vap
2027  * reaches RUN state by wakeupwaiting.
2028  */
2029 static void
2030 markwaiting(struct ieee80211vap *vap0)
2031 {
2032 	struct ieee80211com *ic = vap0->iv_ic;
2033 	struct ieee80211vap *vap;
2034 
2035 	IEEE80211_LOCK_ASSERT(ic);
2036 
2037 	/*
2038 	 * A vap list entry can not disappear since we are running on the
2039 	 * taskqueue and a vap destroy will queue and drain another state
2040 	 * change task.
2041 	 */
2042 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
2043 		if (vap == vap0)
2044 			continue;
2045 		if (vap->iv_state != IEEE80211_S_INIT) {
2046 			/* NB: iv_newstate may drop the lock */
2047 			vap->iv_newstate(vap, IEEE80211_S_INIT, 0);
2048 			IEEE80211_LOCK_ASSERT(ic);
2049 			vap->iv_flags_ext |= IEEE80211_FEXT_SCANWAIT;
2050 		}
2051 	}
2052 }
2053 
2054 /*
2055  * Wakeup all vap's waiting for a scan to complete.  This is the
2056  * companion to markwaiting (above) and is used to coordinate
2057  * multiple vaps scanning.
2058  * This is called from the state taskqueue.
2059  */
2060 static void
2061 wakeupwaiting(struct ieee80211vap *vap0)
2062 {
2063 	struct ieee80211com *ic = vap0->iv_ic;
2064 	struct ieee80211vap *vap;
2065 
2066 	IEEE80211_LOCK_ASSERT(ic);
2067 
2068 	/*
2069 	 * A vap list entry can not disappear since we are running on the
2070 	 * taskqueue and a vap destroy will queue and drain another state
2071 	 * change task.
2072 	 */
2073 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
2074 		if (vap == vap0)
2075 			continue;
2076 		if (vap->iv_flags_ext & IEEE80211_FEXT_SCANWAIT) {
2077 			vap->iv_flags_ext &= ~IEEE80211_FEXT_SCANWAIT;
2078 			/* NB: sta's cannot go INIT->RUN */
2079 			/* NB: iv_newstate may drop the lock */
2080 			vap->iv_newstate(vap,
2081 			    vap->iv_opmode == IEEE80211_M_STA ?
2082 			        IEEE80211_S_SCAN : IEEE80211_S_RUN, 0);
2083 			IEEE80211_LOCK_ASSERT(ic);
2084 		}
2085 	}
2086 }
2087 
2088 /*
2089  * Handle post state change work common to all operating modes.
2090  */
2091 static void
2092 ieee80211_newstate_cb(void *xvap, int npending)
2093 {
2094 	struct ieee80211vap *vap = xvap;
2095 	struct ieee80211com *ic = vap->iv_ic;
2096 	enum ieee80211_state nstate, ostate;
2097 	int arg, rc;
2098 
2099 	IEEE80211_LOCK(ic);
2100 	nstate = vap->iv_nstate;
2101 	arg = vap->iv_nstate_arg;
2102 
2103 	if (vap->iv_flags_ext & IEEE80211_FEXT_REINIT) {
2104 		/*
2105 		 * We have been requested to drop back to the INIT before
2106 		 * proceeding to the new state.
2107 		 */
2108 		/* Deny any state changes while we are here. */
2109 		vap->iv_nstate = IEEE80211_S_INIT;
2110 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
2111 		    "%s: %s -> %s arg %d\n", __func__,
2112 		    ieee80211_state_name[vap->iv_state],
2113 		    ieee80211_state_name[vap->iv_nstate], arg);
2114 		vap->iv_newstate(vap, vap->iv_nstate, 0);
2115 		IEEE80211_LOCK_ASSERT(ic);
2116 		vap->iv_flags_ext &= ~(IEEE80211_FEXT_REINIT |
2117 		    IEEE80211_FEXT_STATEWAIT);
2118 		/* enqueue new state transition after cancel_scan() task */
2119 		ieee80211_new_state_locked(vap, nstate, arg);
2120 		goto done;
2121 	}
2122 
2123 	ostate = vap->iv_state;
2124 	if (nstate == IEEE80211_S_SCAN && ostate != IEEE80211_S_INIT) {
2125 		/*
2126 		 * SCAN was forced; e.g. on beacon miss.  Force other running
2127 		 * vap's to INIT state and mark them as waiting for the scan to
2128 		 * complete.  This insures they don't interfere with our
2129 		 * scanning.  Since we are single threaded the vaps can not
2130 		 * transition again while we are executing.
2131 		 *
2132 		 * XXX not always right, assumes ap follows sta
2133 		 */
2134 		markwaiting(vap);
2135 	}
2136 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
2137 	    "%s: %s -> %s arg %d\n", __func__,
2138 	    ieee80211_state_name[ostate], ieee80211_state_name[nstate], arg);
2139 
2140 	rc = vap->iv_newstate(vap, nstate, arg);
2141 	IEEE80211_LOCK_ASSERT(ic);
2142 	vap->iv_flags_ext &= ~IEEE80211_FEXT_STATEWAIT;
2143 	if (rc != 0) {
2144 		/* State transition failed */
2145 		KASSERT(rc != EINPROGRESS, ("iv_newstate was deferred"));
2146 		KASSERT(nstate != IEEE80211_S_INIT,
2147 		    ("INIT state change failed"));
2148 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
2149 		    "%s: %s returned error %d\n", __func__,
2150 		    ieee80211_state_name[nstate], rc);
2151 		goto done;
2152 	}
2153 
2154 	/* No actual transition, skip post processing */
2155 	if (ostate == nstate)
2156 		goto done;
2157 
2158 	if (nstate == IEEE80211_S_RUN) {
2159 		/*
2160 		 * OACTIVE may be set on the vap if the upper layer
2161 		 * tried to transmit (e.g. IPv6 NDP) before we reach
2162 		 * RUN state.  Clear it and restart xmit.
2163 		 *
2164 		 * Note this can also happen as a result of SLEEP->RUN
2165 		 * (i.e. coming out of power save mode).
2166 		 */
2167 		vap->iv_ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2168 
2169 		/*
2170 		 * XXX TODO Kick-start a VAP queue - this should be a method!
2171 		 */
2172 
2173 		/* bring up any vaps waiting on us */
2174 		wakeupwaiting(vap);
2175 	} else if (nstate == IEEE80211_S_INIT) {
2176 		/*
2177 		 * Flush the scan cache if we did the last scan (XXX?)
2178 		 * and flush any frames on send queues from this vap.
2179 		 * Note the mgt q is used only for legacy drivers and
2180 		 * will go away shortly.
2181 		 */
2182 		ieee80211_scan_flush(vap);
2183 
2184 		/*
2185 		 * XXX TODO: ic/vap queue flush
2186 		 */
2187 	}
2188 done:
2189 	IEEE80211_UNLOCK(ic);
2190 }
2191 
2192 /*
2193  * Public interface for initiating a state machine change.
2194  * This routine single-threads the request and coordinates
2195  * the scheduling of multiple vaps for the purpose of selecting
2196  * an operating channel.  Specifically the following scenarios
2197  * are handled:
2198  * o only one vap can be selecting a channel so on transition to
2199  *   SCAN state if another vap is already scanning then
2200  *   mark the caller for later processing and return without
2201  *   doing anything (XXX? expectations by caller of synchronous operation)
2202  * o only one vap can be doing CAC of a channel so on transition to
2203  *   CAC state if another vap is already scanning for radar then
2204  *   mark the caller for later processing and return without
2205  *   doing anything (XXX? expectations by caller of synchronous operation)
2206  * o if another vap is already running when a request is made
2207  *   to SCAN then an operating channel has been chosen; bypass
2208  *   the scan and just join the channel
2209  *
2210  * Note that the state change call is done through the iv_newstate
2211  * method pointer so any driver routine gets invoked.  The driver
2212  * will normally call back into operating mode-specific
2213  * ieee80211_newstate routines (below) unless it needs to completely
2214  * bypass the state machine (e.g. because the firmware has it's
2215  * own idea how things should work).  Bypassing the net80211 layer
2216  * is usually a mistake and indicates lack of proper integration
2217  * with the net80211 layer.
2218  */
2219 int
2220 ieee80211_new_state_locked(struct ieee80211vap *vap,
2221 	enum ieee80211_state nstate, int arg)
2222 {
2223 	struct ieee80211com *ic = vap->iv_ic;
2224 	struct ieee80211vap *vp;
2225 	enum ieee80211_state ostate;
2226 	int nrunning, nscanning;
2227 
2228 	IEEE80211_LOCK_ASSERT(ic);
2229 
2230 	if (vap->iv_flags_ext & IEEE80211_FEXT_STATEWAIT) {
2231 		if (vap->iv_nstate == IEEE80211_S_INIT ||
2232 		    ((vap->iv_state == IEEE80211_S_INIT ||
2233 		    (vap->iv_flags_ext & IEEE80211_FEXT_REINIT)) &&
2234 		    vap->iv_nstate == IEEE80211_S_SCAN &&
2235 		    nstate > IEEE80211_S_SCAN)) {
2236 			/*
2237 			 * XXX The vap is being stopped/started,
2238 			 * do not allow any other state changes
2239 			 * until this is completed.
2240 			 */
2241 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
2242 			    "%s: %s -> %s (%s) transition discarded\n",
2243 			    __func__,
2244 			    ieee80211_state_name[vap->iv_state],
2245 			    ieee80211_state_name[nstate],
2246 			    ieee80211_state_name[vap->iv_nstate]);
2247 			return -1;
2248 		} else if (vap->iv_state != vap->iv_nstate) {
2249 #if 0
2250 			/* Warn if the previous state hasn't completed. */
2251 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
2252 			    "%s: pending %s -> %s transition lost\n", __func__,
2253 			    ieee80211_state_name[vap->iv_state],
2254 			    ieee80211_state_name[vap->iv_nstate]);
2255 #else
2256 			/* XXX temporarily enable to identify issues */
2257 			if_printf(vap->iv_ifp,
2258 			    "%s: pending %s -> %s transition lost\n",
2259 			    __func__, ieee80211_state_name[vap->iv_state],
2260 			    ieee80211_state_name[vap->iv_nstate]);
2261 #endif
2262 		}
2263 	}
2264 
2265 	nrunning = nscanning = 0;
2266 	/* XXX can track this state instead of calculating */
2267 	TAILQ_FOREACH(vp, &ic->ic_vaps, iv_next) {
2268 		if (vp != vap) {
2269 			if (vp->iv_state >= IEEE80211_S_RUN)
2270 				nrunning++;
2271 			/* XXX doesn't handle bg scan */
2272 			/* NB: CAC+AUTH+ASSOC treated like SCAN */
2273 			else if (vp->iv_state > IEEE80211_S_INIT)
2274 				nscanning++;
2275 		}
2276 	}
2277 	ostate = vap->iv_state;
2278 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
2279 	    "%s: %s -> %s (nrunning %d nscanning %d)\n", __func__,
2280 	    ieee80211_state_name[ostate], ieee80211_state_name[nstate],
2281 	    nrunning, nscanning);
2282 	switch (nstate) {
2283 	case IEEE80211_S_SCAN:
2284 		if (ostate == IEEE80211_S_INIT) {
2285 			/*
2286 			 * INIT -> SCAN happens on initial bringup.
2287 			 */
2288 			KASSERT(!(nscanning && nrunning),
2289 			    ("%d scanning and %d running", nscanning, nrunning));
2290 			if (nscanning) {
2291 				/*
2292 				 * Someone is scanning, defer our state
2293 				 * change until the work has completed.
2294 				 */
2295 				IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
2296 				    "%s: defer %s -> %s\n",
2297 				    __func__, ieee80211_state_name[ostate],
2298 				    ieee80211_state_name[nstate]);
2299 				vap->iv_flags_ext |= IEEE80211_FEXT_SCANWAIT;
2300 				return 0;
2301 			}
2302 			if (nrunning) {
2303 				/*
2304 				 * Someone is operating; just join the channel
2305 				 * they have chosen.
2306 				 */
2307 				/* XXX kill arg? */
2308 				/* XXX check each opmode, adhoc? */
2309 				if (vap->iv_opmode == IEEE80211_M_STA)
2310 					nstate = IEEE80211_S_SCAN;
2311 				else
2312 					nstate = IEEE80211_S_RUN;
2313 #ifdef IEEE80211_DEBUG
2314 				if (nstate != IEEE80211_S_SCAN) {
2315 					IEEE80211_DPRINTF(vap,
2316 					    IEEE80211_MSG_STATE,
2317 					    "%s: override, now %s -> %s\n",
2318 					    __func__,
2319 					    ieee80211_state_name[ostate],
2320 					    ieee80211_state_name[nstate]);
2321 				}
2322 #endif
2323 			}
2324 		}
2325 		break;
2326 	case IEEE80211_S_RUN:
2327 		if (vap->iv_opmode == IEEE80211_M_WDS &&
2328 		    (vap->iv_flags_ext & IEEE80211_FEXT_WDSLEGACY) &&
2329 		    nscanning) {
2330 			/*
2331 			 * Legacy WDS with someone else scanning; don't
2332 			 * go online until that completes as we should
2333 			 * follow the other vap to the channel they choose.
2334 			 */
2335 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
2336 			     "%s: defer %s -> %s (legacy WDS)\n", __func__,
2337 			     ieee80211_state_name[ostate],
2338 			     ieee80211_state_name[nstate]);
2339 			vap->iv_flags_ext |= IEEE80211_FEXT_SCANWAIT;
2340 			return 0;
2341 		}
2342 		if (vap->iv_opmode == IEEE80211_M_HOSTAP &&
2343 		    IEEE80211_IS_CHAN_DFS(ic->ic_bsschan) &&
2344 		    (vap->iv_flags_ext & IEEE80211_FEXT_DFS) &&
2345 		    !IEEE80211_IS_CHAN_CACDONE(ic->ic_bsschan)) {
2346 			/*
2347 			 * This is a DFS channel, transition to CAC state
2348 			 * instead of RUN.  This allows us to initiate
2349 			 * Channel Availability Check (CAC) as specified
2350 			 * by 11h/DFS.
2351 			 */
2352 			nstate = IEEE80211_S_CAC;
2353 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
2354 			     "%s: override %s -> %s (DFS)\n", __func__,
2355 			     ieee80211_state_name[ostate],
2356 			     ieee80211_state_name[nstate]);
2357 		}
2358 		break;
2359 	case IEEE80211_S_INIT:
2360 		/* cancel any scan in progress */
2361 		ieee80211_cancel_scan(vap);
2362 		if (ostate == IEEE80211_S_INIT ) {
2363 			/* XXX don't believe this */
2364 			/* INIT -> INIT. nothing to do */
2365 			vap->iv_flags_ext &= ~IEEE80211_FEXT_SCANWAIT;
2366 		}
2367 		/* fall thru... */
2368 	default:
2369 		break;
2370 	}
2371 	/* defer the state change to a thread */
2372 	vap->iv_nstate = nstate;
2373 	vap->iv_nstate_arg = arg;
2374 	vap->iv_flags_ext |= IEEE80211_FEXT_STATEWAIT;
2375 	ieee80211_runtask(ic, &vap->iv_nstate_task);
2376 	return EINPROGRESS;
2377 }
2378 
2379 int
2380 ieee80211_new_state(struct ieee80211vap *vap,
2381 	enum ieee80211_state nstate, int arg)
2382 {
2383 	struct ieee80211com *ic = vap->iv_ic;
2384 	int rc;
2385 
2386 	IEEE80211_LOCK(ic);
2387 	rc = ieee80211_new_state_locked(vap, nstate, arg);
2388 	IEEE80211_UNLOCK(ic);
2389 	return rc;
2390 }
2391