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