xref: /openbsd-src/sys/net80211/ieee80211_node.c (revision 7350f337b9e3eb4461d99580e625c7ef148d107c)
1 /*	$OpenBSD: ieee80211_node.c,v 1.168 2019/06/10 16:33:02 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_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_curmode = IEEE80211_MODE_AUTO;
819 	ieee80211_setmode(ic, ic->ic_curmode);
820 
821 	ic->ic_scan_count = 0;
822 
823 	/* Scan the next channel. */
824 	ieee80211_next_scan(ifp);
825 }
826 
827 /*
828  * Switch to the next channel marked for scanning.
829  */
830 void
831 ieee80211_next_scan(struct ifnet *ifp)
832 {
833 	struct ieee80211com *ic = (void *)ifp;
834 	struct ieee80211_channel *chan;
835 
836 	chan = ic->ic_bss->ni_chan;
837 	for (;;) {
838 		if (++chan > &ic->ic_channels[IEEE80211_CHAN_MAX])
839 			chan = &ic->ic_channels[0];
840 		if (isset(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan))) {
841 			/*
842 			 * Ignore channels marked passive-only
843 			 * during an active scan.
844 			 */
845 			if ((ic->ic_flags & IEEE80211_F_ASCAN) == 0 ||
846 			    (chan->ic_flags & IEEE80211_CHAN_PASSIVE) == 0)
847 				break;
848 		}
849 		if (chan == ic->ic_bss->ni_chan) {
850 			ieee80211_end_scan(ifp);
851 			return;
852 		}
853 	}
854 	clrbit(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan));
855 	DPRINTF(("chan %d->%d\n",
856 	    ieee80211_chan2ieee(ic, ic->ic_bss->ni_chan),
857 	    ieee80211_chan2ieee(ic, chan)));
858 	ic->ic_bss->ni_chan = chan;
859 	ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
860 }
861 
862 #ifndef IEEE80211_STA_ONLY
863 void
864 ieee80211_create_ibss(struct ieee80211com* ic, struct ieee80211_channel *chan)
865 {
866 	struct ieee80211_node *ni;
867 	struct ifnet *ifp = &ic->ic_if;
868 
869 	ni = ic->ic_bss;
870 	if (ifp->if_flags & IFF_DEBUG)
871 		printf("%s: creating ibss\n", ifp->if_xname);
872 	ic->ic_flags |= IEEE80211_F_SIBSS;
873 	ni->ni_chan = chan;
874 	ni->ni_rates = ic->ic_sup_rates[ieee80211_chan2mode(ic, ni->ni_chan)];
875 	ni->ni_txrate = 0;
876 	IEEE80211_ADDR_COPY(ni->ni_macaddr, ic->ic_myaddr);
877 	IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_myaddr);
878 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
879 		if ((ic->ic_flags & IEEE80211_F_DESBSSID) != 0)
880 			IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_des_bssid);
881 		else
882 			ni->ni_bssid[0] |= 0x02;	/* local bit for IBSS */
883 	}
884 	ni->ni_esslen = ic->ic_des_esslen;
885 	memcpy(ni->ni_essid, ic->ic_des_essid, ni->ni_esslen);
886 	ni->ni_rssi = 0;
887 	ni->ni_rstamp = 0;
888 	memset(ni->ni_tstamp, 0, sizeof(ni->ni_tstamp));
889 	ni->ni_intval = ic->ic_lintval;
890 	ni->ni_capinfo = IEEE80211_CAPINFO_IBSS;
891 	if (ic->ic_flags & IEEE80211_F_WEPON)
892 		ni->ni_capinfo |= IEEE80211_CAPINFO_PRIVACY;
893 	if (ic->ic_flags & IEEE80211_F_HTON) {
894 		const struct ieee80211_edca_ac_params *ac_qap;
895 		struct ieee80211_edca_ac_params *ac;
896 		int aci;
897 
898 		/*
899 		 * Configure HT protection. This will be updated later
900 		 * based on the number of non-HT nodes in the node cache.
901 		 */
902 		ic->ic_protmode = IEEE80211_PROT_NONE;
903 		ni->ni_htop1 = IEEE80211_HTPROT_NONE;
904 		/* Disallow Greenfield mode. None of our drivers support it. */
905 		ni->ni_htop1 |= IEEE80211_HTOP1_NONGF_STA;
906 		if (ic->ic_update_htprot)
907 			ic->ic_update_htprot(ic, ni);
908 
909 		/* Configure QoS EDCA parameters. */
910 		for (aci = 0; aci < EDCA_NUM_AC; aci++) {
911 			ac = &ic->ic_edca_ac[aci];
912 			ac_qap = &ieee80211_qap_edca_table[ic->ic_curmode][aci];
913 			ac->ac_acm       = ac_qap->ac_acm;
914 			ac->ac_aifsn     = ac_qap->ac_aifsn;
915 			ac->ac_ecwmin    = ac_qap->ac_ecwmin;
916 			ac->ac_ecwmax    = ac_qap->ac_ecwmax;
917 			ac->ac_txoplimit = ac_qap->ac_txoplimit;
918 		}
919 		if (ic->ic_updateedca)
920 			(*ic->ic_updateedca)(ic);
921 	}
922 	if (ic->ic_flags & IEEE80211_F_RSNON) {
923 		struct ieee80211_key *k;
924 
925 		/* initialize 256-bit global key counter to a random value */
926 		arc4random_buf(ic->ic_globalcnt, EAPOL_KEY_NONCE_LEN);
927 
928 		ni->ni_rsnprotos = ic->ic_rsnprotos;
929 		ni->ni_rsnakms = ic->ic_rsnakms;
930 		ni->ni_rsnciphers = ic->ic_rsnciphers;
931 		ni->ni_rsngroupcipher = ic->ic_rsngroupcipher;
932 		ni->ni_rsngroupmgmtcipher = ic->ic_rsngroupmgmtcipher;
933 		ni->ni_rsncaps = 0;
934 		if (ic->ic_caps & IEEE80211_C_MFP) {
935 			ni->ni_rsncaps |= IEEE80211_RSNCAP_MFPC;
936 			if (ic->ic_flags & IEEE80211_F_MFPR)
937 				ni->ni_rsncaps |= IEEE80211_RSNCAP_MFPR;
938 		}
939 
940 		ic->ic_def_txkey = 1;
941 		ic->ic_flags &= ~IEEE80211_F_COUNTERM;
942 		k = &ic->ic_nw_keys[ic->ic_def_txkey];
943 		memset(k, 0, sizeof(*k));
944 		k->k_id = ic->ic_def_txkey;
945 		k->k_cipher = ni->ni_rsngroupcipher;
946 		k->k_flags = IEEE80211_KEY_GROUP | IEEE80211_KEY_TX;
947 		k->k_len = ieee80211_cipher_keylen(k->k_cipher);
948 		arc4random_buf(k->k_key, k->k_len);
949 		(*ic->ic_set_key)(ic, ni, k);	/* XXX */
950 
951 		if (ic->ic_caps & IEEE80211_C_MFP) {
952 			ic->ic_igtk_kid = 4;
953 			k = &ic->ic_nw_keys[ic->ic_igtk_kid];
954 			memset(k, 0, sizeof(*k));
955 			k->k_id = ic->ic_igtk_kid;
956 			k->k_cipher = ni->ni_rsngroupmgmtcipher;
957 			k->k_flags = IEEE80211_KEY_IGTK | IEEE80211_KEY_TX;
958 			k->k_len = 16;
959 			arc4random_buf(k->k_key, k->k_len);
960 			(*ic->ic_set_key)(ic, ni, k);	/* XXX */
961 		}
962 		/*
963 		 * In HostAP mode, multicast traffic is sent using ic_bss
964 		 * as the Tx node, so mark our node as valid so we can send
965 		 * multicast frames using the group key we've just configured.
966 		 */
967 		ni->ni_port_valid = 1;
968 		ni->ni_flags |= IEEE80211_NODE_TXPROT;
969 
970 		/* schedule a GTK/IGTK rekeying after 3600s */
971 		timeout_add_sec(&ic->ic_rsn_timeout, 3600);
972 	}
973 	timeout_add_sec(&ic->ic_inact_timeout, IEEE80211_INACT_WAIT);
974 	timeout_add_sec(&ic->ic_node_cache_timeout, IEEE80211_CACHE_WAIT);
975 	ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
976 }
977 #endif	/* IEEE80211_STA_ONLY */
978 
979 int
980 ieee80211_match_bss(struct ieee80211com *ic, struct ieee80211_node *ni)
981 {
982 	u_int8_t rate;
983 	int fail;
984 
985 	fail = 0;
986 	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
987 		fail |= 0x01;
988 	if (ic->ic_des_chan != IEEE80211_CHAN_ANYC &&
989 	    ni->ni_chan != ic->ic_des_chan)
990 		fail |= 0x01;
991 #ifndef IEEE80211_STA_ONLY
992 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
993 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
994 			fail |= 0x02;
995 	} else
996 #endif
997 	{
998 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
999 			fail |= 0x02;
1000 	}
1001 	if (ic->ic_flags & (IEEE80211_F_WEPON | IEEE80211_F_RSNON)) {
1002 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
1003 			fail |= 0x04;
1004 	} else {
1005 		if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
1006 			fail |= 0x04;
1007 	}
1008 
1009 	rate = ieee80211_fix_rate(ic, ni, IEEE80211_F_DONEGO);
1010 	if (rate & IEEE80211_RATE_BASIC)
1011 		fail |= 0x08;
1012 	if (ISSET(ic->ic_flags, IEEE80211_F_AUTO_JOIN) &&
1013 	    ic->ic_des_esslen == 0)
1014 		fail |= 0x10;
1015 	if (ic->ic_des_esslen != 0 &&
1016 	    (ni->ni_esslen != ic->ic_des_esslen ||
1017 	     memcmp(ni->ni_essid, ic->ic_des_essid, ic->ic_des_esslen) != 0))
1018 		fail |= 0x10;
1019 	if ((ic->ic_flags & IEEE80211_F_DESBSSID) &&
1020 	    !IEEE80211_ADDR_EQ(ic->ic_des_bssid, ni->ni_bssid))
1021 		fail |= 0x20;
1022 
1023 	if (ic->ic_flags & IEEE80211_F_RSNON) {
1024 		/*
1025 		 * If at least one RSN IE field from the AP's RSN IE fails
1026 		 * to overlap with any value the STA supports, the STA shall
1027 		 * decline to associate with that AP.
1028 		 */
1029 		if ((ni->ni_rsnprotos & ic->ic_rsnprotos) == 0)
1030 			fail |= 0x40;
1031 		if ((ni->ni_rsnakms & ic->ic_rsnakms) == 0)
1032 			fail |= 0x40;
1033 		if ((ni->ni_rsnakms & ic->ic_rsnakms &
1034 		     ~(IEEE80211_AKM_PSK | IEEE80211_AKM_SHA256_PSK)) == 0) {
1035 			/* AP only supports PSK AKMPs */
1036 			if (!(ic->ic_flags & IEEE80211_F_PSK))
1037 				fail |= 0x40;
1038 		}
1039 		if (ni->ni_rsngroupcipher != IEEE80211_CIPHER_WEP40 &&
1040 		    ni->ni_rsngroupcipher != IEEE80211_CIPHER_TKIP &&
1041 		    ni->ni_rsngroupcipher != IEEE80211_CIPHER_CCMP &&
1042 		    ni->ni_rsngroupcipher != IEEE80211_CIPHER_WEP104)
1043 			fail |= 0x40;
1044 		if ((ni->ni_rsnciphers & ic->ic_rsnciphers) == 0)
1045 			fail |= 0x40;
1046 
1047 		/* we only support BIP as the IGTK cipher */
1048 		if ((ni->ni_rsncaps & IEEE80211_RSNCAP_MFPC) &&
1049 		    ni->ni_rsngroupmgmtcipher != IEEE80211_CIPHER_BIP)
1050 			fail |= 0x40;
1051 
1052 		/* we do not support MFP but AP requires it */
1053 		if (!(ic->ic_caps & IEEE80211_C_MFP) &&
1054 		    (ni->ni_rsncaps & IEEE80211_RSNCAP_MFPR))
1055 			fail |= 0x40;
1056 
1057 		/* we require MFP but AP does not support it */
1058 		if ((ic->ic_caps & IEEE80211_C_MFP) &&
1059 		    (ic->ic_flags & IEEE80211_F_MFPR) &&
1060 		    !(ni->ni_rsncaps & IEEE80211_RSNCAP_MFPC))
1061 			fail |= 0x40;
1062 	}
1063 
1064 	if (ic->ic_if.if_flags & IFF_DEBUG) {
1065 		printf("%s: %c %s%c", ic->ic_if.if_xname, fail ? '-' : '+',
1066 		    ether_sprintf(ni->ni_bssid),
1067 		    fail & 0x20 ? '!' : ' ');
1068 		printf(" %3d%c", ieee80211_chan2ieee(ic, ni->ni_chan),
1069 			fail & 0x01 ? '!' : ' ');
1070 		printf(" %+4d", ni->ni_rssi);
1071 		printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
1072 		    fail & 0x08 ? '!' : ' ');
1073 		printf(" %4s%c",
1074 		    (ni->ni_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
1075 		    (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
1076 		    "????",
1077 		    fail & 0x02 ? '!' : ' ');
1078 		printf(" %7s%c ",
1079 		    (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) ?
1080 		    "privacy" : "no",
1081 		    fail & 0x04 ? '!' : ' ');
1082 		printf(" %3s%c ",
1083 		    (ic->ic_flags & IEEE80211_F_RSNON) ?
1084 		    "rsn" : "no",
1085 		    fail & 0x40 ? '!' : ' ');
1086 		ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
1087 		printf("%s\n", fail & 0x10 ? "!" : "");
1088 	}
1089 
1090 	return fail;
1091 }
1092 
1093 struct ieee80211_node_switch_bss_arg {
1094 	u_int8_t cur_macaddr[IEEE80211_ADDR_LEN];
1095 	u_int8_t sel_macaddr[IEEE80211_ADDR_LEN];
1096 };
1097 
1098 /* Implements ni->ni_unref_cb(). */
1099 void
1100 ieee80211_node_switch_bss(struct ieee80211com *ic, struct ieee80211_node *ni)
1101 {
1102 	struct ifnet *ifp = &ic->ic_if;
1103 	struct ieee80211_node_switch_bss_arg *sba = ni->ni_unref_arg;
1104 	struct ieee80211_node *curbs, *selbs;
1105 
1106 	splassert(IPL_NET);
1107 
1108 	if ((ic->ic_flags & IEEE80211_F_BGSCAN) == 0) {
1109 		free(sba, M_DEVBUF, sizeof(*sba));
1110 		return;
1111 	}
1112 
1113 	ic->ic_xflags &= ~IEEE80211_F_TX_MGMT_ONLY;
1114 
1115 	selbs = ieee80211_find_node(ic, sba->sel_macaddr);
1116 	if (selbs == NULL) {
1117 		free(sba, M_DEVBUF, sizeof(*sba));
1118 		ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1119 		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
1120 		return;
1121 	}
1122 
1123 	curbs = ieee80211_find_node(ic, sba->cur_macaddr);
1124 	if (curbs == NULL) {
1125 		free(sba, M_DEVBUF, sizeof(*sba));
1126 		ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1127 		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
1128 		return;
1129 	}
1130 
1131 	if (ifp->if_flags & IFF_DEBUG) {
1132 		printf("%s: roaming from %s chan %d ",
1133 		    ifp->if_xname, ether_sprintf(curbs->ni_macaddr),
1134 		    ieee80211_chan2ieee(ic, curbs->ni_chan));
1135 		printf("to %s chan %d\n", ether_sprintf(selbs->ni_macaddr),
1136 		    ieee80211_chan2ieee(ic, selbs->ni_chan));
1137 	}
1138 	ieee80211_node_newstate(curbs, IEEE80211_STA_CACHE);
1139 	ieee80211_node_join_bss(ic, selbs); /* frees arg and ic->ic_bss */
1140 }
1141 
1142 void
1143 ieee80211_node_join_bss(struct ieee80211com *ic, struct ieee80211_node *selbs)
1144 {
1145 	enum ieee80211_phymode mode;
1146 	struct ieee80211_node *ni;
1147 
1148 	/* Reinitialize media mode and channels if needed. */
1149 	mode = ieee80211_chan2mode(ic, selbs->ni_chan);
1150 	if (mode != ic->ic_curmode)
1151 		ieee80211_setmode(ic, mode);
1152 
1153 	(*ic->ic_node_copy)(ic, ic->ic_bss, selbs);
1154 	ni = ic->ic_bss;
1155 
1156 	ic->ic_curmode = ieee80211_chan2mode(ic, ni->ni_chan);
1157 
1158 	/* Make sure we send valid rates in an association request. */
1159 	if (ic->ic_opmode == IEEE80211_M_STA)
1160 		ieee80211_fix_rate(ic, ni,
1161 		    IEEE80211_F_DOSORT | IEEE80211_F_DOFRATE |
1162 		    IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
1163 
1164 	if (ic->ic_flags & IEEE80211_F_RSNON)
1165 		ieee80211_choose_rsnparams(ic);
1166 	else if (ic->ic_flags & IEEE80211_F_WEPON)
1167 		ni->ni_rsncipher = IEEE80211_CIPHER_USEGROUP;
1168 
1169 	ieee80211_node_newstate(selbs, IEEE80211_STA_BSS);
1170 #ifndef IEEE80211_STA_ONLY
1171 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
1172 		ieee80211_fix_rate(ic, ni, IEEE80211_F_DOFRATE |
1173 		    IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
1174 		if (ni->ni_rates.rs_nrates == 0) {
1175 			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
1176 			return;
1177 		}
1178 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
1179 	} else
1180 #endif
1181 	{
1182 		int bgscan = ((ic->ic_flags & IEEE80211_F_BGSCAN) &&
1183 		    ic->ic_opmode == IEEE80211_M_STA &&
1184 		    ic->ic_state == IEEE80211_S_RUN);
1185 		int auth_next = (ic->ic_opmode == IEEE80211_M_STA &&
1186 		    ic->ic_state == IEEE80211_S_AUTH);
1187 		int mgt = -1;
1188 
1189 		timeout_del(&ic->ic_bgscan_timeout);
1190 		ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1191 
1192 		/*
1193 		 * After a background scan, we have now switched APs.
1194 		 * Pretend we were just de-authed, which makes
1195 		 * ieee80211_new_state() try to re-auth and thus send
1196 		 * an AUTH frame to our newly selected AP.
1197 		 */
1198 		if (bgscan)
1199 			mgt = IEEE80211_FC0_SUBTYPE_DEAUTH;
1200 		/*
1201 		 * If we are trying another AP after the previous one
1202 		 * failed (state transition AUTH->AUTH), ensure that
1203 		 * ieee80211_new_state() tries to send another auth frame.
1204 		 */
1205 		else if (auth_next)
1206 			mgt = IEEE80211_FC0_SUBTYPE_AUTH;
1207 
1208 		ieee80211_new_state(ic, IEEE80211_S_AUTH, mgt);
1209 	}
1210 }
1211 
1212 struct ieee80211_node *
1213 ieee80211_node_choose_bss(struct ieee80211com *ic, int bgscan,
1214     struct ieee80211_node **curbs)
1215 {
1216 	struct ieee80211_node *ni, *nextbs, *selbs = NULL,
1217 	    *selbs2 = NULL, *selbs5 = NULL;
1218 	uint8_t min_5ghz_rssi;
1219 
1220 	ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
1221 
1222 	for (; ni != NULL; ni = nextbs) {
1223 		nextbs = RBT_NEXT(ieee80211_tree, ni);
1224 		if (ni->ni_fails) {
1225 			/*
1226 			 * The configuration of the access points may change
1227 			 * during my scan.  So delete the entry for the AP
1228 			 * and retry to associate if there is another beacon.
1229 			 */
1230 			if (ni->ni_fails++ > 2)
1231 				ieee80211_free_node(ic, ni);
1232 			continue;
1233 		}
1234 
1235 		if (curbs && ieee80211_node_cmp(ic->ic_bss, ni) == 0)
1236 			*curbs = ni;
1237 
1238 		if (ieee80211_match_bss(ic, ni) != 0)
1239 			continue;
1240 
1241 		if (ic->ic_caps & IEEE80211_C_SCANALLBAND) {
1242 			if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan) &&
1243 			    (selbs2 == NULL || ni->ni_rssi > selbs2->ni_rssi))
1244 				selbs2 = ni;
1245 			else if (IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) &&
1246 			    (selbs5 == NULL || ni->ni_rssi > selbs5->ni_rssi))
1247 				selbs5 = ni;
1248 		} else if (selbs == NULL || ni->ni_rssi > selbs->ni_rssi)
1249 			selbs = ni;
1250 	}
1251 
1252 	if (ic->ic_max_rssi)
1253 		min_5ghz_rssi = IEEE80211_RSSI_THRES_RATIO_5GHZ;
1254 	else
1255 		min_5ghz_rssi = (uint8_t)IEEE80211_RSSI_THRES_5GHZ;
1256 
1257 	/*
1258 	 * Prefer a 5Ghz AP even if its RSSI is weaker than the best 2Ghz AP
1259 	 * (as long as it meets the minimum RSSI threshold) since the 5Ghz band
1260 	 * is usually less saturated.
1261 	 */
1262 	if (selbs5 && selbs5->ni_rssi > min_5ghz_rssi)
1263 		selbs = selbs5;
1264 	else if (selbs5 && selbs2)
1265 		selbs = (selbs5->ni_rssi >= selbs2->ni_rssi ? selbs5 : selbs2);
1266 	else if (selbs2)
1267 		selbs = selbs2;
1268 	else if (selbs5)
1269 		selbs = selbs5;
1270 
1271 	return selbs;
1272 }
1273 
1274 /*
1275  * Complete a scan of potential channels.
1276  */
1277 void
1278 ieee80211_end_scan(struct ifnet *ifp)
1279 {
1280 	struct ieee80211com *ic = (void *)ifp;
1281 	struct ieee80211_node *ni, *selbs = NULL, *curbs = NULL;
1282 	int bgscan = ((ic->ic_flags & IEEE80211_F_BGSCAN) &&
1283 	    ic->ic_opmode == IEEE80211_M_STA &&
1284 	    ic->ic_state == IEEE80211_S_RUN);
1285 
1286 	if (ifp->if_flags & IFF_DEBUG)
1287 		printf("%s: end %s scan\n", ifp->if_xname,
1288 		    bgscan ? "background" :
1289 		    ((ic->ic_flags & IEEE80211_F_ASCAN) ?
1290 		    "active" : "passive"));
1291 
1292 	if (ic->ic_scan_count)
1293 		ic->ic_flags &= ~IEEE80211_F_ASCAN;
1294 
1295 	ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
1296 
1297 #ifndef IEEE80211_STA_ONLY
1298 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
1299 		/* XXX off stack? */
1300 		u_char occupied[howmany(IEEE80211_CHAN_MAX, NBBY)];
1301 		int i, fail;
1302 
1303 		/*
1304 		 * The passive scan to look for existing AP's completed,
1305 		 * select a channel to camp on.  Identify the channels
1306 		 * that already have one or more AP's and try to locate
1307 		 * an unoccupied one.  If that fails, pick a random
1308 		 * channel from the active set.
1309 		 */
1310 		memset(occupied, 0, sizeof(occupied));
1311 		RBT_FOREACH(ni, ieee80211_tree, &ic->ic_tree)
1312 			setbit(occupied, ieee80211_chan2ieee(ic, ni->ni_chan));
1313 		for (i = 0; i < IEEE80211_CHAN_MAX; i++)
1314 			if (isset(ic->ic_chan_active, i) && isclr(occupied, i))
1315 				break;
1316 		if (i == IEEE80211_CHAN_MAX) {
1317 			fail = arc4random() & 3;	/* random 0-3 */
1318 			for (i = 0; i < IEEE80211_CHAN_MAX; i++)
1319 				if (isset(ic->ic_chan_active, i) && fail-- == 0)
1320 					break;
1321 		}
1322 		ieee80211_create_ibss(ic, &ic->ic_channels[i]);
1323 		return;
1324 	}
1325 #endif
1326 	if (ni == NULL) {
1327 		DPRINTF(("no scan candidate\n"));
1328  notfound:
1329 
1330 #ifndef IEEE80211_STA_ONLY
1331 		if (ic->ic_opmode == IEEE80211_M_IBSS &&
1332 		    (ic->ic_flags & IEEE80211_F_IBSSON) &&
1333 		    ic->ic_des_esslen != 0) {
1334 			ieee80211_create_ibss(ic, ic->ic_ibss_chan);
1335 			return;
1336 		}
1337 #endif
1338 		/*
1339 		 * Reset the list of channels to scan and scan the next mode
1340 		 * if nothing has been found.
1341 		 * If the device scans all bands in one fell swoop, return
1342 		 * current scan results to userspace regardless of mode.
1343 		 * This will loop forever until an access point is found.
1344 		 */
1345 		ieee80211_reset_scan(ifp);
1346 		if (ieee80211_next_mode(ifp) == IEEE80211_MODE_AUTO ||
1347 		    (ic->ic_caps & IEEE80211_C_SCANALLBAND))
1348 			ic->ic_scan_count++;
1349 
1350 		ieee80211_next_scan(ifp);
1351 		return;
1352 	}
1353 
1354 	/* Possibly switch which ssid we are associated with */
1355 	if (!bgscan && ic->ic_opmode == IEEE80211_M_STA)
1356 		ieee80211_switch_ess(ic);
1357 
1358 	selbs = ieee80211_node_choose_bss(ic, bgscan, &curbs);
1359 	if (bgscan) {
1360 		struct ieee80211_node_switch_bss_arg *arg;
1361 
1362 		/* AP disappeared? Should not happen. */
1363 		if (selbs == NULL || curbs == NULL) {
1364 			ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1365 			goto notfound;
1366 		}
1367 
1368 		/*
1369 		 * After a background scan we might end up choosing the
1370 		 * same AP again. Do not change ic->ic_bss in this case,
1371 		 * and make background scans less frequent.
1372 		 */
1373 		if (selbs == curbs) {
1374 			if (ic->ic_bgscan_fail < IEEE80211_BGSCAN_FAIL_MAX)
1375 				ic->ic_bgscan_fail++;
1376 			ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1377 			return;
1378 		}
1379 
1380 		arg = malloc(sizeof(*arg), M_DEVBUF, M_NOWAIT | M_ZERO);
1381 		if (arg == NULL) {
1382 			ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1383 			return;
1384 		}
1385 
1386 		ic->ic_bgscan_fail = 0;
1387 
1388 		/*
1389 		 * We are going to switch APs.
1390 		 * Queue a de-auth frame addressed to our current AP.
1391 		 */
1392 		if (IEEE80211_SEND_MGMT(ic, ic->ic_bss,
1393 		    IEEE80211_FC0_SUBTYPE_DEAUTH,
1394 		    IEEE80211_REASON_AUTH_LEAVE) != 0) {
1395 			ic->ic_flags &= ~IEEE80211_F_BGSCAN;
1396 			free(arg, M_DEVBUF, sizeof(*arg));
1397 			return;
1398 		}
1399 
1400 		/* Prevent dispatch of additional data frames to hardware. */
1401 		ic->ic_xflags |= IEEE80211_F_TX_MGMT_ONLY;
1402 
1403 		/*
1404 		 * Install a callback which will switch us to the new AP once
1405 		 * all dispatched frames have been processed by hardware.
1406 		 */
1407 		IEEE80211_ADDR_COPY(arg->cur_macaddr, curbs->ni_macaddr);
1408 		IEEE80211_ADDR_COPY(arg->sel_macaddr, selbs->ni_macaddr);
1409 		ic->ic_bss->ni_unref_arg = arg;
1410 		ic->ic_bss->ni_unref_arg_size = sizeof(*arg);
1411 		ic->ic_bss->ni_unref_cb = ieee80211_node_switch_bss;
1412 		/* F_BGSCAN flag gets cleared in ieee80211_node_join_bss(). */
1413 		return;
1414 	} else if (selbs == NULL)
1415 		goto notfound;
1416 
1417 	ieee80211_node_join_bss(ic, selbs);
1418 }
1419 
1420 /*
1421  * Autoselect the best RSN parameters (protocol, AKMP, pairwise cipher...)
1422  * that are supported by both peers (STA mode only).
1423  */
1424 void
1425 ieee80211_choose_rsnparams(struct ieee80211com *ic)
1426 {
1427 	struct ieee80211_node *ni = ic->ic_bss;
1428 	struct ieee80211_pmk *pmk;
1429 
1430 	/* filter out unsupported protocol versions */
1431 	ni->ni_rsnprotos &= ic->ic_rsnprotos;
1432 	/* prefer RSN (aka WPA2) over WPA */
1433 	if (ni->ni_rsnprotos & IEEE80211_PROTO_RSN)
1434 		ni->ni_rsnprotos = IEEE80211_PROTO_RSN;
1435 	else
1436 		ni->ni_rsnprotos = IEEE80211_PROTO_WPA;
1437 
1438 	/* filter out unsupported AKMPs */
1439 	ni->ni_rsnakms &= ic->ic_rsnakms;
1440 	/* prefer SHA-256 based AKMPs */
1441 	if ((ic->ic_flags & IEEE80211_F_PSK) && (ni->ni_rsnakms &
1442 	    (IEEE80211_AKM_PSK | IEEE80211_AKM_SHA256_PSK))) {
1443 		/* AP supports PSK AKMP and a PSK is configured */
1444 		if (ni->ni_rsnakms & IEEE80211_AKM_SHA256_PSK)
1445 			ni->ni_rsnakms = IEEE80211_AKM_SHA256_PSK;
1446 		else
1447 			ni->ni_rsnakms = IEEE80211_AKM_PSK;
1448 	} else {
1449 		if (ni->ni_rsnakms & IEEE80211_AKM_SHA256_8021X)
1450 			ni->ni_rsnakms = IEEE80211_AKM_SHA256_8021X;
1451 		else
1452 			ni->ni_rsnakms = IEEE80211_AKM_8021X;
1453 		/* check if we have a cached PMK for this AP */
1454 		if (ni->ni_rsnprotos == IEEE80211_PROTO_RSN &&
1455 		    (pmk = ieee80211_pmksa_find(ic, ni, NULL)) != NULL) {
1456 			memcpy(ni->ni_pmkid, pmk->pmk_pmkid,
1457 			    IEEE80211_PMKID_LEN);
1458 			ni->ni_flags |= IEEE80211_NODE_PMKID;
1459 		}
1460 	}
1461 
1462 	/* filter out unsupported pairwise ciphers */
1463 	ni->ni_rsnciphers &= ic->ic_rsnciphers;
1464 	/* prefer CCMP over TKIP */
1465 	if (ni->ni_rsnciphers & IEEE80211_CIPHER_CCMP)
1466 		ni->ni_rsnciphers = IEEE80211_CIPHER_CCMP;
1467 	else
1468 		ni->ni_rsnciphers = IEEE80211_CIPHER_TKIP;
1469 	ni->ni_rsncipher = ni->ni_rsnciphers;
1470 
1471 	/* use MFP if we both support it */
1472 	if ((ic->ic_caps & IEEE80211_C_MFP) &&
1473 	    (ni->ni_rsncaps & IEEE80211_RSNCAP_MFPC))
1474 		ni->ni_flags |= IEEE80211_NODE_MFP;
1475 }
1476 
1477 int
1478 ieee80211_get_rate(struct ieee80211com *ic)
1479 {
1480 	u_int8_t (*rates)[IEEE80211_RATE_MAXSIZE];
1481 	int rate;
1482 
1483 	rates = &ic->ic_bss->ni_rates.rs_rates;
1484 
1485 	if (ic->ic_fixed_rate != -1)
1486 		rate = (*rates)[ic->ic_fixed_rate];
1487 	else if (ic->ic_state == IEEE80211_S_RUN)
1488 		rate = (*rates)[ic->ic_bss->ni_txrate];
1489 	else
1490 		rate = 0;
1491 
1492 	return rate & IEEE80211_RATE_VAL;
1493 }
1494 
1495 struct ieee80211_node *
1496 ieee80211_node_alloc(struct ieee80211com *ic)
1497 {
1498 	return malloc(sizeof(struct ieee80211_node), M_DEVBUF,
1499 	    M_NOWAIT | M_ZERO);
1500 }
1501 
1502 void
1503 ieee80211_node_cleanup(struct ieee80211com *ic, struct ieee80211_node *ni)
1504 {
1505 	if (ni->ni_rsnie != NULL) {
1506 		free(ni->ni_rsnie, M_DEVBUF, 2 + ni->ni_rsnie[1]);
1507 		ni->ni_rsnie = NULL;
1508 	}
1509 	ieee80211_ba_del(ni);
1510 	free(ni->ni_unref_arg, M_DEVBUF, ni->ni_unref_arg_size);
1511 	ni->ni_unref_arg = NULL;
1512 	ni->ni_unref_arg_size = 0;
1513 }
1514 
1515 void
1516 ieee80211_node_free(struct ieee80211com *ic, struct ieee80211_node *ni)
1517 {
1518 	ieee80211_node_cleanup(ic, ni);
1519 	free(ni, M_DEVBUF, 0);
1520 }
1521 
1522 void
1523 ieee80211_node_copy(struct ieee80211com *ic,
1524 	struct ieee80211_node *dst, const struct ieee80211_node *src)
1525 {
1526 	ieee80211_node_cleanup(ic, dst);
1527 	*dst = *src;
1528 	dst->ni_rsnie = NULL;
1529 	if (src->ni_rsnie != NULL)
1530 		ieee80211_save_ie(src->ni_rsnie, &dst->ni_rsnie);
1531 }
1532 
1533 u_int8_t
1534 ieee80211_node_getrssi(struct ieee80211com *ic,
1535     const struct ieee80211_node *ni)
1536 {
1537 	return ni->ni_rssi;
1538 }
1539 
1540 int
1541 ieee80211_node_checkrssi(struct ieee80211com *ic,
1542     const struct ieee80211_node *ni)
1543 {
1544 	uint8_t thres;
1545 
1546 	if (ni->ni_chan == IEEE80211_CHAN_ANYC)
1547 		return 0;
1548 
1549 	if (ic->ic_max_rssi) {
1550 		thres = (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) ?
1551 		    IEEE80211_RSSI_THRES_RATIO_2GHZ :
1552 		    IEEE80211_RSSI_THRES_RATIO_5GHZ;
1553 		return ((ni->ni_rssi * 100) / ic->ic_max_rssi >= thres);
1554 	}
1555 
1556 	thres = (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan)) ?
1557 	    IEEE80211_RSSI_THRES_2GHZ :
1558 	    IEEE80211_RSSI_THRES_5GHZ;
1559 	return (ni->ni_rssi >= (u_int8_t)thres);
1560 }
1561 
1562 void
1563 ieee80211_setup_node(struct ieee80211com *ic,
1564 	struct ieee80211_node *ni, const u_int8_t *macaddr)
1565 {
1566 	int i, s;
1567 
1568 	DPRINTF(("%s\n", ether_sprintf((u_int8_t *)macaddr)));
1569 	IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
1570 	ieee80211_node_newstate(ni, IEEE80211_STA_CACHE);
1571 
1572 	ni->ni_ic = ic;	/* back-pointer */
1573 	/* Initialize cached last sequence numbers with invalid values. */
1574 	ni->ni_rxseq = 0xffffU;
1575 	for (i=0; i < IEEE80211_NUM_TID; ++i)
1576 		ni->ni_qos_rxseqs[i] = 0xffffU;
1577 #ifndef IEEE80211_STA_ONLY
1578 	mq_init(&ni->ni_savedq, IEEE80211_PS_MAX_QUEUE, IPL_NET);
1579 	timeout_set(&ni->ni_eapol_to, ieee80211_eapol_timeout, ni);
1580 	timeout_set(&ni->ni_sa_query_to, ieee80211_sa_query_timeout, ni);
1581 #endif
1582 	s = splnet();
1583 	RBT_INSERT(ieee80211_tree, &ic->ic_tree, ni);
1584 	ic->ic_nnodes++;
1585 	splx(s);
1586 }
1587 
1588 struct ieee80211_node *
1589 ieee80211_alloc_node(struct ieee80211com *ic, const u_int8_t *macaddr)
1590 {
1591 	struct ieee80211_node *ni = ieee80211_alloc_node_helper(ic);
1592 	if (ni != NULL)
1593 		ieee80211_setup_node(ic, ni, macaddr);
1594 	else
1595 		ic->ic_stats.is_rx_nodealloc++;
1596 	return ni;
1597 }
1598 
1599 struct ieee80211_node *
1600 ieee80211_dup_bss(struct ieee80211com *ic, const u_int8_t *macaddr)
1601 {
1602 	struct ieee80211_node *ni = ieee80211_alloc_node_helper(ic);
1603 	if (ni != NULL) {
1604 		ieee80211_setup_node(ic, ni, macaddr);
1605 		/*
1606 		 * Inherit from ic_bss.
1607 		 */
1608 		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
1609 		ni->ni_chan = ic->ic_bss->ni_chan;
1610 	} else
1611 		ic->ic_stats.is_rx_nodealloc++;
1612 	return ni;
1613 }
1614 
1615 struct ieee80211_node *
1616 ieee80211_find_node(struct ieee80211com *ic, const u_int8_t *macaddr)
1617 {
1618 	struct ieee80211_node *ni;
1619 	int cmp;
1620 
1621 	/* similar to RBT_FIND except we compare keys, not nodes */
1622 	ni = RBT_ROOT(ieee80211_tree, &ic->ic_tree);
1623 	while (ni != NULL) {
1624 		cmp = memcmp(macaddr, ni->ni_macaddr, IEEE80211_ADDR_LEN);
1625 		if (cmp < 0)
1626 			ni = RBT_LEFT(ieee80211_tree, ni);
1627 		else if (cmp > 0)
1628 			ni = RBT_RIGHT(ieee80211_tree, ni);
1629 		else
1630 			break;
1631 	}
1632 	return ni;
1633 }
1634 
1635 /*
1636  * Return a reference to the appropriate node for sending
1637  * a data frame.  This handles node discovery in adhoc networks.
1638  *
1639  * Drivers will call this, so increase the reference count before
1640  * returning the node.
1641  */
1642 struct ieee80211_node *
1643 ieee80211_find_txnode(struct ieee80211com *ic, const u_int8_t *macaddr)
1644 {
1645 #ifndef IEEE80211_STA_ONLY
1646 	struct ieee80211_node *ni;
1647 	int s;
1648 #endif
1649 
1650 	/*
1651 	 * The destination address should be in the node table
1652 	 * unless we are operating in station mode or this is a
1653 	 * multicast/broadcast frame.
1654 	 */
1655 	if (ic->ic_opmode == IEEE80211_M_STA || IEEE80211_IS_MULTICAST(macaddr))
1656 		return ieee80211_ref_node(ic->ic_bss);
1657 
1658 #ifndef IEEE80211_STA_ONLY
1659 	s = splnet();
1660 	ni = ieee80211_find_node(ic, macaddr);
1661 	splx(s);
1662 	if (ni == NULL) {
1663 		if (ic->ic_opmode != IEEE80211_M_IBSS &&
1664 		    ic->ic_opmode != IEEE80211_M_AHDEMO)
1665 			return NULL;
1666 
1667 		/*
1668 		 * Fake up a node; this handles node discovery in
1669 		 * adhoc mode.  Note that for the driver's benefit
1670 		 * we we treat this like an association so the driver
1671 		 * has an opportunity to setup its private state.
1672 		 *
1673 		 * XXX need better way to handle this; issue probe
1674 		 *     request so we can deduce rate set, etc.
1675 		 */
1676 		if ((ni = ieee80211_dup_bss(ic, macaddr)) == NULL)
1677 			return NULL;
1678 		/* XXX no rate negotiation; just dup */
1679 		ni->ni_rates = ic->ic_bss->ni_rates;
1680 		ni->ni_txrate = 0;
1681 		if (ic->ic_newassoc)
1682 			(*ic->ic_newassoc)(ic, ni, 1);
1683 	}
1684 	return ieee80211_ref_node(ni);
1685 #else
1686 	return NULL;	/* can't get there */
1687 #endif	/* IEEE80211_STA_ONLY */
1688 }
1689 
1690 /*
1691  * It is usually desirable to process a Rx packet using its sender's
1692  * node-record instead of the BSS record.
1693  *
1694  * - AP mode: keep a node-record for every authenticated/associated
1695  *   station *in the BSS*. For future use, we also track neighboring
1696  *   APs, since they might belong to the same ESS.  APs in the same
1697  *   ESS may bridge packets to each other, forming a Wireless
1698  *   Distribution System (WDS).
1699  *
1700  * - IBSS mode: keep a node-record for every station *in the BSS*.
1701  *   Also track neighboring stations by their beacons/probe responses.
1702  *
1703  * - monitor mode: keep a node-record for every sender, regardless
1704  *   of BSS.
1705  *
1706  * - STA mode: the only available node-record is the BSS record,
1707  *   ic->ic_bss.
1708  *
1709  * Of all the 802.11 Control packets, only the node-records for
1710  * RTS packets node-record can be looked up.
1711  *
1712  * Return non-zero if the packet's node-record is kept, zero
1713  * otherwise.
1714  */
1715 static __inline int
1716 ieee80211_needs_rxnode(struct ieee80211com *ic,
1717     const struct ieee80211_frame *wh, const u_int8_t **bssid)
1718 {
1719 	int monitor, rc = 0;
1720 
1721 	monitor = (ic->ic_opmode == IEEE80211_M_MONITOR);
1722 
1723 	*bssid = NULL;
1724 
1725 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
1726 	case IEEE80211_FC0_TYPE_CTL:
1727 		if (!monitor)
1728 			break;
1729 		return (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
1730 		    IEEE80211_FC0_SUBTYPE_RTS;
1731 	case IEEE80211_FC0_TYPE_MGT:
1732 		*bssid = wh->i_addr3;
1733 		switch (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) {
1734 		case IEEE80211_FC0_SUBTYPE_BEACON:
1735 		case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
1736 			break;
1737 		default:
1738 #ifndef IEEE80211_STA_ONLY
1739 			if (ic->ic_opmode == IEEE80211_M_STA)
1740 				break;
1741 			rc = IEEE80211_ADDR_EQ(*bssid, ic->ic_bss->ni_bssid) ||
1742 			     IEEE80211_ADDR_EQ(*bssid, etherbroadcastaddr);
1743 #endif
1744 			break;
1745 		}
1746 		break;
1747 	case IEEE80211_FC0_TYPE_DATA:
1748 		switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
1749 		case IEEE80211_FC1_DIR_NODS:
1750 			*bssid = wh->i_addr3;
1751 #ifndef IEEE80211_STA_ONLY
1752 			if (ic->ic_opmode == IEEE80211_M_IBSS ||
1753 			    ic->ic_opmode == IEEE80211_M_AHDEMO)
1754 				rc = IEEE80211_ADDR_EQ(*bssid,
1755 				    ic->ic_bss->ni_bssid);
1756 #endif
1757 			break;
1758 		case IEEE80211_FC1_DIR_TODS:
1759 			*bssid = wh->i_addr1;
1760 #ifndef IEEE80211_STA_ONLY
1761 			if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1762 				rc = IEEE80211_ADDR_EQ(*bssid,
1763 				    ic->ic_bss->ni_bssid);
1764 #endif
1765 			break;
1766 		case IEEE80211_FC1_DIR_FROMDS:
1767 		case IEEE80211_FC1_DIR_DSTODS:
1768 			*bssid = wh->i_addr2;
1769 #ifndef IEEE80211_STA_ONLY
1770 			rc = (ic->ic_opmode == IEEE80211_M_HOSTAP);
1771 #endif
1772 			break;
1773 		}
1774 		break;
1775 	}
1776 	return monitor || rc;
1777 }
1778 
1779 /*
1780  * Drivers call this, so increase the reference count before returning
1781  * the node.
1782  */
1783 struct ieee80211_node *
1784 ieee80211_find_rxnode(struct ieee80211com *ic,
1785     const struct ieee80211_frame *wh)
1786 {
1787 	static const u_int8_t zero[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1788 	struct ieee80211_node *ni;
1789 	const u_int8_t *bssid;
1790 	int s;
1791 
1792 	if (!ieee80211_needs_rxnode(ic, wh, &bssid))
1793 		return ieee80211_ref_node(ic->ic_bss);
1794 
1795 	s = splnet();
1796 	ni = ieee80211_find_node(ic, wh->i_addr2);
1797 	splx(s);
1798 
1799 	if (ni != NULL)
1800 		return ieee80211_ref_node(ni);
1801 #ifndef IEEE80211_STA_ONLY
1802 	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1803 		return ieee80211_ref_node(ic->ic_bss);
1804 #endif
1805 	/* XXX see remarks in ieee80211_find_txnode */
1806 	/* XXX no rate negotiation; just dup */
1807 	if ((ni = ieee80211_dup_bss(ic, wh->i_addr2)) == NULL)
1808 		return ieee80211_ref_node(ic->ic_bss);
1809 
1810 	IEEE80211_ADDR_COPY(ni->ni_bssid, (bssid != NULL) ? bssid : zero);
1811 
1812 	ni->ni_rates = ic->ic_bss->ni_rates;
1813 	ni->ni_txrate = 0;
1814 	if (ic->ic_newassoc)
1815 		(*ic->ic_newassoc)(ic, ni, 1);
1816 
1817 	DPRINTF(("faked-up node %p for %s\n", ni,
1818 	    ether_sprintf((u_int8_t *)wh->i_addr2)));
1819 
1820 	return ieee80211_ref_node(ni);
1821 }
1822 
1823 struct ieee80211_node *
1824 ieee80211_find_node_for_beacon(struct ieee80211com *ic,
1825     const u_int8_t *macaddr, const struct ieee80211_channel *chan,
1826     const char *ssid, u_int8_t rssi)
1827 {
1828 	struct ieee80211_node *ni, *keep = NULL;
1829 	int s, score = 0;
1830 
1831 	if ((ni = ieee80211_find_node(ic, macaddr)) != NULL) {
1832 		s = splnet();
1833 
1834 		if (ni->ni_chan != chan && ni->ni_rssi >= rssi)
1835 			score++;
1836 		if (ssid[1] == 0 && ni->ni_esslen != 0)
1837 			score++;
1838 		if (score > 0)
1839 			keep = ni;
1840 
1841 		splx(s);
1842 	}
1843 
1844 	return (keep);
1845 }
1846 
1847 void
1848 ieee80211_ba_del(struct ieee80211_node *ni)
1849 {
1850 	int tid;
1851 
1852 	for (tid = 0; tid < nitems(ni->ni_rx_ba); tid++) {
1853 		struct ieee80211_rx_ba *ba = &ni->ni_rx_ba[tid];
1854 		if (ba->ba_state != IEEE80211_BA_INIT) {
1855 			if (timeout_pending(&ba->ba_to))
1856 				timeout_del(&ba->ba_to);
1857 			if (timeout_pending(&ba->ba_gap_to))
1858 				timeout_del(&ba->ba_gap_to);
1859 			ba->ba_state = IEEE80211_BA_INIT;
1860 		}
1861 	}
1862 
1863 	for (tid = 0; tid < nitems(ni->ni_tx_ba); tid++) {
1864 		struct ieee80211_tx_ba *ba = &ni->ni_tx_ba[tid];
1865 		if (ba->ba_state != IEEE80211_BA_INIT) {
1866 			if (timeout_pending(&ba->ba_to))
1867 				timeout_del(&ba->ba_to);
1868 			ba->ba_state = IEEE80211_BA_INIT;
1869 		}
1870 	}
1871 }
1872 
1873 void
1874 ieee80211_free_node(struct ieee80211com *ic, struct ieee80211_node *ni)
1875 {
1876 	if (ni == ic->ic_bss)
1877 		panic("freeing bss node");
1878 
1879 	splassert(IPL_NET);
1880 
1881 	DPRINTF(("%s\n", ether_sprintf(ni->ni_macaddr)));
1882 #ifndef IEEE80211_STA_ONLY
1883 	timeout_del(&ni->ni_eapol_to);
1884 	timeout_del(&ni->ni_sa_query_to);
1885 	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1886 #endif
1887 	ieee80211_ba_del(ni);
1888 	RBT_REMOVE(ieee80211_tree, &ic->ic_tree, ni);
1889 	ic->ic_nnodes--;
1890 #ifndef IEEE80211_STA_ONLY
1891 	if (mq_purge(&ni->ni_savedq) > 0) {
1892 		if (ic->ic_set_tim != NULL)
1893 			(*ic->ic_set_tim)(ic, ni->ni_associd, 0);
1894 	}
1895 #endif
1896 	(*ic->ic_node_free)(ic, ni);
1897 	/* TBD indicate to drivers that a new node can be allocated */
1898 }
1899 
1900 void
1901 ieee80211_release_node(struct ieee80211com *ic, struct ieee80211_node *ni)
1902 {
1903 	int s;
1904 
1905 	DPRINTF(("%s refcnt %u\n", ether_sprintf(ni->ni_macaddr),
1906 	    ni->ni_refcnt));
1907 	s = splnet();
1908 	if (ieee80211_node_decref(ni) == 0) {
1909 		if (ni->ni_unref_cb) {
1910 			(*ni->ni_unref_cb)(ic, ni);
1911 			ni->ni_unref_cb = NULL;
1912  			/* Freed by callback if necessary: */
1913 			ni->ni_unref_arg = NULL;
1914 			ni->ni_unref_arg_size = 0;
1915 		}
1916 	    	if (ni->ni_state == IEEE80211_STA_COLLECT)
1917 			ieee80211_free_node(ic, ni);
1918 	}
1919 	splx(s);
1920 }
1921 
1922 void
1923 ieee80211_free_allnodes(struct ieee80211com *ic, int clear_ic_bss)
1924 {
1925 	struct ieee80211_node *ni;
1926 	int s;
1927 
1928 	DPRINTF(("freeing all nodes\n"));
1929 	s = splnet();
1930 	while ((ni = RBT_MIN(ieee80211_tree, &ic->ic_tree)) != NULL)
1931 		ieee80211_free_node(ic, ni);
1932 	splx(s);
1933 
1934 	if (clear_ic_bss && ic->ic_bss != NULL)
1935 		ieee80211_node_cleanup(ic, ic->ic_bss);	/* for station mode */
1936 }
1937 
1938 void
1939 ieee80211_clean_cached(struct ieee80211com *ic)
1940 {
1941 	struct ieee80211_node *ni, *next_ni;
1942 	int s;
1943 
1944 	s = splnet();
1945 	for (ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
1946 	    ni != NULL; ni = next_ni) {
1947 		next_ni = RBT_NEXT(ieee80211_tree, ni);
1948 		if (ni->ni_state == IEEE80211_STA_CACHE)
1949 			ieee80211_free_node(ic, ni);
1950 	}
1951 	splx(s);
1952 }
1953 /*
1954  * Timeout inactive nodes.
1955  *
1956  * If called because of a cache timeout, which happens only in hostap and ibss
1957  * modes, clean all inactive cached or authenticated nodes but don't de-auth
1958  * any associated nodes. Also update HT protection settings.
1959  *
1960  * Else, this function is called because a new node must be allocated but the
1961  * node cache is full. In this case, return as soon as a free slot was made
1962  * available. If acting as hostap, clean cached nodes regardless of their
1963  * recent activity and also allow de-authing of authenticated nodes older
1964  * than one cache wait interval, and de-authing of inactive associated nodes.
1965  */
1966 void
1967 ieee80211_clean_nodes(struct ieee80211com *ic, int cache_timeout)
1968 {
1969 	struct ieee80211_node *ni, *next_ni;
1970 	u_int gen = ic->ic_scangen++;		/* NB: ok 'cuz single-threaded*/
1971 	int s;
1972 #ifndef IEEE80211_STA_ONLY
1973 	int nnodes = 0, nonht = 0, nonhtassoc = 0;
1974 	struct ifnet *ifp = &ic->ic_if;
1975 	enum ieee80211_htprot htprot = IEEE80211_HTPROT_NONE;
1976 	enum ieee80211_protmode protmode = IEEE80211_PROT_NONE;
1977 #endif
1978 
1979 	s = splnet();
1980 	for (ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
1981 	    ni != NULL; ni = next_ni) {
1982 		next_ni = RBT_NEXT(ieee80211_tree, ni);
1983 		if (!cache_timeout && ic->ic_nnodes < ic->ic_max_nnodes)
1984 			break;
1985 		if (ni->ni_scangen == gen)	/* previously handled */
1986 			continue;
1987 #ifndef IEEE80211_STA_ONLY
1988 		nnodes++;
1989 		if ((ic->ic_flags & IEEE80211_F_HTON) && cache_timeout) {
1990 			/*
1991 			 * Check if node supports 802.11n.
1992 			 * Only require HT capabilities IE for this check.
1993 			 * Nodes might never reveal their supported MCS to us
1994 			 * unless they go through a full association sequence.
1995 			 * ieee80211_node_supports_ht() could misclassify them.
1996 			 */
1997 			if ((ni->ni_flags & IEEE80211_NODE_HTCAP) == 0) {
1998 				nonht++;
1999 				if (ni->ni_state == IEEE80211_STA_ASSOC)
2000 					nonhtassoc++;
2001 			}
2002 		}
2003 #endif
2004 		ni->ni_scangen = gen;
2005 		if (ni->ni_refcnt > 0)
2006 			continue;
2007 #ifndef IEEE80211_STA_ONLY
2008 		if ((ic->ic_opmode == IEEE80211_M_HOSTAP ||
2009 		    ic->ic_opmode == IEEE80211_M_IBSS) &&
2010 		    ic->ic_state == IEEE80211_S_RUN) {
2011 			if (cache_timeout) {
2012 				if (ni->ni_state != IEEE80211_STA_COLLECT &&
2013 				    (ni->ni_state == IEEE80211_STA_ASSOC ||
2014 				    ni->ni_inact < IEEE80211_INACT_MAX))
2015 					continue;
2016 			} else {
2017 				if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
2018 				    ((ni->ni_state == IEEE80211_STA_ASSOC &&
2019 				    ni->ni_inact < IEEE80211_INACT_MAX) ||
2020 				    (ni->ni_state == IEEE80211_STA_AUTH &&
2021 				     ni->ni_inact == 0)))
2022 				    	continue;
2023 
2024 				if (ic->ic_opmode == IEEE80211_M_IBSS &&
2025 				    ni->ni_state != IEEE80211_STA_COLLECT &&
2026 				    ni->ni_state != IEEE80211_STA_CACHE &&
2027 				    ni->ni_inact < IEEE80211_INACT_MAX)
2028 					continue;
2029 			}
2030 		}
2031 		if (ifp->if_flags & IFF_DEBUG)
2032 			printf("%s: station %s purged from node cache\n",
2033 			    ifp->if_xname, ether_sprintf(ni->ni_macaddr));
2034 #endif
2035 		/*
2036 		 * If we're hostap and the node is authenticated, send
2037 		 * a deauthentication frame. The node will be freed when
2038 		 * the driver calls ieee80211_release_node().
2039 		 */
2040 #ifndef IEEE80211_STA_ONLY
2041 		nnodes--;
2042 		if ((ic->ic_flags & IEEE80211_F_HTON) && cache_timeout) {
2043 			if ((ni->ni_flags & IEEE80211_NODE_HTCAP) == 0) {
2044 				nonht--;
2045 				if (ni->ni_state == IEEE80211_STA_ASSOC)
2046 					nonhtassoc--;
2047 			}
2048 		}
2049 		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
2050 		    ni->ni_state >= IEEE80211_STA_AUTH &&
2051 		    ni->ni_state != IEEE80211_STA_COLLECT) {
2052 			IEEE80211_SEND_MGMT(ic, ni,
2053 			    IEEE80211_FC0_SUBTYPE_DEAUTH,
2054 			    IEEE80211_REASON_AUTH_EXPIRE);
2055 			ieee80211_node_leave(ic, ni);
2056 		} else
2057 #endif
2058 			ieee80211_free_node(ic, ni);
2059 		ic->ic_stats.is_node_timeout++;
2060 	}
2061 
2062 #ifndef IEEE80211_STA_ONLY
2063 	if ((ic->ic_flags & IEEE80211_F_HTON) && cache_timeout) {
2064 		uint16_t htop1 = ic->ic_bss->ni_htop1;
2065 
2066 		/* Update HT protection settings. */
2067 		if (nonht) {
2068 			protmode = IEEE80211_PROT_CTSONLY;
2069 			if (nonhtassoc)
2070 				htprot = IEEE80211_HTPROT_NONHT_MIXED;
2071 			else
2072 				htprot = IEEE80211_HTPROT_NONMEMBER;
2073 		}
2074 		if ((htop1 & IEEE80211_HTOP1_PROT_MASK) != htprot) {
2075 			htop1 &= ~IEEE80211_HTOP1_PROT_MASK;
2076 			htop1 |= htprot;
2077 			ic->ic_bss->ni_htop1 |= htop1;
2078 			ic->ic_protmode = protmode;
2079 			if (ic->ic_update_htprot)
2080 				ic->ic_update_htprot(ic, ic->ic_bss);
2081 		}
2082 	}
2083 
2084 	/*
2085 	 * During a cache timeout we iterate over all nodes.
2086 	 * Check for node leaks by comparing the actual number of cached
2087 	 * nodes with the ic_nnodes count, which is maintained while adding
2088 	 * and removing nodes from the cache.
2089 	 */
2090 	if ((ifp->if_flags & IFF_DEBUG) && cache_timeout &&
2091 	    nnodes != ic->ic_nnodes)
2092 		printf("%s: number of cached nodes is %d, expected %d,"
2093 		    "possible nodes leak\n", ifp->if_xname, nnodes,
2094 		    ic->ic_nnodes);
2095 #endif
2096 	splx(s);
2097 }
2098 
2099 void
2100 ieee80211_iterate_nodes(struct ieee80211com *ic, ieee80211_iter_func *f,
2101     void *arg)
2102 {
2103 	struct ieee80211_node *ni;
2104 	int s;
2105 
2106 	s = splnet();
2107 	RBT_FOREACH(ni, ieee80211_tree, &ic->ic_tree)
2108 		(*f)(arg, ni);
2109 	splx(s);
2110 }
2111 
2112 
2113 /*
2114  * Install received HT caps information in the node's state block.
2115  */
2116 void
2117 ieee80211_setup_htcaps(struct ieee80211_node *ni, const uint8_t *data,
2118     uint8_t len)
2119 {
2120 	uint16_t rxrate;
2121 
2122 	if (len != 26)
2123 		return;
2124 
2125 	ni->ni_htcaps = (data[0] | (data[1] << 8));
2126 	ni->ni_ampdu_param = data[2];
2127 
2128 	memcpy(ni->ni_rxmcs, &data[3], sizeof(ni->ni_rxmcs));
2129 	/* clear reserved bits */
2130 	clrbit(ni->ni_rxmcs, 77);
2131 	clrbit(ni->ni_rxmcs, 78);
2132 	clrbit(ni->ni_rxmcs, 79);
2133 
2134 	/* Max MCS Rx rate in 1Mb/s units (0 means "not specified"). */
2135 	rxrate = ((data[13] | (data[14]) << 8) & IEEE80211_MCS_RX_RATE_HIGH);
2136 	if (rxrate < 1024)
2137 		ni->ni_max_rxrate = rxrate;
2138 
2139 	ni->ni_tx_mcs_set = data[15];
2140 	ni->ni_htxcaps = (data[19] | (data[20] << 8));
2141 	ni->ni_txbfcaps = (data[21] | (data[22] << 8) | (data[23] << 16) |
2142 		(data[24] << 24));
2143 	ni->ni_aselcaps = data[25];
2144 
2145 	ni->ni_flags |= IEEE80211_NODE_HTCAP;
2146 }
2147 
2148 #ifndef IEEE80211_STA_ONLY
2149 /*
2150  * Handle nodes switching from 11n into legacy modes.
2151  */
2152 void
2153 ieee80211_clear_htcaps(struct ieee80211_node *ni)
2154 {
2155 	ni->ni_htcaps = 0;
2156 	ni->ni_ampdu_param = 0;
2157 	memset(ni->ni_rxmcs, 0, sizeof(ni->ni_rxmcs));
2158 	ni->ni_max_rxrate = 0;
2159 	ni->ni_tx_mcs_set = 0;
2160 	ni->ni_htxcaps = 0;
2161 	ni->ni_txbfcaps = 0;
2162 	ni->ni_aselcaps = 0;
2163 
2164 	ni->ni_flags &= ~(IEEE80211_NODE_HT | IEEE80211_NODE_HT_SGI20 |
2165 	    IEEE80211_NODE_HT_SGI40 | IEEE80211_NODE_HTCAP);
2166 
2167 }
2168 #endif
2169 
2170 /*
2171  * Install received HT op information in the node's state block.
2172  */
2173 int
2174 ieee80211_setup_htop(struct ieee80211_node *ni, const uint8_t *data,
2175     uint8_t len, int isprobe)
2176 {
2177 	if (len != 22)
2178 		return 0;
2179 
2180 	ni->ni_primary_chan = data[0]; /* XXX corresponds to ni_chan */
2181 
2182 	ni->ni_htop0 = data[1];
2183 	ni->ni_htop1 = (data[2] | (data[3] << 8));
2184 	ni->ni_htop2 = (data[3] | (data[4] << 8));
2185 
2186 	/*
2187 	 * According to 802.11-2012 Table 8-130 the Basic MCS set is
2188 	 * only "present in Beacon, Probe Response, Mesh Peering Open
2189 	 * and Mesh Peering Confirm frames. Otherwise reserved."
2190 	 */
2191 	if (isprobe)
2192 		memcpy(ni->ni_basic_mcs, &data[6], sizeof(ni->ni_basic_mcs));
2193 
2194 	return 1;
2195 }
2196 
2197 /*
2198  * Install received rate set information in the node's state block.
2199  */
2200 int
2201 ieee80211_setup_rates(struct ieee80211com *ic, struct ieee80211_node *ni,
2202     const u_int8_t *rates, const u_int8_t *xrates, int flags)
2203 {
2204 	struct ieee80211_rateset *rs = &ni->ni_rates;
2205 
2206 	memset(rs, 0, sizeof(*rs));
2207 	rs->rs_nrates = rates[1];
2208 	memcpy(rs->rs_rates, rates + 2, rs->rs_nrates);
2209 	if (xrates != NULL) {
2210 		u_int8_t nxrates;
2211 		/*
2212 		 * Tack on 11g extended supported rate element.
2213 		 */
2214 		nxrates = xrates[1];
2215 		if (rs->rs_nrates + nxrates > IEEE80211_RATE_MAXSIZE) {
2216 			nxrates = IEEE80211_RATE_MAXSIZE - rs->rs_nrates;
2217 			DPRINTF(("extended rate set too large; "
2218 			    "only using %u of %u rates\n",
2219 			    nxrates, xrates[1]));
2220 			ic->ic_stats.is_rx_rstoobig++;
2221 		}
2222 		memcpy(rs->rs_rates + rs->rs_nrates, xrates+2, nxrates);
2223 		rs->rs_nrates += nxrates;
2224 	}
2225 	return ieee80211_fix_rate(ic, ni, flags);
2226 }
2227 
2228 #ifndef IEEE80211_STA_ONLY
2229 /*
2230  * Check if the specified node supports ERP.
2231  */
2232 int
2233 ieee80211_iserp_sta(const struct ieee80211_node *ni)
2234 {
2235 	static const u_int8_t rates[] = { 2, 4, 11, 22, 12, 24, 48 };
2236 	const struct ieee80211_rateset *rs = &ni->ni_rates;
2237 	int i, j;
2238 
2239 	/*
2240 	 * A STA supports ERP operation if it includes all the Clause 19
2241 	 * mandatory rates in its supported rate set.
2242 	 */
2243 	for (i = 0; i < nitems(rates); i++) {
2244 		for (j = 0; j < rs->rs_nrates; j++) {
2245 			if ((rs->rs_rates[j] & IEEE80211_RATE_VAL) == rates[i])
2246 				break;
2247 		}
2248 		if (j == rs->rs_nrates)
2249 			return 0;
2250 	}
2251 	return 1;
2252 }
2253 
2254 /*
2255  * This function is called to notify the 802.1X PACP machine that a new
2256  * 802.1X port is enabled and must be authenticated. For 802.11, a port
2257  * becomes enabled whenever a STA successfully completes Open System
2258  * authentication with an AP.
2259  */
2260 void
2261 ieee80211_needs_auth(struct ieee80211com *ic, struct ieee80211_node *ni)
2262 {
2263 	/*
2264 	 * XXX this could be done via the route socket of via a dedicated
2265 	 * EAP socket or another kernel->userland notification mechanism.
2266 	 * The notification should include the MAC address (ni_macaddr).
2267 	 */
2268 }
2269 
2270 /*
2271  * Handle an HT STA joining an HT network.
2272  */
2273 void
2274 ieee80211_node_join_ht(struct ieee80211com *ic, struct ieee80211_node *ni)
2275 {
2276 	enum ieee80211_htprot;
2277 
2278 	/* Update HT protection setting. */
2279 	if ((ni->ni_flags & IEEE80211_NODE_HT) == 0) {
2280 		uint16_t htop1 = ic->ic_bss->ni_htop1;
2281 		htop1 &= ~IEEE80211_HTOP1_PROT_MASK;
2282 		htop1 |= IEEE80211_HTPROT_NONHT_MIXED;
2283 		ic->ic_bss->ni_htop1 = htop1;
2284 		if (ic->ic_update_htprot)
2285 			ic->ic_update_htprot(ic, ic->ic_bss);
2286 	}
2287 }
2288 
2289 /*
2290  * Handle a station joining an RSN network.
2291  */
2292 void
2293 ieee80211_node_join_rsn(struct ieee80211com *ic, struct ieee80211_node *ni)
2294 {
2295 	DPRINTF(("station %s associated using proto %d akm 0x%x "
2296 	    "cipher 0x%x groupcipher 0x%x\n", ether_sprintf(ni->ni_macaddr),
2297 	    ni->ni_rsnprotos, ni->ni_rsnakms, ni->ni_rsnciphers,
2298 	    ni->ni_rsngroupcipher));
2299 
2300 	ni->ni_rsn_state = RSNA_AUTHENTICATION;
2301 
2302 	ni->ni_key_count = 0;
2303 	ni->ni_port_valid = 0;
2304 	ni->ni_flags &= ~IEEE80211_NODE_TXRXPROT;
2305 	ni->ni_flags &= ~IEEE80211_NODE_RSN_NEW_PTK;
2306 	ni->ni_replaycnt = -1;	/* XXX */
2307 	ni->ni_rsn_retries = 0;
2308 	ni->ni_rsncipher = ni->ni_rsnciphers;
2309 
2310 	ni->ni_rsn_state = RSNA_AUTHENTICATION_2;
2311 
2312 	/* generate a new authenticator nonce (ANonce) */
2313 	arc4random_buf(ni->ni_nonce, EAPOL_KEY_NONCE_LEN);
2314 
2315 	if (!ieee80211_is_8021x_akm(ni->ni_rsnakms)) {
2316 		memcpy(ni->ni_pmk, ic->ic_psk, IEEE80211_PMK_LEN);
2317 		ni->ni_flags |= IEEE80211_NODE_PMK;
2318 		(void)ieee80211_send_4way_msg1(ic, ni);
2319 	} else if (ni->ni_flags & IEEE80211_NODE_PMK) {
2320 		/* skip 802.1X auth if a cached PMK was found */
2321 		(void)ieee80211_send_4way_msg1(ic, ni);
2322 	} else {
2323 		/* no cached PMK found, needs full 802.1X auth */
2324 		ieee80211_needs_auth(ic, ni);
2325 	}
2326 }
2327 
2328 void
2329 ieee80211_count_longslotsta(void *arg, struct ieee80211_node *ni)
2330 {
2331 	int *longslotsta = arg;
2332 
2333 	if (ni->ni_associd == 0 || ni->ni_state == IEEE80211_STA_COLLECT)
2334 		return;
2335 
2336 	if (!(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME))
2337 		(*longslotsta)++;
2338 }
2339 
2340 void
2341 ieee80211_count_nonerpsta(void *arg, struct ieee80211_node *ni)
2342 {
2343 	int *nonerpsta = arg;
2344 
2345 	if (ni->ni_associd == 0 || ni->ni_state == IEEE80211_STA_COLLECT)
2346 		return;
2347 
2348 	if (!ieee80211_iserp_sta(ni))
2349 		(*nonerpsta)++;
2350 }
2351 
2352 void
2353 ieee80211_count_pssta(void *arg, struct ieee80211_node *ni)
2354 {
2355 	int *pssta = arg;
2356 
2357 	if (ni->ni_associd == 0 || ni->ni_state == IEEE80211_STA_COLLECT)
2358 		return;
2359 
2360 	if (ni->ni_pwrsave == IEEE80211_PS_DOZE)
2361 		(*pssta)++;
2362 }
2363 
2364 void
2365 ieee80211_count_rekeysta(void *arg, struct ieee80211_node *ni)
2366 {
2367 	int *rekeysta = arg;
2368 
2369 	if (ni->ni_associd == 0 || ni->ni_state == IEEE80211_STA_COLLECT)
2370 		return;
2371 
2372 	if (ni->ni_flags & IEEE80211_NODE_REKEY)
2373 		(*rekeysta)++;
2374 }
2375 
2376 /*
2377  * Handle a station joining an 11g network.
2378  */
2379 void
2380 ieee80211_node_join_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
2381 {
2382 	int longslotsta = 0, nonerpsta = 0;
2383 
2384 	if (!(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)) {
2385 		/*
2386 		 * Joining STA doesn't support short slot time.  We must
2387 		 * disable the use of short slot time for all other associated
2388 		 * STAs and give the driver a chance to reconfigure the
2389 		 * hardware.
2390 		 */
2391 		ieee80211_iterate_nodes(ic,
2392 		    ieee80211_count_longslotsta, &longslotsta);
2393 		if (longslotsta == 1) {
2394 			if (ic->ic_caps & IEEE80211_C_SHSLOT)
2395 				ieee80211_set_shortslottime(ic, 0);
2396 		}
2397 		DPRINTF(("[%s] station needs long slot time, count %d\n",
2398 		    ether_sprintf(ni->ni_macaddr), longslotsta));
2399 	}
2400 
2401 	if (!ieee80211_iserp_sta(ni)) {
2402 		/*
2403 		 * Joining STA is non-ERP.
2404 		 */
2405 		ieee80211_iterate_nodes(ic,
2406 		    ieee80211_count_nonerpsta, &nonerpsta);
2407 		DPRINTF(("[%s] station is non-ERP, %d non-ERP "
2408 		    "stations associated\n", ether_sprintf(ni->ni_macaddr),
2409 		    nonerpsta));
2410 		/* must enable the use of protection */
2411 		if (ic->ic_protmode != IEEE80211_PROT_NONE) {
2412 			DPRINTF(("enable use of protection\n"));
2413 			ic->ic_flags |= IEEE80211_F_USEPROT;
2414 		}
2415 
2416 		if (!(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE))
2417 			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
2418 	} else
2419 		ni->ni_flags |= IEEE80211_NODE_ERP;
2420 }
2421 
2422 void
2423 ieee80211_node_join(struct ieee80211com *ic, struct ieee80211_node *ni,
2424     int resp)
2425 {
2426 	int newassoc = (ni->ni_state != IEEE80211_STA_ASSOC);
2427 
2428 	if (ni->ni_associd == 0) {
2429 		u_int16_t aid;
2430 
2431 		/*
2432 		 * It would be clever to search the bitmap
2433 		 * more efficiently, but this will do for now.
2434 		 */
2435 		for (aid = 1; aid < ic->ic_max_aid; aid++) {
2436 			if (!IEEE80211_AID_ISSET(aid,
2437 			    ic->ic_aid_bitmap))
2438 				break;
2439 		}
2440 		if (aid >= ic->ic_max_aid) {
2441 			IEEE80211_SEND_MGMT(ic, ni, resp,
2442 			    IEEE80211_REASON_ASSOC_TOOMANY);
2443 			ieee80211_node_leave(ic, ni);
2444 			return;
2445 		}
2446 		ni->ni_associd = aid | 0xc000;
2447 		IEEE80211_AID_SET(ni->ni_associd, ic->ic_aid_bitmap);
2448 		if (ic->ic_curmode == IEEE80211_MODE_11G ||
2449 		    (ic->ic_curmode == IEEE80211_MODE_11N &&
2450 		    IEEE80211_IS_CHAN_2GHZ(ic->ic_bss->ni_chan)))
2451 			ieee80211_node_join_11g(ic, ni);
2452 	}
2453 
2454 	DPRINTF(("station %s %s associated at aid %d\n",
2455 	    ether_sprintf(ni->ni_macaddr), newassoc ? "newly" : "already",
2456 	    ni->ni_associd & ~0xc000));
2457 
2458 	ieee80211_ht_negotiate(ic, ni);
2459 	if (ic->ic_flags & IEEE80211_F_HTON)
2460 		ieee80211_node_join_ht(ic, ni);
2461 
2462 	/* give driver a chance to setup state like ni_txrate */
2463 	if (ic->ic_newassoc)
2464 		(*ic->ic_newassoc)(ic, ni, newassoc);
2465 	IEEE80211_SEND_MGMT(ic, ni, resp, IEEE80211_STATUS_SUCCESS);
2466 	ieee80211_node_newstate(ni, IEEE80211_STA_ASSOC);
2467 
2468 	if (!(ic->ic_flags & IEEE80211_F_RSNON)) {
2469 		ni->ni_port_valid = 1;
2470 		ni->ni_rsncipher = IEEE80211_CIPHER_USEGROUP;
2471 	} else
2472 		ieee80211_node_join_rsn(ic, ni);
2473 
2474 #if NBRIDGE > 0
2475 	/*
2476 	 * If the parent interface is a bridge port, learn
2477 	 * the node's address dynamically on this interface.
2478 	 */
2479 	if (ic->ic_if.if_bridgeidx != 0)
2480 		bridge_update(&ic->ic_if,
2481 		    (struct ether_addr *)ni->ni_macaddr, 0);
2482 #endif
2483 }
2484 
2485 /*
2486  * Handle an HT STA leaving an HT network.
2487  */
2488 void
2489 ieee80211_node_leave_ht(struct ieee80211com *ic, struct ieee80211_node *ni)
2490 {
2491 	struct ieee80211_rx_ba *ba;
2492 	u_int8_t tid;
2493 	int i;
2494 
2495 	/* free all Block Ack records */
2496 	ieee80211_ba_del(ni);
2497 	for (tid = 0; tid < IEEE80211_NUM_TID; tid++) {
2498 		ba = &ni->ni_rx_ba[tid];
2499 		if (ba->ba_buf != NULL) {
2500 			for (i = 0; i < IEEE80211_BA_MAX_WINSZ; i++)
2501 				m_freem(ba->ba_buf[i].m);
2502 			free(ba->ba_buf, M_DEVBUF,
2503 			    IEEE80211_BA_MAX_WINSZ * sizeof(*ba->ba_buf));
2504 			ba->ba_buf = NULL;
2505 		}
2506 	}
2507 
2508 	ieee80211_clear_htcaps(ni);
2509 }
2510 
2511 /*
2512  * Handle a station leaving an RSN network.
2513  */
2514 void
2515 ieee80211_node_leave_rsn(struct ieee80211com *ic, struct ieee80211_node *ni)
2516 {
2517 	int rekeysta = 0;
2518 
2519 	ni->ni_rsn_state = RSNA_DISCONNECTED;
2520 
2521 	ni->ni_rsn_state = RSNA_INITIALIZE;
2522 	if (ni->ni_flags & IEEE80211_NODE_REKEY) {
2523 		ni->ni_flags &= ~IEEE80211_NODE_REKEY;
2524 		ieee80211_iterate_nodes(ic,
2525 		    ieee80211_count_rekeysta, &rekeysta);
2526 		if (rekeysta == 0)
2527 			ieee80211_setkeysdone(ic);
2528 	}
2529 	ni->ni_flags &= ~IEEE80211_NODE_PMK;
2530 	ni->ni_rsn_gstate = RSNA_IDLE;
2531 
2532 	timeout_del(&ni->ni_eapol_to);
2533 	timeout_del(&ni->ni_sa_query_to);
2534 
2535 	ni->ni_rsn_retries = 0;
2536 	ni->ni_flags &= ~IEEE80211_NODE_TXRXPROT;
2537 	ni->ni_port_valid = 0;
2538 	(*ic->ic_delete_key)(ic, ni, &ni->ni_pairwise_key);
2539 }
2540 
2541 /*
2542  * Handle a station leaving an 11g network.
2543  */
2544 void
2545 ieee80211_node_leave_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
2546 {
2547 	int longslotsta = 0, nonerpsta = 0;
2548 
2549 	if (!(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)) {
2550 		/* leaving STA did not support short slot time */
2551 		ieee80211_iterate_nodes(ic,
2552 		    ieee80211_count_longslotsta, &longslotsta);
2553 		if (longslotsta == 1) {
2554 			/*
2555 			 * All associated STAs now support short slot time, so
2556 			 * enable this feature and give the driver a chance to
2557 			 * reconfigure the hardware. Notice that IBSS always
2558 			 * use a long slot time.
2559 			 */
2560 			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
2561 			    ic->ic_opmode != IEEE80211_M_IBSS)
2562 				ieee80211_set_shortslottime(ic, 1);
2563 		}
2564 		DPRINTF(("[%s] long slot time station leaves, count %d\n",
2565 		    ether_sprintf(ni->ni_macaddr), longslotsta));
2566 	}
2567 
2568 	if (!(ni->ni_flags & IEEE80211_NODE_ERP)) {
2569 		/* leaving STA was non-ERP */
2570 		ieee80211_iterate_nodes(ic,
2571 		    ieee80211_count_nonerpsta, &nonerpsta);
2572 		if (nonerpsta == 1) {
2573 			/*
2574 			 * All associated STAs are now ERP capable, disable use
2575 			 * of protection and re-enable short preamble support.
2576 			 */
2577 			ic->ic_flags &= ~IEEE80211_F_USEPROT;
2578 			if (ic->ic_caps & IEEE80211_C_SHPREAMBLE)
2579 				ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
2580 		}
2581 		DPRINTF(("[%s] non-ERP station leaves, count %d\n",
2582 		    ether_sprintf(ni->ni_macaddr), nonerpsta));
2583 	}
2584 }
2585 
2586 /*
2587  * Handle bookkeeping for station deauthentication/disassociation
2588  * when operating as an ap.
2589  */
2590 void
2591 ieee80211_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
2592 {
2593 	if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2594 		panic("not in ap mode, mode %u", ic->ic_opmode);
2595 
2596 	if (ni->ni_state == IEEE80211_STA_COLLECT)
2597 		return;
2598 	/*
2599 	 * If node wasn't previously associated all we need to do is
2600 	 * reclaim the reference.
2601 	 */
2602 	if (ni->ni_associd == 0) {
2603 		ieee80211_node_newstate(ni, IEEE80211_STA_COLLECT);
2604 		return;
2605 	}
2606 
2607 	if (ni->ni_pwrsave == IEEE80211_PS_DOZE)
2608 		ni->ni_pwrsave = IEEE80211_PS_AWAKE;
2609 
2610 	if (mq_purge(&ni->ni_savedq) > 0) {
2611 		if (ic->ic_set_tim != NULL)
2612 			(*ic->ic_set_tim)(ic, ni->ni_associd, 0);
2613 	}
2614 
2615 	if (ic->ic_flags & IEEE80211_F_RSNON)
2616 		ieee80211_node_leave_rsn(ic, ni);
2617 
2618 	if (ic->ic_curmode == IEEE80211_MODE_11G ||
2619 	    (ic->ic_curmode == IEEE80211_MODE_11N &&
2620 	    IEEE80211_IS_CHAN_2GHZ(ic->ic_bss->ni_chan)))
2621 		ieee80211_node_leave_11g(ic, ni);
2622 
2623 	if (ni->ni_flags & IEEE80211_NODE_HT)
2624 		ieee80211_node_leave_ht(ic, ni);
2625 
2626 	if (ic->ic_node_leave != NULL)
2627 		(*ic->ic_node_leave)(ic, ni);
2628 
2629 	ieee80211_node_newstate(ni, IEEE80211_STA_COLLECT);
2630 
2631 #if NBRIDGE > 0
2632 	/*
2633 	 * If the parent interface is a bridge port, delete
2634 	 * any dynamically learned address for this node.
2635 	 */
2636 	if (ic->ic_if.if_bridgeidx != 0)
2637 		bridge_update(&ic->ic_if,
2638 		    (struct ether_addr *)ni->ni_macaddr, 1);
2639 #endif
2640 }
2641 
2642 static int
2643 ieee80211_do_slow_print(struct ieee80211com *ic, int *did_print)
2644 {
2645 	static const struct timeval merge_print_intvl = {
2646 		.tv_sec = 1, .tv_usec = 0
2647 	};
2648 	if ((ic->ic_if.if_flags & IFF_LINK0) == 0)
2649 		return 0;
2650 	if (!*did_print && (ic->ic_if.if_flags & IFF_DEBUG) == 0 &&
2651 	    !ratecheck(&ic->ic_last_merge_print, &merge_print_intvl))
2652 		return 0;
2653 
2654 	*did_print = 1;
2655 	return 1;
2656 }
2657 
2658 /* ieee80211_ibss_merge helps merge 802.11 ad hoc networks.  The
2659  * convention, set by the Wireless Ethernet Compatibility Alliance
2660  * (WECA), is that an 802.11 station will change its BSSID to match
2661  * the "oldest" 802.11 ad hoc network, on the same channel, that
2662  * has the station's desired SSID.  The "oldest" 802.11 network
2663  * sends beacons with the greatest TSF timestamp.
2664  *
2665  * Return ENETRESET if the BSSID changed, 0 otherwise.
2666  *
2667  * XXX Perhaps we should compensate for the time that elapses
2668  * between the MAC receiving the beacon and the host processing it
2669  * in ieee80211_ibss_merge.
2670  */
2671 int
2672 ieee80211_ibss_merge(struct ieee80211com *ic, struct ieee80211_node *ni,
2673     u_int64_t local_tsft)
2674 {
2675 	u_int64_t beacon_tsft;
2676 	int did_print = 0, sign;
2677 	union {
2678 		u_int64_t	word;
2679 		u_int8_t	tstamp[8];
2680 	} u;
2681 
2682 	/* ensure alignment */
2683 	(void)memcpy(&u, &ni->ni_tstamp[0], sizeof(u));
2684 	beacon_tsft = letoh64(u.word);
2685 
2686 	/* we are faster, let the other guy catch up */
2687 	if (beacon_tsft < local_tsft)
2688 		sign = -1;
2689 	else
2690 		sign = 1;
2691 
2692 	if (IEEE80211_ADDR_EQ(ni->ni_bssid, ic->ic_bss->ni_bssid)) {
2693 		if (!ieee80211_do_slow_print(ic, &did_print))
2694 			return 0;
2695 		printf("%s: tsft offset %s%llu\n", ic->ic_if.if_xname,
2696 		    (sign < 0) ? "-" : "",
2697 		    (sign < 0)
2698 			? (local_tsft - beacon_tsft)
2699 			: (beacon_tsft - local_tsft));
2700 		return 0;
2701 	}
2702 
2703 	if (sign < 0)
2704 		return 0;
2705 
2706 	if (ieee80211_match_bss(ic, ni) != 0)
2707 		return 0;
2708 
2709 	if (ieee80211_do_slow_print(ic, &did_print)) {
2710 		printf("%s: ieee80211_ibss_merge: bssid mismatch %s\n",
2711 		    ic->ic_if.if_xname, ether_sprintf(ni->ni_bssid));
2712 		printf("%s: my tsft %llu beacon tsft %llu\n",
2713 		    ic->ic_if.if_xname, local_tsft, beacon_tsft);
2714 		printf("%s: sync TSF with %s\n",
2715 		    ic->ic_if.if_xname, ether_sprintf(ni->ni_macaddr));
2716 	}
2717 
2718 	ic->ic_flags &= ~IEEE80211_F_SIBSS;
2719 
2720 	/* negotiate rates with new IBSS */
2721 	ieee80211_fix_rate(ic, ni, IEEE80211_F_DOFRATE |
2722 	    IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
2723 	if (ni->ni_rates.rs_nrates == 0) {
2724 		if (ieee80211_do_slow_print(ic, &did_print)) {
2725 			printf("%s: rates mismatch, BSSID %s\n",
2726 			    ic->ic_if.if_xname, ether_sprintf(ni->ni_bssid));
2727 		}
2728 		return 0;
2729 	}
2730 
2731 	if (ieee80211_do_slow_print(ic, &did_print)) {
2732 		printf("%s: sync BSSID %s -> ",
2733 		    ic->ic_if.if_xname, ether_sprintf(ic->ic_bss->ni_bssid));
2734 		printf("%s ", ether_sprintf(ni->ni_bssid));
2735 		printf("(from %s)\n", ether_sprintf(ni->ni_macaddr));
2736 	}
2737 
2738 	ieee80211_node_newstate(ni, IEEE80211_STA_BSS);
2739 	(*ic->ic_node_copy)(ic, ic->ic_bss, ni);
2740 
2741 	return ENETRESET;
2742 }
2743 
2744 void
2745 ieee80211_set_tim(struct ieee80211com *ic, int aid, int set)
2746 {
2747 	if (set)
2748 		setbit(ic->ic_tim_bitmap, aid & ~0xc000);
2749 	else
2750 		clrbit(ic->ic_tim_bitmap, aid & ~0xc000);
2751 }
2752 
2753 /*
2754  * This function shall be called by drivers immediately after every DTIM.
2755  * Transmit all group addressed MSDUs buffered at the AP.
2756  */
2757 void
2758 ieee80211_notify_dtim(struct ieee80211com *ic)
2759 {
2760 	/* NB: group addressed MSDUs are buffered in ic_bss */
2761 	struct ieee80211_node *ni = ic->ic_bss;
2762 	struct ifnet *ifp = &ic->ic_if;
2763 	struct ieee80211_frame *wh;
2764 	struct mbuf *m;
2765 
2766 	KASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP);
2767 
2768 	while ((m = mq_dequeue(&ni->ni_savedq)) != NULL) {
2769 		if (!mq_empty(&ni->ni_savedq)) {
2770 			/* more queued frames, set the more data bit */
2771 			wh = mtod(m, struct ieee80211_frame *);
2772 			wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
2773 		}
2774 		mq_enqueue(&ic->ic_pwrsaveq, m);
2775 		if_start(ifp);
2776 	}
2777 	/* XXX assumes everything has been sent */
2778 	ic->ic_tim_mcast_pending = 0;
2779 }
2780 #endif	/* IEEE80211_STA_ONLY */
2781 
2782 /*
2783  * Compare nodes in the tree by lladdr
2784  */
2785 int
2786 ieee80211_node_cmp(const struct ieee80211_node *b1,
2787     const struct ieee80211_node *b2)
2788 {
2789 	return (memcmp(b1->ni_macaddr, b2->ni_macaddr, IEEE80211_ADDR_LEN));
2790 }
2791 
2792 /*
2793  * Compare nodes in the tree by essid
2794  */
2795 int
2796 ieee80211_ess_cmp(const struct ieee80211_ess_rbt *b1,
2797     const struct ieee80211_ess_rbt *b2)
2798 {
2799 	return (memcmp(b1->essid, b2->essid, IEEE80211_NWID_LEN));
2800 }
2801 
2802 /*
2803  * Generate red-black tree function logic
2804  */
2805 RBT_GENERATE(ieee80211_tree, ieee80211_node, ni_node, ieee80211_node_cmp);
2806 RBT_GENERATE(ieee80211_ess_tree, ieee80211_ess_rbt, ess_rbt, ieee80211_ess_cmp);
2807