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