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