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