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