xref: /openbsd/sys/net80211/ieee80211_node.c (revision 097a140d)
1 /*	$OpenBSD: ieee80211_node.c,v 1.184 2021/04/15 18:05:05 stsp Exp $	*/
2 /*	$NetBSD: ieee80211_node.c,v 1.14 2004/05/09 09:18:47 dyoung Exp $	*/
3 
4 /*-
5  * Copyright (c) 2001 Atsushi Onoe
6  * Copyright (c) 2002, 2003 Sam Leffler, Errno Consulting
7  * Copyright (c) 2008 Damien Bergamini
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. The name of the author may not be used to endorse or promote products
19  *    derived from this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
23  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 #include "bridge.h"
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/mbuf.h>
38 #include <sys/malloc.h>
39 #include <sys/kernel.h>
40 #include <sys/socket.h>
41 #include <sys/sockio.h>
42 #include <sys/endian.h>
43 #include <sys/errno.h>
44 #include <sys/sysctl.h>
45 #include <sys/tree.h>
46 
47 #include <net/if.h>
48 #include <net/if_dl.h>
49 #include <net/if_media.h>
50 
51 #include <netinet/in.h>
52 #include <netinet/if_ether.h>
53 
54 #if NBRIDGE > 0
55 #include <net/if_bridge.h>
56 #endif
57 
58 #include <net80211/ieee80211_var.h>
59 #include <net80211/ieee80211_priv.h>
60 
61 struct ieee80211_node *ieee80211_node_alloc(struct ieee80211com *);
62 void ieee80211_node_free(struct ieee80211com *, struct ieee80211_node *);
63 void ieee80211_node_copy(struct ieee80211com *, struct ieee80211_node *,
64     const struct ieee80211_node *);
65 void ieee80211_choose_rsnparams(struct ieee80211com *);
66 u_int8_t ieee80211_node_getrssi(struct ieee80211com *,
67     const struct ieee80211_node *);
68 int ieee80211_node_checkrssi(struct ieee80211com *,
69     const struct ieee80211_node *);
70 int ieee80211_ess_is_better(struct ieee80211com *ic, struct ieee80211_node *,
71     struct ieee80211_node *);
72 void ieee80211_node_set_timeouts(struct ieee80211_node *);
73 void ieee80211_setup_node(struct ieee80211com *, struct ieee80211_node *,
74     const u_int8_t *);
75 struct ieee80211_node *ieee80211_alloc_node_helper(struct ieee80211com *);
76 void ieee80211_node_switch_bss(struct ieee80211com *, struct ieee80211_node *);
77 void ieee80211_node_addba_request(struct ieee80211_node *, int);
78 void ieee80211_node_addba_request_ac_be_to(void *);
79 void ieee80211_node_addba_request_ac_bk_to(void *);
80 void ieee80211_node_addba_request_ac_vi_to(void *);
81 void ieee80211_node_addba_request_ac_vo_to(void *);
82 void ieee80211_needs_auth(struct ieee80211com *, struct ieee80211_node *);
83 #ifndef IEEE80211_STA_ONLY
84 void ieee80211_node_join_ht(struct ieee80211com *, struct ieee80211_node *);
85 void ieee80211_node_join_rsn(struct ieee80211com *, struct ieee80211_node *);
86 void ieee80211_node_join_11g(struct ieee80211com *, struct ieee80211_node *);
87 void ieee80211_node_leave_ht(struct ieee80211com *, struct ieee80211_node *);
88 void ieee80211_node_leave_rsn(struct ieee80211com *, struct ieee80211_node *);
89 void ieee80211_node_leave_11g(struct ieee80211com *, struct ieee80211_node *);
90 void ieee80211_inact_timeout(void *);
91 void ieee80211_node_cache_timeout(void *);
92 #endif
93 void ieee80211_clean_inactive_nodes(struct ieee80211com *, int);
94 
95 #ifndef IEEE80211_STA_ONLY
96 void
97 ieee80211_inact_timeout(void *arg)
98 {
99 	struct ieee80211com *ic = arg;
100 	struct ieee80211_node *ni, *next_ni;
101 	int s;
102 
103 	s = splnet();
104 	for (ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
105 	    ni != NULL; ni = next_ni) {
106 		next_ni = RBT_NEXT(ieee80211_tree, ni);
107 		if (ni->ni_refcnt > 0)
108 			continue;
109 		if (ni->ni_inact < IEEE80211_INACT_MAX)
110 			ni->ni_inact++;
111 	}
112 	splx(s);
113 
114 	timeout_add_sec(&ic->ic_inact_timeout, IEEE80211_INACT_WAIT);
115 }
116 
117 void
118 ieee80211_node_cache_timeout(void *arg)
119 {
120 	struct ieee80211com *ic = arg;
121 
122 	ieee80211_clean_nodes(ic, 1);
123 	timeout_add_sec(&ic->ic_node_cache_timeout, IEEE80211_CACHE_WAIT);
124 }
125 #endif
126 
127 /*
128  * For debug purposes
129  */
130 void
131 ieee80211_print_ess(struct ieee80211_ess *ess)
132 {
133 	ieee80211_print_essid(ess->essid, ess->esslen);
134 	if (ess->flags & IEEE80211_F_RSNON) {
135 		printf(" wpa");
136 		if (ess->rsnprotos & IEEE80211_PROTO_RSN)
137 			printf(",wpa2");
138 		if (ess->rsnprotos & IEEE80211_PROTO_WPA)
139 			printf(",wpa1");
140 
141 		if (ess->rsnakms & IEEE80211_AKM_8021X ||
142 		    ess->rsnakms & IEEE80211_AKM_SHA256_8021X)
143 			printf(",802.1x");
144 		printf(" ");
145 
146 		if (ess->rsnciphers & IEEE80211_CIPHER_USEGROUP)
147 			printf(" usegroup");
148 		if (ess->rsnciphers & IEEE80211_CIPHER_WEP40)
149 			printf(" wep40");
150 		if (ess->rsnciphers & IEEE80211_CIPHER_WEP104)
151 			printf(" wep104");
152 		if (ess->rsnciphers & IEEE80211_CIPHER_TKIP)
153 			printf(" tkip");
154 		if (ess->rsnciphers & IEEE80211_CIPHER_CCMP)
155 			printf(" ccmp");
156 	}
157 	if (ess->flags & IEEE80211_F_WEPON) {
158 		int i = ess->def_txkey;
159 
160 		printf(" wep,");
161 		if (ess->nw_keys[i].k_cipher & IEEE80211_CIPHER_WEP40)
162 			printf("wep40");
163 		if (ess->nw_keys[i].k_cipher & IEEE80211_CIPHER_WEP104)
164 			printf("wep104");
165 	}
166 	if (ess->flags == 0)
167 		printf(" clear");
168 	printf("\n");
169 }
170 
171 void
172 ieee80211_print_ess_list(struct ieee80211com *ic)
173 {
174 	struct ifnet		*ifp = &ic->ic_if;
175 	struct ieee80211_ess	*ess;
176 
177 	printf("%s: known networks\n", ifp->if_xname);
178 	TAILQ_FOREACH(ess, &ic->ic_ess, ess_next) {
179 		ieee80211_print_ess(ess);
180 	}
181 }
182 
183 struct ieee80211_ess *
184 ieee80211_get_ess(struct ieee80211com *ic, const char *nwid, int len)
185 {
186 	struct ieee80211_ess	*ess;
187 
188 	TAILQ_FOREACH(ess, &ic->ic_ess, ess_next) {
189 		if (len == ess->esslen &&
190 		    memcmp(ess->essid, nwid, ess->esslen) == 0)
191 			return ess;
192 	}
193 
194 	return NULL;
195 }
196 
197 void
198 ieee80211_del_ess(struct ieee80211com *ic, char *nwid, int len, int all)
199 {
200 	struct ieee80211_ess *ess, *next;
201 
202 	TAILQ_FOREACH_SAFE(ess, &ic->ic_ess, ess_next, next) {
203 		if (all == 1 || (ess->esslen == len &&
204 		    memcmp(ess->essid, nwid, len) == 0)) {
205 			TAILQ_REMOVE(&ic->ic_ess, ess, ess_next);
206 			explicit_bzero(ess, sizeof(*ess));
207 			free(ess, M_DEVBUF, sizeof(*ess));
208 			if (TAILQ_EMPTY(&ic->ic_ess))
209 				ic->ic_flags &= ~IEEE80211_F_AUTO_JOIN;
210 			if (all != 1)
211 				return;
212 		}
213 	}
214 }
215 
216 /* Keep in sync with ieee80211_ioctl.c:ieee80211_ioctl_setnwkeys() */
217 static int
218 ieee80211_ess_setnwkeys(struct ieee80211_ess *ess,
219     const struct ieee80211_nwkey *nwkey)
220 {
221 	struct ieee80211_key *k;
222 	int error, i;
223 
224 	if (nwkey->i_wepon == IEEE80211_NWKEY_OPEN) {
225 		if (!(ess->flags & IEEE80211_F_WEPON))
226 			return 0;
227 		ess->flags &= ~IEEE80211_F_WEPON;
228 		return ENETRESET;
229 	}
230 	if (nwkey->i_defkid < 1 || nwkey->i_defkid > IEEE80211_WEP_NKID)
231 		return EINVAL;
232 
233 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
234 		if (nwkey->i_key[i].i_keylen == 0 ||
235 		    nwkey->i_key[i].i_keydat == NULL)
236 			continue;	/* entry not set */
237 		if (nwkey->i_key[i].i_keylen > IEEE80211_KEYBUF_SIZE)
238 			return EINVAL;
239 
240 		/* map wep key to ieee80211_key */
241 		k = &ess->nw_keys[i];
242 		memset(k, 0, sizeof(*k));
243 		if (nwkey->i_key[i].i_keylen <= 5)
244 			k->k_cipher = IEEE80211_CIPHER_WEP40;
245 		else
246 			k->k_cipher = IEEE80211_CIPHER_WEP104;
247 		k->k_len = ieee80211_cipher_keylen(k->k_cipher);
248 		k->k_flags = IEEE80211_KEY_GROUP | IEEE80211_KEY_TX;
249 		error = copyin(nwkey->i_key[i].i_keydat, k->k_key, k->k_len);
250 		if (error != 0)
251 			return error;
252 	}
253 	ess->def_txkey = nwkey->i_defkid - 1;
254 	ess->flags |= IEEE80211_F_WEPON;
255 
256 	return ENETRESET;
257 }
258 
259 
260 /* Keep in sync with ieee80211_ioctl.c:ieee80211_ioctl_setwpaparms() */
261 static int
262 ieee80211_ess_setwpaparms(struct ieee80211_ess *ess,
263     const struct ieee80211_wpaparams *wpa)
264 {
265 	if (!wpa->i_enabled) {
266 		if (!(ess->flags & IEEE80211_F_RSNON))
267 			return 0;
268 		ess->flags &= ~IEEE80211_F_RSNON;
269 		ess->rsnprotos = 0;
270 		ess->rsnakms = 0;
271 		ess->rsngroupcipher = 0;
272 		ess->rsnciphers = 0;
273 		return ENETRESET;
274 	}
275 
276 	ess->rsnprotos = 0;
277 	if (wpa->i_protos & IEEE80211_WPA_PROTO_WPA1)
278 		ess->rsnprotos |= IEEE80211_PROTO_WPA;
279 	if (wpa->i_protos & IEEE80211_WPA_PROTO_WPA2)
280 		ess->rsnprotos |= IEEE80211_PROTO_RSN;
281 	if (ess->rsnprotos == 0)	/* set to default (RSN) */
282 		ess->rsnprotos = IEEE80211_PROTO_RSN;
283 
284 	ess->rsnakms = 0;
285 	if (wpa->i_akms & IEEE80211_WPA_AKM_PSK)
286 		ess->rsnakms |= IEEE80211_AKM_PSK;
287 	if (wpa->i_akms & IEEE80211_WPA_AKM_SHA256_PSK)
288 		ess->rsnakms |= IEEE80211_AKM_SHA256_PSK;
289 	if (wpa->i_akms & IEEE80211_WPA_AKM_8021X)
290 		ess->rsnakms |= IEEE80211_AKM_8021X;
291 	if (wpa->i_akms & IEEE80211_WPA_AKM_SHA256_8021X)
292 		ess->rsnakms |= IEEE80211_AKM_SHA256_8021X;
293 	if (ess->rsnakms == 0)	/* set to default (PSK) */
294 		ess->rsnakms = IEEE80211_AKM_PSK;
295 
296 	if (wpa->i_groupcipher == IEEE80211_WPA_CIPHER_WEP40)
297 		ess->rsngroupcipher = IEEE80211_CIPHER_WEP40;
298 	else if (wpa->i_groupcipher == IEEE80211_WPA_CIPHER_TKIP)
299 		ess->rsngroupcipher = IEEE80211_CIPHER_TKIP;
300 	else if (wpa->i_groupcipher == IEEE80211_WPA_CIPHER_CCMP)
301 		ess->rsngroupcipher = IEEE80211_CIPHER_CCMP;
302 	else if (wpa->i_groupcipher == IEEE80211_WPA_CIPHER_WEP104)
303 		ess->rsngroupcipher = IEEE80211_CIPHER_WEP104;
304 	else  {	/* set to default */
305 		if (ess->rsnprotos & IEEE80211_PROTO_WPA)
306 			ess->rsngroupcipher = IEEE80211_CIPHER_TKIP;
307 		else
308 			ess->rsngroupcipher = IEEE80211_CIPHER_CCMP;
309 	}
310 
311 	ess->rsnciphers = 0;
312 	if (wpa->i_ciphers & IEEE80211_WPA_CIPHER_TKIP)
313 		ess->rsnciphers |= IEEE80211_CIPHER_TKIP;
314 	if (wpa->i_ciphers & IEEE80211_WPA_CIPHER_CCMP)
315 		ess->rsnciphers |= IEEE80211_CIPHER_CCMP;
316 	if (wpa->i_ciphers & IEEE80211_WPA_CIPHER_USEGROUP)
317 		ess->rsnciphers = IEEE80211_CIPHER_USEGROUP;
318 	if (ess->rsnciphers == 0) { /* set to default (CCMP, TKIP if WPA1) */
319 		ess->rsnciphers = IEEE80211_CIPHER_CCMP;
320 		if (ess->rsnprotos & IEEE80211_PROTO_WPA)
321 			ess->rsnciphers |= IEEE80211_CIPHER_TKIP;
322 	}
323 
324 	ess->flags |= IEEE80211_F_RSNON;
325 
326 	if (ess->rsnakms &
327 	    (IEEE80211_AKM_8021X|IEEE80211_WPA_AKM_SHA256_8021X))
328 		ess->flags |= IEEE80211_JOIN_8021X;
329 
330 	return ENETRESET;
331 }
332 
333 static void
334 ieee80211_ess_clear_wep(struct ieee80211_ess *ess)
335 {
336 	int i;
337 
338 	/* Disable WEP */
339 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
340 		explicit_bzero(&ess->nw_keys[i], sizeof(ess->nw_keys[0]));
341 	}
342 	ess->def_txkey = 0;
343 	ess->flags &= ~IEEE80211_F_WEPON;
344 }
345 
346 static void
347 ieee80211_ess_clear_wpa(struct ieee80211_ess *ess)
348 {
349 	/* Disable WPA */
350 	ess->rsnprotos = ess->rsnakms = ess->rsngroupcipher =
351 	    ess->rsnciphers = 0;
352 	explicit_bzero(ess->psk, sizeof(ess->psk));
353 	ess->flags &= ~(IEEE80211_F_PSK | IEEE80211_F_RSNON);
354 }
355 
356 int
357 ieee80211_add_ess(struct ieee80211com *ic, struct ieee80211_join *join)
358 {
359 	struct ieee80211_ess *ess;
360 	int new = 0, ness = 0;
361 
362 	/* only valid for station (aka, client) mode */
363 	if (ic->ic_opmode != IEEE80211_M_STA)
364 		return (0);
365 
366 	TAILQ_FOREACH(ess, &ic->ic_ess, ess_next) {
367 		if (ess->esslen == join->i_len &&
368 		    memcmp(ess->essid, join->i_nwid, ess->esslen) == 0)
369 			break;
370 		ness++;
371 	}
372 
373 	if (ess == NULL) {
374 		/* if not found, and wpa/wep are set, then return */
375 		if ((join->i_flags & IEEE80211_JOIN_WPA) &&
376 		    (join->i_flags & IEEE80211_JOIN_NWKEY)) {
377 			return (EINVAL);
378 		}
379 		if (ness > IEEE80211_CACHE_SIZE)
380 			return (ERANGE);
381 		new = 1;
382 		ess = malloc(sizeof(*ess), M_DEVBUF, M_NOWAIT|M_ZERO);
383 		if (ess == NULL)
384 			return (ENOMEM);
385 		memcpy(ess->essid, join->i_nwid, join->i_len);
386 		ess->esslen = join->i_len;
387 	}
388 
389 	if (join->i_flags & IEEE80211_JOIN_WPA) {
390 		if (join->i_wpaparams.i_enabled) {
391 			if (!(ic->ic_caps & IEEE80211_C_RSN)) {
392 				free(ess, M_DEVBUF, sizeof(*ess));
393 				return ENODEV;
394 			}
395 			ieee80211_ess_setwpaparms(ess,
396 			    &join->i_wpaparams);
397 			if (join->i_flags & IEEE80211_JOIN_WPAPSK) {
398 				ess->flags |= IEEE80211_F_PSK;
399 				explicit_bzero(ess->psk, sizeof(ess->psk));
400 				memcpy(ess->psk, &join->i_wpapsk.i_psk,
401 				    sizeof(ess->psk));
402 			}
403 			ieee80211_ess_clear_wep(ess);
404 		} else {
405 			ieee80211_ess_clear_wpa(ess);
406 		}
407 	} else if (join->i_flags & IEEE80211_JOIN_NWKEY) {
408 		if (join->i_nwkey.i_wepon) {
409 			if (!(ic->ic_caps & IEEE80211_C_WEP)) {
410 				free(ess, M_DEVBUF, sizeof(*ess));
411 				return ENODEV;
412 			}
413 			ieee80211_ess_setnwkeys(ess, &join->i_nwkey);
414 			ieee80211_ess_clear_wpa(ess);
415 		} else {
416 			ieee80211_ess_clear_wep(ess);
417 		}
418 	}
419 
420 	if (new)
421 		TAILQ_INSERT_TAIL(&ic->ic_ess, ess, ess_next);
422 
423 	return (0);
424 }
425 
426 uint8_t
427 ieee80211_ess_adjust_rssi(struct ieee80211com *ic, struct ieee80211_node *ni)
428 {
429 	uint8_t rssi = ni->ni_rssi;
430 
431 	/*
432 	 * Slightly punish 2 GHz RSSI values since they are usually
433 	 * stronger than 5 GHz RSSI values.
434 	 */
435 	if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) {
436 		if (ic->ic_max_rssi) {
437 			uint8_t p = (5 * ic->ic_max_rssi) / 100;
438 	 		if (rssi >= p)
439 				rssi -= p; /* punish by 5% */
440 		} else  {
441 			if (rssi >= 8)
442 				rssi -= 8; /* punish by 8 dBm */
443 		}
444 	}
445 
446 	return rssi;
447 }
448 
449 int
450 ieee80211_ess_calculate_score(struct ieee80211com *ic,
451     struct ieee80211_node *ni)
452 {
453 	int score = 0;
454 	uint8_t	min_5ghz_rssi;
455 
456 	if (ic->ic_max_rssi)
457 		min_5ghz_rssi = IEEE80211_RSSI_THRES_RATIO_5GHZ;
458 	else
459 		min_5ghz_rssi = (uint8_t)IEEE80211_RSSI_THRES_5GHZ;
460 
461 	/* not using join any */
462 	if (ieee80211_get_ess(ic, ni->ni_essid, ni->ni_esslen))
463 		score += 32;
464 
465 	/* Calculate the crypto score */
466 	if (ni->ni_rsnprotos & IEEE80211_PROTO_RSN)
467 		score += 16;
468 	if (ni->ni_rsnprotos & IEEE80211_PROTO_WPA)
469 		score += 8;
470 	if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
471 		score += 4;
472 
473 	/* 5GHz with a good signal */
474 	if (IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) &&
475 	    ni->ni_rssi > min_5ghz_rssi)
476 		score += 2;
477 
478 	/* Boost this AP if it had no auth/assoc failures in the past. */
479 	if (ni->ni_fails == 0)
480 		score += 21;
481 
482 	return score;
483 }
484 
485 /*
486  * Given two APs, determine the "better" one of the two.
487  * We compute a score based on the following attributes:
488  *
489  *  crypto: wpa2 > wpa1 > wep > open
490  *  band: 5 GHz > 2 GHz provided 5 GHz rssi is above threshold
491  *  rssi: rssi1 > rssi2 as a numeric comparison with a slight
492  *         disadvantage for 2 GHz APs
493  *
494  * Crypto carries most weight, followed by band, followed by rssi.
495  */
496 int
497 ieee80211_ess_is_better(struct ieee80211com *ic,
498     struct ieee80211_node *nicur, struct ieee80211_node *nican)
499 {
500 	struct ifnet		*ifp = &ic->ic_if;
501 	int			 score_cur = 0, score_can = 0;
502 	int			 cur_rssi, can_rssi;
503 
504 	score_cur = ieee80211_ess_calculate_score(ic, nicur);
505 	score_can = ieee80211_ess_calculate_score(ic, nican);
506 
507 	cur_rssi = ieee80211_ess_adjust_rssi(ic, nicur);
508 	can_rssi = ieee80211_ess_adjust_rssi(ic, nican);
509 
510 	if (can_rssi > cur_rssi)
511 		score_can++;
512 
513 	if ((ifp->if_flags & IFF_DEBUG) && (score_can <= score_cur)) {
514 		printf("%s: AP %s ", ifp->if_xname,
515 		    ether_sprintf(nican->ni_bssid));
516 		ieee80211_print_essid(nican->ni_essid, nican->ni_esslen);
517 		printf(" score %d\n", score_can);
518 	}
519 
520 	return score_can > score_cur;
521 }
522 
523 /* Determine whether a candidate AP belongs to a given ESS. */
524 int
525 ieee80211_match_ess(struct ieee80211_ess *ess, struct ieee80211_node *ni)
526 {
527 	if (ess->esslen != 0 &&
528 	    (ess->esslen != ni->ni_esslen ||
529 	    memcmp(ess->essid, ni->ni_essid, ess->esslen) != 0)) {
530 		ni->ni_assoc_fail |= IEEE80211_NODE_ASSOCFAIL_ESSID;
531 		return 0;
532 	}
533 
534 	if (ess->flags & (IEEE80211_F_PSK | IEEE80211_F_RSNON)) {
535 		/* Ensure same WPA version. */
536 		if ((ni->ni_rsnprotos & IEEE80211_PROTO_RSN) &&
537 		    (ess->rsnprotos & IEEE80211_PROTO_RSN) == 0) {
538 			ni->ni_assoc_fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
539 			return 0;
540 		}
541 		if ((ni->ni_rsnprotos & IEEE80211_PROTO_WPA) &&
542 		    (ess->rsnprotos & IEEE80211_PROTO_WPA) == 0) {
543 			ni->ni_assoc_fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
544 			return 0;
545 		}
546 	} else if (ess->flags & IEEE80211_F_WEPON) {
547 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0) {
548 			ni->ni_assoc_fail |= IEEE80211_NODE_ASSOCFAIL_PRIVACY;
549 			return 0;
550 		}
551 	} else {
552 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) != 0) {
553 			ni->ni_assoc_fail |= IEEE80211_NODE_ASSOCFAIL_PRIVACY;
554 			return 0;
555 		}
556 	}
557 
558 	if (ess->esslen == 0 &&
559 	    (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) != 0) {
560 		ni->ni_assoc_fail |= IEEE80211_NODE_ASSOCFAIL_PRIVACY;
561 		return 0;
562 	}
563 
564 	return 1;
565 }
566 
567 void
568 ieee80211_switch_ess(struct ieee80211com *ic)
569 {
570 	struct ifnet		*ifp = &ic->ic_if;
571 	struct ieee80211_ess	*ess, *seless = NULL;
572 	struct ieee80211_node	*ni, *selni = NULL;
573 
574 	if (!ISSET(ifp->if_flags, IFF_RUNNING))
575 		return;
576 
577 	/* Find the best AP matching an entry on our ESS join list. */
578 	RBT_FOREACH(ni, ieee80211_tree, &ic->ic_tree) {
579 		if ((ic->ic_flags & IEEE80211_F_DESBSSID) &&
580 		    !IEEE80211_ADDR_EQ(ic->ic_des_bssid, ni->ni_bssid))
581 			continue;
582 
583 		TAILQ_FOREACH(ess, &ic->ic_ess, ess_next) {
584 			if (ieee80211_match_ess(ess, ni))
585 				break;
586 		}
587 		if (ess == NULL)
588 			continue;
589 
590 		/*
591 		 * Operate only on ic_des_essid if auto-join is disabled.
592 		 * We might have a password stored for this network.
593 		 */
594 		if (!ISSET(ic->ic_flags, IEEE80211_F_AUTO_JOIN)) {
595 			if (ic->ic_des_esslen == ni->ni_esslen &&
596 			    memcmp(ic->ic_des_essid, ni->ni_essid,
597 			    ni->ni_esslen) == 0) {
598 				ieee80211_set_ess(ic, ess, ni);
599 				return;
600 			}
601 			continue;
602 		}
603 
604 		if (selni == NULL) {
605 			seless = ess;
606 			selni = ni;
607 			continue;
608 		}
609 
610 		if (ieee80211_ess_is_better(ic, selni, ni)) {
611 			seless = ess;
612 			selni = ni;
613 		}
614 	}
615 
616 	if (selni && seless && !(selni->ni_esslen == ic->ic_des_esslen &&
617 	    (memcmp(ic->ic_des_essid, selni->ni_essid,
618 	     IEEE80211_NWID_LEN) == 0))) {
619 		if (ifp->if_flags & IFF_DEBUG) {
620 			printf("%s: best AP %s ", ifp->if_xname,
621 			    ether_sprintf(selni->ni_bssid));
622 			ieee80211_print_essid(selni->ni_essid,
623 			    selni->ni_esslen);
624 			printf(" score %d\n",
625 			    ieee80211_ess_calculate_score(ic, selni));
626 			printf("%s: switching to network ", ifp->if_xname);
627 			ieee80211_print_essid(selni->ni_essid,
628 			    selni->ni_esslen);
629 			if (seless->esslen == 0)
630 				printf(" via join any");
631 			printf("\n");
632 
633 		}
634 		ieee80211_set_ess(ic, seless, selni);
635 	}
636 }
637 
638 void
639 ieee80211_set_ess(struct ieee80211com *ic, struct ieee80211_ess *ess,
640     struct ieee80211_node *ni)
641 {
642 	memset(ic->ic_des_essid, 0, IEEE80211_NWID_LEN);
643 	ic->ic_des_esslen = ni->ni_esslen;
644 	memcpy(ic->ic_des_essid, ni->ni_essid, ic->ic_des_esslen);
645 
646 	ieee80211_disable_wep(ic);
647 	ieee80211_disable_rsn(ic);
648 
649 	if (ess->flags & IEEE80211_F_RSNON) {
650 		explicit_bzero(ic->ic_psk, sizeof(ic->ic_psk));
651 		memcpy(ic->ic_psk, ess->psk, sizeof(ic->ic_psk));
652 
653 		ic->ic_rsnprotos = ess->rsnprotos;
654 		ic->ic_rsnakms = ess->rsnakms;
655 		ic->ic_rsngroupcipher = ess->rsngroupcipher;
656 		ic->ic_rsnciphers = ess->rsnciphers;
657 		ic->ic_flags |= IEEE80211_F_RSNON;
658 		if (ess->flags & IEEE80211_F_PSK)
659 			ic->ic_flags |= IEEE80211_F_PSK;
660 	} else if (ess->flags & IEEE80211_F_WEPON) {
661 		struct ieee80211_key	*k;
662 		int			 i;
663 
664 		for (i = 0; i < IEEE80211_WEP_NKID; i++) {
665 			k = &ic->ic_nw_keys[i];
666 			if (k->k_cipher != IEEE80211_CIPHER_NONE)
667 				(*ic->ic_delete_key)(ic, NULL, k);
668 			memcpy(&ic->ic_nw_keys[i], &ess->nw_keys[i],
669 			    sizeof(struct ieee80211_key));
670 			(*ic->ic_set_key)(ic, NULL, k);
671 		}
672 		ic->ic_def_txkey = ess->def_txkey;
673 		ic->ic_flags |= IEEE80211_F_WEPON;
674 	}
675 }
676 
677 void
678 ieee80211_deselect_ess(struct ieee80211com *ic)
679 {
680 	memset(ic->ic_des_essid, 0, IEEE80211_NWID_LEN);
681 	ic->ic_des_esslen = 0;
682 	ieee80211_disable_wep(ic);
683 	ieee80211_disable_rsn(ic);
684 }
685 
686 void
687 ieee80211_node_attach(struct ifnet *ifp)
688 {
689 	struct ieee80211com *ic = (void *)ifp;
690 #ifndef IEEE80211_STA_ONLY
691 	int size;
692 #endif
693 
694 	RBT_INIT(ieee80211_tree, &ic->ic_tree);
695 	ic->ic_node_alloc = ieee80211_node_alloc;
696 	ic->ic_node_free = ieee80211_node_free;
697 	ic->ic_node_copy = ieee80211_node_copy;
698 	ic->ic_node_getrssi = ieee80211_node_getrssi;
699 	ic->ic_node_checkrssi = ieee80211_node_checkrssi;
700 	ic->ic_scangen = 1;
701 	ic->ic_max_nnodes = ieee80211_cache_size;
702 
703 	if (ic->ic_max_aid == 0)
704 		ic->ic_max_aid = IEEE80211_AID_DEF;
705 	else if (ic->ic_max_aid > IEEE80211_AID_MAX)
706 		ic->ic_max_aid = IEEE80211_AID_MAX;
707 #ifndef IEEE80211_STA_ONLY
708 	size = howmany(ic->ic_max_aid, 32) * sizeof(u_int32_t);
709 	ic->ic_aid_bitmap = malloc(size, M_DEVBUF, M_NOWAIT | M_ZERO);
710 	if (ic->ic_aid_bitmap == NULL) {
711 		/* XXX no way to recover */
712 		printf("%s: no memory for AID bitmap!\n", __func__);
713 		ic->ic_max_aid = 0;
714 	}
715 	if (ic->ic_caps & (IEEE80211_C_HOSTAP | IEEE80211_C_IBSS)) {
716 		ic->ic_tim_len = howmany(ic->ic_max_aid, 8);
717 		ic->ic_tim_bitmap = malloc(ic->ic_tim_len, M_DEVBUF,
718 		    M_NOWAIT | M_ZERO);
719 		if (ic->ic_tim_bitmap == NULL) {
720 			printf("%s: no memory for TIM bitmap!\n", __func__);
721 			ic->ic_tim_len = 0;
722 		} else
723 			ic->ic_set_tim = ieee80211_set_tim;
724 		timeout_set(&ic->ic_rsn_timeout,
725 		    ieee80211_gtk_rekey_timeout, ic);
726 		timeout_set(&ic->ic_inact_timeout,
727 		    ieee80211_inact_timeout, ic);
728 		timeout_set(&ic->ic_node_cache_timeout,
729 		    ieee80211_node_cache_timeout, ic);
730 	}
731 #endif
732 	TAILQ_INIT(&ic->ic_ess);
733 }
734 
735 struct ieee80211_node *
736 ieee80211_alloc_node_helper(struct ieee80211com *ic)
737 {
738 	struct ieee80211_node *ni;
739 	if (ic->ic_nnodes >= ic->ic_max_nnodes)
740 		ieee80211_clean_nodes(ic, 0);
741 	if (ic->ic_nnodes >= ic->ic_max_nnodes)
742 		return NULL;
743 	ni = (*ic->ic_node_alloc)(ic);
744 	return ni;
745 }
746 
747 void
748 ieee80211_node_lateattach(struct ifnet *ifp)
749 {
750 	struct ieee80211com *ic = (void *)ifp;
751 	struct ieee80211_node *ni;
752 
753 	ni = ieee80211_alloc_node_helper(ic);
754 	if (ni == NULL)
755 		panic("unable to setup initial BSS node");
756 	ni->ni_chan = IEEE80211_CHAN_ANYC;
757 	ic->ic_bss = ieee80211_ref_node(ni);
758 	ic->ic_txpower = IEEE80211_TXPOWER_MAX;
759 #ifndef IEEE80211_STA_ONLY
760 	mq_init(&ni->ni_savedq, IEEE80211_PS_MAX_QUEUE, IPL_NET);
761 #endif
762 }
763 
764 void
765 ieee80211_node_detach(struct ifnet *ifp)
766 {
767 	struct ieee80211com *ic = (void *)ifp;
768 
769 	if (ic->ic_bss != NULL) {
770 		(*ic->ic_node_free)(ic, ic->ic_bss);
771 		ic->ic_bss = NULL;
772 	}
773 	ieee80211_del_ess(ic, NULL, 0, 1);
774 	ieee80211_free_allnodes(ic, 1);
775 #ifndef IEEE80211_STA_ONLY
776 	free(ic->ic_aid_bitmap, M_DEVBUF,
777 	    howmany(ic->ic_max_aid, 32) * sizeof(u_int32_t));
778 	free(ic->ic_tim_bitmap, M_DEVBUF, ic->ic_tim_len);
779 	timeout_del(&ic->ic_inact_timeout);
780 	timeout_del(&ic->ic_node_cache_timeout);
781 	timeout_del(&ic->ic_tkip_micfail_timeout);
782 #endif
783 	timeout_del(&ic->ic_rsn_timeout);
784 }
785 
786 /*
787  * AP scanning support.
788  */
789 
790 /*
791  * Initialize the active channel set based on the set
792  * of available channels and the current PHY mode.
793  */
794 void
795 ieee80211_reset_scan(struct ifnet *ifp)
796 {
797 	struct ieee80211com *ic = (void *)ifp;
798 
799 	memcpy(ic->ic_chan_scan, ic->ic_chan_active,
800 		sizeof(ic->ic_chan_active));
801 	/* NB: hack, setup so next_scan starts with the first channel */
802 	if (ic->ic_bss != NULL && ic->ic_bss->ni_chan == IEEE80211_CHAN_ANYC)
803 		ic->ic_bss->ni_chan = &ic->ic_channels[IEEE80211_CHAN_MAX];
804 }
805 
806 /*
807  * Increase a node's inactivity counter.
808  * This counter get reset to zero if a frame is received.
809  * This function is intended for station mode only.
810  * See ieee80211_node_cache_timeout() for hostap mode.
811  */
812 void
813 ieee80211_node_raise_inact(void *arg, struct ieee80211_node *ni)
814 {
815 	if (ni->ni_refcnt == 0 && ni->ni_inact < IEEE80211_INACT_SCAN)
816 		ni->ni_inact++;
817 }
818 
819 /*
820  * Begin an active scan.
821  */
822 void
823 ieee80211_begin_scan(struct ifnet *ifp)
824 {
825 	struct ieee80211com *ic = (void *)ifp;
826 
827 	/*
828 	 * In all but hostap mode scanning starts off in
829 	 * an active mode before switching to passive.
830 	 */
831 #ifndef IEEE80211_STA_ONLY
832 	if (ic->ic_opmode != IEEE80211_M_HOSTAP)
833 #endif
834 	{
835 		ic->ic_flags |= IEEE80211_F_ASCAN;
836 		ic->ic_stats.is_scan_active++;
837 	}
838 #ifndef IEEE80211_STA_ONLY
839 	else
840 		ic->ic_stats.is_scan_passive++;
841 #endif
842 	if (ifp->if_flags & IFF_DEBUG)
843 		printf("%s: begin %s scan\n", ifp->if_xname,
844 			(ic->ic_flags & IEEE80211_F_ASCAN) ?
845 				"active" : "passive");
846 
847 
848 	if (ic->ic_opmode == IEEE80211_M_STA) {
849 		ieee80211_node_cleanup(ic, ic->ic_bss);
850 		ieee80211_iterate_nodes(ic, ieee80211_node_raise_inact, NULL);
851 	}
852 
853 	/*
854 	 * Reset the current mode. Setting the current mode will also
855 	 * reset scan state.
856 	 */
857 	if (IFM_MODE(ic->ic_media.ifm_cur->ifm_media) == IFM_AUTO)
858 		ic->ic_curmode = IEEE80211_MODE_AUTO;
859 	ieee80211_setmode(ic, ic->ic_curmode);
860 
861 	ic->ic_scan_count = 0;
862 
863 	/* Scan the next channel. */
864 	ieee80211_next_scan(ifp);
865 }
866 
867 /*
868  * Switch to the next channel marked for scanning.
869  */
870 void
871 ieee80211_next_scan(struct ifnet *ifp)
872 {
873 	struct ieee80211com *ic = (void *)ifp;
874 	struct ieee80211_channel *chan;
875 
876 	chan = ic->ic_bss->ni_chan;
877 	for (;;) {
878 		if (++chan > &ic->ic_channels[IEEE80211_CHAN_MAX])
879 			chan = &ic->ic_channels[0];
880 		if (isset(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan))) {
881 			/*
882 			 * Ignore channels marked passive-only
883 			 * during an active scan.
884 			 */
885 			if ((ic->ic_flags & IEEE80211_F_ASCAN) == 0 ||
886 			    (chan->ic_flags & IEEE80211_CHAN_PASSIVE) == 0)
887 				break;
888 		}
889 		if (chan == ic->ic_bss->ni_chan) {
890 			ieee80211_end_scan(ifp);
891 			return;
892 		}
893 	}
894 	clrbit(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan));
895 	DPRINTF(("chan %d->%d\n",
896 	    ieee80211_chan2ieee(ic, ic->ic_bss->ni_chan),
897 	    ieee80211_chan2ieee(ic, chan)));
898 	ic->ic_bss->ni_chan = chan;
899 	ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
900 }
901 
902 #ifndef IEEE80211_STA_ONLY
903 void
904 ieee80211_create_ibss(struct ieee80211com* ic, struct ieee80211_channel *chan)
905 {
906 	enum ieee80211_phymode mode;
907 	struct ieee80211_node *ni;
908 	struct ifnet *ifp = &ic->ic_if;
909 
910 	ni = ic->ic_bss;
911 	if (ifp->if_flags & IFF_DEBUG)
912 		printf("%s: creating ibss\n", ifp->if_xname);
913 	ic->ic_flags |= IEEE80211_F_SIBSS;
914 	ni->ni_chan = chan;
915 	if ((ic->ic_flags & IEEE80211_F_VHTON) && IEEE80211_IS_CHAN_5GHZ(chan))
916 		mode = IEEE80211_MODE_11AC;
917 	else if (ic->ic_flags & IEEE80211_F_HTON)
918 		mode = IEEE80211_MODE_11N;
919 	else
920 		mode = ieee80211_chan2mode(ic, ni->ni_chan);
921 	ieee80211_setmode(ic, mode);
922 	/* Pick an appropriate mode for supported legacy rates. */
923 	if (ic->ic_curmode == IEEE80211_MODE_11AC) {
924 		mode = IEEE80211_MODE_11A;
925 	} else if (ic->ic_curmode == IEEE80211_MODE_11N) {
926 		if (IEEE80211_IS_CHAN_5GHZ(chan))
927 			mode = IEEE80211_MODE_11A;
928 		else
929 			mode = IEEE80211_MODE_11G;
930 	} else {
931 		mode = ic->ic_curmode;
932 	}
933 	ni->ni_rates = ic->ic_sup_rates[mode];
934 	ni->ni_txrate = 0;
935 	IEEE80211_ADDR_COPY(ni->ni_macaddr, ic->ic_myaddr);
936 	IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_myaddr);
937 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
938 		if ((ic->ic_flags & IEEE80211_F_DESBSSID) != 0)
939 			IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_des_bssid);
940 		else
941 			ni->ni_bssid[0] |= 0x02;	/* local bit for IBSS */
942 	}
943 	ni->ni_esslen = ic->ic_des_esslen;
944 	memcpy(ni->ni_essid, ic->ic_des_essid, ni->ni_esslen);
945 	ni->ni_rssi = 0;
946 	ni->ni_rstamp = 0;
947 	memset(ni->ni_tstamp, 0, sizeof(ni->ni_tstamp));
948 	ni->ni_intval = ic->ic_lintval;
949 	ni->ni_capinfo = IEEE80211_CAPINFO_IBSS;
950 	if (ic->ic_flags & IEEE80211_F_WEPON)
951 		ni->ni_capinfo |= IEEE80211_CAPINFO_PRIVACY;
952 	if (ic->ic_flags & IEEE80211_F_HTON) {
953 		const struct ieee80211_edca_ac_params *ac_qap;
954 		struct ieee80211_edca_ac_params *ac;
955 		int aci;
956 
957 		/*
958 		 * Configure HT protection. This will be updated later
959 		 * based on the number of non-HT nodes in the node cache.
960 		 */
961 		ic->ic_protmode = IEEE80211_PROT_NONE;
962 		ni->ni_htop1 = IEEE80211_HTPROT_NONE;
963 		/* Disallow Greenfield mode. None of our drivers support it. */
964 		ni->ni_htop1 |= IEEE80211_HTOP1_NONGF_STA;
965 		if (ic->ic_update_htprot)
966 			ic->ic_update_htprot(ic, ni);
967 
968 		/* Configure QoS EDCA parameters. */
969 		for (aci = 0; aci < EDCA_NUM_AC; aci++) {
970 			ac = &ic->ic_edca_ac[aci];
971 			ac_qap = &ieee80211_qap_edca_table[ic->ic_curmode][aci];
972 			ac->ac_acm       = ac_qap->ac_acm;
973 			ac->ac_aifsn     = ac_qap->ac_aifsn;
974 			ac->ac_ecwmin    = ac_qap->ac_ecwmin;
975 			ac->ac_ecwmax    = ac_qap->ac_ecwmax;
976 			ac->ac_txoplimit = ac_qap->ac_txoplimit;
977 		}
978 		if (ic->ic_updateedca)
979 			(*ic->ic_updateedca)(ic);
980 	}
981 	if (ic->ic_flags & IEEE80211_F_RSNON) {
982 		struct ieee80211_key *k;
983 
984 		/* initialize 256-bit global key counter to a random value */
985 		arc4random_buf(ic->ic_globalcnt, EAPOL_KEY_NONCE_LEN);
986 
987 		ni->ni_rsnprotos = ic->ic_rsnprotos;
988 		ni->ni_rsnakms = ic->ic_rsnakms;
989 		ni->ni_rsnciphers = ic->ic_rsnciphers;
990 		ni->ni_rsngroupcipher = ic->ic_rsngroupcipher;
991 		ni->ni_rsngroupmgmtcipher = ic->ic_rsngroupmgmtcipher;
992 		ni->ni_rsncaps = 0;
993 		if (ic->ic_caps & IEEE80211_C_MFP) {
994 			ni->ni_rsncaps |= IEEE80211_RSNCAP_MFPC;
995 			if (ic->ic_flags & IEEE80211_F_MFPR)
996 				ni->ni_rsncaps |= IEEE80211_RSNCAP_MFPR;
997 		}
998 
999 		ic->ic_def_txkey = 1;
1000 		ic->ic_flags &= ~IEEE80211_F_COUNTERM;
1001 		k = &ic->ic_nw_keys[ic->ic_def_txkey];
1002 		memset(k, 0, sizeof(*k));
1003 		k->k_id = ic->ic_def_txkey;
1004 		k->k_cipher = ni->ni_rsngroupcipher;
1005 		k->k_flags = IEEE80211_KEY_GROUP | IEEE80211_KEY_TX;
1006 		k->k_len = ieee80211_cipher_keylen(k->k_cipher);
1007 		arc4random_buf(k->k_key, k->k_len);
1008 		(*ic->ic_set_key)(ic, ni, k);	/* XXX */
1009 
1010 		if (ic->ic_caps & IEEE80211_C_MFP) {
1011 			ic->ic_igtk_kid = 4;
1012 			k = &ic->ic_nw_keys[ic->ic_igtk_kid];
1013 			memset(k, 0, sizeof(*k));
1014 			k->k_id = ic->ic_igtk_kid;
1015 			k->k_cipher = ni->ni_rsngroupmgmtcipher;
1016 			k->k_flags = IEEE80211_KEY_IGTK | IEEE80211_KEY_TX;
1017 			k->k_len = 16;
1018 			arc4random_buf(k->k_key, k->k_len);
1019 			(*ic->ic_set_key)(ic, ni, k);	/* XXX */
1020 		}
1021 		/*
1022 		 * In HostAP mode, multicast traffic is sent using ic_bss
1023 		 * as the Tx node, so mark our node as valid so we can send
1024 		 * multicast frames using the group key we've just configured.
1025 		 */
1026 		ni->ni_port_valid = 1;
1027 		ni->ni_flags |= IEEE80211_NODE_TXPROT;
1028 
1029 		/* schedule a GTK/IGTK rekeying after 3600s */
1030 		timeout_add_sec(&ic->ic_rsn_timeout, 3600);
1031 	}
1032 	timeout_add_sec(&ic->ic_inact_timeout, IEEE80211_INACT_WAIT);
1033 	timeout_add_sec(&ic->ic_node_cache_timeout, IEEE80211_CACHE_WAIT);
1034 	ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
1035 }
1036 #endif	/* IEEE80211_STA_ONLY */
1037 
1038 int
1039 ieee80211_match_bss(struct ieee80211com *ic, struct ieee80211_node *ni,
1040     int bgscan)
1041 {
1042 	u_int8_t rate;
1043 	int fail;
1044 
1045 	fail = 0;
1046 	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
1047 		fail |= IEEE80211_NODE_ASSOCFAIL_CHAN;
1048 	if (ic->ic_des_chan != IEEE80211_CHAN_ANYC &&
1049 	    ni->ni_chan != ic->ic_des_chan)
1050 		fail |= IEEE80211_NODE_ASSOCFAIL_CHAN;
1051 #ifndef IEEE80211_STA_ONLY
1052 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
1053 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
1054 			fail |= IEEE80211_NODE_ASSOCFAIL_IBSS;
1055 	} else
1056 #endif
1057 	{
1058 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
1059 			fail |= IEEE80211_NODE_ASSOCFAIL_IBSS;
1060 	}
1061 	if (ic->ic_flags & (IEEE80211_F_WEPON | IEEE80211_F_RSNON)) {
1062 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
1063 			fail |= IEEE80211_NODE_ASSOCFAIL_PRIVACY;
1064 	} else {
1065 		if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
1066 			fail |= IEEE80211_NODE_ASSOCFAIL_PRIVACY;
1067 	}
1068 
1069 	rate = ieee80211_fix_rate(ic, ni, IEEE80211_F_DONEGO);
1070 	if (rate & IEEE80211_RATE_BASIC)
1071 		fail |= IEEE80211_NODE_ASSOCFAIL_BASIC_RATE;
1072 	if (ic->ic_des_esslen == 0)
1073 		fail |= IEEE80211_NODE_ASSOCFAIL_ESSID;
1074 	if (ic->ic_des_esslen != 0 &&
1075 	    (ni->ni_esslen != ic->ic_des_esslen ||
1076 	     memcmp(ni->ni_essid, ic->ic_des_essid, ic->ic_des_esslen) != 0))
1077 		fail |= IEEE80211_NODE_ASSOCFAIL_ESSID;
1078 	if ((ic->ic_flags & IEEE80211_F_DESBSSID) &&
1079 	    !IEEE80211_ADDR_EQ(ic->ic_des_bssid, ni->ni_bssid))
1080 		fail |= IEEE80211_NODE_ASSOCFAIL_BSSID;
1081 
1082 	if (ic->ic_flags & IEEE80211_F_RSNON) {
1083 		/*
1084 		 * If at least one RSN IE field from the AP's RSN IE fails
1085 		 * to overlap with any value the STA supports, the STA shall
1086 		 * decline to associate with that AP.
1087 		 */
1088 		if ((ni->ni_rsnprotos & ic->ic_rsnprotos) == 0)
1089 			fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
1090 		if ((ni->ni_rsnakms & ic->ic_rsnakms) == 0)
1091 			fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
1092 		if ((ni->ni_rsnakms & ic->ic_rsnakms &
1093 		     ~(IEEE80211_AKM_PSK | IEEE80211_AKM_SHA256_PSK)) == 0) {
1094 			/* AP only supports PSK AKMPs */
1095 			if (!(ic->ic_flags & IEEE80211_F_PSK))
1096 				fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
1097 		}
1098 		if (ni->ni_rsngroupcipher != IEEE80211_CIPHER_WEP40 &&
1099 		    ni->ni_rsngroupcipher != IEEE80211_CIPHER_TKIP &&
1100 		    ni->ni_rsngroupcipher != IEEE80211_CIPHER_CCMP &&
1101 		    ni->ni_rsngroupcipher != IEEE80211_CIPHER_WEP104)
1102 			fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
1103 		if ((ni->ni_rsnciphers & ic->ic_rsnciphers) == 0)
1104 			fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
1105 
1106 		/* we only support BIP as the IGTK cipher */
1107 		if ((ni->ni_rsncaps & IEEE80211_RSNCAP_MFPC) &&
1108 		    ni->ni_rsngroupmgmtcipher != IEEE80211_CIPHER_BIP)
1109 			fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
1110 
1111 		/* we do not support MFP but AP requires it */
1112 		if (!(ic->ic_caps & IEEE80211_C_MFP) &&
1113 		    (ni->ni_rsncaps & IEEE80211_RSNCAP_MFPR))
1114 			fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
1115 
1116 		/* we require MFP but AP does not support it */
1117 		if ((ic->ic_caps & IEEE80211_C_MFP) &&
1118 		    (ic->ic_flags & IEEE80211_F_MFPR) &&
1119 		    !(ni->ni_rsncaps & IEEE80211_RSNCAP_MFPC))
1120 			fail |= IEEE80211_NODE_ASSOCFAIL_WPA_PROTO;
1121 	}
1122 
1123 	if (ic->ic_if.if_flags & IFF_DEBUG) {
1124 		printf("%s: %c %s%c", ic->ic_if.if_xname, fail ? '-' : '+',
1125 		    ether_sprintf(ni->ni_bssid),
1126 		    fail & IEEE80211_NODE_ASSOCFAIL_BSSID ? '!' : ' ');
1127 		printf(" %3d%c", ieee80211_chan2ieee(ic, ni->ni_chan),
1128 			fail & IEEE80211_NODE_ASSOCFAIL_CHAN ? '!' : ' ');
1129 		printf(" %+4d", ni->ni_rssi);
1130 		printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
1131 		    fail & IEEE80211_NODE_ASSOCFAIL_BASIC_RATE ? '!' : ' ');
1132 		printf(" %4s%c",
1133 		    (ni->ni_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
1134 		    (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
1135 		    "????",
1136 		    fail & IEEE80211_NODE_ASSOCFAIL_IBSS ? '!' : ' ');
1137 		printf(" %7s%c ",
1138 		    (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) ?
1139 		    "privacy" : "no",
1140 		    fail & IEEE80211_NODE_ASSOCFAIL_PRIVACY ? '!' : ' ');
1141 		printf(" %3s%c ",
1142 		    (ic->ic_flags & IEEE80211_F_RSNON) ?
1143 		    "rsn" : "no",
1144 		    fail & IEEE80211_NODE_ASSOCFAIL_WPA_PROTO ? '!' : ' ');
1145 		ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
1146 		printf("%s\n",
1147 		    fail & IEEE80211_NODE_ASSOCFAIL_ESSID ? "!" : "");
1148 	}
1149 
1150 	/* We don't care about unrelated networks during background scans. */
1151 	if (bgscan) {
1152 		if ((fail & IEEE80211_NODE_ASSOCFAIL_ESSID) == 0)
1153 			ni->ni_assoc_fail = fail;
1154 	} else
1155 		ni->ni_assoc_fail = fail;
1156 	if ((fail & IEEE80211_NODE_ASSOCFAIL_ESSID) == 0)
1157 		ic->ic_bss->ni_assoc_fail = ni->ni_assoc_fail;
1158 
1159 	return fail;
1160 }
1161 
1162 struct ieee80211_node_switch_bss_arg {
1163 	u_int8_t cur_macaddr[IEEE80211_ADDR_LEN];
1164 	u_int8_t sel_macaddr[IEEE80211_ADDR_LEN];
1165 };
1166 
1167 /* Implements ni->ni_unref_cb(). */
1168 void
1169 ieee80211_node_switch_bss(struct ieee80211com *ic, struct ieee80211_node *ni)
1170 {
1171 	struct ifnet *ifp = &ic->ic_if;
1172 	struct ieee80211_node_switch_bss_arg *sba = ni->ni_unref_arg;
1173 	struct ieee80211_node *curbs, *selbs;
1174 
1175 	splassert(IPL_NET);
1176 
1177 	if ((ic->ic_flags & IEEE80211_F_BGSCAN) == 0) {
1178 		free(sba, M_DEVBUF, sizeof(*sba));
1179 		return;
1180 	}
1181 
1182 	ic->ic_xflags &= ~IEEE80211_F_TX_MGMT_ONLY;
1183 
1184 	selbs = ieee80211_find_node(ic, sba->sel_macaddr);
1185 	if (selbs == NULL) {
1186 		free(sba, M_DEVBUF, sizeof(*sba));
1187 		ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1188 		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
1189 		return;
1190 	}
1191 
1192 	curbs = ieee80211_find_node(ic, sba->cur_macaddr);
1193 	if (curbs == NULL) {
1194 		free(sba, M_DEVBUF, sizeof(*sba));
1195 		ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1196 		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
1197 		return;
1198 	}
1199 
1200 	if (ifp->if_flags & IFF_DEBUG) {
1201 		printf("%s: roaming from %s chan %d ",
1202 		    ifp->if_xname, ether_sprintf(curbs->ni_macaddr),
1203 		    ieee80211_chan2ieee(ic, curbs->ni_chan));
1204 		printf("to %s chan %d\n", ether_sprintf(selbs->ni_macaddr),
1205 		    ieee80211_chan2ieee(ic, selbs->ni_chan));
1206 	}
1207 	ieee80211_node_newstate(curbs, IEEE80211_STA_CACHE);
1208 	ieee80211_node_join_bss(ic, selbs); /* frees arg and ic->ic_bss */
1209 }
1210 
1211 void
1212 ieee80211_node_join_bss(struct ieee80211com *ic, struct ieee80211_node *selbs)
1213 {
1214 	enum ieee80211_phymode mode;
1215 	struct ieee80211_node *ni;
1216 	uint32_t assoc_fail = 0;
1217 
1218 	/* Reinitialize media mode and channels if needed. */
1219 	mode = ieee80211_chan2mode(ic, selbs->ni_chan);
1220 	if (mode != ic->ic_curmode)
1221 		ieee80211_setmode(ic, mode);
1222 
1223 	/* Keep recorded association failures for this BSS/ESS intact. */
1224 	if (IEEE80211_ADDR_EQ(ic->ic_bss->ni_macaddr, selbs->ni_macaddr) ||
1225 	    (ic->ic_des_esslen > 0 && ic->ic_des_esslen == selbs->ni_esslen &&
1226 	    memcmp(ic->ic_des_essid, selbs->ni_essid, selbs->ni_esslen) == 0))
1227 		assoc_fail = ic->ic_bss->ni_assoc_fail;
1228 
1229 	(*ic->ic_node_copy)(ic, ic->ic_bss, selbs);
1230 	ni = ic->ic_bss;
1231 	ni->ni_assoc_fail |= assoc_fail;
1232 
1233 	ic->ic_curmode = ieee80211_chan2mode(ic, ni->ni_chan);
1234 
1235 	/* Make sure we send valid rates in an association request. */
1236 	if (ic->ic_opmode == IEEE80211_M_STA)
1237 		ieee80211_fix_rate(ic, ni,
1238 		    IEEE80211_F_DOSORT | IEEE80211_F_DOFRATE |
1239 		    IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
1240 
1241 	if (ic->ic_flags & IEEE80211_F_RSNON)
1242 		ieee80211_choose_rsnparams(ic);
1243 	else if (ic->ic_flags & IEEE80211_F_WEPON)
1244 		ni->ni_rsncipher = IEEE80211_CIPHER_USEGROUP;
1245 
1246 	ieee80211_node_newstate(selbs, IEEE80211_STA_BSS);
1247 #ifndef IEEE80211_STA_ONLY
1248 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
1249 		ieee80211_fix_rate(ic, ni, IEEE80211_F_DOFRATE |
1250 		    IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
1251 		if (ni->ni_rates.rs_nrates == 0) {
1252 			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
1253 			return;
1254 		}
1255 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
1256 	} else
1257 #endif
1258 	{
1259 		int bgscan = ((ic->ic_flags & IEEE80211_F_BGSCAN) &&
1260 		    ic->ic_opmode == IEEE80211_M_STA &&
1261 		    ic->ic_state == IEEE80211_S_RUN);
1262 		int auth_next = (ic->ic_opmode == IEEE80211_M_STA &&
1263 		    ic->ic_state == IEEE80211_S_AUTH);
1264 		int mgt = -1;
1265 
1266 		timeout_del(&ic->ic_bgscan_timeout);
1267 		ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1268 
1269 		/*
1270 		 * After a background scan, we have now switched APs.
1271 		 * Pretend we were just de-authed, which makes
1272 		 * ieee80211_new_state() try to re-auth and thus send
1273 		 * an AUTH frame to our newly selected AP.
1274 		 */
1275 		if (bgscan)
1276 			mgt = IEEE80211_FC0_SUBTYPE_DEAUTH;
1277 		/*
1278 		 * If we are trying another AP after the previous one
1279 		 * failed (state transition AUTH->AUTH), ensure that
1280 		 * ieee80211_new_state() tries to send another auth frame.
1281 		 */
1282 		else if (auth_next)
1283 			mgt = IEEE80211_FC0_SUBTYPE_AUTH;
1284 
1285 		ieee80211_new_state(ic, IEEE80211_S_AUTH, mgt);
1286 	}
1287 }
1288 
1289 struct ieee80211_node *
1290 ieee80211_node_choose_bss(struct ieee80211com *ic, int bgscan,
1291     struct ieee80211_node **curbs)
1292 {
1293 	struct ieee80211_node *ni, *nextbs, *selbs = NULL,
1294 	    *selbs2 = NULL, *selbs5 = NULL;
1295 	uint8_t min_5ghz_rssi;
1296 
1297 	ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
1298 
1299 	for (; ni != NULL; ni = nextbs) {
1300 		nextbs = RBT_NEXT(ieee80211_tree, ni);
1301 		if (ni->ni_fails) {
1302 			/*
1303 			 * The configuration of the access points may change
1304 			 * during my scan.  So delete the entry for the AP
1305 			 * and retry to associate if there is another beacon.
1306 			 */
1307 			if (ni->ni_fails++ > 2)
1308 				ieee80211_free_node(ic, ni);
1309 			continue;
1310 		}
1311 
1312 		if (curbs && ieee80211_node_cmp(ic->ic_bss, ni) == 0)
1313 			*curbs = ni;
1314 
1315 		if (ieee80211_match_bss(ic, ni, bgscan) != 0)
1316 			continue;
1317 
1318 		if (ic->ic_caps & IEEE80211_C_SCANALLBAND) {
1319 			if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan) &&
1320 			    (selbs2 == NULL || ni->ni_rssi > selbs2->ni_rssi))
1321 				selbs2 = ni;
1322 			else if (IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) &&
1323 			    (selbs5 == NULL || ni->ni_rssi > selbs5->ni_rssi))
1324 				selbs5 = ni;
1325 		} else if (selbs == NULL || ni->ni_rssi > selbs->ni_rssi)
1326 			selbs = ni;
1327 	}
1328 
1329 	if (ic->ic_max_rssi)
1330 		min_5ghz_rssi = IEEE80211_RSSI_THRES_RATIO_5GHZ;
1331 	else
1332 		min_5ghz_rssi = (uint8_t)IEEE80211_RSSI_THRES_5GHZ;
1333 
1334 	/*
1335 	 * Prefer a 5Ghz AP even if its RSSI is weaker than the best 2Ghz AP
1336 	 * (as long as it meets the minimum RSSI threshold) since the 5Ghz band
1337 	 * is usually less saturated.
1338 	 */
1339 	if (selbs5 && selbs5->ni_rssi > min_5ghz_rssi)
1340 		selbs = selbs5;
1341 	else if (selbs5 && selbs2)
1342 		selbs = (selbs5->ni_rssi >= selbs2->ni_rssi ? selbs5 : selbs2);
1343 	else if (selbs2)
1344 		selbs = selbs2;
1345 	else if (selbs5)
1346 		selbs = selbs5;
1347 
1348 	return selbs;
1349 }
1350 
1351 /*
1352  * Complete a scan of potential channels.
1353  */
1354 void
1355 ieee80211_end_scan(struct ifnet *ifp)
1356 {
1357 	struct ieee80211com *ic = (void *)ifp;
1358 	struct ieee80211_node *ni, *selbs = NULL, *curbs = NULL;
1359 	int bgscan = ((ic->ic_flags & IEEE80211_F_BGSCAN) &&
1360 	    ic->ic_opmode == IEEE80211_M_STA &&
1361 	    ic->ic_state == IEEE80211_S_RUN);
1362 
1363 	if (ifp->if_flags & IFF_DEBUG)
1364 		printf("%s: end %s scan\n", ifp->if_xname,
1365 		    bgscan ? "background" :
1366 		    ((ic->ic_flags & IEEE80211_F_ASCAN) ?
1367 		    "active" : "passive"));
1368 
1369 	if (ic->ic_scan_count)
1370 		ic->ic_flags &= ~IEEE80211_F_ASCAN;
1371 
1372 	if (ic->ic_opmode == IEEE80211_M_STA)
1373 		ieee80211_clean_inactive_nodes(ic, IEEE80211_INACT_SCAN);
1374 
1375 	ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
1376 
1377 #ifndef IEEE80211_STA_ONLY
1378 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
1379 		/* XXX off stack? */
1380 		u_char occupied[howmany(IEEE80211_CHAN_MAX, NBBY)];
1381 		int i, fail;
1382 
1383 		/*
1384 		 * The passive scan to look for existing AP's completed,
1385 		 * select a channel to camp on.  Identify the channels
1386 		 * that already have one or more AP's and try to locate
1387 		 * an unoccupied one.  If that fails, pick a random
1388 		 * channel from the active set.
1389 		 */
1390 		memset(occupied, 0, sizeof(occupied));
1391 		RBT_FOREACH(ni, ieee80211_tree, &ic->ic_tree)
1392 			setbit(occupied, ieee80211_chan2ieee(ic, ni->ni_chan));
1393 		for (i = 0; i < IEEE80211_CHAN_MAX; i++)
1394 			if (isset(ic->ic_chan_active, i) && isclr(occupied, i))
1395 				break;
1396 		if (i == IEEE80211_CHAN_MAX) {
1397 			fail = arc4random() & 3;	/* random 0-3 */
1398 			for (i = 0; i < IEEE80211_CHAN_MAX; i++)
1399 				if (isset(ic->ic_chan_active, i) && fail-- == 0)
1400 					break;
1401 		}
1402 		ieee80211_create_ibss(ic, &ic->ic_channels[i]);
1403 		return;
1404 	}
1405 #endif
1406 	if (ni == NULL) {
1407 		DPRINTF(("no scan candidate\n"));
1408  notfound:
1409 
1410 #ifndef IEEE80211_STA_ONLY
1411 		if (ic->ic_opmode == IEEE80211_M_IBSS &&
1412 		    (ic->ic_flags & IEEE80211_F_IBSSON) &&
1413 		    ic->ic_des_esslen != 0) {
1414 			ieee80211_create_ibss(ic, ic->ic_ibss_chan);
1415 			return;
1416 		}
1417 #endif
1418 		/*
1419 		 * Reset the list of channels to scan and scan the next mode
1420 		 * if nothing has been found.
1421 		 * If the device scans all bands in one fell swoop, return
1422 		 * current scan results to userspace regardless of mode.
1423 		 * This will loop forever until an access point is found.
1424 		 */
1425 		ieee80211_reset_scan(ifp);
1426 		if (ieee80211_next_mode(ifp) == IEEE80211_MODE_AUTO ||
1427 		    (ic->ic_caps & IEEE80211_C_SCANALLBAND))
1428 			ic->ic_scan_count++;
1429 
1430 		ieee80211_next_scan(ifp);
1431 		return;
1432 	}
1433 
1434 	/* Possibly switch which ssid we are associated with */
1435 	if (!bgscan && ic->ic_opmode == IEEE80211_M_STA)
1436 		ieee80211_switch_ess(ic);
1437 
1438 	selbs = ieee80211_node_choose_bss(ic, bgscan, &curbs);
1439 	if (bgscan) {
1440 		struct ieee80211_node_switch_bss_arg *arg;
1441 
1442 		/* AP disappeared? Should not happen. */
1443 		if (selbs == NULL || curbs == NULL) {
1444 			ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1445 			goto notfound;
1446 		}
1447 
1448 		/*
1449 		 * After a background scan we might end up choosing the
1450 		 * same AP again. Or the newly selected AP's RSSI level
1451 		 * might be low enough to trigger another background scan.
1452 		 * Do not change ic->ic_bss in these cases and make
1453 		 * background scans less frequent.
1454 		 */
1455 		if (selbs == curbs || !(*ic->ic_node_checkrssi)(ic, selbs)) {
1456 			if (ic->ic_bgscan_fail < IEEE80211_BGSCAN_FAIL_MAX) {
1457 				if (ic->ic_bgscan_fail <= 0)
1458 					ic->ic_bgscan_fail = 1;
1459 				else
1460 					ic->ic_bgscan_fail *= 2;
1461 			}
1462 			ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1463 
1464 			/*
1465 			 * HT is negotiated during association so we must use
1466 			 * ic_bss to check HT. The nodes tree was re-populated
1467 			 * during background scan and therefore selbs and curbs
1468 			 * may not carry HT information.
1469 			 */
1470 			ni = ic->ic_bss;
1471 			if (ni->ni_flags & IEEE80211_NODE_VHT)
1472 				ieee80211_setmode(ic, IEEE80211_MODE_11AC);
1473 			else if (ni->ni_flags & IEEE80211_NODE_HT)
1474 				ieee80211_setmode(ic, IEEE80211_MODE_11N);
1475 			else
1476 				ieee80211_setmode(ic,
1477 				    ieee80211_chan2mode(ic, ni->ni_chan));
1478 			return;
1479 		}
1480 
1481 		arg = malloc(sizeof(*arg), M_DEVBUF, M_NOWAIT | M_ZERO);
1482 		if (arg == NULL) {
1483 			ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1484 			return;
1485 		}
1486 
1487 		ic->ic_bgscan_fail = 0;
1488 
1489 		/*
1490 		 * We are going to switch APs. Stop A-MPDU Tx and
1491 		 * queue a de-auth frame addressed to our current AP.
1492 		 */
1493 		 ieee80211_stop_ampdu_tx(ic, ic->ic_bss,
1494 		    IEEE80211_FC0_SUBTYPE_DEAUTH);
1495 		if (IEEE80211_SEND_MGMT(ic, ic->ic_bss,
1496 		    IEEE80211_FC0_SUBTYPE_DEAUTH,
1497 		    IEEE80211_REASON_AUTH_LEAVE) != 0) {
1498 			ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1499 			free(arg, M_DEVBUF, sizeof(*arg));
1500 			return;
1501 		}
1502 
1503 		/* Prevent dispatch of additional data frames to hardware. */
1504 		ic->ic_xflags |= IEEE80211_F_TX_MGMT_ONLY;
1505 
1506 		/*
1507 		 * Install a callback which will switch us to the new AP once
1508 		 * all dispatched frames have been processed by hardware.
1509 		 */
1510 		IEEE80211_ADDR_COPY(arg->cur_macaddr, curbs->ni_macaddr);
1511 		IEEE80211_ADDR_COPY(arg->sel_macaddr, selbs->ni_macaddr);
1512 		ic->ic_bss->ni_unref_arg = arg;
1513 		ic->ic_bss->ni_unref_arg_size = sizeof(*arg);
1514 		ic->ic_bss->ni_unref_cb = ieee80211_node_switch_bss;
1515 		/* F_BGSCAN flag gets cleared in ieee80211_node_join_bss(). */
1516 		return;
1517 	} else if (selbs == NULL)
1518 		goto notfound;
1519 
1520 	ieee80211_node_join_bss(ic, selbs);
1521 }
1522 
1523 /*
1524  * Autoselect the best RSN parameters (protocol, AKMP, pairwise cipher...)
1525  * that are supported by both peers (STA mode only).
1526  */
1527 void
1528 ieee80211_choose_rsnparams(struct ieee80211com *ic)
1529 {
1530 	struct ieee80211_node *ni = ic->ic_bss;
1531 	struct ieee80211_pmk *pmk;
1532 
1533 	/* filter out unsupported protocol versions */
1534 	ni->ni_rsnprotos &= ic->ic_rsnprotos;
1535 	/* prefer RSN (aka WPA2) over WPA */
1536 	if (ni->ni_rsnprotos & IEEE80211_PROTO_RSN)
1537 		ni->ni_rsnprotos = IEEE80211_PROTO_RSN;
1538 	else
1539 		ni->ni_rsnprotos = IEEE80211_PROTO_WPA;
1540 
1541 	/* filter out unsupported AKMPs */
1542 	ni->ni_rsnakms &= ic->ic_rsnakms;
1543 	/* prefer SHA-256 based AKMPs */
1544 	if ((ic->ic_flags & IEEE80211_F_PSK) && (ni->ni_rsnakms &
1545 	    (IEEE80211_AKM_PSK | IEEE80211_AKM_SHA256_PSK))) {
1546 		/* AP supports PSK AKMP and a PSK is configured */
1547 		if (ni->ni_rsnakms & IEEE80211_AKM_SHA256_PSK)
1548 			ni->ni_rsnakms = IEEE80211_AKM_SHA256_PSK;
1549 		else
1550 			ni->ni_rsnakms = IEEE80211_AKM_PSK;
1551 	} else {
1552 		if (ni->ni_rsnakms & IEEE80211_AKM_SHA256_8021X)
1553 			ni->ni_rsnakms = IEEE80211_AKM_SHA256_8021X;
1554 		else
1555 			ni->ni_rsnakms = IEEE80211_AKM_8021X;
1556 		/* check if we have a cached PMK for this AP */
1557 		if (ni->ni_rsnprotos == IEEE80211_PROTO_RSN &&
1558 		    (pmk = ieee80211_pmksa_find(ic, ni, NULL)) != NULL) {
1559 			memcpy(ni->ni_pmkid, pmk->pmk_pmkid,
1560 			    IEEE80211_PMKID_LEN);
1561 			ni->ni_flags |= IEEE80211_NODE_PMKID;
1562 		}
1563 	}
1564 
1565 	/* filter out unsupported pairwise ciphers */
1566 	ni->ni_rsnciphers &= ic->ic_rsnciphers;
1567 	/* prefer CCMP over TKIP */
1568 	if (ni->ni_rsnciphers & IEEE80211_CIPHER_CCMP)
1569 		ni->ni_rsnciphers = IEEE80211_CIPHER_CCMP;
1570 	else
1571 		ni->ni_rsnciphers = IEEE80211_CIPHER_TKIP;
1572 	ni->ni_rsncipher = ni->ni_rsnciphers;
1573 
1574 	/* use MFP if we both support it */
1575 	if ((ic->ic_caps & IEEE80211_C_MFP) &&
1576 	    (ni->ni_rsncaps & IEEE80211_RSNCAP_MFPC))
1577 		ni->ni_flags |= IEEE80211_NODE_MFP;
1578 }
1579 
1580 int
1581 ieee80211_get_rate(struct ieee80211com *ic)
1582 {
1583 	u_int8_t (*rates)[IEEE80211_RATE_MAXSIZE];
1584 	int rate;
1585 
1586 	rates = &ic->ic_bss->ni_rates.rs_rates;
1587 
1588 	if (ic->ic_fixed_rate != -1)
1589 		rate = (*rates)[ic->ic_fixed_rate];
1590 	else if (ic->ic_state == IEEE80211_S_RUN)
1591 		rate = (*rates)[ic->ic_bss->ni_txrate];
1592 	else
1593 		rate = 0;
1594 
1595 	return rate & IEEE80211_RATE_VAL;
1596 }
1597 
1598 struct ieee80211_node *
1599 ieee80211_node_alloc(struct ieee80211com *ic)
1600 {
1601 	return malloc(sizeof(struct ieee80211_node), M_DEVBUF,
1602 	    M_NOWAIT | M_ZERO);
1603 }
1604 
1605 void
1606 ieee80211_node_cleanup(struct ieee80211com *ic, struct ieee80211_node *ni)
1607 {
1608 	if (ni->ni_rsnie != NULL) {
1609 		free(ni->ni_rsnie, M_DEVBUF, 2 + ni->ni_rsnie[1]);
1610 		ni->ni_rsnie = NULL;
1611 	}
1612 	ieee80211_ba_del(ni);
1613 	ni->ni_unref_cb = NULL;
1614 	free(ni->ni_unref_arg, M_DEVBUF, ni->ni_unref_arg_size);
1615 	ni->ni_unref_arg = NULL;
1616 	ni->ni_unref_arg_size = 0;
1617 
1618 #ifndef IEEE80211_STA_ONLY
1619 	mq_purge(&ni->ni_savedq);
1620 #endif
1621 }
1622 
1623 void
1624 ieee80211_node_free(struct ieee80211com *ic, struct ieee80211_node *ni)
1625 {
1626 	ieee80211_node_cleanup(ic, ni);
1627 	free(ni, M_DEVBUF, 0);
1628 }
1629 
1630 void
1631 ieee80211_node_copy(struct ieee80211com *ic,
1632 	struct ieee80211_node *dst, const struct ieee80211_node *src)
1633 {
1634 	ieee80211_node_cleanup(ic, dst);
1635 	*dst = *src;
1636 	dst->ni_rsnie = NULL;
1637 	if (src->ni_rsnie != NULL)
1638 		ieee80211_save_ie(src->ni_rsnie, &dst->ni_rsnie);
1639 	ieee80211_node_set_timeouts(dst);
1640 #ifndef IEEE80211_STA_ONLY
1641 	mq_init(&dst->ni_savedq, IEEE80211_PS_MAX_QUEUE, IPL_NET);
1642 #endif
1643 }
1644 
1645 u_int8_t
1646 ieee80211_node_getrssi(struct ieee80211com *ic,
1647     const struct ieee80211_node *ni)
1648 {
1649 	return ni->ni_rssi;
1650 }
1651 
1652 int
1653 ieee80211_node_checkrssi(struct ieee80211com *ic,
1654     const struct ieee80211_node *ni)
1655 {
1656 	uint8_t thres;
1657 
1658 	if (ni->ni_chan == IEEE80211_CHAN_ANYC)
1659 		return 0;
1660 
1661 	if (ic->ic_max_rssi) {
1662 		thres = (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) ?
1663 		    IEEE80211_RSSI_THRES_RATIO_2GHZ :
1664 		    IEEE80211_RSSI_THRES_RATIO_5GHZ;
1665 		return ((ni->ni_rssi * 100) / ic->ic_max_rssi >= thres);
1666 	}
1667 
1668 	thres = (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) ?
1669 	    IEEE80211_RSSI_THRES_2GHZ :
1670 	    IEEE80211_RSSI_THRES_5GHZ;
1671 	return (ni->ni_rssi >= (u_int8_t)thres);
1672 }
1673 
1674 void
1675 ieee80211_node_set_timeouts(struct ieee80211_node *ni)
1676 {
1677 	int i;
1678 
1679 #ifndef IEEE80211_STA_ONLY
1680 	timeout_set(&ni->ni_eapol_to, ieee80211_eapol_timeout, ni);
1681 	timeout_set(&ni->ni_sa_query_to, ieee80211_sa_query_timeout, ni);
1682 #endif
1683 	timeout_set(&ni->ni_addba_req_to[EDCA_AC_BE],
1684 	    ieee80211_node_addba_request_ac_be_to, ni);
1685 	timeout_set(&ni->ni_addba_req_to[EDCA_AC_BK],
1686 	    ieee80211_node_addba_request_ac_bk_to, ni);
1687 	timeout_set(&ni->ni_addba_req_to[EDCA_AC_VI],
1688 	    ieee80211_node_addba_request_ac_vi_to, ni);
1689 	timeout_set(&ni->ni_addba_req_to[EDCA_AC_VO],
1690 	    ieee80211_node_addba_request_ac_vo_to, ni);
1691 	for (i = 0; i < nitems(ni->ni_addba_req_intval); i++)
1692 		ni->ni_addba_req_intval[i] = 1;
1693 }
1694 
1695 void
1696 ieee80211_setup_node(struct ieee80211com *ic,
1697 	struct ieee80211_node *ni, const u_int8_t *macaddr)
1698 {
1699 	int i, s;
1700 
1701 	DPRINTF(("%s\n", ether_sprintf((u_int8_t *)macaddr)));
1702 	IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
1703 	ieee80211_node_newstate(ni, IEEE80211_STA_CACHE);
1704 
1705 	ni->ni_ic = ic;	/* back-pointer */
1706 	/* Initialize cached last sequence numbers with invalid values. */
1707 	ni->ni_rxseq = 0xffffU;
1708 	for (i=0; i < IEEE80211_NUM_TID; ++i)
1709 		ni->ni_qos_rxseqs[i] = 0xffffU;
1710 #ifndef IEEE80211_STA_ONLY
1711 	mq_init(&ni->ni_savedq, IEEE80211_PS_MAX_QUEUE, IPL_NET);
1712 #endif
1713 	ieee80211_node_set_timeouts(ni);
1714 
1715 	s = splnet();
1716 	RBT_INSERT(ieee80211_tree, &ic->ic_tree, ni);
1717 	ic->ic_nnodes++;
1718 	splx(s);
1719 }
1720 
1721 struct ieee80211_node *
1722 ieee80211_alloc_node(struct ieee80211com *ic, const u_int8_t *macaddr)
1723 {
1724 	struct ieee80211_node *ni = ieee80211_alloc_node_helper(ic);
1725 	if (ni != NULL)
1726 		ieee80211_setup_node(ic, ni, macaddr);
1727 	else
1728 		ic->ic_stats.is_rx_nodealloc++;
1729 	return ni;
1730 }
1731 
1732 struct ieee80211_node *
1733 ieee80211_dup_bss(struct ieee80211com *ic, const u_int8_t *macaddr)
1734 {
1735 	struct ieee80211_node *ni = ieee80211_alloc_node_helper(ic);
1736 	if (ni != NULL) {
1737 		ieee80211_setup_node(ic, ni, macaddr);
1738 		/*
1739 		 * Inherit from ic_bss.
1740 		 */
1741 		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
1742 		ni->ni_chan = ic->ic_bss->ni_chan;
1743 	} else
1744 		ic->ic_stats.is_rx_nodealloc++;
1745 	return ni;
1746 }
1747 
1748 struct ieee80211_node *
1749 ieee80211_find_node(struct ieee80211com *ic, const u_int8_t *macaddr)
1750 {
1751 	struct ieee80211_node *ni;
1752 	int cmp;
1753 
1754 	/* similar to RBT_FIND except we compare keys, not nodes */
1755 	ni = RBT_ROOT(ieee80211_tree, &ic->ic_tree);
1756 	while (ni != NULL) {
1757 		cmp = memcmp(macaddr, ni->ni_macaddr, IEEE80211_ADDR_LEN);
1758 		if (cmp < 0)
1759 			ni = RBT_LEFT(ieee80211_tree, ni);
1760 		else if (cmp > 0)
1761 			ni = RBT_RIGHT(ieee80211_tree, ni);
1762 		else
1763 			break;
1764 	}
1765 	return ni;
1766 }
1767 
1768 /*
1769  * Return a reference to the appropriate node for sending
1770  * a data frame.  This handles node discovery in adhoc networks.
1771  *
1772  * Drivers will call this, so increase the reference count before
1773  * returning the node.
1774  */
1775 struct ieee80211_node *
1776 ieee80211_find_txnode(struct ieee80211com *ic, const u_int8_t *macaddr)
1777 {
1778 #ifndef IEEE80211_STA_ONLY
1779 	struct ieee80211_node *ni;
1780 	int s;
1781 #endif
1782 
1783 	/*
1784 	 * The destination address should be in the node table
1785 	 * unless we are operating in station mode or this is a
1786 	 * multicast/broadcast frame.
1787 	 */
1788 	if (ic->ic_opmode == IEEE80211_M_STA || IEEE80211_IS_MULTICAST(macaddr))
1789 		return ieee80211_ref_node(ic->ic_bss);
1790 
1791 #ifndef IEEE80211_STA_ONLY
1792 	s = splnet();
1793 	ni = ieee80211_find_node(ic, macaddr);
1794 	splx(s);
1795 	if (ni == NULL) {
1796 		if (ic->ic_opmode != IEEE80211_M_IBSS &&
1797 		    ic->ic_opmode != IEEE80211_M_AHDEMO)
1798 			return NULL;
1799 
1800 		/*
1801 		 * Fake up a node; this handles node discovery in
1802 		 * adhoc mode.  Note that for the driver's benefit
1803 		 * we we treat this like an association so the driver
1804 		 * has an opportunity to setup its private state.
1805 		 *
1806 		 * XXX need better way to handle this; issue probe
1807 		 *     request so we can deduce rate set, etc.
1808 		 */
1809 		if ((ni = ieee80211_dup_bss(ic, macaddr)) == NULL)
1810 			return NULL;
1811 		/* XXX no rate negotiation; just dup */
1812 		ni->ni_rates = ic->ic_bss->ni_rates;
1813 		ni->ni_txrate = 0;
1814 		if (ic->ic_newassoc)
1815 			(*ic->ic_newassoc)(ic, ni, 1);
1816 	}
1817 	return ieee80211_ref_node(ni);
1818 #else
1819 	return NULL;	/* can't get there */
1820 #endif	/* IEEE80211_STA_ONLY */
1821 }
1822 
1823 /*
1824  * It is usually desirable to process a Rx packet using its sender's
1825  * node-record instead of the BSS record.
1826  *
1827  * - AP mode: keep a node-record for every authenticated/associated
1828  *   station *in the BSS*. For future use, we also track neighboring
1829  *   APs, since they might belong to the same ESS.  APs in the same
1830  *   ESS may bridge packets to each other, forming a Wireless
1831  *   Distribution System (WDS).
1832  *
1833  * - IBSS mode: keep a node-record for every station *in the BSS*.
1834  *   Also track neighboring stations by their beacons/probe responses.
1835  *
1836  * - monitor mode: keep a node-record for every sender, regardless
1837  *   of BSS.
1838  *
1839  * - STA mode: the only available node-record is the BSS record,
1840  *   ic->ic_bss.
1841  *
1842  * Of all the 802.11 Control packets, only the node-records for
1843  * RTS packets node-record can be looked up.
1844  *
1845  * Return non-zero if the packet's node-record is kept, zero
1846  * otherwise.
1847  */
1848 static __inline int
1849 ieee80211_needs_rxnode(struct ieee80211com *ic,
1850     const struct ieee80211_frame *wh, const u_int8_t **bssid)
1851 {
1852 	int monitor, rc = 0;
1853 
1854 	monitor = (ic->ic_opmode == IEEE80211_M_MONITOR);
1855 
1856 	*bssid = NULL;
1857 
1858 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
1859 	case IEEE80211_FC0_TYPE_CTL:
1860 		if (!monitor)
1861 			break;
1862 		return (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
1863 		    IEEE80211_FC0_SUBTYPE_RTS;
1864 	case IEEE80211_FC0_TYPE_MGT:
1865 		*bssid = wh->i_addr3;
1866 		switch (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) {
1867 		case IEEE80211_FC0_SUBTYPE_BEACON:
1868 		case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
1869 			break;
1870 		default:
1871 #ifndef IEEE80211_STA_ONLY
1872 			if (ic->ic_opmode == IEEE80211_M_STA)
1873 				break;
1874 			rc = IEEE80211_ADDR_EQ(*bssid, ic->ic_bss->ni_bssid) ||
1875 			     IEEE80211_ADDR_EQ(*bssid, etherbroadcastaddr);
1876 #endif
1877 			break;
1878 		}
1879 		break;
1880 	case IEEE80211_FC0_TYPE_DATA:
1881 		switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
1882 		case IEEE80211_FC1_DIR_NODS:
1883 			*bssid = wh->i_addr3;
1884 #ifndef IEEE80211_STA_ONLY
1885 			if (ic->ic_opmode == IEEE80211_M_IBSS ||
1886 			    ic->ic_opmode == IEEE80211_M_AHDEMO)
1887 				rc = IEEE80211_ADDR_EQ(*bssid,
1888 				    ic->ic_bss->ni_bssid);
1889 #endif
1890 			break;
1891 		case IEEE80211_FC1_DIR_TODS:
1892 			*bssid = wh->i_addr1;
1893 #ifndef IEEE80211_STA_ONLY
1894 			if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1895 				rc = IEEE80211_ADDR_EQ(*bssid,
1896 				    ic->ic_bss->ni_bssid);
1897 #endif
1898 			break;
1899 		case IEEE80211_FC1_DIR_FROMDS:
1900 		case IEEE80211_FC1_DIR_DSTODS:
1901 			*bssid = wh->i_addr2;
1902 #ifndef IEEE80211_STA_ONLY
1903 			rc = (ic->ic_opmode == IEEE80211_M_HOSTAP);
1904 #endif
1905 			break;
1906 		}
1907 		break;
1908 	}
1909 	return monitor || rc;
1910 }
1911 
1912 /*
1913  * Drivers call this, so increase the reference count before returning
1914  * the node.
1915  */
1916 struct ieee80211_node *
1917 ieee80211_find_rxnode(struct ieee80211com *ic,
1918     const struct ieee80211_frame *wh)
1919 {
1920 	static const u_int8_t zero[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1921 	struct ieee80211_node *ni;
1922 	const u_int8_t *bssid;
1923 	int s;
1924 
1925 	if (!ieee80211_needs_rxnode(ic, wh, &bssid))
1926 		return ieee80211_ref_node(ic->ic_bss);
1927 
1928 	s = splnet();
1929 	ni = ieee80211_find_node(ic, wh->i_addr2);
1930 	splx(s);
1931 
1932 	if (ni != NULL)
1933 		return ieee80211_ref_node(ni);
1934 #ifndef IEEE80211_STA_ONLY
1935 	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1936 		return ieee80211_ref_node(ic->ic_bss);
1937 #endif
1938 	/* XXX see remarks in ieee80211_find_txnode */
1939 	/* XXX no rate negotiation; just dup */
1940 	if ((ni = ieee80211_dup_bss(ic, wh->i_addr2)) == NULL)
1941 		return ieee80211_ref_node(ic->ic_bss);
1942 
1943 	IEEE80211_ADDR_COPY(ni->ni_bssid, (bssid != NULL) ? bssid : zero);
1944 
1945 	ni->ni_rates = ic->ic_bss->ni_rates;
1946 	ni->ni_txrate = 0;
1947 	if (ic->ic_newassoc)
1948 		(*ic->ic_newassoc)(ic, ni, 1);
1949 
1950 	DPRINTF(("faked-up node %p for %s\n", ni,
1951 	    ether_sprintf((u_int8_t *)wh->i_addr2)));
1952 
1953 	return ieee80211_ref_node(ni);
1954 }
1955 
1956 struct ieee80211_node *
1957 ieee80211_find_node_for_beacon(struct ieee80211com *ic,
1958     const u_int8_t *macaddr, const struct ieee80211_channel *chan,
1959     const char *ssid, u_int8_t rssi)
1960 {
1961 	struct ieee80211_node *ni, *keep = NULL;
1962 	int s, score = 0;
1963 
1964 	if ((ni = ieee80211_find_node(ic, macaddr)) != NULL) {
1965 		s = splnet();
1966 
1967 		if (ni->ni_chan != chan && ni->ni_rssi >= rssi)
1968 			score++;
1969 		if (ssid[1] == 0 && ni->ni_esslen != 0)
1970 			score++;
1971 		if (score > 0)
1972 			keep = ni;
1973 
1974 		splx(s);
1975 	}
1976 
1977 	return (keep);
1978 }
1979 
1980 void
1981 ieee80211_ba_del(struct ieee80211_node *ni)
1982 {
1983 	int tid;
1984 
1985 	for (tid = 0; tid < nitems(ni->ni_rx_ba); tid++) {
1986 		struct ieee80211_rx_ba *ba = &ni->ni_rx_ba[tid];
1987 		if (ba->ba_state != IEEE80211_BA_INIT) {
1988 			if (timeout_pending(&ba->ba_to))
1989 				timeout_del(&ba->ba_to);
1990 			if (timeout_pending(&ba->ba_gap_to))
1991 				timeout_del(&ba->ba_gap_to);
1992 			ba->ba_state = IEEE80211_BA_INIT;
1993 		}
1994 	}
1995 
1996 	for (tid = 0; tid < nitems(ni->ni_tx_ba); tid++) {
1997 		struct ieee80211_tx_ba *ba = &ni->ni_tx_ba[tid];
1998 		if (ba->ba_state != IEEE80211_BA_INIT) {
1999 			if (timeout_pending(&ba->ba_to))
2000 				timeout_del(&ba->ba_to);
2001 			ba->ba_state = IEEE80211_BA_INIT;
2002 		}
2003 	}
2004 
2005 	timeout_del(&ni->ni_addba_req_to[EDCA_AC_BE]);
2006 	timeout_del(&ni->ni_addba_req_to[EDCA_AC_BK]);
2007 	timeout_del(&ni->ni_addba_req_to[EDCA_AC_VI]);
2008 	timeout_del(&ni->ni_addba_req_to[EDCA_AC_VO]);
2009 }
2010 
2011 void
2012 ieee80211_free_node(struct ieee80211com *ic, struct ieee80211_node *ni)
2013 {
2014 	if (ni == ic->ic_bss)
2015 		panic("freeing bss node");
2016 
2017 	splassert(IPL_NET);
2018 
2019 	DPRINTF(("%s\n", ether_sprintf(ni->ni_macaddr)));
2020 #ifndef IEEE80211_STA_ONLY
2021 	timeout_del(&ni->ni_eapol_to);
2022 	timeout_del(&ni->ni_sa_query_to);
2023 	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
2024 #endif
2025 	ieee80211_ba_del(ni);
2026 	RBT_REMOVE(ieee80211_tree, &ic->ic_tree, ni);
2027 	ic->ic_nnodes--;
2028 #ifndef IEEE80211_STA_ONLY
2029 	if (mq_purge(&ni->ni_savedq) > 0) {
2030 		if (ic->ic_set_tim != NULL)
2031 			(*ic->ic_set_tim)(ic, ni->ni_associd, 0);
2032 	}
2033 #endif
2034 	(*ic->ic_node_free)(ic, ni);
2035 	/* TBD indicate to drivers that a new node can be allocated */
2036 }
2037 
2038 void
2039 ieee80211_release_node(struct ieee80211com *ic, struct ieee80211_node *ni)
2040 {
2041 	int s;
2042 
2043 	DPRINTF(("%s refcnt %u\n", ether_sprintf(ni->ni_macaddr),
2044 	    ni->ni_refcnt));
2045 	s = splnet();
2046 	if (ieee80211_node_decref(ni) == 0) {
2047 		if (ni->ni_unref_cb) {
2048 			(*ni->ni_unref_cb)(ic, ni);
2049 			ni->ni_unref_cb = NULL;
2050  			/* Freed by callback if necessary: */
2051 			ni->ni_unref_arg = NULL;
2052 			ni->ni_unref_arg_size = 0;
2053 		}
2054 	    	if (ni->ni_state == IEEE80211_STA_COLLECT)
2055 			ieee80211_free_node(ic, ni);
2056 	}
2057 	splx(s);
2058 }
2059 
2060 void
2061 ieee80211_free_allnodes(struct ieee80211com *ic, int clear_ic_bss)
2062 {
2063 	struct ieee80211_node *ni;
2064 	int s;
2065 
2066 	DPRINTF(("freeing all nodes\n"));
2067 	s = splnet();
2068 	while ((ni = RBT_MIN(ieee80211_tree, &ic->ic_tree)) != NULL)
2069 		ieee80211_free_node(ic, ni);
2070 	splx(s);
2071 
2072 	if (clear_ic_bss && ic->ic_bss != NULL)
2073 		ieee80211_node_cleanup(ic, ic->ic_bss);
2074 }
2075 
2076 void
2077 ieee80211_clean_cached(struct ieee80211com *ic)
2078 {
2079 	struct ieee80211_node *ni, *next_ni;
2080 	int s;
2081 
2082 	s = splnet();
2083 	for (ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
2084 	    ni != NULL; ni = next_ni) {
2085 		next_ni = RBT_NEXT(ieee80211_tree, ni);
2086 		if (ni->ni_state == IEEE80211_STA_CACHE)
2087 			ieee80211_free_node(ic, ni);
2088 	}
2089 	splx(s);
2090 }
2091 /*
2092  * Timeout inactive nodes.
2093  *
2094  * If called because of a cache timeout, which happens only in hostap and ibss
2095  * modes, clean all inactive cached or authenticated nodes but don't de-auth
2096  * any associated nodes. Also update HT protection settings.
2097  *
2098  * Else, this function is called because a new node must be allocated but the
2099  * node cache is full. In this case, return as soon as a free slot was made
2100  * available. If acting as hostap, clean cached nodes regardless of their
2101  * recent activity and also allow de-authing of authenticated nodes older
2102  * than one cache wait interval, and de-authing of inactive associated nodes.
2103  */
2104 void
2105 ieee80211_clean_nodes(struct ieee80211com *ic, int cache_timeout)
2106 {
2107 	struct ieee80211_node *ni, *next_ni;
2108 	u_int gen = ic->ic_scangen++;		/* NB: ok 'cuz single-threaded*/
2109 	int s;
2110 #ifndef IEEE80211_STA_ONLY
2111 	int nnodes = 0, nonht = 0, nonhtassoc = 0;
2112 	struct ifnet *ifp = &ic->ic_if;
2113 	enum ieee80211_htprot htprot = IEEE80211_HTPROT_NONE;
2114 	enum ieee80211_protmode protmode = IEEE80211_PROT_NONE;
2115 #endif
2116 
2117 	s = splnet();
2118 	for (ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
2119 	    ni != NULL; ni = next_ni) {
2120 		next_ni = RBT_NEXT(ieee80211_tree, ni);
2121 		if (!cache_timeout && ic->ic_nnodes < ic->ic_max_nnodes)
2122 			break;
2123 		if (ni->ni_scangen == gen)	/* previously handled */
2124 			continue;
2125 #ifndef IEEE80211_STA_ONLY
2126 		nnodes++;
2127 		if ((ic->ic_flags & IEEE80211_F_HTON) && cache_timeout) {
2128 			/*
2129 			 * Check if node supports 802.11n.
2130 			 * Only require HT capabilities IE for this check.
2131 			 * Nodes might never reveal their supported MCS to us
2132 			 * unless they go through a full association sequence.
2133 			 * ieee80211_node_supports_ht() could misclassify them.
2134 			 */
2135 			if ((ni->ni_flags & IEEE80211_NODE_HTCAP) == 0) {
2136 				nonht++;
2137 				if (ni->ni_state == IEEE80211_STA_ASSOC)
2138 					nonhtassoc++;
2139 			}
2140 		}
2141 #endif
2142 		ni->ni_scangen = gen;
2143 		if (ni->ni_refcnt > 0)
2144 			continue;
2145 #ifndef IEEE80211_STA_ONLY
2146 		if ((ic->ic_opmode == IEEE80211_M_HOSTAP ||
2147 		    ic->ic_opmode == IEEE80211_M_IBSS) &&
2148 		    ic->ic_state == IEEE80211_S_RUN) {
2149 			if (cache_timeout) {
2150 				if (ni->ni_state != IEEE80211_STA_COLLECT &&
2151 				    (ni->ni_state == IEEE80211_STA_ASSOC ||
2152 				    ni->ni_inact < IEEE80211_INACT_MAX))
2153 					continue;
2154 			} else {
2155 				if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
2156 				    ((ni->ni_state == IEEE80211_STA_ASSOC &&
2157 				    ni->ni_inact < IEEE80211_INACT_MAX) ||
2158 				    (ni->ni_state == IEEE80211_STA_AUTH &&
2159 				     ni->ni_inact == 0)))
2160 				    	continue;
2161 
2162 				if (ic->ic_opmode == IEEE80211_M_IBSS &&
2163 				    ni->ni_state != IEEE80211_STA_COLLECT &&
2164 				    ni->ni_state != IEEE80211_STA_CACHE &&
2165 				    ni->ni_inact < IEEE80211_INACT_MAX)
2166 					continue;
2167 			}
2168 		}
2169 		if (ifp->if_flags & IFF_DEBUG)
2170 			printf("%s: station %s purged from node cache\n",
2171 			    ifp->if_xname, ether_sprintf(ni->ni_macaddr));
2172 #endif
2173 		/*
2174 		 * If we're hostap and the node is authenticated, send
2175 		 * a deauthentication frame. The node will be freed when
2176 		 * the driver calls ieee80211_release_node().
2177 		 */
2178 #ifndef IEEE80211_STA_ONLY
2179 		nnodes--;
2180 		if ((ic->ic_flags & IEEE80211_F_HTON) && cache_timeout) {
2181 			if ((ni->ni_flags & IEEE80211_NODE_HTCAP) == 0) {
2182 				nonht--;
2183 				if (ni->ni_state == IEEE80211_STA_ASSOC)
2184 					nonhtassoc--;
2185 			}
2186 		}
2187 		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
2188 		    ni->ni_state >= IEEE80211_STA_AUTH &&
2189 		    ni->ni_state != IEEE80211_STA_COLLECT) {
2190 			IEEE80211_SEND_MGMT(ic, ni,
2191 			    IEEE80211_FC0_SUBTYPE_DEAUTH,
2192 			    IEEE80211_REASON_AUTH_EXPIRE);
2193 			ieee80211_node_leave(ic, ni);
2194 		} else
2195 #endif
2196 			ieee80211_free_node(ic, ni);
2197 		ic->ic_stats.is_node_timeout++;
2198 	}
2199 
2200 #ifndef IEEE80211_STA_ONLY
2201 	if ((ic->ic_flags & IEEE80211_F_HTON) && cache_timeout) {
2202 		uint16_t htop1 = ic->ic_bss->ni_htop1;
2203 
2204 		/* Update HT protection settings. */
2205 		if (nonht) {
2206 			protmode = IEEE80211_PROT_CTSONLY;
2207 			if (nonhtassoc)
2208 				htprot = IEEE80211_HTPROT_NONHT_MIXED;
2209 			else
2210 				htprot = IEEE80211_HTPROT_NONMEMBER;
2211 		}
2212 		if ((htop1 & IEEE80211_HTOP1_PROT_MASK) != htprot) {
2213 			htop1 &= ~IEEE80211_HTOP1_PROT_MASK;
2214 			htop1 |= htprot;
2215 			ic->ic_bss->ni_htop1 = htop1;
2216 			ic->ic_protmode = protmode;
2217 			if (ic->ic_update_htprot)
2218 				ic->ic_update_htprot(ic, ic->ic_bss);
2219 		}
2220 	}
2221 
2222 	/*
2223 	 * During a cache timeout we iterate over all nodes.
2224 	 * Check for node leaks by comparing the actual number of cached
2225 	 * nodes with the ic_nnodes count, which is maintained while adding
2226 	 * and removing nodes from the cache.
2227 	 */
2228 	if ((ifp->if_flags & IFF_DEBUG) && cache_timeout &&
2229 	    nnodes != ic->ic_nnodes)
2230 		printf("%s: number of cached nodes is %d, expected %d,"
2231 		    "possible nodes leak\n", ifp->if_xname, nnodes,
2232 		    ic->ic_nnodes);
2233 #endif
2234 	splx(s);
2235 }
2236 
2237 void
2238 ieee80211_clean_inactive_nodes(struct ieee80211com *ic, int inact_max)
2239 {
2240 	struct ieee80211_node *ni, *next_ni;
2241 	u_int gen = ic->ic_scangen++;	/* NB: ok 'cuz single-threaded*/
2242 	int s;
2243 
2244 	s = splnet();
2245 	for (ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
2246 	    ni != NULL; ni = next_ni) {
2247 		next_ni = RBT_NEXT(ieee80211_tree, ni);
2248 		if (ni->ni_scangen == gen)	/* previously handled */
2249 			continue;
2250 		ni->ni_scangen = gen;
2251 		if (ni->ni_refcnt > 0 || ni->ni_inact < inact_max)
2252 			continue;
2253 		ieee80211_free_node(ic, ni);
2254 		ic->ic_stats.is_node_timeout++;
2255 	}
2256 
2257 	splx(s);
2258 }
2259 
2260 void
2261 ieee80211_iterate_nodes(struct ieee80211com *ic, ieee80211_iter_func *f,
2262     void *arg)
2263 {
2264 	struct ieee80211_node *ni;
2265 	int s;
2266 
2267 	s = splnet();
2268 	RBT_FOREACH(ni, ieee80211_tree, &ic->ic_tree)
2269 		(*f)(arg, ni);
2270 	splx(s);
2271 }
2272 
2273 
2274 /*
2275  * Install received HT caps information in the node's state block.
2276  */
2277 void
2278 ieee80211_setup_htcaps(struct ieee80211_node *ni, const uint8_t *data,
2279     uint8_t len)
2280 {
2281 	uint16_t rxrate;
2282 
2283 	if (len != 26)
2284 		return;
2285 
2286 	ni->ni_htcaps = (data[0] | (data[1] << 8));
2287 	ni->ni_ampdu_param = data[2];
2288 
2289 	memcpy(ni->ni_rxmcs, &data[3], sizeof(ni->ni_rxmcs));
2290 	/* clear reserved bits */
2291 	clrbit(ni->ni_rxmcs, 77);
2292 	clrbit(ni->ni_rxmcs, 78);
2293 	clrbit(ni->ni_rxmcs, 79);
2294 
2295 	/* Max MCS Rx rate in 1Mb/s units (0 means "not specified"). */
2296 	rxrate = ((data[13] | (data[14]) << 8) & IEEE80211_MCS_RX_RATE_HIGH);
2297 	if (rxrate < 1024)
2298 		ni->ni_max_rxrate = rxrate;
2299 
2300 	ni->ni_tx_mcs_set = data[15];
2301 	ni->ni_htxcaps = (data[19] | (data[20] << 8));
2302 	ni->ni_txbfcaps = (data[21] | (data[22] << 8) | (data[23] << 16) |
2303 		(data[24] << 24));
2304 	ni->ni_aselcaps = data[25];
2305 
2306 	ni->ni_flags |= IEEE80211_NODE_HTCAP;
2307 }
2308 
2309 #ifndef IEEE80211_STA_ONLY
2310 /*
2311  * Handle nodes switching from 11n into legacy modes.
2312  */
2313 void
2314 ieee80211_clear_htcaps(struct ieee80211_node *ni)
2315 {
2316 	ni->ni_htcaps = 0;
2317 	ni->ni_ampdu_param = 0;
2318 	memset(ni->ni_rxmcs, 0, sizeof(ni->ni_rxmcs));
2319 	ni->ni_max_rxrate = 0;
2320 	ni->ni_tx_mcs_set = 0;
2321 	ni->ni_htxcaps = 0;
2322 	ni->ni_txbfcaps = 0;
2323 	ni->ni_aselcaps = 0;
2324 
2325 	ni->ni_flags &= ~(IEEE80211_NODE_HT | IEEE80211_NODE_HT_SGI20 |
2326 	    IEEE80211_NODE_HT_SGI40 | IEEE80211_NODE_HTCAP);
2327 
2328 }
2329 #endif
2330 
2331 /*
2332  * Install received HT op information in the node's state block.
2333  */
2334 int
2335 ieee80211_setup_htop(struct ieee80211_node *ni, const uint8_t *data,
2336     uint8_t len, int isprobe)
2337 {
2338 	if (len != 22)
2339 		return 0;
2340 
2341 	ni->ni_primary_chan = data[0]; /* XXX corresponds to ni_chan */
2342 
2343 	ni->ni_htop0 = data[1];
2344 	ni->ni_htop1 = (data[2] | (data[3] << 8));
2345 	ni->ni_htop2 = (data[3] | (data[4] << 8));
2346 
2347 	/*
2348 	 * According to 802.11-2012 Table 8-130 the Basic MCS set is
2349 	 * only "present in Beacon, Probe Response, Mesh Peering Open
2350 	 * and Mesh Peering Confirm frames. Otherwise reserved."
2351 	 */
2352 	if (isprobe)
2353 		memcpy(ni->ni_basic_mcs, &data[6], sizeof(ni->ni_basic_mcs));
2354 
2355 	return 1;
2356 }
2357 
2358 /*
2359  * Install received rate set information in the node's state block.
2360  */
2361 int
2362 ieee80211_setup_rates(struct ieee80211com *ic, struct ieee80211_node *ni,
2363     const u_int8_t *rates, const u_int8_t *xrates, int flags)
2364 {
2365 	struct ieee80211_rateset *rs = &ni->ni_rates;
2366 
2367 	memset(rs, 0, sizeof(*rs));
2368 	rs->rs_nrates = rates[1];
2369 	memcpy(rs->rs_rates, rates + 2, rs->rs_nrates);
2370 	if (xrates != NULL) {
2371 		u_int8_t nxrates;
2372 		/*
2373 		 * Tack on 11g extended supported rate element.
2374 		 */
2375 		nxrates = xrates[1];
2376 		if (rs->rs_nrates + nxrates > IEEE80211_RATE_MAXSIZE) {
2377 			nxrates = IEEE80211_RATE_MAXSIZE - rs->rs_nrates;
2378 			DPRINTF(("extended rate set too large; "
2379 			    "only using %u of %u rates\n",
2380 			    nxrates, xrates[1]));
2381 			ic->ic_stats.is_rx_rstoobig++;
2382 		}
2383 		memcpy(rs->rs_rates + rs->rs_nrates, xrates+2, nxrates);
2384 		rs->rs_nrates += nxrates;
2385 	}
2386 	return ieee80211_fix_rate(ic, ni, flags);
2387 }
2388 
2389 void
2390 ieee80211_node_trigger_addba_req(struct ieee80211_node *ni, int tid)
2391 {
2392 	if (ni->ni_tx_ba[tid].ba_state == IEEE80211_BA_INIT &&
2393 	    !timeout_pending(&ni->ni_addba_req_to[tid])) {
2394 		timeout_add_sec(&ni->ni_addba_req_to[tid],
2395 		    ni->ni_addba_req_intval[tid]);
2396 	}
2397 }
2398 
2399 void
2400 ieee80211_node_addba_request(struct ieee80211_node *ni, int tid)
2401 {
2402 	struct ieee80211com *ic = ni->ni_ic;
2403 	uint16_t ssn = ni->ni_qos_txseqs[tid];
2404 
2405 	ieee80211_addba_request(ic, ni, ssn, tid);
2406 }
2407 
2408 void
2409 ieee80211_node_addba_request_ac_be_to(void *arg)
2410 {
2411 	struct ieee80211_node *ni = arg;
2412 	ieee80211_node_addba_request(ni, EDCA_AC_BE);
2413 }
2414 
2415 void
2416 ieee80211_node_addba_request_ac_bk_to(void *arg)
2417 {
2418 	struct ieee80211_node *ni = arg;
2419 	ieee80211_node_addba_request(ni, EDCA_AC_BK);
2420 }
2421 
2422 void
2423 ieee80211_node_addba_request_ac_vi_to(void *arg)
2424 {
2425 	struct ieee80211_node *ni = arg;
2426 	ieee80211_node_addba_request(ni, EDCA_AC_VI);
2427 }
2428 
2429 void
2430 ieee80211_node_addba_request_ac_vo_to(void *arg)
2431 {
2432 	struct ieee80211_node *ni = arg;
2433 	ieee80211_node_addba_request(ni, EDCA_AC_VO);
2434 }
2435 
2436 #ifndef IEEE80211_STA_ONLY
2437 /*
2438  * Check if the specified node supports ERP.
2439  */
2440 int
2441 ieee80211_iserp_sta(const struct ieee80211_node *ni)
2442 {
2443 	static const u_int8_t rates[] = { 2, 4, 11, 22, 12, 24, 48 };
2444 	const struct ieee80211_rateset *rs = &ni->ni_rates;
2445 	int i, j;
2446 
2447 	/*
2448 	 * A STA supports ERP operation if it includes all the Clause 19
2449 	 * mandatory rates in its supported rate set.
2450 	 */
2451 	for (i = 0; i < nitems(rates); i++) {
2452 		for (j = 0; j < rs->rs_nrates; j++) {
2453 			if ((rs->rs_rates[j] & IEEE80211_RATE_VAL) == rates[i])
2454 				break;
2455 		}
2456 		if (j == rs->rs_nrates)
2457 			return 0;
2458 	}
2459 	return 1;
2460 }
2461 
2462 /*
2463  * This function is called to notify the 802.1X PACP machine that a new
2464  * 802.1X port is enabled and must be authenticated. For 802.11, a port
2465  * becomes enabled whenever a STA successfully completes Open System
2466  * authentication with an AP.
2467  */
2468 void
2469 ieee80211_needs_auth(struct ieee80211com *ic, struct ieee80211_node *ni)
2470 {
2471 	/*
2472 	 * XXX this could be done via the route socket of via a dedicated
2473 	 * EAP socket or another kernel->userland notification mechanism.
2474 	 * The notification should include the MAC address (ni_macaddr).
2475 	 */
2476 }
2477 
2478 /*
2479  * Handle an HT STA joining an HT network.
2480  */
2481 void
2482 ieee80211_node_join_ht(struct ieee80211com *ic, struct ieee80211_node *ni)
2483 {
2484 	enum ieee80211_htprot;
2485 
2486 	/* Update HT protection setting. */
2487 	if ((ni->ni_flags & IEEE80211_NODE_HT) == 0) {
2488 		uint16_t htop1 = ic->ic_bss->ni_htop1;
2489 		htop1 &= ~IEEE80211_HTOP1_PROT_MASK;
2490 		htop1 |= IEEE80211_HTPROT_NONHT_MIXED;
2491 		ic->ic_bss->ni_htop1 = htop1;
2492 		if (ic->ic_update_htprot)
2493 			ic->ic_update_htprot(ic, ic->ic_bss);
2494 	}
2495 }
2496 
2497 /*
2498  * Handle a station joining an RSN network.
2499  */
2500 void
2501 ieee80211_node_join_rsn(struct ieee80211com *ic, struct ieee80211_node *ni)
2502 {
2503 	DPRINTF(("station %s associated using proto %d akm 0x%x "
2504 	    "cipher 0x%x groupcipher 0x%x\n", ether_sprintf(ni->ni_macaddr),
2505 	    ni->ni_rsnprotos, ni->ni_rsnakms, ni->ni_rsnciphers,
2506 	    ni->ni_rsngroupcipher));
2507 
2508 	ni->ni_rsn_state = RSNA_AUTHENTICATION;
2509 
2510 	ni->ni_key_count = 0;
2511 	ni->ni_port_valid = 0;
2512 	ni->ni_flags &= ~IEEE80211_NODE_TXRXPROT;
2513 	ni->ni_flags &= ~IEEE80211_NODE_RSN_NEW_PTK;
2514 	ni->ni_replaycnt = -1;	/* XXX */
2515 	ni->ni_rsn_retries = 0;
2516 	ni->ni_rsncipher = ni->ni_rsnciphers;
2517 
2518 	ni->ni_rsn_state = RSNA_AUTHENTICATION_2;
2519 
2520 	/* generate a new authenticator nonce (ANonce) */
2521 	arc4random_buf(ni->ni_nonce, EAPOL_KEY_NONCE_LEN);
2522 
2523 	if (!ieee80211_is_8021x_akm(ni->ni_rsnakms)) {
2524 		memcpy(ni->ni_pmk, ic->ic_psk, IEEE80211_PMK_LEN);
2525 		ni->ni_flags |= IEEE80211_NODE_PMK;
2526 		(void)ieee80211_send_4way_msg1(ic, ni);
2527 	} else if (ni->ni_flags & IEEE80211_NODE_PMK) {
2528 		/* skip 802.1X auth if a cached PMK was found */
2529 		(void)ieee80211_send_4way_msg1(ic, ni);
2530 	} else {
2531 		/* no cached PMK found, needs full 802.1X auth */
2532 		ieee80211_needs_auth(ic, ni);
2533 	}
2534 }
2535 
2536 void
2537 ieee80211_count_longslotsta(void *arg, struct ieee80211_node *ni)
2538 {
2539 	int *longslotsta = arg;
2540 
2541 	if (ni->ni_associd == 0 || ni->ni_state == IEEE80211_STA_COLLECT)
2542 		return;
2543 
2544 	if (!(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME))
2545 		(*longslotsta)++;
2546 }
2547 
2548 void
2549 ieee80211_count_nonerpsta(void *arg, struct ieee80211_node *ni)
2550 {
2551 	int *nonerpsta = arg;
2552 
2553 	if (ni->ni_associd == 0 || ni->ni_state == IEEE80211_STA_COLLECT)
2554 		return;
2555 
2556 	if (!ieee80211_iserp_sta(ni))
2557 		(*nonerpsta)++;
2558 }
2559 
2560 void
2561 ieee80211_count_pssta(void *arg, struct ieee80211_node *ni)
2562 {
2563 	int *pssta = arg;
2564 
2565 	if (ni->ni_associd == 0 || ni->ni_state == IEEE80211_STA_COLLECT)
2566 		return;
2567 
2568 	if (ni->ni_pwrsave == IEEE80211_PS_DOZE)
2569 		(*pssta)++;
2570 }
2571 
2572 void
2573 ieee80211_count_rekeysta(void *arg, struct ieee80211_node *ni)
2574 {
2575 	int *rekeysta = arg;
2576 
2577 	if (ni->ni_associd == 0 || ni->ni_state == IEEE80211_STA_COLLECT)
2578 		return;
2579 
2580 	if (ni->ni_flags & IEEE80211_NODE_REKEY)
2581 		(*rekeysta)++;
2582 }
2583 
2584 /*
2585  * Handle a station joining an 11g network.
2586  */
2587 void
2588 ieee80211_node_join_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
2589 {
2590 	int longslotsta = 0, nonerpsta = 0;
2591 
2592 	if (!(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)) {
2593 		/*
2594 		 * Joining STA doesn't support short slot time.  We must
2595 		 * disable the use of short slot time for all other associated
2596 		 * STAs and give the driver a chance to reconfigure the
2597 		 * hardware.
2598 		 */
2599 		ieee80211_iterate_nodes(ic,
2600 		    ieee80211_count_longslotsta, &longslotsta);
2601 		if (longslotsta == 1) {
2602 			if (ic->ic_caps & IEEE80211_C_SHSLOT)
2603 				ieee80211_set_shortslottime(ic, 0);
2604 		}
2605 		DPRINTF(("[%s] station needs long slot time, count %d\n",
2606 		    ether_sprintf(ni->ni_macaddr), longslotsta));
2607 	}
2608 
2609 	if (!ieee80211_iserp_sta(ni)) {
2610 		/*
2611 		 * Joining STA is non-ERP.
2612 		 */
2613 		ieee80211_iterate_nodes(ic,
2614 		    ieee80211_count_nonerpsta, &nonerpsta);
2615 		DPRINTF(("[%s] station is non-ERP, %d non-ERP "
2616 		    "stations associated\n", ether_sprintf(ni->ni_macaddr),
2617 		    nonerpsta));
2618 		/* must enable the use of protection */
2619 		if (ic->ic_protmode != IEEE80211_PROT_NONE) {
2620 			DPRINTF(("enable use of protection\n"));
2621 			ic->ic_flags |= IEEE80211_F_USEPROT;
2622 		}
2623 
2624 		if (!(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE))
2625 			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
2626 	} else
2627 		ni->ni_flags |= IEEE80211_NODE_ERP;
2628 }
2629 
2630 void
2631 ieee80211_node_join(struct ieee80211com *ic, struct ieee80211_node *ni,
2632     int resp)
2633 {
2634 	int newassoc = (ni->ni_state != IEEE80211_STA_ASSOC);
2635 
2636 	if (ni->ni_associd == 0) {
2637 		u_int16_t aid;
2638 
2639 		/*
2640 		 * It would be clever to search the bitmap
2641 		 * more efficiently, but this will do for now.
2642 		 */
2643 		for (aid = 1; aid < ic->ic_max_aid; aid++) {
2644 			if (!IEEE80211_AID_ISSET(aid,
2645 			    ic->ic_aid_bitmap))
2646 				break;
2647 		}
2648 		if (aid >= ic->ic_max_aid) {
2649 			IEEE80211_SEND_MGMT(ic, ni, resp,
2650 			    IEEE80211_REASON_ASSOC_TOOMANY);
2651 			ieee80211_node_leave(ic, ni);
2652 			return;
2653 		}
2654 		ni->ni_associd = aid | 0xc000;
2655 		IEEE80211_AID_SET(ni->ni_associd, ic->ic_aid_bitmap);
2656 		if (ic->ic_curmode == IEEE80211_MODE_11G ||
2657 		    (ic->ic_curmode == IEEE80211_MODE_11N &&
2658 		    IEEE80211_IS_CHAN_2GHZ(ic->ic_bss->ni_chan)))
2659 			ieee80211_node_join_11g(ic, ni);
2660 	}
2661 
2662 	DPRINTF(("station %s %s associated at aid %d\n",
2663 	    ether_sprintf(ni->ni_macaddr), newassoc ? "newly" : "already",
2664 	    ni->ni_associd & ~0xc000));
2665 
2666 	ieee80211_ht_negotiate(ic, ni);
2667 	if (ic->ic_flags & IEEE80211_F_HTON)
2668 		ieee80211_node_join_ht(ic, ni);
2669 
2670 	/* give driver a chance to setup state like ni_txrate */
2671 	if (ic->ic_newassoc)
2672 		(*ic->ic_newassoc)(ic, ni, newassoc);
2673 	IEEE80211_SEND_MGMT(ic, ni, resp, IEEE80211_STATUS_SUCCESS);
2674 	ieee80211_node_newstate(ni, IEEE80211_STA_ASSOC);
2675 
2676 	if (!(ic->ic_flags & IEEE80211_F_RSNON)) {
2677 		ni->ni_port_valid = 1;
2678 		ni->ni_rsncipher = IEEE80211_CIPHER_USEGROUP;
2679 	} else
2680 		ieee80211_node_join_rsn(ic, ni);
2681 
2682 #if NBRIDGE > 0
2683 	/*
2684 	 * If the parent interface is a bridge port, learn
2685 	 * the node's address dynamically on this interface.
2686 	 */
2687 	if (ic->ic_if.if_bridgeidx != 0)
2688 		bridge_update(&ic->ic_if,
2689 		    (struct ether_addr *)ni->ni_macaddr, 0);
2690 #endif
2691 }
2692 
2693 /*
2694  * Handle an HT STA leaving an HT network.
2695  */
2696 void
2697 ieee80211_node_leave_ht(struct ieee80211com *ic, struct ieee80211_node *ni)
2698 {
2699 	struct ieee80211_rx_ba *ba;
2700 	u_int8_t tid;
2701 	int i;
2702 
2703 	/* free all Block Ack records */
2704 	ieee80211_ba_del(ni);
2705 	for (tid = 0; tid < IEEE80211_NUM_TID; tid++) {
2706 		ba = &ni->ni_rx_ba[tid];
2707 		if (ba->ba_buf != NULL) {
2708 			for (i = 0; i < IEEE80211_BA_MAX_WINSZ; i++)
2709 				m_freem(ba->ba_buf[i].m);
2710 			free(ba->ba_buf, M_DEVBUF,
2711 			    IEEE80211_BA_MAX_WINSZ * sizeof(*ba->ba_buf));
2712 			ba->ba_buf = NULL;
2713 		}
2714 	}
2715 
2716 	ieee80211_clear_htcaps(ni);
2717 }
2718 
2719 /*
2720  * Handle a station leaving an RSN network.
2721  */
2722 void
2723 ieee80211_node_leave_rsn(struct ieee80211com *ic, struct ieee80211_node *ni)
2724 {
2725 	int rekeysta = 0;
2726 
2727 	ni->ni_rsn_state = RSNA_INITIALIZE;
2728 	if (ni->ni_flags & IEEE80211_NODE_REKEY) {
2729 		ni->ni_flags &= ~IEEE80211_NODE_REKEY;
2730 		ieee80211_iterate_nodes(ic,
2731 		    ieee80211_count_rekeysta, &rekeysta);
2732 		if (rekeysta == 0)
2733 			ieee80211_setkeysdone(ic);
2734 	}
2735 	ni->ni_flags &= ~IEEE80211_NODE_PMK;
2736 	ni->ni_rsn_gstate = RSNA_IDLE;
2737 
2738 	timeout_del(&ni->ni_eapol_to);
2739 	timeout_del(&ni->ni_sa_query_to);
2740 
2741 	ni->ni_rsn_retries = 0;
2742 	ni->ni_flags &= ~IEEE80211_NODE_TXRXPROT;
2743 	ni->ni_port_valid = 0;
2744 	(*ic->ic_delete_key)(ic, ni, &ni->ni_pairwise_key);
2745 }
2746 
2747 /*
2748  * Handle a station leaving an 11g network.
2749  */
2750 void
2751 ieee80211_node_leave_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
2752 {
2753 	int longslotsta = 0, nonerpsta = 0;
2754 
2755 	if (!(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)) {
2756 		/* leaving STA did not support short slot time */
2757 		ieee80211_iterate_nodes(ic,
2758 		    ieee80211_count_longslotsta, &longslotsta);
2759 		if (longslotsta == 1) {
2760 			/*
2761 			 * All associated STAs now support short slot time, so
2762 			 * enable this feature and give the driver a chance to
2763 			 * reconfigure the hardware. Notice that IBSS always
2764 			 * use a long slot time.
2765 			 */
2766 			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
2767 			    ic->ic_opmode != IEEE80211_M_IBSS)
2768 				ieee80211_set_shortslottime(ic, 1);
2769 		}
2770 		DPRINTF(("[%s] long slot time station leaves, count %d\n",
2771 		    ether_sprintf(ni->ni_macaddr), longslotsta));
2772 	}
2773 
2774 	if (!(ni->ni_flags & IEEE80211_NODE_ERP)) {
2775 		/* leaving STA was non-ERP */
2776 		ieee80211_iterate_nodes(ic,
2777 		    ieee80211_count_nonerpsta, &nonerpsta);
2778 		if (nonerpsta == 1) {
2779 			/*
2780 			 * All associated STAs are now ERP capable, disable use
2781 			 * of protection and re-enable short preamble support.
2782 			 */
2783 			ic->ic_flags &= ~IEEE80211_F_USEPROT;
2784 			if (ic->ic_caps & IEEE80211_C_SHPREAMBLE)
2785 				ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
2786 		}
2787 		DPRINTF(("[%s] non-ERP station leaves, count %d\n",
2788 		    ether_sprintf(ni->ni_macaddr), nonerpsta));
2789 	}
2790 }
2791 
2792 /*
2793  * Handle bookkeeping for station deauthentication/disassociation
2794  * when operating as an ap.
2795  */
2796 void
2797 ieee80211_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
2798 {
2799 	if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2800 		panic("not in ap mode, mode %u", ic->ic_opmode);
2801 
2802 	if (ni->ni_state == IEEE80211_STA_COLLECT)
2803 		return;
2804 	/*
2805 	 * If node wasn't previously associated all we need to do is
2806 	 * reclaim the reference.
2807 	 */
2808 	if (ni->ni_associd == 0) {
2809 		ieee80211_node_newstate(ni, IEEE80211_STA_COLLECT);
2810 		return;
2811 	}
2812 
2813 	if (ni->ni_pwrsave == IEEE80211_PS_DOZE)
2814 		ni->ni_pwrsave = IEEE80211_PS_AWAKE;
2815 
2816 	if (mq_purge(&ni->ni_savedq) > 0) {
2817 		if (ic->ic_set_tim != NULL)
2818 			(*ic->ic_set_tim)(ic, ni->ni_associd, 0);
2819 	}
2820 
2821 	if (ic->ic_flags & IEEE80211_F_RSNON)
2822 		ieee80211_node_leave_rsn(ic, ni);
2823 
2824 	if (ic->ic_curmode == IEEE80211_MODE_11G ||
2825 	    (ic->ic_curmode == IEEE80211_MODE_11N &&
2826 	    IEEE80211_IS_CHAN_2GHZ(ic->ic_bss->ni_chan)))
2827 		ieee80211_node_leave_11g(ic, ni);
2828 
2829 	if (ni->ni_flags & IEEE80211_NODE_HT)
2830 		ieee80211_node_leave_ht(ic, ni);
2831 
2832 	if (ic->ic_node_leave != NULL)
2833 		(*ic->ic_node_leave)(ic, ni);
2834 
2835 	ieee80211_node_newstate(ni, IEEE80211_STA_COLLECT);
2836 
2837 #if NBRIDGE > 0
2838 	/*
2839 	 * If the parent interface is a bridge port, delete
2840 	 * any dynamically learned address for this node.
2841 	 */
2842 	if (ic->ic_if.if_bridgeidx != 0)
2843 		bridge_update(&ic->ic_if,
2844 		    (struct ether_addr *)ni->ni_macaddr, 1);
2845 #endif
2846 }
2847 
2848 static int
2849 ieee80211_do_slow_print(struct ieee80211com *ic, int *did_print)
2850 {
2851 	static const struct timeval merge_print_intvl = {
2852 		.tv_sec = 1, .tv_usec = 0
2853 	};
2854 	if ((ic->ic_if.if_flags & IFF_LINK0) == 0)
2855 		return 0;
2856 	if (!*did_print && (ic->ic_if.if_flags & IFF_DEBUG) == 0 &&
2857 	    !ratecheck(&ic->ic_last_merge_print, &merge_print_intvl))
2858 		return 0;
2859 
2860 	*did_print = 1;
2861 	return 1;
2862 }
2863 
2864 /* ieee80211_ibss_merge helps merge 802.11 ad hoc networks.  The
2865  * convention, set by the Wireless Ethernet Compatibility Alliance
2866  * (WECA), is that an 802.11 station will change its BSSID to match
2867  * the "oldest" 802.11 ad hoc network, on the same channel, that
2868  * has the station's desired SSID.  The "oldest" 802.11 network
2869  * sends beacons with the greatest TSF timestamp.
2870  *
2871  * Return ENETRESET if the BSSID changed, 0 otherwise.
2872  *
2873  * XXX Perhaps we should compensate for the time that elapses
2874  * between the MAC receiving the beacon and the host processing it
2875  * in ieee80211_ibss_merge.
2876  */
2877 int
2878 ieee80211_ibss_merge(struct ieee80211com *ic, struct ieee80211_node *ni,
2879     u_int64_t local_tsft)
2880 {
2881 	u_int64_t beacon_tsft;
2882 	int did_print = 0, sign;
2883 	union {
2884 		u_int64_t	word;
2885 		u_int8_t	tstamp[8];
2886 	} u;
2887 
2888 	/* ensure alignment */
2889 	(void)memcpy(&u, &ni->ni_tstamp[0], sizeof(u));
2890 	beacon_tsft = letoh64(u.word);
2891 
2892 	/* we are faster, let the other guy catch up */
2893 	if (beacon_tsft < local_tsft)
2894 		sign = -1;
2895 	else
2896 		sign = 1;
2897 
2898 	if (IEEE80211_ADDR_EQ(ni->ni_bssid, ic->ic_bss->ni_bssid)) {
2899 		if (!ieee80211_do_slow_print(ic, &did_print))
2900 			return 0;
2901 		printf("%s: tsft offset %s%llu\n", ic->ic_if.if_xname,
2902 		    (sign < 0) ? "-" : "",
2903 		    (sign < 0)
2904 			? (local_tsft - beacon_tsft)
2905 			: (beacon_tsft - local_tsft));
2906 		return 0;
2907 	}
2908 
2909 	if (sign < 0)
2910 		return 0;
2911 
2912 	if (ieee80211_match_bss(ic, ni, 0) != 0)
2913 		return 0;
2914 
2915 	if (ieee80211_do_slow_print(ic, &did_print)) {
2916 		printf("%s: ieee80211_ibss_merge: bssid mismatch %s\n",
2917 		    ic->ic_if.if_xname, ether_sprintf(ni->ni_bssid));
2918 		printf("%s: my tsft %llu beacon tsft %llu\n",
2919 		    ic->ic_if.if_xname, local_tsft, beacon_tsft);
2920 		printf("%s: sync TSF with %s\n",
2921 		    ic->ic_if.if_xname, ether_sprintf(ni->ni_macaddr));
2922 	}
2923 
2924 	ic->ic_flags &= ~IEEE80211_F_SIBSS;
2925 
2926 	/* negotiate rates with new IBSS */
2927 	ieee80211_fix_rate(ic, ni, IEEE80211_F_DOFRATE |
2928 	    IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
2929 	if (ni->ni_rates.rs_nrates == 0) {
2930 		if (ieee80211_do_slow_print(ic, &did_print)) {
2931 			printf("%s: rates mismatch, BSSID %s\n",
2932 			    ic->ic_if.if_xname, ether_sprintf(ni->ni_bssid));
2933 		}
2934 		return 0;
2935 	}
2936 
2937 	if (ieee80211_do_slow_print(ic, &did_print)) {
2938 		printf("%s: sync BSSID %s -> ",
2939 		    ic->ic_if.if_xname, ether_sprintf(ic->ic_bss->ni_bssid));
2940 		printf("%s ", ether_sprintf(ni->ni_bssid));
2941 		printf("(from %s)\n", ether_sprintf(ni->ni_macaddr));
2942 	}
2943 
2944 	ieee80211_node_newstate(ni, IEEE80211_STA_BSS);
2945 	(*ic->ic_node_copy)(ic, ic->ic_bss, ni);
2946 
2947 	return ENETRESET;
2948 }
2949 
2950 void
2951 ieee80211_set_tim(struct ieee80211com *ic, int aid, int set)
2952 {
2953 	if (set)
2954 		setbit(ic->ic_tim_bitmap, aid & ~0xc000);
2955 	else
2956 		clrbit(ic->ic_tim_bitmap, aid & ~0xc000);
2957 }
2958 
2959 /*
2960  * This function shall be called by drivers immediately after every DTIM.
2961  * Transmit all group addressed MSDUs buffered at the AP.
2962  */
2963 void
2964 ieee80211_notify_dtim(struct ieee80211com *ic)
2965 {
2966 	/* NB: group addressed MSDUs are buffered in ic_bss */
2967 	struct ieee80211_node *ni = ic->ic_bss;
2968 	struct ifnet *ifp = &ic->ic_if;
2969 	struct ieee80211_frame *wh;
2970 	struct mbuf *m;
2971 
2972 	KASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP);
2973 
2974 	while ((m = mq_dequeue(&ni->ni_savedq)) != NULL) {
2975 		if (!mq_empty(&ni->ni_savedq)) {
2976 			/* more queued frames, set the more data bit */
2977 			wh = mtod(m, struct ieee80211_frame *);
2978 			wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
2979 		}
2980 		mq_enqueue(&ic->ic_pwrsaveq, m);
2981 		if_start(ifp);
2982 	}
2983 	/* XXX assumes everything has been sent */
2984 	ic->ic_tim_mcast_pending = 0;
2985 }
2986 #endif	/* IEEE80211_STA_ONLY */
2987 
2988 /*
2989  * Compare nodes in the tree by lladdr
2990  */
2991 int
2992 ieee80211_node_cmp(const struct ieee80211_node *b1,
2993     const struct ieee80211_node *b2)
2994 {
2995 	return (memcmp(b1->ni_macaddr, b2->ni_macaddr, IEEE80211_ADDR_LEN));
2996 }
2997 
2998 /*
2999  * Compare nodes in the tree by essid
3000  */
3001 int
3002 ieee80211_ess_cmp(const struct ieee80211_ess_rbt *b1,
3003     const struct ieee80211_ess_rbt *b2)
3004 {
3005 	return (memcmp(b1->essid, b2->essid, IEEE80211_NWID_LEN));
3006 }
3007 
3008 /*
3009  * Generate red-black tree function logic
3010  */
3011 RBT_GENERATE(ieee80211_tree, ieee80211_node, ni_node, ieee80211_node_cmp);
3012 RBT_GENERATE(ieee80211_ess_tree, ieee80211_ess_rbt, ess_rbt, ieee80211_ess_cmp);
3013