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