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