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