xref: /freebsd/sys/net80211/ieee80211_proto.c (revision 325151a3)
1 /*-
2  * Copyright (c) 2001 Atsushi Onoe
3  * Copyright (c) 2002-2008 Sam Leffler, Errno Consulting
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 /*
31  * IEEE 802.11 protocol support.
32  */
33 
34 #include "opt_inet.h"
35 #include "opt_wlan.h"
36 
37 #include <sys/param.h>
38 #include <sys/kernel.h>
39 #include <sys/systm.h>
40 
41 #include <sys/socket.h>
42 #include <sys/sockio.h>
43 
44 #include <net/if.h>
45 #include <net/if_var.h>
46 #include <net/if_media.h>
47 #include <net/ethernet.h>		/* XXX for ether_sprintf */
48 
49 #include <net80211/ieee80211_var.h>
50 #include <net80211/ieee80211_adhoc.h>
51 #include <net80211/ieee80211_sta.h>
52 #include <net80211/ieee80211_hostap.h>
53 #include <net80211/ieee80211_wds.h>
54 #ifdef IEEE80211_SUPPORT_MESH
55 #include <net80211/ieee80211_mesh.h>
56 #endif
57 #include <net80211/ieee80211_monitor.h>
58 #include <net80211/ieee80211_input.h>
59 
60 /* XXX tunables */
61 #define	AGGRESSIVE_MODE_SWITCH_HYSTERESIS	3	/* pkts / 100ms */
62 #define	HIGH_PRI_SWITCH_THRESH			10	/* pkts / 100ms */
63 
64 const char *ieee80211_mgt_subtype_name[] = {
65 	"assoc_req",	"assoc_resp",	"reassoc_req",	"reassoc_resp",
66 	"probe_req",	"probe_resp",	"reserved#6",	"reserved#7",
67 	"beacon",	"atim",		"disassoc",	"auth",
68 	"deauth",	"action",	"action_noack",	"reserved#15"
69 };
70 const char *ieee80211_ctl_subtype_name[] = {
71 	"reserved#0",	"reserved#1",	"reserved#2",	"reserved#3",
72 	"reserved#3",	"reserved#5",	"reserved#6",	"reserved#7",
73 	"reserved#8",	"reserved#9",	"ps_poll",	"rts",
74 	"cts",		"ack",		"cf_end",	"cf_end_ack"
75 };
76 const char *ieee80211_opmode_name[IEEE80211_OPMODE_MAX] = {
77 	"IBSS",		/* IEEE80211_M_IBSS */
78 	"STA",		/* IEEE80211_M_STA */
79 	"WDS",		/* IEEE80211_M_WDS */
80 	"AHDEMO",	/* IEEE80211_M_AHDEMO */
81 	"HOSTAP",	/* IEEE80211_M_HOSTAP */
82 	"MONITOR",	/* IEEE80211_M_MONITOR */
83 	"MBSS"		/* IEEE80211_M_MBSS */
84 };
85 const char *ieee80211_state_name[IEEE80211_S_MAX] = {
86 	"INIT",		/* IEEE80211_S_INIT */
87 	"SCAN",		/* IEEE80211_S_SCAN */
88 	"AUTH",		/* IEEE80211_S_AUTH */
89 	"ASSOC",	/* IEEE80211_S_ASSOC */
90 	"CAC",		/* IEEE80211_S_CAC */
91 	"RUN",		/* IEEE80211_S_RUN */
92 	"CSA",		/* IEEE80211_S_CSA */
93 	"SLEEP",	/* IEEE80211_S_SLEEP */
94 };
95 const char *ieee80211_wme_acnames[] = {
96 	"WME_AC_BE",
97 	"WME_AC_BK",
98 	"WME_AC_VI",
99 	"WME_AC_VO",
100 	"WME_UPSD",
101 };
102 
103 static void beacon_miss(void *, int);
104 static void beacon_swmiss(void *, int);
105 static void parent_updown(void *, int);
106 static void update_mcast(void *, int);
107 static void update_promisc(void *, int);
108 static void update_channel(void *, int);
109 static void update_chw(void *, int);
110 static void update_wme(void *, int);
111 static void ieee80211_newstate_cb(void *, int);
112 
113 static int
114 null_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
115 	const struct ieee80211_bpf_params *params)
116 {
117 
118 	ic_printf(ni->ni_ic, "missing ic_raw_xmit callback, drop frame\n");
119 	m_freem(m);
120 	return ENETDOWN;
121 }
122 
123 void
124 ieee80211_proto_attach(struct ieee80211com *ic)
125 {
126 	uint8_t hdrlen;
127 
128 	/* override the 802.3 setting */
129 	hdrlen = ic->ic_headroom
130 		+ sizeof(struct ieee80211_qosframe_addr4)
131 		+ IEEE80211_WEP_IVLEN + IEEE80211_WEP_KIDLEN
132 		+ IEEE80211_WEP_EXTIVLEN;
133 	/* XXX no way to recalculate on ifdetach */
134 	if (ALIGN(hdrlen) > max_linkhdr) {
135 		/* XXX sanity check... */
136 		max_linkhdr = ALIGN(hdrlen);
137 		max_hdr = max_linkhdr + max_protohdr;
138 		max_datalen = MHLEN - max_hdr;
139 	}
140 	ic->ic_protmode = IEEE80211_PROT_CTSONLY;
141 
142 	TASK_INIT(&ic->ic_parent_task, 0, parent_updown, ic);
143 	TASK_INIT(&ic->ic_mcast_task, 0, update_mcast, ic);
144 	TASK_INIT(&ic->ic_promisc_task, 0, update_promisc, ic);
145 	TASK_INIT(&ic->ic_chan_task, 0, update_channel, ic);
146 	TASK_INIT(&ic->ic_bmiss_task, 0, beacon_miss, ic);
147 	TASK_INIT(&ic->ic_chw_task, 0, update_chw, ic);
148 	TASK_INIT(&ic->ic_wme_task, 0, update_wme, ic);
149 
150 	ic->ic_wme.wme_hipri_switch_hysteresis =
151 		AGGRESSIVE_MODE_SWITCH_HYSTERESIS;
152 
153 	/* initialize management frame handlers */
154 	ic->ic_send_mgmt = ieee80211_send_mgmt;
155 	ic->ic_raw_xmit = null_raw_xmit;
156 
157 	ieee80211_adhoc_attach(ic);
158 	ieee80211_sta_attach(ic);
159 	ieee80211_wds_attach(ic);
160 	ieee80211_hostap_attach(ic);
161 #ifdef IEEE80211_SUPPORT_MESH
162 	ieee80211_mesh_attach(ic);
163 #endif
164 	ieee80211_monitor_attach(ic);
165 }
166 
167 void
168 ieee80211_proto_detach(struct ieee80211com *ic)
169 {
170 	ieee80211_monitor_detach(ic);
171 #ifdef IEEE80211_SUPPORT_MESH
172 	ieee80211_mesh_detach(ic);
173 #endif
174 	ieee80211_hostap_detach(ic);
175 	ieee80211_wds_detach(ic);
176 	ieee80211_adhoc_detach(ic);
177 	ieee80211_sta_detach(ic);
178 }
179 
180 static void
181 null_update_beacon(struct ieee80211vap *vap, int item)
182 {
183 }
184 
185 void
186 ieee80211_proto_vattach(struct ieee80211vap *vap)
187 {
188 	struct ieee80211com *ic = vap->iv_ic;
189 	struct ifnet *ifp = vap->iv_ifp;
190 	int i;
191 
192 	/* override the 802.3 setting */
193 	ifp->if_hdrlen = ic->ic_headroom
194                 + sizeof(struct ieee80211_qosframe_addr4)
195                 + IEEE80211_WEP_IVLEN + IEEE80211_WEP_KIDLEN
196                 + IEEE80211_WEP_EXTIVLEN;
197 
198 	vap->iv_rtsthreshold = IEEE80211_RTS_DEFAULT;
199 	vap->iv_fragthreshold = IEEE80211_FRAG_DEFAULT;
200 	vap->iv_bmiss_max = IEEE80211_BMISS_MAX;
201 	callout_init_mtx(&vap->iv_swbmiss, IEEE80211_LOCK_OBJ(ic), 0);
202 	callout_init(&vap->iv_mgtsend, 1);
203 	TASK_INIT(&vap->iv_nstate_task, 0, ieee80211_newstate_cb, vap);
204 	TASK_INIT(&vap->iv_swbmiss_task, 0, beacon_swmiss, vap);
205 	/*
206 	 * Install default tx rate handling: no fixed rate, lowest
207 	 * supported rate for mgmt and multicast frames.  Default
208 	 * max retry count.  These settings can be changed by the
209 	 * driver and/or user applications.
210 	 */
211 	for (i = IEEE80211_MODE_11A; i < IEEE80211_MODE_MAX; i++) {
212 		const struct ieee80211_rateset *rs = &ic->ic_sup_rates[i];
213 
214 		vap->iv_txparms[i].ucastrate = IEEE80211_FIXED_RATE_NONE;
215 
216 		/*
217 		 * Setting the management rate to MCS 0 assumes that the
218 		 * BSS Basic rate set is empty and the BSS Basic MCS set
219 		 * is not.
220 		 *
221 		 * Since we're not checking this, default to the lowest
222 		 * defined rate for this mode.
223 		 *
224 		 * At least one 11n AP (DLINK DIR-825) is reported to drop
225 		 * some MCS management traffic (eg BA response frames.)
226 		 *
227 		 * See also: 9.6.0 of the 802.11n-2009 specification.
228 		 */
229 #ifdef	NOTYET
230 		if (i == IEEE80211_MODE_11NA || i == IEEE80211_MODE_11NG) {
231 			vap->iv_txparms[i].mgmtrate = 0 | IEEE80211_RATE_MCS;
232 			vap->iv_txparms[i].mcastrate = 0 | IEEE80211_RATE_MCS;
233 		} else {
234 			vap->iv_txparms[i].mgmtrate =
235 			    rs->rs_rates[0] & IEEE80211_RATE_VAL;
236 			vap->iv_txparms[i].mcastrate =
237 			    rs->rs_rates[0] & IEEE80211_RATE_VAL;
238 		}
239 #endif
240 		vap->iv_txparms[i].mgmtrate = rs->rs_rates[0] & IEEE80211_RATE_VAL;
241 		vap->iv_txparms[i].mcastrate = rs->rs_rates[0] & IEEE80211_RATE_VAL;
242 		vap->iv_txparms[i].maxretry = IEEE80211_TXMAX_DEFAULT;
243 	}
244 	vap->iv_roaming = IEEE80211_ROAMING_AUTO;
245 
246 	vap->iv_update_beacon = null_update_beacon;
247 	vap->iv_deliver_data = ieee80211_deliver_data;
248 
249 	/* attach support for operating mode */
250 	ic->ic_vattach[vap->iv_opmode](vap);
251 }
252 
253 void
254 ieee80211_proto_vdetach(struct ieee80211vap *vap)
255 {
256 #define	FREEAPPIE(ie) do { \
257 	if (ie != NULL) \
258 		IEEE80211_FREE(ie, M_80211_NODE_IE); \
259 } while (0)
260 	/*
261 	 * Detach operating mode module.
262 	 */
263 	if (vap->iv_opdetach != NULL)
264 		vap->iv_opdetach(vap);
265 	/*
266 	 * This should not be needed as we detach when reseting
267 	 * the state but be conservative here since the
268 	 * authenticator may do things like spawn kernel threads.
269 	 */
270 	if (vap->iv_auth->ia_detach != NULL)
271 		vap->iv_auth->ia_detach(vap);
272 	/*
273 	 * Detach any ACL'ator.
274 	 */
275 	if (vap->iv_acl != NULL)
276 		vap->iv_acl->iac_detach(vap);
277 
278 	FREEAPPIE(vap->iv_appie_beacon);
279 	FREEAPPIE(vap->iv_appie_probereq);
280 	FREEAPPIE(vap->iv_appie_proberesp);
281 	FREEAPPIE(vap->iv_appie_assocreq);
282 	FREEAPPIE(vap->iv_appie_assocresp);
283 	FREEAPPIE(vap->iv_appie_wpa);
284 #undef FREEAPPIE
285 }
286 
287 /*
288  * Simple-minded authenticator module support.
289  */
290 
291 #define	IEEE80211_AUTH_MAX	(IEEE80211_AUTH_WPA+1)
292 /* XXX well-known names */
293 static const char *auth_modnames[IEEE80211_AUTH_MAX] = {
294 	"wlan_internal",	/* IEEE80211_AUTH_NONE */
295 	"wlan_internal",	/* IEEE80211_AUTH_OPEN */
296 	"wlan_internal",	/* IEEE80211_AUTH_SHARED */
297 	"wlan_xauth",		/* IEEE80211_AUTH_8021X	 */
298 	"wlan_internal",	/* IEEE80211_AUTH_AUTO */
299 	"wlan_xauth",		/* IEEE80211_AUTH_WPA */
300 };
301 static const struct ieee80211_authenticator *authenticators[IEEE80211_AUTH_MAX];
302 
303 static const struct ieee80211_authenticator auth_internal = {
304 	.ia_name		= "wlan_internal",
305 	.ia_attach		= NULL,
306 	.ia_detach		= NULL,
307 	.ia_node_join		= NULL,
308 	.ia_node_leave		= NULL,
309 };
310 
311 /*
312  * Setup internal authenticators once; they are never unregistered.
313  */
314 static void
315 ieee80211_auth_setup(void)
316 {
317 	ieee80211_authenticator_register(IEEE80211_AUTH_OPEN, &auth_internal);
318 	ieee80211_authenticator_register(IEEE80211_AUTH_SHARED, &auth_internal);
319 	ieee80211_authenticator_register(IEEE80211_AUTH_AUTO, &auth_internal);
320 }
321 SYSINIT(wlan_auth, SI_SUB_DRIVERS, SI_ORDER_FIRST, ieee80211_auth_setup, NULL);
322 
323 const struct ieee80211_authenticator *
324 ieee80211_authenticator_get(int auth)
325 {
326 	if (auth >= IEEE80211_AUTH_MAX)
327 		return NULL;
328 	if (authenticators[auth] == NULL)
329 		ieee80211_load_module(auth_modnames[auth]);
330 	return authenticators[auth];
331 }
332 
333 void
334 ieee80211_authenticator_register(int type,
335 	const struct ieee80211_authenticator *auth)
336 {
337 	if (type >= IEEE80211_AUTH_MAX)
338 		return;
339 	authenticators[type] = auth;
340 }
341 
342 void
343 ieee80211_authenticator_unregister(int type)
344 {
345 
346 	if (type >= IEEE80211_AUTH_MAX)
347 		return;
348 	authenticators[type] = NULL;
349 }
350 
351 /*
352  * Very simple-minded ACL module support.
353  */
354 /* XXX just one for now */
355 static	const struct ieee80211_aclator *acl = NULL;
356 
357 void
358 ieee80211_aclator_register(const struct ieee80211_aclator *iac)
359 {
360 	printf("wlan: %s acl policy registered\n", iac->iac_name);
361 	acl = iac;
362 }
363 
364 void
365 ieee80211_aclator_unregister(const struct ieee80211_aclator *iac)
366 {
367 	if (acl == iac)
368 		acl = NULL;
369 	printf("wlan: %s acl policy unregistered\n", iac->iac_name);
370 }
371 
372 const struct ieee80211_aclator *
373 ieee80211_aclator_get(const char *name)
374 {
375 	if (acl == NULL)
376 		ieee80211_load_module("wlan_acl");
377 	return acl != NULL && strcmp(acl->iac_name, name) == 0 ? acl : NULL;
378 }
379 
380 void
381 ieee80211_print_essid(const uint8_t *essid, int len)
382 {
383 	const uint8_t *p;
384 	int i;
385 
386 	if (len > IEEE80211_NWID_LEN)
387 		len = IEEE80211_NWID_LEN;
388 	/* determine printable or not */
389 	for (i = 0, p = essid; i < len; i++, p++) {
390 		if (*p < ' ' || *p > 0x7e)
391 			break;
392 	}
393 	if (i == len) {
394 		printf("\"");
395 		for (i = 0, p = essid; i < len; i++, p++)
396 			printf("%c", *p);
397 		printf("\"");
398 	} else {
399 		printf("0x");
400 		for (i = 0, p = essid; i < len; i++, p++)
401 			printf("%02x", *p);
402 	}
403 }
404 
405 void
406 ieee80211_dump_pkt(struct ieee80211com *ic,
407 	const uint8_t *buf, int len, int rate, int rssi)
408 {
409 	const struct ieee80211_frame *wh;
410 	int i;
411 
412 	wh = (const struct ieee80211_frame *)buf;
413 	switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
414 	case IEEE80211_FC1_DIR_NODS:
415 		printf("NODS %s", ether_sprintf(wh->i_addr2));
416 		printf("->%s", ether_sprintf(wh->i_addr1));
417 		printf("(%s)", ether_sprintf(wh->i_addr3));
418 		break;
419 	case IEEE80211_FC1_DIR_TODS:
420 		printf("TODS %s", ether_sprintf(wh->i_addr2));
421 		printf("->%s", ether_sprintf(wh->i_addr3));
422 		printf("(%s)", ether_sprintf(wh->i_addr1));
423 		break;
424 	case IEEE80211_FC1_DIR_FROMDS:
425 		printf("FRDS %s", ether_sprintf(wh->i_addr3));
426 		printf("->%s", ether_sprintf(wh->i_addr1));
427 		printf("(%s)", ether_sprintf(wh->i_addr2));
428 		break;
429 	case IEEE80211_FC1_DIR_DSTODS:
430 		printf("DSDS %s", ether_sprintf((const uint8_t *)&wh[1]));
431 		printf("->%s", ether_sprintf(wh->i_addr3));
432 		printf("(%s", ether_sprintf(wh->i_addr2));
433 		printf("->%s)", ether_sprintf(wh->i_addr1));
434 		break;
435 	}
436 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
437 	case IEEE80211_FC0_TYPE_DATA:
438 		printf(" data");
439 		break;
440 	case IEEE80211_FC0_TYPE_MGT:
441 		printf(" %s", ieee80211_mgt_subtype_name[
442 		    (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK)
443 		    >> IEEE80211_FC0_SUBTYPE_SHIFT]);
444 		break;
445 	default:
446 		printf(" type#%d", wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK);
447 		break;
448 	}
449 	if (IEEE80211_QOS_HAS_SEQ(wh)) {
450 		const struct ieee80211_qosframe *qwh =
451 			(const struct ieee80211_qosframe *)buf;
452 		printf(" QoS [TID %u%s]", qwh->i_qos[0] & IEEE80211_QOS_TID,
453 			qwh->i_qos[0] & IEEE80211_QOS_ACKPOLICY ? " ACM" : "");
454 	}
455 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
456 		int off;
457 
458 		off = ieee80211_anyhdrspace(ic, wh);
459 		printf(" WEP [IV %.02x %.02x %.02x",
460 			buf[off+0], buf[off+1], buf[off+2]);
461 		if (buf[off+IEEE80211_WEP_IVLEN] & IEEE80211_WEP_EXTIV)
462 			printf(" %.02x %.02x %.02x",
463 				buf[off+4], buf[off+5], buf[off+6]);
464 		printf(" KID %u]", buf[off+IEEE80211_WEP_IVLEN] >> 6);
465 	}
466 	if (rate >= 0)
467 		printf(" %dM", rate / 2);
468 	if (rssi >= 0)
469 		printf(" +%d", rssi);
470 	printf("\n");
471 	if (len > 0) {
472 		for (i = 0; i < len; i++) {
473 			if ((i & 1) == 0)
474 				printf(" ");
475 			printf("%02x", buf[i]);
476 		}
477 		printf("\n");
478 	}
479 }
480 
481 static __inline int
482 findrix(const struct ieee80211_rateset *rs, int r)
483 {
484 	int i;
485 
486 	for (i = 0; i < rs->rs_nrates; i++)
487 		if ((rs->rs_rates[i] & IEEE80211_RATE_VAL) == r)
488 			return i;
489 	return -1;
490 }
491 
492 int
493 ieee80211_fix_rate(struct ieee80211_node *ni,
494 	struct ieee80211_rateset *nrs, int flags)
495 {
496 	struct ieee80211vap *vap = ni->ni_vap;
497 	struct ieee80211com *ic = ni->ni_ic;
498 	int i, j, rix, error;
499 	int okrate, badrate, fixedrate, ucastrate;
500 	const struct ieee80211_rateset *srs;
501 	uint8_t r;
502 
503 	error = 0;
504 	okrate = badrate = 0;
505 	ucastrate = vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)].ucastrate;
506 	if (ucastrate != IEEE80211_FIXED_RATE_NONE) {
507 		/*
508 		 * Workaround awkwardness with fixed rate.  We are called
509 		 * to check both the legacy rate set and the HT rate set
510 		 * but we must apply any legacy fixed rate check only to the
511 		 * legacy rate set and vice versa.  We cannot tell what type
512 		 * of rate set we've been given (legacy or HT) but we can
513 		 * distinguish the fixed rate type (MCS have 0x80 set).
514 		 * So to deal with this the caller communicates whether to
515 		 * check MCS or legacy rate using the flags and we use the
516 		 * type of any fixed rate to avoid applying an MCS to a
517 		 * legacy rate and vice versa.
518 		 */
519 		if (ucastrate & 0x80) {
520 			if (flags & IEEE80211_F_DOFRATE)
521 				flags &= ~IEEE80211_F_DOFRATE;
522 		} else if ((ucastrate & 0x80) == 0) {
523 			if (flags & IEEE80211_F_DOFMCS)
524 				flags &= ~IEEE80211_F_DOFMCS;
525 		}
526 		/* NB: required to make MCS match below work */
527 		ucastrate &= IEEE80211_RATE_VAL;
528 	}
529 	fixedrate = IEEE80211_FIXED_RATE_NONE;
530 	/*
531 	 * XXX we are called to process both MCS and legacy rates;
532 	 * we must use the appropriate basic rate set or chaos will
533 	 * ensue; for now callers that want MCS must supply
534 	 * IEEE80211_F_DOBRS; at some point we'll need to split this
535 	 * function so there are two variants, one for MCS and one
536 	 * for legacy rates.
537 	 */
538 	if (flags & IEEE80211_F_DOBRS)
539 		srs = (const struct ieee80211_rateset *)
540 		    ieee80211_get_suphtrates(ic, ni->ni_chan);
541 	else
542 		srs = ieee80211_get_suprates(ic, ni->ni_chan);
543 	for (i = 0; i < nrs->rs_nrates; ) {
544 		if (flags & IEEE80211_F_DOSORT) {
545 			/*
546 			 * Sort rates.
547 			 */
548 			for (j = i + 1; j < nrs->rs_nrates; j++) {
549 				if (IEEE80211_RV(nrs->rs_rates[i]) >
550 				    IEEE80211_RV(nrs->rs_rates[j])) {
551 					r = nrs->rs_rates[i];
552 					nrs->rs_rates[i] = nrs->rs_rates[j];
553 					nrs->rs_rates[j] = r;
554 				}
555 			}
556 		}
557 		r = nrs->rs_rates[i] & IEEE80211_RATE_VAL;
558 		badrate = r;
559 		/*
560 		 * Check for fixed rate.
561 		 */
562 		if (r == ucastrate)
563 			fixedrate = r;
564 		/*
565 		 * Check against supported rates.
566 		 */
567 		rix = findrix(srs, r);
568 		if (flags & IEEE80211_F_DONEGO) {
569 			if (rix < 0) {
570 				/*
571 				 * A rate in the node's rate set is not
572 				 * supported.  If this is a basic rate and we
573 				 * are operating as a STA then this is an error.
574 				 * Otherwise we just discard/ignore the rate.
575 				 */
576 				if ((flags & IEEE80211_F_JOIN) &&
577 				    (nrs->rs_rates[i] & IEEE80211_RATE_BASIC))
578 					error++;
579 			} else if ((flags & IEEE80211_F_JOIN) == 0) {
580 				/*
581 				 * Overwrite with the supported rate
582 				 * value so any basic rate bit is set.
583 				 */
584 				nrs->rs_rates[i] = srs->rs_rates[rix];
585 			}
586 		}
587 		if ((flags & IEEE80211_F_DODEL) && rix < 0) {
588 			/*
589 			 * Delete unacceptable rates.
590 			 */
591 			nrs->rs_nrates--;
592 			for (j = i; j < nrs->rs_nrates; j++)
593 				nrs->rs_rates[j] = nrs->rs_rates[j + 1];
594 			nrs->rs_rates[j] = 0;
595 			continue;
596 		}
597 		if (rix >= 0)
598 			okrate = nrs->rs_rates[i];
599 		i++;
600 	}
601 	if (okrate == 0 || error != 0 ||
602 	    ((flags & (IEEE80211_F_DOFRATE|IEEE80211_F_DOFMCS)) &&
603 	     fixedrate != ucastrate)) {
604 		IEEE80211_NOTE(vap, IEEE80211_MSG_XRATE | IEEE80211_MSG_11N, ni,
605 		    "%s: flags 0x%x okrate %d error %d fixedrate 0x%x "
606 		    "ucastrate %x\n", __func__, fixedrate, ucastrate, flags);
607 		return badrate | IEEE80211_RATE_BASIC;
608 	} else
609 		return IEEE80211_RV(okrate);
610 }
611 
612 /*
613  * Reset 11g-related state.
614  */
615 void
616 ieee80211_reset_erp(struct ieee80211com *ic)
617 {
618 	ic->ic_flags &= ~IEEE80211_F_USEPROT;
619 	ic->ic_nonerpsta = 0;
620 	ic->ic_longslotsta = 0;
621 	/*
622 	 * Short slot time is enabled only when operating in 11g
623 	 * and not in an IBSS.  We must also honor whether or not
624 	 * the driver is capable of doing it.
625 	 */
626 	ieee80211_set_shortslottime(ic,
627 		IEEE80211_IS_CHAN_A(ic->ic_curchan) ||
628 		IEEE80211_IS_CHAN_HT(ic->ic_curchan) ||
629 		(IEEE80211_IS_CHAN_ANYG(ic->ic_curchan) &&
630 		ic->ic_opmode == IEEE80211_M_HOSTAP &&
631 		(ic->ic_caps & IEEE80211_C_SHSLOT)));
632 	/*
633 	 * Set short preamble and ERP barker-preamble flags.
634 	 */
635 	if (IEEE80211_IS_CHAN_A(ic->ic_curchan) ||
636 	    (ic->ic_caps & IEEE80211_C_SHPREAMBLE)) {
637 		ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
638 		ic->ic_flags &= ~IEEE80211_F_USEBARKER;
639 	} else {
640 		ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
641 		ic->ic_flags |= IEEE80211_F_USEBARKER;
642 	}
643 }
644 
645 /*
646  * Set the short slot time state and notify the driver.
647  */
648 void
649 ieee80211_set_shortslottime(struct ieee80211com *ic, int onoff)
650 {
651 	if (onoff)
652 		ic->ic_flags |= IEEE80211_F_SHSLOT;
653 	else
654 		ic->ic_flags &= ~IEEE80211_F_SHSLOT;
655 	/* notify driver */
656 	if (ic->ic_updateslot != NULL)
657 		ic->ic_updateslot(ic);
658 }
659 
660 /*
661  * Check if the specified rate set supports ERP.
662  * NB: the rate set is assumed to be sorted.
663  */
664 int
665 ieee80211_iserp_rateset(const struct ieee80211_rateset *rs)
666 {
667 	static const int rates[] = { 2, 4, 11, 22, 12, 24, 48 };
668 	int i, j;
669 
670 	if (rs->rs_nrates < nitems(rates))
671 		return 0;
672 	for (i = 0; i < nitems(rates); i++) {
673 		for (j = 0; j < rs->rs_nrates; j++) {
674 			int r = rs->rs_rates[j] & IEEE80211_RATE_VAL;
675 			if (rates[i] == r)
676 				goto next;
677 			if (r > rates[i])
678 				return 0;
679 		}
680 		return 0;
681 	next:
682 		;
683 	}
684 	return 1;
685 }
686 
687 /*
688  * Mark the basic rates for the rate table based on the
689  * operating mode.  For real 11g we mark all the 11b rates
690  * and 6, 12, and 24 OFDM.  For 11b compatibility we mark only
691  * 11b rates.  There's also a pseudo 11a-mode used to mark only
692  * the basic OFDM rates.
693  */
694 static void
695 setbasicrates(struct ieee80211_rateset *rs,
696     enum ieee80211_phymode mode, int add)
697 {
698 	static const struct ieee80211_rateset basic[IEEE80211_MODE_MAX] = {
699 	    [IEEE80211_MODE_11A]	= { 3, { 12, 24, 48 } },
700 	    [IEEE80211_MODE_11B]	= { 2, { 2, 4 } },
701 					    /* NB: mixed b/g */
702 	    [IEEE80211_MODE_11G]	= { 4, { 2, 4, 11, 22 } },
703 	    [IEEE80211_MODE_TURBO_A]	= { 3, { 12, 24, 48 } },
704 	    [IEEE80211_MODE_TURBO_G]	= { 4, { 2, 4, 11, 22 } },
705 	    [IEEE80211_MODE_STURBO_A]	= { 3, { 12, 24, 48 } },
706 	    [IEEE80211_MODE_HALF]	= { 3, { 6, 12, 24 } },
707 	    [IEEE80211_MODE_QUARTER]	= { 3, { 3, 6, 12 } },
708 	    [IEEE80211_MODE_11NA]	= { 3, { 12, 24, 48 } },
709 					    /* NB: mixed b/g */
710 	    [IEEE80211_MODE_11NG]	= { 4, { 2, 4, 11, 22 } },
711 	};
712 	int i, j;
713 
714 	for (i = 0; i < rs->rs_nrates; i++) {
715 		if (!add)
716 			rs->rs_rates[i] &= IEEE80211_RATE_VAL;
717 		for (j = 0; j < basic[mode].rs_nrates; j++)
718 			if (basic[mode].rs_rates[j] == rs->rs_rates[i]) {
719 				rs->rs_rates[i] |= IEEE80211_RATE_BASIC;
720 				break;
721 			}
722 	}
723 }
724 
725 /*
726  * Set the basic rates in a rate set.
727  */
728 void
729 ieee80211_setbasicrates(struct ieee80211_rateset *rs,
730     enum ieee80211_phymode mode)
731 {
732 	setbasicrates(rs, mode, 0);
733 }
734 
735 /*
736  * Add basic rates to a rate set.
737  */
738 void
739 ieee80211_addbasicrates(struct ieee80211_rateset *rs,
740     enum ieee80211_phymode mode)
741 {
742 	setbasicrates(rs, mode, 1);
743 }
744 
745 /*
746  * WME protocol support.
747  *
748  * The default 11a/b/g/n parameters come from the WiFi Alliance WMM
749  * System Interopability Test Plan (v1.4, Appendix F) and the 802.11n
750  * Draft 2.0 Test Plan (Appendix D).
751  *
752  * Static/Dynamic Turbo mode settings come from Atheros.
753  */
754 typedef struct phyParamType {
755 	uint8_t		aifsn;
756 	uint8_t		logcwmin;
757 	uint8_t		logcwmax;
758 	uint16_t	txopLimit;
759 	uint8_t 	acm;
760 } paramType;
761 
762 static const struct phyParamType phyParamForAC_BE[IEEE80211_MODE_MAX] = {
763 	[IEEE80211_MODE_AUTO]	= { 3, 4,  6,  0, 0 },
764 	[IEEE80211_MODE_11A]	= { 3, 4,  6,  0, 0 },
765 	[IEEE80211_MODE_11B]	= { 3, 4,  6,  0, 0 },
766 	[IEEE80211_MODE_11G]	= { 3, 4,  6,  0, 0 },
767 	[IEEE80211_MODE_FH]	= { 3, 4,  6,  0, 0 },
768 	[IEEE80211_MODE_TURBO_A]= { 2, 3,  5,  0, 0 },
769 	[IEEE80211_MODE_TURBO_G]= { 2, 3,  5,  0, 0 },
770 	[IEEE80211_MODE_STURBO_A]={ 2, 3,  5,  0, 0 },
771 	[IEEE80211_MODE_HALF]	= { 3, 4,  6,  0, 0 },
772 	[IEEE80211_MODE_QUARTER]= { 3, 4,  6,  0, 0 },
773 	[IEEE80211_MODE_11NA]	= { 3, 4,  6,  0, 0 },
774 	[IEEE80211_MODE_11NG]	= { 3, 4,  6,  0, 0 },
775 };
776 static const struct phyParamType phyParamForAC_BK[IEEE80211_MODE_MAX] = {
777 	[IEEE80211_MODE_AUTO]	= { 7, 4, 10,  0, 0 },
778 	[IEEE80211_MODE_11A]	= { 7, 4, 10,  0, 0 },
779 	[IEEE80211_MODE_11B]	= { 7, 4, 10,  0, 0 },
780 	[IEEE80211_MODE_11G]	= { 7, 4, 10,  0, 0 },
781 	[IEEE80211_MODE_FH]	= { 7, 4, 10,  0, 0 },
782 	[IEEE80211_MODE_TURBO_A]= { 7, 3, 10,  0, 0 },
783 	[IEEE80211_MODE_TURBO_G]= { 7, 3, 10,  0, 0 },
784 	[IEEE80211_MODE_STURBO_A]={ 7, 3, 10,  0, 0 },
785 	[IEEE80211_MODE_HALF]	= { 7, 4, 10,  0, 0 },
786 	[IEEE80211_MODE_QUARTER]= { 7, 4, 10,  0, 0 },
787 	[IEEE80211_MODE_11NA]	= { 7, 4, 10,  0, 0 },
788 	[IEEE80211_MODE_11NG]	= { 7, 4, 10,  0, 0 },
789 };
790 static const struct phyParamType phyParamForAC_VI[IEEE80211_MODE_MAX] = {
791 	[IEEE80211_MODE_AUTO]	= { 1, 3, 4,  94, 0 },
792 	[IEEE80211_MODE_11A]	= { 1, 3, 4,  94, 0 },
793 	[IEEE80211_MODE_11B]	= { 1, 3, 4, 188, 0 },
794 	[IEEE80211_MODE_11G]	= { 1, 3, 4,  94, 0 },
795 	[IEEE80211_MODE_FH]	= { 1, 3, 4, 188, 0 },
796 	[IEEE80211_MODE_TURBO_A]= { 1, 2, 3,  94, 0 },
797 	[IEEE80211_MODE_TURBO_G]= { 1, 2, 3,  94, 0 },
798 	[IEEE80211_MODE_STURBO_A]={ 1, 2, 3,  94, 0 },
799 	[IEEE80211_MODE_HALF]	= { 1, 3, 4,  94, 0 },
800 	[IEEE80211_MODE_QUARTER]= { 1, 3, 4,  94, 0 },
801 	[IEEE80211_MODE_11NA]	= { 1, 3, 4,  94, 0 },
802 	[IEEE80211_MODE_11NG]	= { 1, 3, 4,  94, 0 },
803 };
804 static const struct phyParamType phyParamForAC_VO[IEEE80211_MODE_MAX] = {
805 	[IEEE80211_MODE_AUTO]	= { 1, 2, 3,  47, 0 },
806 	[IEEE80211_MODE_11A]	= { 1, 2, 3,  47, 0 },
807 	[IEEE80211_MODE_11B]	= { 1, 2, 3, 102, 0 },
808 	[IEEE80211_MODE_11G]	= { 1, 2, 3,  47, 0 },
809 	[IEEE80211_MODE_FH]	= { 1, 2, 3, 102, 0 },
810 	[IEEE80211_MODE_TURBO_A]= { 1, 2, 2,  47, 0 },
811 	[IEEE80211_MODE_TURBO_G]= { 1, 2, 2,  47, 0 },
812 	[IEEE80211_MODE_STURBO_A]={ 1, 2, 2,  47, 0 },
813 	[IEEE80211_MODE_HALF]	= { 1, 2, 3,  47, 0 },
814 	[IEEE80211_MODE_QUARTER]= { 1, 2, 3,  47, 0 },
815 	[IEEE80211_MODE_11NA]	= { 1, 2, 3,  47, 0 },
816 	[IEEE80211_MODE_11NG]	= { 1, 2, 3,  47, 0 },
817 };
818 
819 static const struct phyParamType bssPhyParamForAC_BE[IEEE80211_MODE_MAX] = {
820 	[IEEE80211_MODE_AUTO]	= { 3, 4, 10,  0, 0 },
821 	[IEEE80211_MODE_11A]	= { 3, 4, 10,  0, 0 },
822 	[IEEE80211_MODE_11B]	= { 3, 4, 10,  0, 0 },
823 	[IEEE80211_MODE_11G]	= { 3, 4, 10,  0, 0 },
824 	[IEEE80211_MODE_FH]	= { 3, 4, 10,  0, 0 },
825 	[IEEE80211_MODE_TURBO_A]= { 2, 3, 10,  0, 0 },
826 	[IEEE80211_MODE_TURBO_G]= { 2, 3, 10,  0, 0 },
827 	[IEEE80211_MODE_STURBO_A]={ 2, 3, 10,  0, 0 },
828 	[IEEE80211_MODE_HALF]	= { 3, 4, 10,  0, 0 },
829 	[IEEE80211_MODE_QUARTER]= { 3, 4, 10,  0, 0 },
830 	[IEEE80211_MODE_11NA]	= { 3, 4, 10,  0, 0 },
831 	[IEEE80211_MODE_11NG]	= { 3, 4, 10,  0, 0 },
832 };
833 static const struct phyParamType bssPhyParamForAC_VI[IEEE80211_MODE_MAX] = {
834 	[IEEE80211_MODE_AUTO]	= { 2, 3, 4,  94, 0 },
835 	[IEEE80211_MODE_11A]	= { 2, 3, 4,  94, 0 },
836 	[IEEE80211_MODE_11B]	= { 2, 3, 4, 188, 0 },
837 	[IEEE80211_MODE_11G]	= { 2, 3, 4,  94, 0 },
838 	[IEEE80211_MODE_FH]	= { 2, 3, 4, 188, 0 },
839 	[IEEE80211_MODE_TURBO_A]= { 2, 2, 3,  94, 0 },
840 	[IEEE80211_MODE_TURBO_G]= { 2, 2, 3,  94, 0 },
841 	[IEEE80211_MODE_STURBO_A]={ 2, 2, 3,  94, 0 },
842 	[IEEE80211_MODE_HALF]	= { 2, 3, 4,  94, 0 },
843 	[IEEE80211_MODE_QUARTER]= { 2, 3, 4,  94, 0 },
844 	[IEEE80211_MODE_11NA]	= { 2, 3, 4,  94, 0 },
845 	[IEEE80211_MODE_11NG]	= { 2, 3, 4,  94, 0 },
846 };
847 static const struct phyParamType bssPhyParamForAC_VO[IEEE80211_MODE_MAX] = {
848 	[IEEE80211_MODE_AUTO]	= { 2, 2, 3,  47, 0 },
849 	[IEEE80211_MODE_11A]	= { 2, 2, 3,  47, 0 },
850 	[IEEE80211_MODE_11B]	= { 2, 2, 3, 102, 0 },
851 	[IEEE80211_MODE_11G]	= { 2, 2, 3,  47, 0 },
852 	[IEEE80211_MODE_FH]	= { 2, 2, 3, 102, 0 },
853 	[IEEE80211_MODE_TURBO_A]= { 1, 2, 2,  47, 0 },
854 	[IEEE80211_MODE_TURBO_G]= { 1, 2, 2,  47, 0 },
855 	[IEEE80211_MODE_STURBO_A]={ 1, 2, 2,  47, 0 },
856 	[IEEE80211_MODE_HALF]	= { 2, 2, 3,  47, 0 },
857 	[IEEE80211_MODE_QUARTER]= { 2, 2, 3,  47, 0 },
858 	[IEEE80211_MODE_11NA]	= { 2, 2, 3,  47, 0 },
859 	[IEEE80211_MODE_11NG]	= { 2, 2, 3,  47, 0 },
860 };
861 
862 static void
863 _setifsparams(struct wmeParams *wmep, const paramType *phy)
864 {
865 	wmep->wmep_aifsn = phy->aifsn;
866 	wmep->wmep_logcwmin = phy->logcwmin;
867 	wmep->wmep_logcwmax = phy->logcwmax;
868 	wmep->wmep_txopLimit = phy->txopLimit;
869 }
870 
871 static void
872 setwmeparams(struct ieee80211vap *vap, const char *type, int ac,
873 	struct wmeParams *wmep, const paramType *phy)
874 {
875 	wmep->wmep_acm = phy->acm;
876 	_setifsparams(wmep, phy);
877 
878 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
879 	    "set %s (%s) [acm %u aifsn %u logcwmin %u logcwmax %u txop %u]\n",
880 	    ieee80211_wme_acnames[ac], type,
881 	    wmep->wmep_acm, wmep->wmep_aifsn, wmep->wmep_logcwmin,
882 	    wmep->wmep_logcwmax, wmep->wmep_txopLimit);
883 }
884 
885 static void
886 ieee80211_wme_initparams_locked(struct ieee80211vap *vap)
887 {
888 	struct ieee80211com *ic = vap->iv_ic;
889 	struct ieee80211_wme_state *wme = &ic->ic_wme;
890 	const paramType *pPhyParam, *pBssPhyParam;
891 	struct wmeParams *wmep;
892 	enum ieee80211_phymode mode;
893 	int i;
894 
895 	IEEE80211_LOCK_ASSERT(ic);
896 
897 	if ((ic->ic_caps & IEEE80211_C_WME) == 0 || ic->ic_nrunning > 1)
898 		return;
899 
900 	/*
901 	 * Clear the wme cap_info field so a qoscount from a previous
902 	 * vap doesn't confuse later code which only parses the beacon
903 	 * field and updates hardware when said field changes.
904 	 * Otherwise the hardware is programmed with defaults, not what
905 	 * the beacon actually announces.
906 	 */
907 	wme->wme_wmeChanParams.cap_info = 0;
908 
909 	/*
910 	 * Select mode; we can be called early in which case we
911 	 * always use auto mode.  We know we'll be called when
912 	 * entering the RUN state with bsschan setup properly
913 	 * so state will eventually get set correctly
914 	 */
915 	if (ic->ic_bsschan != IEEE80211_CHAN_ANYC)
916 		mode = ieee80211_chan2mode(ic->ic_bsschan);
917 	else
918 		mode = IEEE80211_MODE_AUTO;
919 	for (i = 0; i < WME_NUM_AC; i++) {
920 		switch (i) {
921 		case WME_AC_BK:
922 			pPhyParam = &phyParamForAC_BK[mode];
923 			pBssPhyParam = &phyParamForAC_BK[mode];
924 			break;
925 		case WME_AC_VI:
926 			pPhyParam = &phyParamForAC_VI[mode];
927 			pBssPhyParam = &bssPhyParamForAC_VI[mode];
928 			break;
929 		case WME_AC_VO:
930 			pPhyParam = &phyParamForAC_VO[mode];
931 			pBssPhyParam = &bssPhyParamForAC_VO[mode];
932 			break;
933 		case WME_AC_BE:
934 		default:
935 			pPhyParam = &phyParamForAC_BE[mode];
936 			pBssPhyParam = &bssPhyParamForAC_BE[mode];
937 			break;
938 		}
939 		wmep = &wme->wme_wmeChanParams.cap_wmeParams[i];
940 		if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
941 			setwmeparams(vap, "chan", i, wmep, pPhyParam);
942 		} else {
943 			setwmeparams(vap, "chan", i, wmep, pBssPhyParam);
944 		}
945 		wmep = &wme->wme_wmeBssChanParams.cap_wmeParams[i];
946 		setwmeparams(vap, "bss ", i, wmep, pBssPhyParam);
947 	}
948 	/* NB: check ic_bss to avoid NULL deref on initial attach */
949 	if (vap->iv_bss != NULL) {
950 		/*
951 		 * Calculate agressive mode switching threshold based
952 		 * on beacon interval.  This doesn't need locking since
953 		 * we're only called before entering the RUN state at
954 		 * which point we start sending beacon frames.
955 		 */
956 		wme->wme_hipri_switch_thresh =
957 			(HIGH_PRI_SWITCH_THRESH * vap->iv_bss->ni_intval) / 100;
958 		wme->wme_flags &= ~WME_F_AGGRMODE;
959 		ieee80211_wme_updateparams(vap);
960 	}
961 }
962 
963 void
964 ieee80211_wme_initparams(struct ieee80211vap *vap)
965 {
966 	struct ieee80211com *ic = vap->iv_ic;
967 
968 	IEEE80211_LOCK(ic);
969 	ieee80211_wme_initparams_locked(vap);
970 	IEEE80211_UNLOCK(ic);
971 }
972 
973 /*
974  * Update WME parameters for ourself and the BSS.
975  */
976 void
977 ieee80211_wme_updateparams_locked(struct ieee80211vap *vap)
978 {
979 	static const paramType aggrParam[IEEE80211_MODE_MAX] = {
980 	    [IEEE80211_MODE_AUTO]	= { 2, 4, 10, 64, 0 },
981 	    [IEEE80211_MODE_11A]	= { 2, 4, 10, 64, 0 },
982 	    [IEEE80211_MODE_11B]	= { 2, 5, 10, 64, 0 },
983 	    [IEEE80211_MODE_11G]	= { 2, 4, 10, 64, 0 },
984 	    [IEEE80211_MODE_FH]		= { 2, 5, 10, 64, 0 },
985 	    [IEEE80211_MODE_TURBO_A]	= { 1, 3, 10, 64, 0 },
986 	    [IEEE80211_MODE_TURBO_G]	= { 1, 3, 10, 64, 0 },
987 	    [IEEE80211_MODE_STURBO_A]	= { 1, 3, 10, 64, 0 },
988 	    [IEEE80211_MODE_HALF]	= { 2, 4, 10, 64, 0 },
989 	    [IEEE80211_MODE_QUARTER]	= { 2, 4, 10, 64, 0 },
990 	    [IEEE80211_MODE_11NA]	= { 2, 4, 10, 64, 0 },	/* XXXcheck*/
991 	    [IEEE80211_MODE_11NG]	= { 2, 4, 10, 64, 0 },	/* XXXcheck*/
992 	};
993 	struct ieee80211com *ic = vap->iv_ic;
994 	struct ieee80211_wme_state *wme = &ic->ic_wme;
995 	const struct wmeParams *wmep;
996 	struct wmeParams *chanp, *bssp;
997 	enum ieee80211_phymode mode;
998 	int i;
999 	int do_aggrmode = 0;
1000 
1001        	/*
1002 	 * Set up the channel access parameters for the physical
1003 	 * device.  First populate the configured settings.
1004 	 */
1005 	for (i = 0; i < WME_NUM_AC; i++) {
1006 		chanp = &wme->wme_chanParams.cap_wmeParams[i];
1007 		wmep = &wme->wme_wmeChanParams.cap_wmeParams[i];
1008 		chanp->wmep_aifsn = wmep->wmep_aifsn;
1009 		chanp->wmep_logcwmin = wmep->wmep_logcwmin;
1010 		chanp->wmep_logcwmax = wmep->wmep_logcwmax;
1011 		chanp->wmep_txopLimit = wmep->wmep_txopLimit;
1012 
1013 		chanp = &wme->wme_bssChanParams.cap_wmeParams[i];
1014 		wmep = &wme->wme_wmeBssChanParams.cap_wmeParams[i];
1015 		chanp->wmep_aifsn = wmep->wmep_aifsn;
1016 		chanp->wmep_logcwmin = wmep->wmep_logcwmin;
1017 		chanp->wmep_logcwmax = wmep->wmep_logcwmax;
1018 		chanp->wmep_txopLimit = wmep->wmep_txopLimit;
1019 	}
1020 
1021 	/*
1022 	 * Select mode; we can be called early in which case we
1023 	 * always use auto mode.  We know we'll be called when
1024 	 * entering the RUN state with bsschan setup properly
1025 	 * so state will eventually get set correctly
1026 	 */
1027 	if (ic->ic_bsschan != IEEE80211_CHAN_ANYC)
1028 		mode = ieee80211_chan2mode(ic->ic_bsschan);
1029 	else
1030 		mode = IEEE80211_MODE_AUTO;
1031 
1032 	/*
1033 	 * This implements agressive mode as found in certain
1034 	 * vendors' AP's.  When there is significant high
1035 	 * priority (VI/VO) traffic in the BSS throttle back BE
1036 	 * traffic by using conservative parameters.  Otherwise
1037 	 * BE uses agressive params to optimize performance of
1038 	 * legacy/non-QoS traffic.
1039 	 */
1040 
1041 	/* Hostap? Only if aggressive mode is enabled */
1042         if (vap->iv_opmode == IEEE80211_M_HOSTAP &&
1043 	     (wme->wme_flags & WME_F_AGGRMODE) != 0)
1044 		do_aggrmode = 1;
1045 
1046 	/*
1047 	 * Station? Only if we're in a non-QoS BSS.
1048 	 */
1049 	else if ((vap->iv_opmode == IEEE80211_M_STA &&
1050 	     (vap->iv_bss->ni_flags & IEEE80211_NODE_QOS) == 0))
1051 		do_aggrmode = 1;
1052 
1053 	/*
1054 	 * IBSS? Only if we we have WME enabled.
1055 	 */
1056 	else if ((vap->iv_opmode == IEEE80211_M_IBSS) &&
1057 	    (vap->iv_flags & IEEE80211_F_WME))
1058 		do_aggrmode = 1;
1059 
1060 	/*
1061 	 * If WME is disabled on this VAP, default to aggressive mode
1062 	 * regardless of the configuration.
1063 	 */
1064 	if ((vap->iv_flags & IEEE80211_F_WME) == 0)
1065 		do_aggrmode = 1;
1066 
1067 	/* XXX WDS? */
1068 
1069 	/* XXX MBSS? */
1070 
1071 	if (do_aggrmode) {
1072 		chanp = &wme->wme_chanParams.cap_wmeParams[WME_AC_BE];
1073 		bssp = &wme->wme_bssChanParams.cap_wmeParams[WME_AC_BE];
1074 
1075 		chanp->wmep_aifsn = bssp->wmep_aifsn = aggrParam[mode].aifsn;
1076 		chanp->wmep_logcwmin = bssp->wmep_logcwmin =
1077 		    aggrParam[mode].logcwmin;
1078 		chanp->wmep_logcwmax = bssp->wmep_logcwmax =
1079 		    aggrParam[mode].logcwmax;
1080 		chanp->wmep_txopLimit = bssp->wmep_txopLimit =
1081 		    (vap->iv_flags & IEEE80211_F_BURST) ?
1082 			aggrParam[mode].txopLimit : 0;
1083 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
1084 		    "update %s (chan+bss) [acm %u aifsn %u logcwmin %u "
1085 		    "logcwmax %u txop %u]\n", ieee80211_wme_acnames[WME_AC_BE],
1086 		    chanp->wmep_acm, chanp->wmep_aifsn, chanp->wmep_logcwmin,
1087 		    chanp->wmep_logcwmax, chanp->wmep_txopLimit);
1088 	}
1089 
1090 
1091 	/*
1092 	 * Change the contention window based on the number of associated
1093 	 * stations.  If the number of associated stations is 1 and
1094 	 * aggressive mode is enabled, lower the contention window even
1095 	 * further.
1096 	 */
1097 	if (vap->iv_opmode == IEEE80211_M_HOSTAP &&
1098 	    ic->ic_sta_assoc < 2 && (wme->wme_flags & WME_F_AGGRMODE) != 0) {
1099 		static const uint8_t logCwMin[IEEE80211_MODE_MAX] = {
1100 		    [IEEE80211_MODE_AUTO]	= 3,
1101 		    [IEEE80211_MODE_11A]	= 3,
1102 		    [IEEE80211_MODE_11B]	= 4,
1103 		    [IEEE80211_MODE_11G]	= 3,
1104 		    [IEEE80211_MODE_FH]		= 4,
1105 		    [IEEE80211_MODE_TURBO_A]	= 3,
1106 		    [IEEE80211_MODE_TURBO_G]	= 3,
1107 		    [IEEE80211_MODE_STURBO_A]	= 3,
1108 		    [IEEE80211_MODE_HALF]	= 3,
1109 		    [IEEE80211_MODE_QUARTER]	= 3,
1110 		    [IEEE80211_MODE_11NA]	= 3,
1111 		    [IEEE80211_MODE_11NG]	= 3,
1112 		};
1113 		chanp = &wme->wme_chanParams.cap_wmeParams[WME_AC_BE];
1114 		bssp = &wme->wme_bssChanParams.cap_wmeParams[WME_AC_BE];
1115 
1116 		chanp->wmep_logcwmin = bssp->wmep_logcwmin = logCwMin[mode];
1117 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
1118 		    "update %s (chan+bss) logcwmin %u\n",
1119 		    ieee80211_wme_acnames[WME_AC_BE], chanp->wmep_logcwmin);
1120 	}
1121 
1122 	/*
1123 	 * Arrange for the beacon update.
1124 	 *
1125 	 * XXX what about MBSS, WDS?
1126 	 */
1127 	if (vap->iv_opmode == IEEE80211_M_HOSTAP
1128 	    || vap->iv_opmode == IEEE80211_M_IBSS) {
1129 		/*
1130 		 * Arrange for a beacon update and bump the parameter
1131 		 * set number so associated stations load the new values.
1132 		 */
1133 		wme->wme_bssChanParams.cap_info =
1134 			(wme->wme_bssChanParams.cap_info+1) & WME_QOSINFO_COUNT;
1135 		ieee80211_beacon_notify(vap, IEEE80211_BEACON_WME);
1136 	}
1137 
1138 	/* schedule the deferred WME update */
1139 	ieee80211_runtask(ic, &ic->ic_wme_task);
1140 
1141 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
1142 	    "%s: WME params updated, cap_info 0x%x\n", __func__,
1143 	    vap->iv_opmode == IEEE80211_M_STA ?
1144 		wme->wme_wmeChanParams.cap_info :
1145 		wme->wme_bssChanParams.cap_info);
1146 }
1147 
1148 void
1149 ieee80211_wme_updateparams(struct ieee80211vap *vap)
1150 {
1151 	struct ieee80211com *ic = vap->iv_ic;
1152 
1153 	if (ic->ic_caps & IEEE80211_C_WME) {
1154 		IEEE80211_LOCK(ic);
1155 		ieee80211_wme_updateparams_locked(vap);
1156 		IEEE80211_UNLOCK(ic);
1157 	}
1158 }
1159 
1160 static void
1161 parent_updown(void *arg, int npending)
1162 {
1163 	struct ieee80211com *ic = arg;
1164 
1165 	ic->ic_parent(ic);
1166 }
1167 
1168 static void
1169 update_mcast(void *arg, int npending)
1170 {
1171 	struct ieee80211com *ic = arg;
1172 
1173 	ic->ic_update_mcast(ic);
1174 }
1175 
1176 static void
1177 update_promisc(void *arg, int npending)
1178 {
1179 	struct ieee80211com *ic = arg;
1180 
1181 	ic->ic_update_promisc(ic);
1182 }
1183 
1184 static void
1185 update_channel(void *arg, int npending)
1186 {
1187 	struct ieee80211com *ic = arg;
1188 
1189 	ic->ic_set_channel(ic);
1190 	ieee80211_radiotap_chan_change(ic);
1191 }
1192 
1193 static void
1194 update_chw(void *arg, int npending)
1195 {
1196 	struct ieee80211com *ic = arg;
1197 
1198 	/*
1199 	 * XXX should we defer the channel width _config_ update until now?
1200 	 */
1201 	ic->ic_update_chw(ic);
1202 }
1203 
1204 static void
1205 update_wme(void *arg, int npending)
1206 {
1207 	struct ieee80211com *ic = arg;
1208 
1209 	/*
1210 	 * XXX should we defer the WME configuration update until now?
1211 	 */
1212 	ic->ic_wme.wme_update(ic);
1213 }
1214 
1215 /*
1216  * Block until the parent is in a known state.  This is
1217  * used after any operations that dispatch a task (e.g.
1218  * to auto-configure the parent device up/down).
1219  */
1220 void
1221 ieee80211_waitfor_parent(struct ieee80211com *ic)
1222 {
1223 	taskqueue_block(ic->ic_tq);
1224 	ieee80211_draintask(ic, &ic->ic_parent_task);
1225 	ieee80211_draintask(ic, &ic->ic_mcast_task);
1226 	ieee80211_draintask(ic, &ic->ic_promisc_task);
1227 	ieee80211_draintask(ic, &ic->ic_chan_task);
1228 	ieee80211_draintask(ic, &ic->ic_bmiss_task);
1229 	ieee80211_draintask(ic, &ic->ic_chw_task);
1230 	ieee80211_draintask(ic, &ic->ic_wme_task);
1231 	taskqueue_unblock(ic->ic_tq);
1232 }
1233 
1234 /*
1235  * Check to see whether the current channel needs reset.
1236  *
1237  * Some devices don't handle being given an invalid channel
1238  * in their operating mode very well (eg wpi(4) will throw a
1239  * firmware exception.)
1240  *
1241  * Return 0 if we're ok, 1 if the channel needs to be reset.
1242  *
1243  * See PR kern/202502.
1244  */
1245 static int
1246 ieee80211_start_check_reset_chan(struct ieee80211vap *vap)
1247 {
1248 	struct ieee80211com *ic = vap->iv_ic;
1249 
1250 	if ((vap->iv_opmode == IEEE80211_M_IBSS &&
1251 	     IEEE80211_IS_CHAN_NOADHOC(ic->ic_curchan)) ||
1252 	    (vap->iv_opmode == IEEE80211_M_HOSTAP &&
1253 	     IEEE80211_IS_CHAN_NOHOSTAP(ic->ic_curchan)))
1254 		return (1);
1255 	return (0);
1256 }
1257 
1258 /*
1259  * Reset the curchan to a known good state.
1260  */
1261 static void
1262 ieee80211_start_reset_chan(struct ieee80211vap *vap)
1263 {
1264 	struct ieee80211com *ic = vap->iv_ic;
1265 
1266 	ic->ic_curchan = &ic->ic_channels[0];
1267 }
1268 
1269 /*
1270  * Start a vap running.  If this is the first vap to be
1271  * set running on the underlying device then we
1272  * automatically bring the device up.
1273  */
1274 void
1275 ieee80211_start_locked(struct ieee80211vap *vap)
1276 {
1277 	struct ifnet *ifp = vap->iv_ifp;
1278 	struct ieee80211com *ic = vap->iv_ic;
1279 
1280 	IEEE80211_LOCK_ASSERT(ic);
1281 
1282 	IEEE80211_DPRINTF(vap,
1283 		IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1284 		"start running, %d vaps running\n", ic->ic_nrunning);
1285 
1286 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1287 		/*
1288 		 * Mark us running.  Note that it's ok to do this first;
1289 		 * if we need to bring the parent device up we defer that
1290 		 * to avoid dropping the com lock.  We expect the device
1291 		 * to respond to being marked up by calling back into us
1292 		 * through ieee80211_start_all at which point we'll come
1293 		 * back in here and complete the work.
1294 		 */
1295 		ifp->if_drv_flags |= IFF_DRV_RUNNING;
1296 		/*
1297 		 * We are not running; if this we are the first vap
1298 		 * to be brought up auto-up the parent if necessary.
1299 		 */
1300 		if (ic->ic_nrunning++ == 0) {
1301 
1302 			/* reset the channel to a known good channel */
1303 			if (ieee80211_start_check_reset_chan(vap))
1304 				ieee80211_start_reset_chan(vap);
1305 
1306 			IEEE80211_DPRINTF(vap,
1307 			    IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1308 			    "%s: up parent %s\n", __func__, ic->ic_name);
1309 			ieee80211_runtask(ic, &ic->ic_parent_task);
1310 			return;
1311 		}
1312 	}
1313 	/*
1314 	 * If the parent is up and running, then kick the
1315 	 * 802.11 state machine as appropriate.
1316 	 */
1317 	if (vap->iv_roaming != IEEE80211_ROAMING_MANUAL) {
1318 		if (vap->iv_opmode == IEEE80211_M_STA) {
1319 #if 0
1320 			/* XXX bypasses scan too easily; disable for now */
1321 			/*
1322 			 * Try to be intelligent about clocking the state
1323 			 * machine.  If we're currently in RUN state then
1324 			 * we should be able to apply any new state/parameters
1325 			 * simply by re-associating.  Otherwise we need to
1326 			 * re-scan to select an appropriate ap.
1327 			 */
1328 			if (vap->iv_state >= IEEE80211_S_RUN)
1329 				ieee80211_new_state_locked(vap,
1330 				    IEEE80211_S_ASSOC, 1);
1331 			else
1332 #endif
1333 				ieee80211_new_state_locked(vap,
1334 				    IEEE80211_S_SCAN, 0);
1335 		} else {
1336 			/*
1337 			 * For monitor+wds mode there's nothing to do but
1338 			 * start running.  Otherwise if this is the first
1339 			 * vap to be brought up, start a scan which may be
1340 			 * preempted if the station is locked to a particular
1341 			 * channel.
1342 			 */
1343 			vap->iv_flags_ext |= IEEE80211_FEXT_REINIT;
1344 			if (vap->iv_opmode == IEEE80211_M_MONITOR ||
1345 			    vap->iv_opmode == IEEE80211_M_WDS)
1346 				ieee80211_new_state_locked(vap,
1347 				    IEEE80211_S_RUN, -1);
1348 			else
1349 				ieee80211_new_state_locked(vap,
1350 				    IEEE80211_S_SCAN, 0);
1351 		}
1352 	}
1353 }
1354 
1355 /*
1356  * Start a single vap.
1357  */
1358 void
1359 ieee80211_init(void *arg)
1360 {
1361 	struct ieee80211vap *vap = arg;
1362 
1363 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1364 	    "%s\n", __func__);
1365 
1366 	IEEE80211_LOCK(vap->iv_ic);
1367 	ieee80211_start_locked(vap);
1368 	IEEE80211_UNLOCK(vap->iv_ic);
1369 }
1370 
1371 /*
1372  * Start all runnable vap's on a device.
1373  */
1374 void
1375 ieee80211_start_all(struct ieee80211com *ic)
1376 {
1377 	struct ieee80211vap *vap;
1378 
1379 	IEEE80211_LOCK(ic);
1380 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1381 		struct ifnet *ifp = vap->iv_ifp;
1382 		if (IFNET_IS_UP_RUNNING(ifp))	/* NB: avoid recursion */
1383 			ieee80211_start_locked(vap);
1384 	}
1385 	IEEE80211_UNLOCK(ic);
1386 }
1387 
1388 /*
1389  * Stop a vap.  We force it down using the state machine
1390  * then mark it's ifnet not running.  If this is the last
1391  * vap running on the underlying device then we close it
1392  * too to insure it will be properly initialized when the
1393  * next vap is brought up.
1394  */
1395 void
1396 ieee80211_stop_locked(struct ieee80211vap *vap)
1397 {
1398 	struct ieee80211com *ic = vap->iv_ic;
1399 	struct ifnet *ifp = vap->iv_ifp;
1400 
1401 	IEEE80211_LOCK_ASSERT(ic);
1402 
1403 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1404 	    "stop running, %d vaps running\n", ic->ic_nrunning);
1405 
1406 	ieee80211_new_state_locked(vap, IEEE80211_S_INIT, -1);
1407 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1408 		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;	/* mark us stopped */
1409 		if (--ic->ic_nrunning == 0) {
1410 			IEEE80211_DPRINTF(vap,
1411 			    IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1412 			    "down parent %s\n", ic->ic_name);
1413 			ieee80211_runtask(ic, &ic->ic_parent_task);
1414 		}
1415 	}
1416 }
1417 
1418 void
1419 ieee80211_stop(struct ieee80211vap *vap)
1420 {
1421 	struct ieee80211com *ic = vap->iv_ic;
1422 
1423 	IEEE80211_LOCK(ic);
1424 	ieee80211_stop_locked(vap);
1425 	IEEE80211_UNLOCK(ic);
1426 }
1427 
1428 /*
1429  * Stop all vap's running on a device.
1430  */
1431 void
1432 ieee80211_stop_all(struct ieee80211com *ic)
1433 {
1434 	struct ieee80211vap *vap;
1435 
1436 	IEEE80211_LOCK(ic);
1437 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1438 		struct ifnet *ifp = vap->iv_ifp;
1439 		if (IFNET_IS_UP_RUNNING(ifp))	/* NB: avoid recursion */
1440 			ieee80211_stop_locked(vap);
1441 	}
1442 	IEEE80211_UNLOCK(ic);
1443 
1444 	ieee80211_waitfor_parent(ic);
1445 }
1446 
1447 /*
1448  * Stop all vap's running on a device and arrange
1449  * for those that were running to be resumed.
1450  */
1451 void
1452 ieee80211_suspend_all(struct ieee80211com *ic)
1453 {
1454 	struct ieee80211vap *vap;
1455 
1456 	IEEE80211_LOCK(ic);
1457 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1458 		struct ifnet *ifp = vap->iv_ifp;
1459 		if (IFNET_IS_UP_RUNNING(ifp)) {	/* NB: avoid recursion */
1460 			vap->iv_flags_ext |= IEEE80211_FEXT_RESUME;
1461 			ieee80211_stop_locked(vap);
1462 		}
1463 	}
1464 	IEEE80211_UNLOCK(ic);
1465 
1466 	ieee80211_waitfor_parent(ic);
1467 }
1468 
1469 /*
1470  * Start all vap's marked for resume.
1471  */
1472 void
1473 ieee80211_resume_all(struct ieee80211com *ic)
1474 {
1475 	struct ieee80211vap *vap;
1476 
1477 	IEEE80211_LOCK(ic);
1478 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1479 		struct ifnet *ifp = vap->iv_ifp;
1480 		if (!IFNET_IS_UP_RUNNING(ifp) &&
1481 		    (vap->iv_flags_ext & IEEE80211_FEXT_RESUME)) {
1482 			vap->iv_flags_ext &= ~IEEE80211_FEXT_RESUME;
1483 			ieee80211_start_locked(vap);
1484 		}
1485 	}
1486 	IEEE80211_UNLOCK(ic);
1487 }
1488 
1489 void
1490 ieee80211_beacon_miss(struct ieee80211com *ic)
1491 {
1492 	IEEE80211_LOCK(ic);
1493 	if ((ic->ic_flags & IEEE80211_F_SCAN) == 0) {
1494 		/* Process in a taskq, the handler may reenter the driver */
1495 		ieee80211_runtask(ic, &ic->ic_bmiss_task);
1496 	}
1497 	IEEE80211_UNLOCK(ic);
1498 }
1499 
1500 static void
1501 beacon_miss(void *arg, int npending)
1502 {
1503 	struct ieee80211com *ic = arg;
1504 	struct ieee80211vap *vap;
1505 
1506 	IEEE80211_LOCK(ic);
1507 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1508 		/*
1509 		 * We only pass events through for sta vap's in RUN state;
1510 		 * may be too restrictive but for now this saves all the
1511 		 * handlers duplicating these checks.
1512 		 */
1513 		if (vap->iv_opmode == IEEE80211_M_STA &&
1514 		    vap->iv_state >= IEEE80211_S_RUN &&
1515 		    vap->iv_bmiss != NULL)
1516 			vap->iv_bmiss(vap);
1517 	}
1518 	IEEE80211_UNLOCK(ic);
1519 }
1520 
1521 static void
1522 beacon_swmiss(void *arg, int npending)
1523 {
1524 	struct ieee80211vap *vap = arg;
1525 	struct ieee80211com *ic = vap->iv_ic;
1526 
1527 	IEEE80211_LOCK(ic);
1528 	if (vap->iv_state == IEEE80211_S_RUN) {
1529 		/* XXX Call multiple times if npending > zero? */
1530 		vap->iv_bmiss(vap);
1531 	}
1532 	IEEE80211_UNLOCK(ic);
1533 }
1534 
1535 /*
1536  * Software beacon miss handling.  Check if any beacons
1537  * were received in the last period.  If not post a
1538  * beacon miss; otherwise reset the counter.
1539  */
1540 void
1541 ieee80211_swbmiss(void *arg)
1542 {
1543 	struct ieee80211vap *vap = arg;
1544 	struct ieee80211com *ic = vap->iv_ic;
1545 
1546 	IEEE80211_LOCK_ASSERT(ic);
1547 
1548 	/* XXX sleep state? */
1549 	KASSERT(vap->iv_state == IEEE80211_S_RUN,
1550 	    ("wrong state %d", vap->iv_state));
1551 
1552 	if (ic->ic_flags & IEEE80211_F_SCAN) {
1553 		/*
1554 		 * If scanning just ignore and reset state.  If we get a
1555 		 * bmiss after coming out of scan because we haven't had
1556 		 * time to receive a beacon then we should probe the AP
1557 		 * before posting a real bmiss (unless iv_bmiss_max has
1558 		 * been artifiically lowered).  A cleaner solution might
1559 		 * be to disable the timer on scan start/end but to handle
1560 		 * case of multiple sta vap's we'd need to disable the
1561 		 * timers of all affected vap's.
1562 		 */
1563 		vap->iv_swbmiss_count = 0;
1564 	} else if (vap->iv_swbmiss_count == 0) {
1565 		if (vap->iv_bmiss != NULL)
1566 			ieee80211_runtask(ic, &vap->iv_swbmiss_task);
1567 	} else
1568 		vap->iv_swbmiss_count = 0;
1569 	callout_reset(&vap->iv_swbmiss, vap->iv_swbmiss_period,
1570 		ieee80211_swbmiss, vap);
1571 }
1572 
1573 /*
1574  * Start an 802.11h channel switch.  We record the parameters,
1575  * mark the operation pending, notify each vap through the
1576  * beacon update mechanism so it can update the beacon frame
1577  * contents, and then switch vap's to CSA state to block outbound
1578  * traffic.  Devices that handle CSA directly can use the state
1579  * switch to do the right thing so long as they call
1580  * ieee80211_csa_completeswitch when it's time to complete the
1581  * channel change.  Devices that depend on the net80211 layer can
1582  * use ieee80211_beacon_update to handle the countdown and the
1583  * channel switch.
1584  */
1585 void
1586 ieee80211_csa_startswitch(struct ieee80211com *ic,
1587 	struct ieee80211_channel *c, int mode, int count)
1588 {
1589 	struct ieee80211vap *vap;
1590 
1591 	IEEE80211_LOCK_ASSERT(ic);
1592 
1593 	ic->ic_csa_newchan = c;
1594 	ic->ic_csa_mode = mode;
1595 	ic->ic_csa_count = count;
1596 	ic->ic_flags |= IEEE80211_F_CSAPENDING;
1597 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1598 		if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
1599 		    vap->iv_opmode == IEEE80211_M_IBSS ||
1600 		    vap->iv_opmode == IEEE80211_M_MBSS)
1601 			ieee80211_beacon_notify(vap, IEEE80211_BEACON_CSA);
1602 		/* switch to CSA state to block outbound traffic */
1603 		if (vap->iv_state == IEEE80211_S_RUN)
1604 			ieee80211_new_state_locked(vap, IEEE80211_S_CSA, 0);
1605 	}
1606 	ieee80211_notify_csa(ic, c, mode, count);
1607 }
1608 
1609 /*
1610  * Complete the channel switch by transitioning all CSA VAPs to RUN.
1611  * This is called by both the completion and cancellation functions
1612  * so each VAP is placed back in the RUN state and can thus transmit.
1613  */
1614 static void
1615 csa_completeswitch(struct ieee80211com *ic)
1616 {
1617 	struct ieee80211vap *vap;
1618 
1619 	ic->ic_csa_newchan = NULL;
1620 	ic->ic_flags &= ~IEEE80211_F_CSAPENDING;
1621 
1622 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
1623 		if (vap->iv_state == IEEE80211_S_CSA)
1624 			ieee80211_new_state_locked(vap, IEEE80211_S_RUN, 0);
1625 }
1626 
1627 /*
1628  * Complete an 802.11h channel switch started by ieee80211_csa_startswitch.
1629  * We clear state and move all vap's in CSA state to RUN state
1630  * so they can again transmit.
1631  *
1632  * Although this may not be completely correct, update the BSS channel
1633  * for each VAP to the newly configured channel. The setcurchan sets
1634  * the current operating channel for the interface (so the radio does
1635  * switch over) but the VAP BSS isn't updated, leading to incorrectly
1636  * reported information via ioctl.
1637  */
1638 void
1639 ieee80211_csa_completeswitch(struct ieee80211com *ic)
1640 {
1641 	struct ieee80211vap *vap;
1642 
1643 	IEEE80211_LOCK_ASSERT(ic);
1644 
1645 	KASSERT(ic->ic_flags & IEEE80211_F_CSAPENDING, ("csa not pending"));
1646 
1647 	ieee80211_setcurchan(ic, ic->ic_csa_newchan);
1648 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
1649 		if (vap->iv_state == IEEE80211_S_CSA)
1650 			vap->iv_bss->ni_chan = ic->ic_curchan;
1651 
1652 	csa_completeswitch(ic);
1653 }
1654 
1655 /*
1656  * Cancel an 802.11h channel switch started by ieee80211_csa_startswitch.
1657  * We clear state and move all vap's in CSA state to RUN state
1658  * so they can again transmit.
1659  */
1660 void
1661 ieee80211_csa_cancelswitch(struct ieee80211com *ic)
1662 {
1663 	IEEE80211_LOCK_ASSERT(ic);
1664 
1665 	csa_completeswitch(ic);
1666 }
1667 
1668 /*
1669  * Complete a DFS CAC started by ieee80211_dfs_cac_start.
1670  * We clear state and move all vap's in CAC state to RUN state.
1671  */
1672 void
1673 ieee80211_cac_completeswitch(struct ieee80211vap *vap0)
1674 {
1675 	struct ieee80211com *ic = vap0->iv_ic;
1676 	struct ieee80211vap *vap;
1677 
1678 	IEEE80211_LOCK(ic);
1679 	/*
1680 	 * Complete CAC state change for lead vap first; then
1681 	 * clock all the other vap's waiting.
1682 	 */
1683 	KASSERT(vap0->iv_state == IEEE80211_S_CAC,
1684 	    ("wrong state %d", vap0->iv_state));
1685 	ieee80211_new_state_locked(vap0, IEEE80211_S_RUN, 0);
1686 
1687 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
1688 		if (vap->iv_state == IEEE80211_S_CAC)
1689 			ieee80211_new_state_locked(vap, IEEE80211_S_RUN, 0);
1690 	IEEE80211_UNLOCK(ic);
1691 }
1692 
1693 /*
1694  * Force all vap's other than the specified vap to the INIT state
1695  * and mark them as waiting for a scan to complete.  These vaps
1696  * will be brought up when the scan completes and the scanning vap
1697  * reaches RUN state by wakeupwaiting.
1698  */
1699 static void
1700 markwaiting(struct ieee80211vap *vap0)
1701 {
1702 	struct ieee80211com *ic = vap0->iv_ic;
1703 	struct ieee80211vap *vap;
1704 
1705 	IEEE80211_LOCK_ASSERT(ic);
1706 
1707 	/*
1708 	 * A vap list entry can not disappear since we are running on the
1709 	 * taskqueue and a vap destroy will queue and drain another state
1710 	 * change task.
1711 	 */
1712 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1713 		if (vap == vap0)
1714 			continue;
1715 		if (vap->iv_state != IEEE80211_S_INIT) {
1716 			/* NB: iv_newstate may drop the lock */
1717 			vap->iv_newstate(vap, IEEE80211_S_INIT, 0);
1718 			IEEE80211_LOCK_ASSERT(ic);
1719 			vap->iv_flags_ext |= IEEE80211_FEXT_SCANWAIT;
1720 		}
1721 	}
1722 }
1723 
1724 /*
1725  * Wakeup all vap's waiting for a scan to complete.  This is the
1726  * companion to markwaiting (above) and is used to coordinate
1727  * multiple vaps scanning.
1728  * This is called from the state taskqueue.
1729  */
1730 static void
1731 wakeupwaiting(struct ieee80211vap *vap0)
1732 {
1733 	struct ieee80211com *ic = vap0->iv_ic;
1734 	struct ieee80211vap *vap;
1735 
1736 	IEEE80211_LOCK_ASSERT(ic);
1737 
1738 	/*
1739 	 * A vap list entry can not disappear since we are running on the
1740 	 * taskqueue and a vap destroy will queue and drain another state
1741 	 * change task.
1742 	 */
1743 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1744 		if (vap == vap0)
1745 			continue;
1746 		if (vap->iv_flags_ext & IEEE80211_FEXT_SCANWAIT) {
1747 			vap->iv_flags_ext &= ~IEEE80211_FEXT_SCANWAIT;
1748 			/* NB: sta's cannot go INIT->RUN */
1749 			/* NB: iv_newstate may drop the lock */
1750 			vap->iv_newstate(vap,
1751 			    vap->iv_opmode == IEEE80211_M_STA ?
1752 			        IEEE80211_S_SCAN : IEEE80211_S_RUN, 0);
1753 			IEEE80211_LOCK_ASSERT(ic);
1754 		}
1755 	}
1756 }
1757 
1758 /*
1759  * Handle post state change work common to all operating modes.
1760  */
1761 static void
1762 ieee80211_newstate_cb(void *xvap, int npending)
1763 {
1764 	struct ieee80211vap *vap = xvap;
1765 	struct ieee80211com *ic = vap->iv_ic;
1766 	enum ieee80211_state nstate, ostate;
1767 	int arg, rc;
1768 
1769 	IEEE80211_LOCK(ic);
1770 	nstate = vap->iv_nstate;
1771 	arg = vap->iv_nstate_arg;
1772 
1773 	if (vap->iv_flags_ext & IEEE80211_FEXT_REINIT) {
1774 		/*
1775 		 * We have been requested to drop back to the INIT before
1776 		 * proceeding to the new state.
1777 		 */
1778 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1779 		    "%s: %s -> %s arg %d\n", __func__,
1780 		    ieee80211_state_name[vap->iv_state],
1781 		    ieee80211_state_name[IEEE80211_S_INIT], arg);
1782 		vap->iv_newstate(vap, IEEE80211_S_INIT, arg);
1783 		IEEE80211_LOCK_ASSERT(ic);
1784 		vap->iv_flags_ext &= ~IEEE80211_FEXT_REINIT;
1785 	}
1786 
1787 	ostate = vap->iv_state;
1788 	if (nstate == IEEE80211_S_SCAN && ostate != IEEE80211_S_INIT) {
1789 		/*
1790 		 * SCAN was forced; e.g. on beacon miss.  Force other running
1791 		 * vap's to INIT state and mark them as waiting for the scan to
1792 		 * complete.  This insures they don't interfere with our
1793 		 * scanning.  Since we are single threaded the vaps can not
1794 		 * transition again while we are executing.
1795 		 *
1796 		 * XXX not always right, assumes ap follows sta
1797 		 */
1798 		markwaiting(vap);
1799 	}
1800 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1801 	    "%s: %s -> %s arg %d\n", __func__,
1802 	    ieee80211_state_name[ostate], ieee80211_state_name[nstate], arg);
1803 
1804 	rc = vap->iv_newstate(vap, nstate, arg);
1805 	IEEE80211_LOCK_ASSERT(ic);
1806 	vap->iv_flags_ext &= ~IEEE80211_FEXT_STATEWAIT;
1807 	if (rc != 0) {
1808 		/* State transition failed */
1809 		KASSERT(rc != EINPROGRESS, ("iv_newstate was deferred"));
1810 		KASSERT(nstate != IEEE80211_S_INIT,
1811 		    ("INIT state change failed"));
1812 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1813 		    "%s: %s returned error %d\n", __func__,
1814 		    ieee80211_state_name[nstate], rc);
1815 		goto done;
1816 	}
1817 
1818 	/* No actual transition, skip post processing */
1819 	if (ostate == nstate)
1820 		goto done;
1821 
1822 	if (nstate == IEEE80211_S_RUN) {
1823 		/*
1824 		 * OACTIVE may be set on the vap if the upper layer
1825 		 * tried to transmit (e.g. IPv6 NDP) before we reach
1826 		 * RUN state.  Clear it and restart xmit.
1827 		 *
1828 		 * Note this can also happen as a result of SLEEP->RUN
1829 		 * (i.e. coming out of power save mode).
1830 		 */
1831 		vap->iv_ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1832 
1833 		/*
1834 		 * XXX TODO Kick-start a VAP queue - this should be a method!
1835 		 */
1836 
1837 		/* bring up any vaps waiting on us */
1838 		wakeupwaiting(vap);
1839 	} else if (nstate == IEEE80211_S_INIT) {
1840 		/*
1841 		 * Flush the scan cache if we did the last scan (XXX?)
1842 		 * and flush any frames on send queues from this vap.
1843 		 * Note the mgt q is used only for legacy drivers and
1844 		 * will go away shortly.
1845 		 */
1846 		ieee80211_scan_flush(vap);
1847 
1848 		/*
1849 		 * XXX TODO: ic/vap queue flush
1850 		 */
1851 	}
1852 done:
1853 	IEEE80211_UNLOCK(ic);
1854 }
1855 
1856 /*
1857  * Public interface for initiating a state machine change.
1858  * This routine single-threads the request and coordinates
1859  * the scheduling of multiple vaps for the purpose of selecting
1860  * an operating channel.  Specifically the following scenarios
1861  * are handled:
1862  * o only one vap can be selecting a channel so on transition to
1863  *   SCAN state if another vap is already scanning then
1864  *   mark the caller for later processing and return without
1865  *   doing anything (XXX? expectations by caller of synchronous operation)
1866  * o only one vap can be doing CAC of a channel so on transition to
1867  *   CAC state if another vap is already scanning for radar then
1868  *   mark the caller for later processing and return without
1869  *   doing anything (XXX? expectations by caller of synchronous operation)
1870  * o if another vap is already running when a request is made
1871  *   to SCAN then an operating channel has been chosen; bypass
1872  *   the scan and just join the channel
1873  *
1874  * Note that the state change call is done through the iv_newstate
1875  * method pointer so any driver routine gets invoked.  The driver
1876  * will normally call back into operating mode-specific
1877  * ieee80211_newstate routines (below) unless it needs to completely
1878  * bypass the state machine (e.g. because the firmware has it's
1879  * own idea how things should work).  Bypassing the net80211 layer
1880  * is usually a mistake and indicates lack of proper integration
1881  * with the net80211 layer.
1882  */
1883 int
1884 ieee80211_new_state_locked(struct ieee80211vap *vap,
1885 	enum ieee80211_state nstate, int arg)
1886 {
1887 	struct ieee80211com *ic = vap->iv_ic;
1888 	struct ieee80211vap *vp;
1889 	enum ieee80211_state ostate;
1890 	int nrunning, nscanning;
1891 
1892 	IEEE80211_LOCK_ASSERT(ic);
1893 
1894 	if (vap->iv_flags_ext & IEEE80211_FEXT_STATEWAIT) {
1895 		if (vap->iv_nstate == IEEE80211_S_INIT) {
1896 			/*
1897 			 * XXX The vap is being stopped, do no allow any other
1898 			 * state changes until this is completed.
1899 			 */
1900 			return -1;
1901 		} else if (vap->iv_state != vap->iv_nstate) {
1902 #if 0
1903 			/* Warn if the previous state hasn't completed. */
1904 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1905 			    "%s: pending %s -> %s transition lost\n", __func__,
1906 			    ieee80211_state_name[vap->iv_state],
1907 			    ieee80211_state_name[vap->iv_nstate]);
1908 #else
1909 			/* XXX temporarily enable to identify issues */
1910 			if_printf(vap->iv_ifp,
1911 			    "%s: pending %s -> %s transition lost\n",
1912 			    __func__, ieee80211_state_name[vap->iv_state],
1913 			    ieee80211_state_name[vap->iv_nstate]);
1914 #endif
1915 		}
1916 	}
1917 
1918 	nrunning = nscanning = 0;
1919 	/* XXX can track this state instead of calculating */
1920 	TAILQ_FOREACH(vp, &ic->ic_vaps, iv_next) {
1921 		if (vp != vap) {
1922 			if (vp->iv_state >= IEEE80211_S_RUN)
1923 				nrunning++;
1924 			/* XXX doesn't handle bg scan */
1925 			/* NB: CAC+AUTH+ASSOC treated like SCAN */
1926 			else if (vp->iv_state > IEEE80211_S_INIT)
1927 				nscanning++;
1928 		}
1929 	}
1930 	ostate = vap->iv_state;
1931 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1932 	    "%s: %s -> %s (nrunning %d nscanning %d)\n", __func__,
1933 	    ieee80211_state_name[ostate], ieee80211_state_name[nstate],
1934 	    nrunning, nscanning);
1935 	switch (nstate) {
1936 	case IEEE80211_S_SCAN:
1937 		if (ostate == IEEE80211_S_INIT) {
1938 			/*
1939 			 * INIT -> SCAN happens on initial bringup.
1940 			 */
1941 			KASSERT(!(nscanning && nrunning),
1942 			    ("%d scanning and %d running", nscanning, nrunning));
1943 			if (nscanning) {
1944 				/*
1945 				 * Someone is scanning, defer our state
1946 				 * change until the work has completed.
1947 				 */
1948 				IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1949 				    "%s: defer %s -> %s\n",
1950 				    __func__, ieee80211_state_name[ostate],
1951 				    ieee80211_state_name[nstate]);
1952 				vap->iv_flags_ext |= IEEE80211_FEXT_SCANWAIT;
1953 				return 0;
1954 			}
1955 			if (nrunning) {
1956 				/*
1957 				 * Someone is operating; just join the channel
1958 				 * they have chosen.
1959 				 */
1960 				/* XXX kill arg? */
1961 				/* XXX check each opmode, adhoc? */
1962 				if (vap->iv_opmode == IEEE80211_M_STA)
1963 					nstate = IEEE80211_S_SCAN;
1964 				else
1965 					nstate = IEEE80211_S_RUN;
1966 #ifdef IEEE80211_DEBUG
1967 				if (nstate != IEEE80211_S_SCAN) {
1968 					IEEE80211_DPRINTF(vap,
1969 					    IEEE80211_MSG_STATE,
1970 					    "%s: override, now %s -> %s\n",
1971 					    __func__,
1972 					    ieee80211_state_name[ostate],
1973 					    ieee80211_state_name[nstate]);
1974 				}
1975 #endif
1976 			}
1977 		}
1978 		break;
1979 	case IEEE80211_S_RUN:
1980 		if (vap->iv_opmode == IEEE80211_M_WDS &&
1981 		    (vap->iv_flags_ext & IEEE80211_FEXT_WDSLEGACY) &&
1982 		    nscanning) {
1983 			/*
1984 			 * Legacy WDS with someone else scanning; don't
1985 			 * go online until that completes as we should
1986 			 * follow the other vap to the channel they choose.
1987 			 */
1988 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1989 			     "%s: defer %s -> %s (legacy WDS)\n", __func__,
1990 			     ieee80211_state_name[ostate],
1991 			     ieee80211_state_name[nstate]);
1992 			vap->iv_flags_ext |= IEEE80211_FEXT_SCANWAIT;
1993 			return 0;
1994 		}
1995 		if (vap->iv_opmode == IEEE80211_M_HOSTAP &&
1996 		    IEEE80211_IS_CHAN_DFS(ic->ic_bsschan) &&
1997 		    (vap->iv_flags_ext & IEEE80211_FEXT_DFS) &&
1998 		    !IEEE80211_IS_CHAN_CACDONE(ic->ic_bsschan)) {
1999 			/*
2000 			 * This is a DFS channel, transition to CAC state
2001 			 * instead of RUN.  This allows us to initiate
2002 			 * Channel Availability Check (CAC) as specified
2003 			 * by 11h/DFS.
2004 			 */
2005 			nstate = IEEE80211_S_CAC;
2006 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
2007 			     "%s: override %s -> %s (DFS)\n", __func__,
2008 			     ieee80211_state_name[ostate],
2009 			     ieee80211_state_name[nstate]);
2010 		}
2011 		break;
2012 	case IEEE80211_S_INIT:
2013 		/* cancel any scan in progress */
2014 		ieee80211_cancel_scan(vap);
2015 		if (ostate == IEEE80211_S_INIT ) {
2016 			/* XXX don't believe this */
2017 			/* INIT -> INIT. nothing to do */
2018 			vap->iv_flags_ext &= ~IEEE80211_FEXT_SCANWAIT;
2019 		}
2020 		/* fall thru... */
2021 	default:
2022 		break;
2023 	}
2024 	/* defer the state change to a thread */
2025 	vap->iv_nstate = nstate;
2026 	vap->iv_nstate_arg = arg;
2027 	vap->iv_flags_ext |= IEEE80211_FEXT_STATEWAIT;
2028 	ieee80211_runtask(ic, &vap->iv_nstate_task);
2029 	return EINPROGRESS;
2030 }
2031 
2032 int
2033 ieee80211_new_state(struct ieee80211vap *vap,
2034 	enum ieee80211_state nstate, int arg)
2035 {
2036 	struct ieee80211com *ic = vap->iv_ic;
2037 	int rc;
2038 
2039 	IEEE80211_LOCK(ic);
2040 	rc = ieee80211_new_state_locked(vap, nstate, arg);
2041 	IEEE80211_UNLOCK(ic);
2042 	return rc;
2043 }
2044