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