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