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