xref: /freebsd/sys/net80211/ieee80211_proto.c (revision f5f47d5068fb97df18eb114a66ae8ef51a0b3c8c)
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_media.h>
46 #include <net/ethernet.h>		/* XXX for ether_sprintf */
47 
48 #include <net80211/ieee80211_var.h>
49 #include <net80211/ieee80211_adhoc.h>
50 #include <net80211/ieee80211_sta.h>
51 #include <net80211/ieee80211_hostap.h>
52 #include <net80211/ieee80211_wds.h>
53 #ifdef IEEE80211_SUPPORT_MESH
54 #include <net80211/ieee80211_mesh.h>
55 #endif
56 #include <net80211/ieee80211_monitor.h>
57 #include <net80211/ieee80211_input.h>
58 
59 /* XXX tunables */
60 #define	AGGRESSIVE_MODE_SWITCH_HYSTERESIS	3	/* pkts / 100ms */
61 #define	HIGH_PRI_SWITCH_THRESH			10	/* pkts / 100ms */
62 
63 const char *ieee80211_mgt_subtype_name[] = {
64 	"assoc_req",	"assoc_resp",	"reassoc_req",	"reassoc_resp",
65 	"probe_req",	"probe_resp",	"reserved#6",	"reserved#7",
66 	"beacon",	"atim",		"disassoc",	"auth",
67 	"deauth",	"action",	"action_noack",	"reserved#15"
68 };
69 const char *ieee80211_ctl_subtype_name[] = {
70 	"reserved#0",	"reserved#1",	"reserved#2",	"reserved#3",
71 	"reserved#3",	"reserved#5",	"reserved#6",	"reserved#7",
72 	"reserved#8",	"reserved#9",	"ps_poll",	"rts",
73 	"cts",		"ack",		"cf_end",	"cf_end_ack"
74 };
75 const char *ieee80211_opmode_name[IEEE80211_OPMODE_MAX] = {
76 	"IBSS",		/* IEEE80211_M_IBSS */
77 	"STA",		/* IEEE80211_M_STA */
78 	"WDS",		/* IEEE80211_M_WDS */
79 	"AHDEMO",	/* IEEE80211_M_AHDEMO */
80 	"HOSTAP",	/* IEEE80211_M_HOSTAP */
81 	"MONITOR",	/* IEEE80211_M_MONITOR */
82 	"MBSS"		/* IEEE80211_M_MBSS */
83 };
84 const char *ieee80211_state_name[IEEE80211_S_MAX] = {
85 	"INIT",		/* IEEE80211_S_INIT */
86 	"SCAN",		/* IEEE80211_S_SCAN */
87 	"AUTH",		/* IEEE80211_S_AUTH */
88 	"ASSOC",	/* IEEE80211_S_ASSOC */
89 	"CAC",		/* IEEE80211_S_CAC */
90 	"RUN",		/* IEEE80211_S_RUN */
91 	"CSA",		/* IEEE80211_S_CSA */
92 	"SLEEP",	/* IEEE80211_S_SLEEP */
93 };
94 const char *ieee80211_wme_acnames[] = {
95 	"WME_AC_BE",
96 	"WME_AC_BK",
97 	"WME_AC_VI",
98 	"WME_AC_VO",
99 	"WME_UPSD",
100 };
101 
102 static void beacon_miss(void *, int);
103 static void beacon_swmiss(void *, int);
104 static void parent_updown(void *, int);
105 static void update_mcast(void *, int);
106 static void update_promisc(void *, int);
107 static void update_channel(void *, int);
108 static void update_chw(void *, int);
109 static void ieee80211_newstate_cb(void *, int);
110 static int ieee80211_new_state_locked(struct ieee80211vap *,
111 	enum ieee80211_state, 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 	struct ifnet *ifp = ni->ni_ic->ic_ifp;
118 
119 	if_printf(ifp, "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 	struct ifnet *ifp = ic->ic_ifp;
128 
129 	/* override the 802.3 setting */
130 	ifp->if_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(ifp->if_hdrlen) > max_linkhdr) {
136 		/* XXX sanity check... */
137 		max_linkhdr = ALIGN(ifp->if_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, ifp);
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 
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_ifp->if_hdrlen;
194 
195 	vap->iv_rtsthreshold = IEEE80211_RTS_DEFAULT;
196 	vap->iv_fragthreshold = IEEE80211_FRAG_DEFAULT;
197 	vap->iv_bmiss_max = IEEE80211_BMISS_MAX;
198 	callout_init_mtx(&vap->iv_swbmiss, IEEE80211_LOCK_OBJ(ic), 0);
199 	callout_init(&vap->iv_mgtsend, CALLOUT_MPSAFE);
200 	TASK_INIT(&vap->iv_nstate_task, 0, ieee80211_newstate_cb, vap);
201 	TASK_INIT(&vap->iv_swbmiss_task, 0, beacon_swmiss, vap);
202 	/*
203 	 * Install default tx rate handling: no fixed rate, lowest
204 	 * supported rate for mgmt and multicast frames.  Default
205 	 * max retry count.  These settings can be changed by the
206 	 * driver and/or user applications.
207 	 */
208 	for (i = IEEE80211_MODE_11A; i < IEEE80211_MODE_MAX; i++) {
209 		const struct ieee80211_rateset *rs = &ic->ic_sup_rates[i];
210 
211 		vap->iv_txparms[i].ucastrate = IEEE80211_FIXED_RATE_NONE;
212 
213 		/*
214 		 * Setting the management rate to MCS 0 assumes that the
215 		 * BSS Basic rate set is empty and the BSS Basic MCS set
216 		 * is not.
217 		 *
218 		 * Since we're not checking this, default to the lowest
219 		 * defined rate for this mode.
220 		 *
221 		 * At least one 11n AP (DLINK DIR-825) is reported to drop
222 		 * some MCS management traffic (eg BA response frames.)
223 		 *
224 		 * See also: 9.6.0 of the 802.11n-2009 specification.
225 		 */
226 #ifdef	NOTYET
227 		if (i == IEEE80211_MODE_11NA || i == IEEE80211_MODE_11NG) {
228 			vap->iv_txparms[i].mgmtrate = 0 | IEEE80211_RATE_MCS;
229 			vap->iv_txparms[i].mcastrate = 0 | IEEE80211_RATE_MCS;
230 		} else {
231 			vap->iv_txparms[i].mgmtrate =
232 			    rs->rs_rates[0] & IEEE80211_RATE_VAL;
233 			vap->iv_txparms[i].mcastrate =
234 			    rs->rs_rates[0] & IEEE80211_RATE_VAL;
235 		}
236 #endif
237 		vap->iv_txparms[i].mgmtrate = rs->rs_rates[0] & IEEE80211_RATE_VAL;
238 		vap->iv_txparms[i].mcastrate = rs->rs_rates[0] & IEEE80211_RATE_VAL;
239 		vap->iv_txparms[i].maxretry = IEEE80211_TXMAX_DEFAULT;
240 	}
241 	vap->iv_roaming = IEEE80211_ROAMING_AUTO;
242 
243 	vap->iv_update_beacon = null_update_beacon;
244 	vap->iv_deliver_data = ieee80211_deliver_data;
245 
246 	/* attach support for operating mode */
247 	ic->ic_vattach[vap->iv_opmode](vap);
248 }
249 
250 void
251 ieee80211_proto_vdetach(struct ieee80211vap *vap)
252 {
253 #define	FREEAPPIE(ie) do { \
254 	if (ie != NULL) \
255 		free(ie, M_80211_NODE_IE); \
256 } while (0)
257 	/*
258 	 * Detach operating mode module.
259 	 */
260 	if (vap->iv_opdetach != NULL)
261 		vap->iv_opdetach(vap);
262 	/*
263 	 * This should not be needed as we detach when reseting
264 	 * the state but be conservative here since the
265 	 * authenticator may do things like spawn kernel threads.
266 	 */
267 	if (vap->iv_auth->ia_detach != NULL)
268 		vap->iv_auth->ia_detach(vap);
269 	/*
270 	 * Detach any ACL'ator.
271 	 */
272 	if (vap->iv_acl != NULL)
273 		vap->iv_acl->iac_detach(vap);
274 
275 	FREEAPPIE(vap->iv_appie_beacon);
276 	FREEAPPIE(vap->iv_appie_probereq);
277 	FREEAPPIE(vap->iv_appie_proberesp);
278 	FREEAPPIE(vap->iv_appie_assocreq);
279 	FREEAPPIE(vap->iv_appie_assocresp);
280 	FREEAPPIE(vap->iv_appie_wpa);
281 #undef FREEAPPIE
282 }
283 
284 /*
285  * Simple-minded authenticator module support.
286  */
287 
288 #define	IEEE80211_AUTH_MAX	(IEEE80211_AUTH_WPA+1)
289 /* XXX well-known names */
290 static const char *auth_modnames[IEEE80211_AUTH_MAX] = {
291 	"wlan_internal",	/* IEEE80211_AUTH_NONE */
292 	"wlan_internal",	/* IEEE80211_AUTH_OPEN */
293 	"wlan_internal",	/* IEEE80211_AUTH_SHARED */
294 	"wlan_xauth",		/* IEEE80211_AUTH_8021X	 */
295 	"wlan_internal",	/* IEEE80211_AUTH_AUTO */
296 	"wlan_xauth",		/* IEEE80211_AUTH_WPA */
297 };
298 static const struct ieee80211_authenticator *authenticators[IEEE80211_AUTH_MAX];
299 
300 static const struct ieee80211_authenticator auth_internal = {
301 	.ia_name		= "wlan_internal",
302 	.ia_attach		= NULL,
303 	.ia_detach		= NULL,
304 	.ia_node_join		= NULL,
305 	.ia_node_leave		= NULL,
306 };
307 
308 /*
309  * Setup internal authenticators once; they are never unregistered.
310  */
311 static void
312 ieee80211_auth_setup(void)
313 {
314 	ieee80211_authenticator_register(IEEE80211_AUTH_OPEN, &auth_internal);
315 	ieee80211_authenticator_register(IEEE80211_AUTH_SHARED, &auth_internal);
316 	ieee80211_authenticator_register(IEEE80211_AUTH_AUTO, &auth_internal);
317 }
318 SYSINIT(wlan_auth, SI_SUB_DRIVERS, SI_ORDER_FIRST, ieee80211_auth_setup, NULL);
319 
320 const struct ieee80211_authenticator *
321 ieee80211_authenticator_get(int auth)
322 {
323 	if (auth >= IEEE80211_AUTH_MAX)
324 		return NULL;
325 	if (authenticators[auth] == NULL)
326 		ieee80211_load_module(auth_modnames[auth]);
327 	return authenticators[auth];
328 }
329 
330 void
331 ieee80211_authenticator_register(int type,
332 	const struct ieee80211_authenticator *auth)
333 {
334 	if (type >= IEEE80211_AUTH_MAX)
335 		return;
336 	authenticators[type] = auth;
337 }
338 
339 void
340 ieee80211_authenticator_unregister(int type)
341 {
342 
343 	if (type >= IEEE80211_AUTH_MAX)
344 		return;
345 	authenticators[type] = NULL;
346 }
347 
348 /*
349  * Very simple-minded ACL module support.
350  */
351 /* XXX just one for now */
352 static	const struct ieee80211_aclator *acl = NULL;
353 
354 void
355 ieee80211_aclator_register(const struct ieee80211_aclator *iac)
356 {
357 	printf("wlan: %s acl policy registered\n", iac->iac_name);
358 	acl = iac;
359 }
360 
361 void
362 ieee80211_aclator_unregister(const struct ieee80211_aclator *iac)
363 {
364 	if (acl == iac)
365 		acl = NULL;
366 	printf("wlan: %s acl policy unregistered\n", iac->iac_name);
367 }
368 
369 const struct ieee80211_aclator *
370 ieee80211_aclator_get(const char *name)
371 {
372 	if (acl == NULL)
373 		ieee80211_load_module("wlan_acl");
374 	return acl != NULL && strcmp(acl->iac_name, name) == 0 ? acl : NULL;
375 }
376 
377 void
378 ieee80211_print_essid(const uint8_t *essid, int len)
379 {
380 	const uint8_t *p;
381 	int i;
382 
383 	if (len > IEEE80211_NWID_LEN)
384 		len = IEEE80211_NWID_LEN;
385 	/* determine printable or not */
386 	for (i = 0, p = essid; i < len; i++, p++) {
387 		if (*p < ' ' || *p > 0x7e)
388 			break;
389 	}
390 	if (i == len) {
391 		printf("\"");
392 		for (i = 0, p = essid; i < len; i++, p++)
393 			printf("%c", *p);
394 		printf("\"");
395 	} else {
396 		printf("0x");
397 		for (i = 0, p = essid; i < len; i++, p++)
398 			printf("%02x", *p);
399 	}
400 }
401 
402 void
403 ieee80211_dump_pkt(struct ieee80211com *ic,
404 	const uint8_t *buf, int len, int rate, int rssi)
405 {
406 	const struct ieee80211_frame *wh;
407 	int i;
408 
409 	wh = (const struct ieee80211_frame *)buf;
410 	switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
411 	case IEEE80211_FC1_DIR_NODS:
412 		printf("NODS %s", ether_sprintf(wh->i_addr2));
413 		printf("->%s", ether_sprintf(wh->i_addr1));
414 		printf("(%s)", ether_sprintf(wh->i_addr3));
415 		break;
416 	case IEEE80211_FC1_DIR_TODS:
417 		printf("TODS %s", ether_sprintf(wh->i_addr2));
418 		printf("->%s", ether_sprintf(wh->i_addr3));
419 		printf("(%s)", ether_sprintf(wh->i_addr1));
420 		break;
421 	case IEEE80211_FC1_DIR_FROMDS:
422 		printf("FRDS %s", ether_sprintf(wh->i_addr3));
423 		printf("->%s", ether_sprintf(wh->i_addr1));
424 		printf("(%s)", ether_sprintf(wh->i_addr2));
425 		break;
426 	case IEEE80211_FC1_DIR_DSTODS:
427 		printf("DSDS %s", ether_sprintf((const uint8_t *)&wh[1]));
428 		printf("->%s", ether_sprintf(wh->i_addr3));
429 		printf("(%s", ether_sprintf(wh->i_addr2));
430 		printf("->%s)", ether_sprintf(wh->i_addr1));
431 		break;
432 	}
433 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
434 	case IEEE80211_FC0_TYPE_DATA:
435 		printf(" data");
436 		break;
437 	case IEEE80211_FC0_TYPE_MGT:
438 		printf(" %s", ieee80211_mgt_subtype_name[
439 		    (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK)
440 		    >> IEEE80211_FC0_SUBTYPE_SHIFT]);
441 		break;
442 	default:
443 		printf(" type#%d", wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK);
444 		break;
445 	}
446 	if (IEEE80211_QOS_HAS_SEQ(wh)) {
447 		const struct ieee80211_qosframe *qwh =
448 			(const struct ieee80211_qosframe *)buf;
449 		printf(" QoS [TID %u%s]", qwh->i_qos[0] & IEEE80211_QOS_TID,
450 			qwh->i_qos[0] & IEEE80211_QOS_ACKPOLICY ? " ACM" : "");
451 	}
452 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
453 		int off;
454 
455 		off = ieee80211_anyhdrspace(ic, wh);
456 		printf(" WEP [IV %.02x %.02x %.02x",
457 			buf[off+0], buf[off+1], buf[off+2]);
458 		if (buf[off+IEEE80211_WEP_IVLEN] & IEEE80211_WEP_EXTIV)
459 			printf(" %.02x %.02x %.02x",
460 				buf[off+4], buf[off+5], buf[off+6]);
461 		printf(" KID %u]", buf[off+IEEE80211_WEP_IVLEN] >> 6);
462 	}
463 	if (rate >= 0)
464 		printf(" %dM", rate / 2);
465 	if (rssi >= 0)
466 		printf(" +%d", rssi);
467 	printf("\n");
468 	if (len > 0) {
469 		for (i = 0; i < len; i++) {
470 			if ((i & 1) == 0)
471 				printf(" ");
472 			printf("%02x", buf[i]);
473 		}
474 		printf("\n");
475 	}
476 }
477 
478 static __inline int
479 findrix(const struct ieee80211_rateset *rs, int r)
480 {
481 	int i;
482 
483 	for (i = 0; i < rs->rs_nrates; i++)
484 		if ((rs->rs_rates[i] & IEEE80211_RATE_VAL) == r)
485 			return i;
486 	return -1;
487 }
488 
489 int
490 ieee80211_fix_rate(struct ieee80211_node *ni,
491 	struct ieee80211_rateset *nrs, int flags)
492 {
493 #define	RV(v)	((v) & IEEE80211_RATE_VAL)
494 	struct ieee80211vap *vap = ni->ni_vap;
495 	struct ieee80211com *ic = ni->ni_ic;
496 	int i, j, rix, error;
497 	int okrate, badrate, fixedrate, ucastrate;
498 	const struct ieee80211_rateset *srs;
499 	uint8_t r;
500 
501 	error = 0;
502 	okrate = badrate = 0;
503 	ucastrate = vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)].ucastrate;
504 	if (ucastrate != IEEE80211_FIXED_RATE_NONE) {
505 		/*
506 		 * Workaround awkwardness with fixed rate.  We are called
507 		 * to check both the legacy rate set and the HT rate set
508 		 * but we must apply any legacy fixed rate check only to the
509 		 * legacy rate set and vice versa.  We cannot tell what type
510 		 * of rate set we've been given (legacy or HT) but we can
511 		 * distinguish the fixed rate type (MCS have 0x80 set).
512 		 * So to deal with this the caller communicates whether to
513 		 * check MCS or legacy rate using the flags and we use the
514 		 * type of any fixed rate to avoid applying an MCS to a
515 		 * legacy rate and vice versa.
516 		 */
517 		if (ucastrate & 0x80) {
518 			if (flags & IEEE80211_F_DOFRATE)
519 				flags &= ~IEEE80211_F_DOFRATE;
520 		} else if ((ucastrate & 0x80) == 0) {
521 			if (flags & IEEE80211_F_DOFMCS)
522 				flags &= ~IEEE80211_F_DOFMCS;
523 		}
524 		/* NB: required to make MCS match below work */
525 		ucastrate &= IEEE80211_RATE_VAL;
526 	}
527 	fixedrate = IEEE80211_FIXED_RATE_NONE;
528 	/*
529 	 * XXX we are called to process both MCS and legacy rates;
530 	 * we must use the appropriate basic rate set or chaos will
531 	 * ensue; for now callers that want MCS must supply
532 	 * IEEE80211_F_DOBRS; at some point we'll need to split this
533 	 * function so there are two variants, one for MCS and one
534 	 * for legacy rates.
535 	 */
536 	if (flags & IEEE80211_F_DOBRS)
537 		srs = (const struct ieee80211_rateset *)
538 		    ieee80211_get_suphtrates(ic, ni->ni_chan);
539 	else
540 		srs = ieee80211_get_suprates(ic, ni->ni_chan);
541 	for (i = 0; i < nrs->rs_nrates; ) {
542 		if (flags & IEEE80211_F_DOSORT) {
543 			/*
544 			 * Sort rates.
545 			 */
546 			for (j = i + 1; j < nrs->rs_nrates; j++) {
547 				if (RV(nrs->rs_rates[i]) > RV(nrs->rs_rates[j])) {
548 					r = nrs->rs_rates[i];
549 					nrs->rs_rates[i] = nrs->rs_rates[j];
550 					nrs->rs_rates[j] = r;
551 				}
552 			}
553 		}
554 		r = nrs->rs_rates[i] & IEEE80211_RATE_VAL;
555 		badrate = r;
556 		/*
557 		 * Check for fixed rate.
558 		 */
559 		if (r == ucastrate)
560 			fixedrate = r;
561 		/*
562 		 * Check against supported rates.
563 		 */
564 		rix = findrix(srs, r);
565 		if (flags & IEEE80211_F_DONEGO) {
566 			if (rix < 0) {
567 				/*
568 				 * A rate in the node's rate set is not
569 				 * supported.  If this is a basic rate and we
570 				 * are operating as a STA then this is an error.
571 				 * Otherwise we just discard/ignore the rate.
572 				 */
573 				if ((flags & IEEE80211_F_JOIN) &&
574 				    (nrs->rs_rates[i] & IEEE80211_RATE_BASIC))
575 					error++;
576 			} else if ((flags & IEEE80211_F_JOIN) == 0) {
577 				/*
578 				 * Overwrite with the supported rate
579 				 * value so any basic rate bit is set.
580 				 */
581 				nrs->rs_rates[i] = srs->rs_rates[rix];
582 			}
583 		}
584 		if ((flags & IEEE80211_F_DODEL) && rix < 0) {
585 			/*
586 			 * Delete unacceptable rates.
587 			 */
588 			nrs->rs_nrates--;
589 			for (j = i; j < nrs->rs_nrates; j++)
590 				nrs->rs_rates[j] = nrs->rs_rates[j + 1];
591 			nrs->rs_rates[j] = 0;
592 			continue;
593 		}
594 		if (rix >= 0)
595 			okrate = nrs->rs_rates[i];
596 		i++;
597 	}
598 	if (okrate == 0 || error != 0 ||
599 	    ((flags & (IEEE80211_F_DOFRATE|IEEE80211_F_DOFMCS)) &&
600 	     fixedrate != ucastrate)) {
601 		IEEE80211_NOTE(vap, IEEE80211_MSG_XRATE | IEEE80211_MSG_11N, ni,
602 		    "%s: flags 0x%x okrate %d error %d fixedrate 0x%x "
603 		    "ucastrate %x\n", __func__, fixedrate, ucastrate, flags);
604 		return badrate | IEEE80211_RATE_BASIC;
605 	} else
606 		return RV(okrate);
607 #undef RV
608 }
609 
610 /*
611  * Reset 11g-related state.
612  */
613 void
614 ieee80211_reset_erp(struct ieee80211com *ic)
615 {
616 	ic->ic_flags &= ~IEEE80211_F_USEPROT;
617 	ic->ic_nonerpsta = 0;
618 	ic->ic_longslotsta = 0;
619 	/*
620 	 * Short slot time is enabled only when operating in 11g
621 	 * and not in an IBSS.  We must also honor whether or not
622 	 * the driver is capable of doing it.
623 	 */
624 	ieee80211_set_shortslottime(ic,
625 		IEEE80211_IS_CHAN_A(ic->ic_curchan) ||
626 		IEEE80211_IS_CHAN_HT(ic->ic_curchan) ||
627 		(IEEE80211_IS_CHAN_ANYG(ic->ic_curchan) &&
628 		ic->ic_opmode == IEEE80211_M_HOSTAP &&
629 		(ic->ic_caps & IEEE80211_C_SHSLOT)));
630 	/*
631 	 * Set short preamble and ERP barker-preamble flags.
632 	 */
633 	if (IEEE80211_IS_CHAN_A(ic->ic_curchan) ||
634 	    (ic->ic_caps & IEEE80211_C_SHPREAMBLE)) {
635 		ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
636 		ic->ic_flags &= ~IEEE80211_F_USEBARKER;
637 	} else {
638 		ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
639 		ic->ic_flags |= IEEE80211_F_USEBARKER;
640 	}
641 }
642 
643 /*
644  * Set the short slot time state and notify the driver.
645  */
646 void
647 ieee80211_set_shortslottime(struct ieee80211com *ic, int onoff)
648 {
649 	if (onoff)
650 		ic->ic_flags |= IEEE80211_F_SHSLOT;
651 	else
652 		ic->ic_flags &= ~IEEE80211_F_SHSLOT;
653 	/* notify driver */
654 	if (ic->ic_updateslot != NULL)
655 		ic->ic_updateslot(ic->ic_ifp);
656 }
657 
658 /*
659  * Check if the specified rate set supports ERP.
660  * NB: the rate set is assumed to be sorted.
661  */
662 int
663 ieee80211_iserp_rateset(const struct ieee80211_rateset *rs)
664 {
665 #define N(a)	(sizeof(a) / sizeof(a[0]))
666 	static const int rates[] = { 2, 4, 11, 22, 12, 24, 48 };
667 	int i, j;
668 
669 	if (rs->rs_nrates < N(rates))
670 		return 0;
671 	for (i = 0; i < N(rates); i++) {
672 		for (j = 0; j < rs->rs_nrates; j++) {
673 			int r = rs->rs_rates[j] & IEEE80211_RATE_VAL;
674 			if (rates[i] == r)
675 				goto next;
676 			if (r > rates[i])
677 				return 0;
678 		}
679 		return 0;
680 	next:
681 		;
682 	}
683 	return 1;
684 #undef N
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 
1000        	/*
1001 	 * Set up the channel access parameters for the physical
1002 	 * device.  First populate the configured settings.
1003 	 */
1004 	for (i = 0; i < WME_NUM_AC; i++) {
1005 		chanp = &wme->wme_chanParams.cap_wmeParams[i];
1006 		wmep = &wme->wme_wmeChanParams.cap_wmeParams[i];
1007 		chanp->wmep_aifsn = wmep->wmep_aifsn;
1008 		chanp->wmep_logcwmin = wmep->wmep_logcwmin;
1009 		chanp->wmep_logcwmax = wmep->wmep_logcwmax;
1010 		chanp->wmep_txopLimit = wmep->wmep_txopLimit;
1011 
1012 		chanp = &wme->wme_bssChanParams.cap_wmeParams[i];
1013 		wmep = &wme->wme_wmeBssChanParams.cap_wmeParams[i];
1014 		chanp->wmep_aifsn = wmep->wmep_aifsn;
1015 		chanp->wmep_logcwmin = wmep->wmep_logcwmin;
1016 		chanp->wmep_logcwmax = wmep->wmep_logcwmax;
1017 		chanp->wmep_txopLimit = wmep->wmep_txopLimit;
1018 	}
1019 
1020 	/*
1021 	 * Select mode; we can be called early in which case we
1022 	 * always use auto mode.  We know we'll be called when
1023 	 * entering the RUN state with bsschan setup properly
1024 	 * so state will eventually get set correctly
1025 	 */
1026 	if (ic->ic_bsschan != IEEE80211_CHAN_ANYC)
1027 		mode = ieee80211_chan2mode(ic->ic_bsschan);
1028 	else
1029 		mode = IEEE80211_MODE_AUTO;
1030 
1031 	/*
1032 	 * This implements agressive mode as found in certain
1033 	 * vendors' AP's.  When there is significant high
1034 	 * priority (VI/VO) traffic in the BSS throttle back BE
1035 	 * traffic by using conservative parameters.  Otherwise
1036 	 * BE uses agressive params to optimize performance of
1037 	 * legacy/non-QoS traffic.
1038 	 */
1039         if ((vap->iv_opmode == IEEE80211_M_HOSTAP &&
1040 	     (wme->wme_flags & WME_F_AGGRMODE) != 0) ||
1041 	    (vap->iv_opmode == IEEE80211_M_STA &&
1042 	     (vap->iv_bss->ni_flags & IEEE80211_NODE_QOS) == 0) ||
1043 	    (vap->iv_flags & IEEE80211_F_WME) == 0) {
1044 		chanp = &wme->wme_chanParams.cap_wmeParams[WME_AC_BE];
1045 		bssp = &wme->wme_bssChanParams.cap_wmeParams[WME_AC_BE];
1046 
1047 		chanp->wmep_aifsn = bssp->wmep_aifsn = aggrParam[mode].aifsn;
1048 		chanp->wmep_logcwmin = bssp->wmep_logcwmin =
1049 		    aggrParam[mode].logcwmin;
1050 		chanp->wmep_logcwmax = bssp->wmep_logcwmax =
1051 		    aggrParam[mode].logcwmax;
1052 		chanp->wmep_txopLimit = bssp->wmep_txopLimit =
1053 		    (vap->iv_flags & IEEE80211_F_BURST) ?
1054 			aggrParam[mode].txopLimit : 0;
1055 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
1056 		    "update %s (chan+bss) [acm %u aifsn %u logcwmin %u "
1057 		    "logcwmax %u txop %u]\n", ieee80211_wme_acnames[WME_AC_BE],
1058 		    chanp->wmep_acm, chanp->wmep_aifsn, chanp->wmep_logcwmin,
1059 		    chanp->wmep_logcwmax, chanp->wmep_txopLimit);
1060 	}
1061 
1062 	if (vap->iv_opmode == IEEE80211_M_HOSTAP &&
1063 	    ic->ic_sta_assoc < 2 && (wme->wme_flags & WME_F_AGGRMODE) != 0) {
1064 		static const uint8_t logCwMin[IEEE80211_MODE_MAX] = {
1065 		    [IEEE80211_MODE_AUTO]	= 3,
1066 		    [IEEE80211_MODE_11A]	= 3,
1067 		    [IEEE80211_MODE_11B]	= 4,
1068 		    [IEEE80211_MODE_11G]	= 3,
1069 		    [IEEE80211_MODE_FH]		= 4,
1070 		    [IEEE80211_MODE_TURBO_A]	= 3,
1071 		    [IEEE80211_MODE_TURBO_G]	= 3,
1072 		    [IEEE80211_MODE_STURBO_A]	= 3,
1073 		    [IEEE80211_MODE_HALF]	= 3,
1074 		    [IEEE80211_MODE_QUARTER]	= 3,
1075 		    [IEEE80211_MODE_11NA]	= 3,
1076 		    [IEEE80211_MODE_11NG]	= 3,
1077 		};
1078 		chanp = &wme->wme_chanParams.cap_wmeParams[WME_AC_BE];
1079 		bssp = &wme->wme_bssChanParams.cap_wmeParams[WME_AC_BE];
1080 
1081 		chanp->wmep_logcwmin = bssp->wmep_logcwmin = logCwMin[mode];
1082 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
1083 		    "update %s (chan+bss) logcwmin %u\n",
1084 		    ieee80211_wme_acnames[WME_AC_BE], chanp->wmep_logcwmin);
1085     	}
1086 	if (vap->iv_opmode == IEEE80211_M_HOSTAP) {	/* XXX ibss? */
1087 		/*
1088 		 * Arrange for a beacon update and bump the parameter
1089 		 * set number so associated stations load the new values.
1090 		 */
1091 		wme->wme_bssChanParams.cap_info =
1092 			(wme->wme_bssChanParams.cap_info+1) & WME_QOSINFO_COUNT;
1093 		ieee80211_beacon_notify(vap, IEEE80211_BEACON_WME);
1094 	}
1095 
1096 	wme->wme_update(ic);
1097 
1098 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
1099 	    "%s: WME params updated, cap_info 0x%x\n", __func__,
1100 	    vap->iv_opmode == IEEE80211_M_STA ?
1101 		wme->wme_wmeChanParams.cap_info :
1102 		wme->wme_bssChanParams.cap_info);
1103 }
1104 
1105 void
1106 ieee80211_wme_updateparams(struct ieee80211vap *vap)
1107 {
1108 	struct ieee80211com *ic = vap->iv_ic;
1109 
1110 	if (ic->ic_caps & IEEE80211_C_WME) {
1111 		IEEE80211_LOCK(ic);
1112 		ieee80211_wme_updateparams_locked(vap);
1113 		IEEE80211_UNLOCK(ic);
1114 	}
1115 }
1116 
1117 static void
1118 parent_updown(void *arg, int npending)
1119 {
1120 	struct ifnet *parent = arg;
1121 
1122 	parent->if_ioctl(parent, SIOCSIFFLAGS, NULL);
1123 }
1124 
1125 static void
1126 update_mcast(void *arg, int npending)
1127 {
1128 	struct ieee80211com *ic = arg;
1129 	struct ifnet *parent = ic->ic_ifp;
1130 
1131 	ic->ic_update_mcast(parent);
1132 }
1133 
1134 static void
1135 update_promisc(void *arg, int npending)
1136 {
1137 	struct ieee80211com *ic = arg;
1138 	struct ifnet *parent = ic->ic_ifp;
1139 
1140 	ic->ic_update_promisc(parent);
1141 }
1142 
1143 static void
1144 update_channel(void *arg, int npending)
1145 {
1146 	struct ieee80211com *ic = arg;
1147 
1148 	ic->ic_set_channel(ic);
1149 	ieee80211_radiotap_chan_change(ic);
1150 }
1151 
1152 static void
1153 update_chw(void *arg, int npending)
1154 {
1155 	struct ieee80211com *ic = arg;
1156 
1157 	/*
1158 	 * XXX should we defer the channel width _config_ update until now?
1159 	 */
1160 	ic->ic_update_chw(ic);
1161 }
1162 
1163 /*
1164  * Block until the parent is in a known state.  This is
1165  * used after any operations that dispatch a task (e.g.
1166  * to auto-configure the parent device up/down).
1167  */
1168 void
1169 ieee80211_waitfor_parent(struct ieee80211com *ic)
1170 {
1171 	taskqueue_block(ic->ic_tq);
1172 	ieee80211_draintask(ic, &ic->ic_parent_task);
1173 	ieee80211_draintask(ic, &ic->ic_mcast_task);
1174 	ieee80211_draintask(ic, &ic->ic_promisc_task);
1175 	ieee80211_draintask(ic, &ic->ic_chan_task);
1176 	ieee80211_draintask(ic, &ic->ic_bmiss_task);
1177 	ieee80211_draintask(ic, &ic->ic_chw_task);
1178 	taskqueue_unblock(ic->ic_tq);
1179 }
1180 
1181 /*
1182  * Start a vap running.  If this is the first vap to be
1183  * set running on the underlying device then we
1184  * automatically bring the device up.
1185  */
1186 void
1187 ieee80211_start_locked(struct ieee80211vap *vap)
1188 {
1189 	struct ifnet *ifp = vap->iv_ifp;
1190 	struct ieee80211com *ic = vap->iv_ic;
1191 	struct ifnet *parent = ic->ic_ifp;
1192 
1193 	IEEE80211_LOCK_ASSERT(ic);
1194 
1195 	IEEE80211_DPRINTF(vap,
1196 		IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1197 		"start running, %d vaps running\n", ic->ic_nrunning);
1198 
1199 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1200 		/*
1201 		 * Mark us running.  Note that it's ok to do this first;
1202 		 * if we need to bring the parent device up we defer that
1203 		 * to avoid dropping the com lock.  We expect the device
1204 		 * to respond to being marked up by calling back into us
1205 		 * through ieee80211_start_all at which point we'll come
1206 		 * back in here and complete the work.
1207 		 */
1208 		ifp->if_drv_flags |= IFF_DRV_RUNNING;
1209 		/*
1210 		 * We are not running; if this we are the first vap
1211 		 * to be brought up auto-up the parent if necessary.
1212 		 */
1213 		if (ic->ic_nrunning++ == 0 &&
1214 		    (parent->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1215 			IEEE80211_DPRINTF(vap,
1216 			    IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1217 			    "%s: up parent %s\n", __func__, parent->if_xname);
1218 			parent->if_flags |= IFF_UP;
1219 			ieee80211_runtask(ic, &ic->ic_parent_task);
1220 			return;
1221 		}
1222 	}
1223 	/*
1224 	 * If the parent is up and running, then kick the
1225 	 * 802.11 state machine as appropriate.
1226 	 */
1227 	if ((parent->if_drv_flags & IFF_DRV_RUNNING) &&
1228 	    vap->iv_roaming != IEEE80211_ROAMING_MANUAL) {
1229 		if (vap->iv_opmode == IEEE80211_M_STA) {
1230 #if 0
1231 			/* XXX bypasses scan too easily; disable for now */
1232 			/*
1233 			 * Try to be intelligent about clocking the state
1234 			 * machine.  If we're currently in RUN state then
1235 			 * we should be able to apply any new state/parameters
1236 			 * simply by re-associating.  Otherwise we need to
1237 			 * re-scan to select an appropriate ap.
1238 			 */
1239 			if (vap->iv_state >= IEEE80211_S_RUN)
1240 				ieee80211_new_state_locked(vap,
1241 				    IEEE80211_S_ASSOC, 1);
1242 			else
1243 #endif
1244 				ieee80211_new_state_locked(vap,
1245 				    IEEE80211_S_SCAN, 0);
1246 		} else {
1247 			/*
1248 			 * For monitor+wds mode there's nothing to do but
1249 			 * start running.  Otherwise if this is the first
1250 			 * vap to be brought up, start a scan which may be
1251 			 * preempted if the station is locked to a particular
1252 			 * channel.
1253 			 */
1254 			vap->iv_flags_ext |= IEEE80211_FEXT_REINIT;
1255 			if (vap->iv_opmode == IEEE80211_M_MONITOR ||
1256 			    vap->iv_opmode == IEEE80211_M_WDS)
1257 				ieee80211_new_state_locked(vap,
1258 				    IEEE80211_S_RUN, -1);
1259 			else
1260 				ieee80211_new_state_locked(vap,
1261 				    IEEE80211_S_SCAN, 0);
1262 		}
1263 	}
1264 }
1265 
1266 /*
1267  * Start a single vap.
1268  */
1269 void
1270 ieee80211_init(void *arg)
1271 {
1272 	struct ieee80211vap *vap = arg;
1273 
1274 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1275 	    "%s\n", __func__);
1276 
1277 	IEEE80211_LOCK(vap->iv_ic);
1278 	ieee80211_start_locked(vap);
1279 	IEEE80211_UNLOCK(vap->iv_ic);
1280 }
1281 
1282 /*
1283  * Start all runnable vap's on a device.
1284  */
1285 void
1286 ieee80211_start_all(struct ieee80211com *ic)
1287 {
1288 	struct ieee80211vap *vap;
1289 
1290 	IEEE80211_LOCK(ic);
1291 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1292 		struct ifnet *ifp = vap->iv_ifp;
1293 		if (IFNET_IS_UP_RUNNING(ifp))	/* NB: avoid recursion */
1294 			ieee80211_start_locked(vap);
1295 	}
1296 	IEEE80211_UNLOCK(ic);
1297 }
1298 
1299 /*
1300  * Stop a vap.  We force it down using the state machine
1301  * then mark it's ifnet not running.  If this is the last
1302  * vap running on the underlying device then we close it
1303  * too to insure it will be properly initialized when the
1304  * next vap is brought up.
1305  */
1306 void
1307 ieee80211_stop_locked(struct ieee80211vap *vap)
1308 {
1309 	struct ieee80211com *ic = vap->iv_ic;
1310 	struct ifnet *ifp = vap->iv_ifp;
1311 	struct ifnet *parent = ic->ic_ifp;
1312 
1313 	IEEE80211_LOCK_ASSERT(ic);
1314 
1315 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1316 	    "stop running, %d vaps running\n", ic->ic_nrunning);
1317 
1318 	ieee80211_new_state_locked(vap, IEEE80211_S_INIT, -1);
1319 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1320 		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;	/* mark us stopped */
1321 		if (--ic->ic_nrunning == 0 &&
1322 		    (parent->if_drv_flags & IFF_DRV_RUNNING)) {
1323 			IEEE80211_DPRINTF(vap,
1324 			    IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1325 			    "down parent %s\n", parent->if_xname);
1326 			parent->if_flags &= ~IFF_UP;
1327 			ieee80211_runtask(ic, &ic->ic_parent_task);
1328 		}
1329 	}
1330 }
1331 
1332 void
1333 ieee80211_stop(struct ieee80211vap *vap)
1334 {
1335 	struct ieee80211com *ic = vap->iv_ic;
1336 
1337 	IEEE80211_LOCK(ic);
1338 	ieee80211_stop_locked(vap);
1339 	IEEE80211_UNLOCK(ic);
1340 }
1341 
1342 /*
1343  * Stop all vap's running on a device.
1344  */
1345 void
1346 ieee80211_stop_all(struct ieee80211com *ic)
1347 {
1348 	struct ieee80211vap *vap;
1349 
1350 	IEEE80211_LOCK(ic);
1351 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1352 		struct ifnet *ifp = vap->iv_ifp;
1353 		if (IFNET_IS_UP_RUNNING(ifp))	/* NB: avoid recursion */
1354 			ieee80211_stop_locked(vap);
1355 	}
1356 	IEEE80211_UNLOCK(ic);
1357 
1358 	ieee80211_waitfor_parent(ic);
1359 }
1360 
1361 /*
1362  * Stop all vap's running on a device and arrange
1363  * for those that were running to be resumed.
1364  */
1365 void
1366 ieee80211_suspend_all(struct ieee80211com *ic)
1367 {
1368 	struct ieee80211vap *vap;
1369 
1370 	IEEE80211_LOCK(ic);
1371 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1372 		struct ifnet *ifp = vap->iv_ifp;
1373 		if (IFNET_IS_UP_RUNNING(ifp)) {	/* NB: avoid recursion */
1374 			vap->iv_flags_ext |= IEEE80211_FEXT_RESUME;
1375 			ieee80211_stop_locked(vap);
1376 		}
1377 	}
1378 	IEEE80211_UNLOCK(ic);
1379 
1380 	ieee80211_waitfor_parent(ic);
1381 }
1382 
1383 /*
1384  * Start all vap's marked for resume.
1385  */
1386 void
1387 ieee80211_resume_all(struct ieee80211com *ic)
1388 {
1389 	struct ieee80211vap *vap;
1390 
1391 	IEEE80211_LOCK(ic);
1392 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1393 		struct ifnet *ifp = vap->iv_ifp;
1394 		if (!IFNET_IS_UP_RUNNING(ifp) &&
1395 		    (vap->iv_flags_ext & IEEE80211_FEXT_RESUME)) {
1396 			vap->iv_flags_ext &= ~IEEE80211_FEXT_RESUME;
1397 			ieee80211_start_locked(vap);
1398 		}
1399 	}
1400 	IEEE80211_UNLOCK(ic);
1401 }
1402 
1403 void
1404 ieee80211_beacon_miss(struct ieee80211com *ic)
1405 {
1406 	IEEE80211_LOCK(ic);
1407 	if ((ic->ic_flags & IEEE80211_F_SCAN) == 0) {
1408 		/* Process in a taskq, the handler may reenter the driver */
1409 		ieee80211_runtask(ic, &ic->ic_bmiss_task);
1410 	}
1411 	IEEE80211_UNLOCK(ic);
1412 }
1413 
1414 static void
1415 beacon_miss(void *arg, int npending)
1416 {
1417 	struct ieee80211com *ic = arg;
1418 	struct ieee80211vap *vap;
1419 
1420 	IEEE80211_LOCK(ic);
1421 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1422 		/*
1423 		 * We only pass events through for sta vap's in RUN state;
1424 		 * may be too restrictive but for now this saves all the
1425 		 * handlers duplicating these checks.
1426 		 */
1427 		if (vap->iv_opmode == IEEE80211_M_STA &&
1428 		    vap->iv_state >= IEEE80211_S_RUN &&
1429 		    vap->iv_bmiss != NULL)
1430 			vap->iv_bmiss(vap);
1431 	}
1432 	IEEE80211_UNLOCK(ic);
1433 }
1434 
1435 static void
1436 beacon_swmiss(void *arg, int npending)
1437 {
1438 	struct ieee80211vap *vap = arg;
1439 	struct ieee80211com *ic = vap->iv_ic;
1440 
1441 	IEEE80211_LOCK(ic);
1442 	if (vap->iv_state == IEEE80211_S_RUN) {
1443 		/* XXX Call multiple times if npending > zero? */
1444 		vap->iv_bmiss(vap);
1445 	}
1446 	IEEE80211_UNLOCK(ic);
1447 }
1448 
1449 /*
1450  * Software beacon miss handling.  Check if any beacons
1451  * were received in the last period.  If not post a
1452  * beacon miss; otherwise reset the counter.
1453  */
1454 void
1455 ieee80211_swbmiss(void *arg)
1456 {
1457 	struct ieee80211vap *vap = arg;
1458 	struct ieee80211com *ic = vap->iv_ic;
1459 
1460 	IEEE80211_LOCK_ASSERT(ic);
1461 
1462 	/* XXX sleep state? */
1463 	KASSERT(vap->iv_state == IEEE80211_S_RUN,
1464 	    ("wrong state %d", vap->iv_state));
1465 
1466 	if (ic->ic_flags & IEEE80211_F_SCAN) {
1467 		/*
1468 		 * If scanning just ignore and reset state.  If we get a
1469 		 * bmiss after coming out of scan because we haven't had
1470 		 * time to receive a beacon then we should probe the AP
1471 		 * before posting a real bmiss (unless iv_bmiss_max has
1472 		 * been artifiically lowered).  A cleaner solution might
1473 		 * be to disable the timer on scan start/end but to handle
1474 		 * case of multiple sta vap's we'd need to disable the
1475 		 * timers of all affected vap's.
1476 		 */
1477 		vap->iv_swbmiss_count = 0;
1478 	} else if (vap->iv_swbmiss_count == 0) {
1479 		if (vap->iv_bmiss != NULL)
1480 			ieee80211_runtask(ic, &vap->iv_swbmiss_task);
1481 	} else
1482 		vap->iv_swbmiss_count = 0;
1483 	callout_reset(&vap->iv_swbmiss, vap->iv_swbmiss_period,
1484 		ieee80211_swbmiss, vap);
1485 }
1486 
1487 /*
1488  * Start an 802.11h channel switch.  We record the parameters,
1489  * mark the operation pending, notify each vap through the
1490  * beacon update mechanism so it can update the beacon frame
1491  * contents, and then switch vap's to CSA state to block outbound
1492  * traffic.  Devices that handle CSA directly can use the state
1493  * switch to do the right thing so long as they call
1494  * ieee80211_csa_completeswitch when it's time to complete the
1495  * channel change.  Devices that depend on the net80211 layer can
1496  * use ieee80211_beacon_update to handle the countdown and the
1497  * channel switch.
1498  */
1499 void
1500 ieee80211_csa_startswitch(struct ieee80211com *ic,
1501 	struct ieee80211_channel *c, int mode, int count)
1502 {
1503 	struct ieee80211vap *vap;
1504 
1505 	IEEE80211_LOCK_ASSERT(ic);
1506 
1507 	ic->ic_csa_newchan = c;
1508 	ic->ic_csa_mode = mode;
1509 	ic->ic_csa_count = count;
1510 	ic->ic_flags |= IEEE80211_F_CSAPENDING;
1511 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1512 		if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
1513 		    vap->iv_opmode == IEEE80211_M_IBSS ||
1514 		    vap->iv_opmode == IEEE80211_M_MBSS)
1515 			ieee80211_beacon_notify(vap, IEEE80211_BEACON_CSA);
1516 		/* switch to CSA state to block outbound traffic */
1517 		if (vap->iv_state == IEEE80211_S_RUN)
1518 			ieee80211_new_state_locked(vap, IEEE80211_S_CSA, 0);
1519 	}
1520 	ieee80211_notify_csa(ic, c, mode, count);
1521 }
1522 
1523 /*
1524  * Complete the channel switch by transitioning all CSA VAPs to RUN.
1525  * This is called by both the completion and cancellation functions
1526  * so each VAP is placed back in the RUN state and can thus transmit.
1527  */
1528 static void
1529 csa_completeswitch(struct ieee80211com *ic)
1530 {
1531 	struct ieee80211vap *vap;
1532 
1533 	ic->ic_csa_newchan = NULL;
1534 	ic->ic_flags &= ~IEEE80211_F_CSAPENDING;
1535 
1536 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
1537 		if (vap->iv_state == IEEE80211_S_CSA)
1538 			ieee80211_new_state_locked(vap, IEEE80211_S_RUN, 0);
1539 }
1540 
1541 /*
1542  * Complete an 802.11h channel switch started by ieee80211_csa_startswitch.
1543  * We clear state and move all vap's in CSA state to RUN state
1544  * so they can again transmit.
1545  *
1546  * Although this may not be completely correct, update the BSS channel
1547  * for each VAP to the newly configured channel. The setcurchan sets
1548  * the current operating channel for the interface (so the radio does
1549  * switch over) but the VAP BSS isn't updated, leading to incorrectly
1550  * reported information via ioctl.
1551  */
1552 void
1553 ieee80211_csa_completeswitch(struct ieee80211com *ic)
1554 {
1555 	struct ieee80211vap *vap;
1556 
1557 	IEEE80211_LOCK_ASSERT(ic);
1558 
1559 	KASSERT(ic->ic_flags & IEEE80211_F_CSAPENDING, ("csa not pending"));
1560 
1561 	ieee80211_setcurchan(ic, ic->ic_csa_newchan);
1562 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
1563 		if (vap->iv_state == IEEE80211_S_CSA)
1564 			vap->iv_bss->ni_chan = ic->ic_curchan;
1565 
1566 	csa_completeswitch(ic);
1567 }
1568 
1569 /*
1570  * Cancel an 802.11h channel switch started by ieee80211_csa_startswitch.
1571  * We clear state and move all vap's in CSA state to RUN state
1572  * so they can again transmit.
1573  */
1574 void
1575 ieee80211_csa_cancelswitch(struct ieee80211com *ic)
1576 {
1577 	IEEE80211_LOCK_ASSERT(ic);
1578 
1579 	csa_completeswitch(ic);
1580 }
1581 
1582 /*
1583  * Complete a DFS CAC started by ieee80211_dfs_cac_start.
1584  * We clear state and move all vap's in CAC state to RUN state.
1585  */
1586 void
1587 ieee80211_cac_completeswitch(struct ieee80211vap *vap0)
1588 {
1589 	struct ieee80211com *ic = vap0->iv_ic;
1590 	struct ieee80211vap *vap;
1591 
1592 	IEEE80211_LOCK(ic);
1593 	/*
1594 	 * Complete CAC state change for lead vap first; then
1595 	 * clock all the other vap's waiting.
1596 	 */
1597 	KASSERT(vap0->iv_state == IEEE80211_S_CAC,
1598 	    ("wrong state %d", vap0->iv_state));
1599 	ieee80211_new_state_locked(vap0, IEEE80211_S_RUN, 0);
1600 
1601 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
1602 		if (vap->iv_state == IEEE80211_S_CAC)
1603 			ieee80211_new_state_locked(vap, IEEE80211_S_RUN, 0);
1604 	IEEE80211_UNLOCK(ic);
1605 }
1606 
1607 /*
1608  * Force all vap's other than the specified vap to the INIT state
1609  * and mark them as waiting for a scan to complete.  These vaps
1610  * will be brought up when the scan completes and the scanning vap
1611  * reaches RUN state by wakeupwaiting.
1612  */
1613 static void
1614 markwaiting(struct ieee80211vap *vap0)
1615 {
1616 	struct ieee80211com *ic = vap0->iv_ic;
1617 	struct ieee80211vap *vap;
1618 
1619 	IEEE80211_LOCK_ASSERT(ic);
1620 
1621 	/*
1622 	 * A vap list entry can not disappear since we are running on the
1623 	 * taskqueue and a vap destroy will queue and drain another state
1624 	 * change task.
1625 	 */
1626 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1627 		if (vap == vap0)
1628 			continue;
1629 		if (vap->iv_state != IEEE80211_S_INIT) {
1630 			/* NB: iv_newstate may drop the lock */
1631 			vap->iv_newstate(vap, IEEE80211_S_INIT, 0);
1632 			IEEE80211_LOCK_ASSERT(ic);
1633 			vap->iv_flags_ext |= IEEE80211_FEXT_SCANWAIT;
1634 		}
1635 	}
1636 }
1637 
1638 /*
1639  * Wakeup all vap's waiting for a scan to complete.  This is the
1640  * companion to markwaiting (above) and is used to coordinate
1641  * multiple vaps scanning.
1642  * This is called from the state taskqueue.
1643  */
1644 static void
1645 wakeupwaiting(struct ieee80211vap *vap0)
1646 {
1647 	struct ieee80211com *ic = vap0->iv_ic;
1648 	struct ieee80211vap *vap;
1649 
1650 	IEEE80211_LOCK_ASSERT(ic);
1651 
1652 	/*
1653 	 * A vap list entry can not disappear since we are running on the
1654 	 * taskqueue and a vap destroy will queue and drain another state
1655 	 * change task.
1656 	 */
1657 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1658 		if (vap == vap0)
1659 			continue;
1660 		if (vap->iv_flags_ext & IEEE80211_FEXT_SCANWAIT) {
1661 			vap->iv_flags_ext &= ~IEEE80211_FEXT_SCANWAIT;
1662 			/* NB: sta's cannot go INIT->RUN */
1663 			/* NB: iv_newstate may drop the lock */
1664 			vap->iv_newstate(vap,
1665 			    vap->iv_opmode == IEEE80211_M_STA ?
1666 			        IEEE80211_S_SCAN : IEEE80211_S_RUN, 0);
1667 			IEEE80211_LOCK_ASSERT(ic);
1668 		}
1669 	}
1670 }
1671 
1672 /*
1673  * Handle post state change work common to all operating modes.
1674  */
1675 static void
1676 ieee80211_newstate_cb(void *xvap, int npending)
1677 {
1678 	struct ieee80211vap *vap = xvap;
1679 	struct ieee80211com *ic = vap->iv_ic;
1680 	enum ieee80211_state nstate, ostate;
1681 	int arg, rc;
1682 
1683 	IEEE80211_LOCK(ic);
1684 	nstate = vap->iv_nstate;
1685 	arg = vap->iv_nstate_arg;
1686 
1687 	if (vap->iv_flags_ext & IEEE80211_FEXT_REINIT) {
1688 		/*
1689 		 * We have been requested to drop back to the INIT before
1690 		 * proceeding to the new state.
1691 		 */
1692 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1693 		    "%s: %s -> %s arg %d\n", __func__,
1694 		    ieee80211_state_name[vap->iv_state],
1695 		    ieee80211_state_name[IEEE80211_S_INIT], arg);
1696 		vap->iv_newstate(vap, IEEE80211_S_INIT, arg);
1697 		IEEE80211_LOCK_ASSERT(ic);
1698 		vap->iv_flags_ext &= ~IEEE80211_FEXT_REINIT;
1699 	}
1700 
1701 	ostate = vap->iv_state;
1702 	if (nstate == IEEE80211_S_SCAN && ostate != IEEE80211_S_INIT) {
1703 		/*
1704 		 * SCAN was forced; e.g. on beacon miss.  Force other running
1705 		 * vap's to INIT state and mark them as waiting for the scan to
1706 		 * complete.  This insures they don't interfere with our
1707 		 * scanning.  Since we are single threaded the vaps can not
1708 		 * transition again while we are executing.
1709 		 *
1710 		 * XXX not always right, assumes ap follows sta
1711 		 */
1712 		markwaiting(vap);
1713 	}
1714 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1715 	    "%s: %s -> %s arg %d\n", __func__,
1716 	    ieee80211_state_name[ostate], ieee80211_state_name[nstate], arg);
1717 
1718 	rc = vap->iv_newstate(vap, nstate, arg);
1719 	IEEE80211_LOCK_ASSERT(ic);
1720 	vap->iv_flags_ext &= ~IEEE80211_FEXT_STATEWAIT;
1721 	if (rc != 0) {
1722 		/* State transition failed */
1723 		KASSERT(rc != EINPROGRESS, ("iv_newstate was deferred"));
1724 		KASSERT(nstate != IEEE80211_S_INIT,
1725 		    ("INIT state change failed"));
1726 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1727 		    "%s: %s returned error %d\n", __func__,
1728 		    ieee80211_state_name[nstate], rc);
1729 		goto done;
1730 	}
1731 
1732 	/* No actual transition, skip post processing */
1733 	if (ostate == nstate)
1734 		goto done;
1735 
1736 	if (nstate == IEEE80211_S_RUN) {
1737 		/*
1738 		 * OACTIVE may be set on the vap if the upper layer
1739 		 * tried to transmit (e.g. IPv6 NDP) before we reach
1740 		 * RUN state.  Clear it and restart xmit.
1741 		 *
1742 		 * Note this can also happen as a result of SLEEP->RUN
1743 		 * (i.e. coming out of power save mode).
1744 		 */
1745 		IF_LOCK(&vap->iv_ifp->if_snd);
1746 		vap->iv_ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1747 		IF_UNLOCK(&vap->iv_ifp->if_snd);
1748 		if_start(vap->iv_ifp);
1749 
1750 		/* bring up any vaps waiting on us */
1751 		wakeupwaiting(vap);
1752 	} else if (nstate == IEEE80211_S_INIT) {
1753 		/*
1754 		 * Flush the scan cache if we did the last scan (XXX?)
1755 		 * and flush any frames on send queues from this vap.
1756 		 * Note the mgt q is used only for legacy drivers and
1757 		 * will go away shortly.
1758 		 */
1759 		ieee80211_scan_flush(vap);
1760 
1761 		/* XXX NB: cast for altq */
1762 		ieee80211_flush_ifq((struct ifqueue *)&ic->ic_ifp->if_snd, vap);
1763 	}
1764 done:
1765 	IEEE80211_UNLOCK(ic);
1766 }
1767 
1768 /*
1769  * Public interface for initiating a state machine change.
1770  * This routine single-threads the request and coordinates
1771  * the scheduling of multiple vaps for the purpose of selecting
1772  * an operating channel.  Specifically the following scenarios
1773  * are handled:
1774  * o only one vap can be selecting a channel so on transition to
1775  *   SCAN state if another vap is already scanning then
1776  *   mark the caller for later processing and return without
1777  *   doing anything (XXX? expectations by caller of synchronous operation)
1778  * o only one vap can be doing CAC of a channel so on transition to
1779  *   CAC state if another vap is already scanning for radar then
1780  *   mark the caller for later processing and return without
1781  *   doing anything (XXX? expectations by caller of synchronous operation)
1782  * o if another vap is already running when a request is made
1783  *   to SCAN then an operating channel has been chosen; bypass
1784  *   the scan and just join the channel
1785  *
1786  * Note that the state change call is done through the iv_newstate
1787  * method pointer so any driver routine gets invoked.  The driver
1788  * will normally call back into operating mode-specific
1789  * ieee80211_newstate routines (below) unless it needs to completely
1790  * bypass the state machine (e.g. because the firmware has it's
1791  * own idea how things should work).  Bypassing the net80211 layer
1792  * is usually a mistake and indicates lack of proper integration
1793  * with the net80211 layer.
1794  */
1795 static int
1796 ieee80211_new_state_locked(struct ieee80211vap *vap,
1797 	enum ieee80211_state nstate, int arg)
1798 {
1799 	struct ieee80211com *ic = vap->iv_ic;
1800 	struct ieee80211vap *vp;
1801 	enum ieee80211_state ostate;
1802 	int nrunning, nscanning;
1803 
1804 	IEEE80211_LOCK_ASSERT(ic);
1805 
1806 	if (vap->iv_flags_ext & IEEE80211_FEXT_STATEWAIT) {
1807 		if (vap->iv_nstate == IEEE80211_S_INIT) {
1808 			/*
1809 			 * XXX The vap is being stopped, do no allow any other
1810 			 * state changes until this is completed.
1811 			 */
1812 			return -1;
1813 		} else if (vap->iv_state != vap->iv_nstate) {
1814 #if 0
1815 			/* Warn if the previous state hasn't completed. */
1816 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1817 			    "%s: pending %s -> %s transition lost\n", __func__,
1818 			    ieee80211_state_name[vap->iv_state],
1819 			    ieee80211_state_name[vap->iv_nstate]);
1820 #else
1821 			/* XXX temporarily enable to identify issues */
1822 			if_printf(vap->iv_ifp,
1823 			    "%s: pending %s -> %s transition lost\n",
1824 			    __func__, ieee80211_state_name[vap->iv_state],
1825 			    ieee80211_state_name[vap->iv_nstate]);
1826 #endif
1827 		}
1828 	}
1829 
1830 	nrunning = nscanning = 0;
1831 	/* XXX can track this state instead of calculating */
1832 	TAILQ_FOREACH(vp, &ic->ic_vaps, iv_next) {
1833 		if (vp != vap) {
1834 			if (vp->iv_state >= IEEE80211_S_RUN)
1835 				nrunning++;
1836 			/* XXX doesn't handle bg scan */
1837 			/* NB: CAC+AUTH+ASSOC treated like SCAN */
1838 			else if (vp->iv_state > IEEE80211_S_INIT)
1839 				nscanning++;
1840 		}
1841 	}
1842 	ostate = vap->iv_state;
1843 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1844 	    "%s: %s -> %s (nrunning %d nscanning %d)\n", __func__,
1845 	    ieee80211_state_name[ostate], ieee80211_state_name[nstate],
1846 	    nrunning, nscanning);
1847 	switch (nstate) {
1848 	case IEEE80211_S_SCAN:
1849 		if (ostate == IEEE80211_S_INIT) {
1850 			/*
1851 			 * INIT -> SCAN happens on initial bringup.
1852 			 */
1853 			KASSERT(!(nscanning && nrunning),
1854 			    ("%d scanning and %d running", nscanning, nrunning));
1855 			if (nscanning) {
1856 				/*
1857 				 * Someone is scanning, defer our state
1858 				 * change until the work has completed.
1859 				 */
1860 				IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1861 				    "%s: defer %s -> %s\n",
1862 				    __func__, ieee80211_state_name[ostate],
1863 				    ieee80211_state_name[nstate]);
1864 				vap->iv_flags_ext |= IEEE80211_FEXT_SCANWAIT;
1865 				return 0;
1866 			}
1867 			if (nrunning) {
1868 				/*
1869 				 * Someone is operating; just join the channel
1870 				 * they have chosen.
1871 				 */
1872 				/* XXX kill arg? */
1873 				/* XXX check each opmode, adhoc? */
1874 				if (vap->iv_opmode == IEEE80211_M_STA)
1875 					nstate = IEEE80211_S_SCAN;
1876 				else
1877 					nstate = IEEE80211_S_RUN;
1878 #ifdef IEEE80211_DEBUG
1879 				if (nstate != IEEE80211_S_SCAN) {
1880 					IEEE80211_DPRINTF(vap,
1881 					    IEEE80211_MSG_STATE,
1882 					    "%s: override, now %s -> %s\n",
1883 					    __func__,
1884 					    ieee80211_state_name[ostate],
1885 					    ieee80211_state_name[nstate]);
1886 				}
1887 #endif
1888 			}
1889 		}
1890 		break;
1891 	case IEEE80211_S_RUN:
1892 		if (vap->iv_opmode == IEEE80211_M_WDS &&
1893 		    (vap->iv_flags_ext & IEEE80211_FEXT_WDSLEGACY) &&
1894 		    nscanning) {
1895 			/*
1896 			 * Legacy WDS with someone else scanning; don't
1897 			 * go online until that completes as we should
1898 			 * follow the other vap to the channel they choose.
1899 			 */
1900 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1901 			     "%s: defer %s -> %s (legacy WDS)\n", __func__,
1902 			     ieee80211_state_name[ostate],
1903 			     ieee80211_state_name[nstate]);
1904 			vap->iv_flags_ext |= IEEE80211_FEXT_SCANWAIT;
1905 			return 0;
1906 		}
1907 		if (vap->iv_opmode == IEEE80211_M_HOSTAP &&
1908 		    IEEE80211_IS_CHAN_DFS(ic->ic_bsschan) &&
1909 		    (vap->iv_flags_ext & IEEE80211_FEXT_DFS) &&
1910 		    !IEEE80211_IS_CHAN_CACDONE(ic->ic_bsschan)) {
1911 			/*
1912 			 * This is a DFS channel, transition to CAC state
1913 			 * instead of RUN.  This allows us to initiate
1914 			 * Channel Availability Check (CAC) as specified
1915 			 * by 11h/DFS.
1916 			 */
1917 			nstate = IEEE80211_S_CAC;
1918 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1919 			     "%s: override %s -> %s (DFS)\n", __func__,
1920 			     ieee80211_state_name[ostate],
1921 			     ieee80211_state_name[nstate]);
1922 		}
1923 		break;
1924 	case IEEE80211_S_INIT:
1925 		/* cancel any scan in progress */
1926 		ieee80211_cancel_scan(vap);
1927 		if (ostate == IEEE80211_S_INIT ) {
1928 			/* XXX don't believe this */
1929 			/* INIT -> INIT. nothing to do */
1930 			vap->iv_flags_ext &= ~IEEE80211_FEXT_SCANWAIT;
1931 		}
1932 		/* fall thru... */
1933 	default:
1934 		break;
1935 	}
1936 	/* defer the state change to a thread */
1937 	vap->iv_nstate = nstate;
1938 	vap->iv_nstate_arg = arg;
1939 	vap->iv_flags_ext |= IEEE80211_FEXT_STATEWAIT;
1940 	ieee80211_runtask(ic, &vap->iv_nstate_task);
1941 	return EINPROGRESS;
1942 }
1943 
1944 int
1945 ieee80211_new_state(struct ieee80211vap *vap,
1946 	enum ieee80211_state nstate, int arg)
1947 {
1948 	struct ieee80211com *ic = vap->iv_ic;
1949 	int rc;
1950 
1951 	IEEE80211_LOCK(ic);
1952 	rc = ieee80211_new_state_locked(vap, nstate, arg);
1953 	IEEE80211_UNLOCK(ic);
1954 	return rc;
1955 }
1956