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