xref: /openbsd-src/sys/net80211/ieee80211_node.c (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1 /*	$OpenBSD: ieee80211_node.c,v 1.105 2016/09/15 03:32:48 dlg 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 void ieee80211_setup_node(struct ieee80211com *, struct ieee80211_node *,
69     const u_int8_t *);
70 void ieee80211_free_node(struct ieee80211com *, struct ieee80211_node *);
71 void ieee80211_ba_del(struct ieee80211_node *);
72 struct ieee80211_node *ieee80211_alloc_node_helper(struct ieee80211com *);
73 void ieee80211_node_cleanup(struct ieee80211com *, struct ieee80211_node *);
74 void ieee80211_needs_auth(struct ieee80211com *, struct ieee80211_node *);
75 #ifndef IEEE80211_STA_ONLY
76 void ieee80211_node_join_ht(struct ieee80211com *, struct ieee80211_node *);
77 void ieee80211_node_join_rsn(struct ieee80211com *, struct ieee80211_node *);
78 void ieee80211_node_join_11g(struct ieee80211com *, struct ieee80211_node *);
79 void ieee80211_node_leave_ht(struct ieee80211com *, struct ieee80211_node *);
80 void ieee80211_node_leave_rsn(struct ieee80211com *, struct ieee80211_node *);
81 void ieee80211_node_leave_11g(struct ieee80211com *, struct ieee80211_node *);
82 void ieee80211_inact_timeout(void *);
83 void ieee80211_node_cache_timeout(void *);
84 #endif
85 
86 #ifndef IEEE80211_STA_ONLY
87 void
88 ieee80211_inact_timeout(void *arg)
89 {
90 	struct ieee80211com *ic = arg;
91 	struct ieee80211_node *ni, *next_ni;
92 	int s;
93 
94 	s = splnet();
95 	for (ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
96 	    ni != NULL; ni = next_ni) {
97 		next_ni = RBT_NEXT(ieee80211_tree, ni);
98 		if (ni->ni_refcnt > 0)
99 			continue;
100 		if (ni->ni_inact < IEEE80211_INACT_MAX)
101 			ni->ni_inact++;
102 	}
103 	splx(s);
104 
105 	timeout_add_sec(&ic->ic_inact_timeout, IEEE80211_INACT_WAIT);
106 }
107 
108 void
109 ieee80211_node_cache_timeout(void *arg)
110 {
111 	struct ieee80211com *ic = arg;
112 
113 	ieee80211_clean_nodes(ic, 1);
114 	timeout_add_sec(&ic->ic_node_cache_timeout, IEEE80211_CACHE_WAIT);
115 }
116 #endif
117 
118 void
119 ieee80211_node_attach(struct ifnet *ifp)
120 {
121 	struct ieee80211com *ic = (void *)ifp;
122 #ifndef IEEE80211_STA_ONLY
123 	int size;
124 #endif
125 
126 	RBT_INIT(ieee80211_tree, &ic->ic_tree);
127 	ic->ic_node_alloc = ieee80211_node_alloc;
128 	ic->ic_node_free = ieee80211_node_free;
129 	ic->ic_node_copy = ieee80211_node_copy;
130 	ic->ic_node_getrssi = ieee80211_node_getrssi;
131 	ic->ic_scangen = 1;
132 	ic->ic_max_nnodes = ieee80211_cache_size;
133 
134 	if (ic->ic_max_aid == 0)
135 		ic->ic_max_aid = IEEE80211_AID_DEF;
136 	else if (ic->ic_max_aid > IEEE80211_AID_MAX)
137 		ic->ic_max_aid = IEEE80211_AID_MAX;
138 #ifndef IEEE80211_STA_ONLY
139 	size = howmany(ic->ic_max_aid, 32) * sizeof(u_int32_t);
140 	ic->ic_aid_bitmap = malloc(size, M_DEVBUF, M_NOWAIT | M_ZERO);
141 	if (ic->ic_aid_bitmap == NULL) {
142 		/* XXX no way to recover */
143 		printf("%s: no memory for AID bitmap!\n", __func__);
144 		ic->ic_max_aid = 0;
145 	}
146 	if (ic->ic_caps & (IEEE80211_C_HOSTAP | IEEE80211_C_IBSS)) {
147 		ic->ic_tim_len = howmany(ic->ic_max_aid, 8);
148 		ic->ic_tim_bitmap = malloc(ic->ic_tim_len, M_DEVBUF,
149 		    M_NOWAIT | M_ZERO);
150 		if (ic->ic_tim_bitmap == NULL) {
151 			printf("%s: no memory for TIM bitmap!\n", __func__);
152 			ic->ic_tim_len = 0;
153 		} else
154 			ic->ic_set_tim = ieee80211_set_tim;
155 		timeout_set(&ic->ic_rsn_timeout,
156 		    ieee80211_gtk_rekey_timeout, ic);
157 		timeout_set(&ic->ic_inact_timeout,
158 		    ieee80211_inact_timeout, ic);
159 		timeout_set(&ic->ic_node_cache_timeout,
160 		    ieee80211_node_cache_timeout, ic);
161 	}
162 #endif
163 }
164 
165 struct ieee80211_node *
166 ieee80211_alloc_node_helper(struct ieee80211com *ic)
167 {
168 	struct ieee80211_node *ni;
169 	if (ic->ic_nnodes >= ic->ic_max_nnodes)
170 		ieee80211_clean_nodes(ic, 0);
171 	if (ic->ic_nnodes >= ic->ic_max_nnodes)
172 		return NULL;
173 	ni = (*ic->ic_node_alloc)(ic);
174 	return ni;
175 }
176 
177 void
178 ieee80211_node_lateattach(struct ifnet *ifp)
179 {
180 	struct ieee80211com *ic = (void *)ifp;
181 	struct ieee80211_node *ni;
182 
183 	ni = ieee80211_alloc_node_helper(ic);
184 	if (ni == NULL)
185 		panic("unable to setup inital BSS node");
186 	ni->ni_chan = IEEE80211_CHAN_ANYC;
187 	ic->ic_bss = ieee80211_ref_node(ni);
188 	ic->ic_txpower = IEEE80211_TXPOWER_MAX;
189 #ifndef IEEE80211_STA_ONLY
190 	mq_init(&ni->ni_savedq, IEEE80211_PS_MAX_QUEUE, IPL_NET);
191 #endif
192 }
193 
194 void
195 ieee80211_node_detach(struct ifnet *ifp)
196 {
197 	struct ieee80211com *ic = (void *)ifp;
198 
199 	if (ic->ic_bss != NULL) {
200 		(*ic->ic_node_free)(ic, ic->ic_bss);
201 		ic->ic_bss = NULL;
202 	}
203 	ieee80211_free_allnodes(ic);
204 #ifndef IEEE80211_STA_ONLY
205 	if (ic->ic_aid_bitmap != NULL)
206 		free(ic->ic_aid_bitmap, M_DEVBUF, 0);
207 	if (ic->ic_tim_bitmap != NULL)
208 		free(ic->ic_tim_bitmap, M_DEVBUF, 0);
209 	timeout_del(&ic->ic_inact_timeout);
210 	timeout_del(&ic->ic_node_cache_timeout);
211 #endif
212 	timeout_del(&ic->ic_rsn_timeout);
213 }
214 
215 /*
216  * AP scanning support.
217  */
218 
219 /*
220  * Initialize the active channel set based on the set
221  * of available channels and the current PHY mode.
222  */
223 void
224 ieee80211_reset_scan(struct ifnet *ifp)
225 {
226 	struct ieee80211com *ic = (void *)ifp;
227 
228 	memcpy(ic->ic_chan_scan, ic->ic_chan_active,
229 		sizeof(ic->ic_chan_active));
230 	/* NB: hack, setup so next_scan starts with the first channel */
231 	if (ic->ic_bss != NULL && ic->ic_bss->ni_chan == IEEE80211_CHAN_ANYC)
232 		ic->ic_bss->ni_chan = &ic->ic_channels[IEEE80211_CHAN_MAX];
233 }
234 
235 /*
236  * Begin an active scan.
237  */
238 void
239 ieee80211_begin_scan(struct ifnet *ifp)
240 {
241 	struct ieee80211com *ic = (void *)ifp;
242 
243 	if (ic->ic_scan_lock & IEEE80211_SCAN_LOCKED)
244 		return;
245 	ic->ic_scan_lock |= IEEE80211_SCAN_LOCKED;
246 
247 	/*
248 	 * In all but hostap mode scanning starts off in
249 	 * an active mode before switching to passive.
250 	 */
251 #ifndef IEEE80211_STA_ONLY
252 	if (ic->ic_opmode != IEEE80211_M_HOSTAP)
253 #endif
254 	{
255 		ic->ic_flags |= IEEE80211_F_ASCAN;
256 		ic->ic_stats.is_scan_active++;
257 	}
258 #ifndef IEEE80211_STA_ONLY
259 	else
260 		ic->ic_stats.is_scan_passive++;
261 #endif
262 	if (ifp->if_flags & IFF_DEBUG)
263 		printf("%s: begin %s scan\n", ifp->if_xname,
264 			(ic->ic_flags & IEEE80211_F_ASCAN) ?
265 				"active" : "passive");
266 
267 	/*
268 	 * Flush any previously seen AP's. Note that the latter
269 	 * assumes we don't act as both an AP and a station,
270 	 * otherwise we'll potentially flush state of stations
271 	 * associated with us.
272 	 */
273 	ieee80211_free_allnodes(ic);
274 
275 	/*
276 	 * Reset the current mode. Setting the current mode will also
277 	 * reset scan state.
278 	 */
279 	if (IFM_MODE(ic->ic_media.ifm_cur->ifm_media) == IFM_AUTO)
280 		ic->ic_curmode = IEEE80211_MODE_AUTO;
281 	ieee80211_setmode(ic, ic->ic_curmode);
282 
283 	ic->ic_scan_count = 0;
284 
285 	/* Scan the next channel. */
286 	ieee80211_next_scan(ifp);
287 }
288 
289 /*
290  * Switch to the next channel marked for scanning.
291  */
292 void
293 ieee80211_next_scan(struct ifnet *ifp)
294 {
295 	struct ieee80211com *ic = (void *)ifp;
296 	struct ieee80211_channel *chan;
297 
298 	chan = ic->ic_bss->ni_chan;
299 	for (;;) {
300 		if (++chan > &ic->ic_channels[IEEE80211_CHAN_MAX])
301 			chan = &ic->ic_channels[0];
302 		if (isset(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan))) {
303 			/*
304 			 * Ignore channels marked passive-only
305 			 * during an active scan.
306 			 */
307 			if ((ic->ic_flags & IEEE80211_F_ASCAN) == 0 ||
308 			    (chan->ic_flags & IEEE80211_CHAN_PASSIVE) == 0)
309 				break;
310 		}
311 		if (chan == ic->ic_bss->ni_chan) {
312 			ieee80211_end_scan(ifp);
313 			return;
314 		}
315 	}
316 	clrbit(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan));
317 	DPRINTF(("chan %d->%d\n",
318 	    ieee80211_chan2ieee(ic, ic->ic_bss->ni_chan),
319 	    ieee80211_chan2ieee(ic, chan)));
320 	ic->ic_bss->ni_chan = chan;
321 	ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
322 }
323 
324 #ifndef IEEE80211_STA_ONLY
325 void
326 ieee80211_create_ibss(struct ieee80211com* ic, struct ieee80211_channel *chan)
327 {
328 	struct ieee80211_node *ni;
329 	struct ifnet *ifp = &ic->ic_if;
330 
331 	ni = ic->ic_bss;
332 	if (ifp->if_flags & IFF_DEBUG)
333 		printf("%s: creating ibss\n", ifp->if_xname);
334 	ic->ic_flags |= IEEE80211_F_SIBSS;
335 	ni->ni_chan = chan;
336 	ni->ni_rates = ic->ic_sup_rates[ieee80211_chan2mode(ic, ni->ni_chan)];
337 	ni->ni_txrate = 0;
338 	IEEE80211_ADDR_COPY(ni->ni_macaddr, ic->ic_myaddr);
339 	IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_myaddr);
340 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
341 		if ((ic->ic_flags & IEEE80211_F_DESBSSID) != 0)
342 			IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_des_bssid);
343 		else
344 			ni->ni_bssid[0] |= 0x02;	/* local bit for IBSS */
345 	}
346 	ni->ni_esslen = ic->ic_des_esslen;
347 	memcpy(ni->ni_essid, ic->ic_des_essid, ni->ni_esslen);
348 	ni->ni_rssi = 0;
349 	ni->ni_rstamp = 0;
350 	memset(ni->ni_tstamp, 0, sizeof(ni->ni_tstamp));
351 	ni->ni_intval = ic->ic_lintval;
352 	ni->ni_capinfo = IEEE80211_CAPINFO_IBSS;
353 	if (ic->ic_flags & IEEE80211_F_WEPON)
354 		ni->ni_capinfo |= IEEE80211_CAPINFO_PRIVACY;
355 	if (ic->ic_flags & IEEE80211_F_RSNON) {
356 		struct ieee80211_key *k;
357 
358 		/* initialize 256-bit global key counter to a random value */
359 		arc4random_buf(ic->ic_globalcnt, EAPOL_KEY_NONCE_LEN);
360 
361 		ni->ni_rsnprotos = ic->ic_rsnprotos;
362 		ni->ni_rsnakms = ic->ic_rsnakms;
363 		ni->ni_rsnciphers = ic->ic_rsnciphers;
364 		ni->ni_rsngroupcipher = ic->ic_rsngroupcipher;
365 		ni->ni_rsngroupmgmtcipher = ic->ic_rsngroupmgmtcipher;
366 		ni->ni_rsncaps = 0;
367 		if (ic->ic_caps & IEEE80211_C_MFP) {
368 			ni->ni_rsncaps |= IEEE80211_RSNCAP_MFPC;
369 			if (ic->ic_flags & IEEE80211_F_MFPR)
370 				ni->ni_rsncaps |= IEEE80211_RSNCAP_MFPR;
371 		}
372 
373 		ic->ic_def_txkey = 1;
374 		k = &ic->ic_nw_keys[ic->ic_def_txkey];
375 		memset(k, 0, sizeof(*k));
376 		k->k_id = ic->ic_def_txkey;
377 		k->k_cipher = ni->ni_rsngroupcipher;
378 		k->k_flags = IEEE80211_KEY_GROUP | IEEE80211_KEY_TX;
379 		k->k_len = ieee80211_cipher_keylen(k->k_cipher);
380 		arc4random_buf(k->k_key, k->k_len);
381 		(*ic->ic_set_key)(ic, ni, k);	/* XXX */
382 
383 		if (ic->ic_caps & IEEE80211_C_MFP) {
384 			ic->ic_igtk_kid = 4;
385 			k = &ic->ic_nw_keys[ic->ic_igtk_kid];
386 			memset(k, 0, sizeof(*k));
387 			k->k_id = ic->ic_igtk_kid;
388 			k->k_cipher = ni->ni_rsngroupmgmtcipher;
389 			k->k_flags = IEEE80211_KEY_IGTK | IEEE80211_KEY_TX;
390 			k->k_len = 16;
391 			arc4random_buf(k->k_key, k->k_len);
392 			(*ic->ic_set_key)(ic, ni, k);	/* XXX */
393 		}
394 		/*
395 		 * In HostAP mode, multicast traffic is sent using ic_bss
396 		 * as the Tx node, so mark our node as valid so we can send
397 		 * multicast frames using the group key we've just configured.
398 		 */
399 		ni->ni_port_valid = 1;
400 		ni->ni_flags |= IEEE80211_NODE_TXPROT;
401 
402 		/* schedule a GTK/IGTK rekeying after 3600s */
403 		timeout_add_sec(&ic->ic_rsn_timeout, 3600);
404 	}
405 	timeout_add_sec(&ic->ic_inact_timeout, IEEE80211_INACT_WAIT);
406 	timeout_add_sec(&ic->ic_node_cache_timeout, IEEE80211_CACHE_WAIT);
407 	ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
408 }
409 #endif	/* IEEE80211_STA_ONLY */
410 
411 int
412 ieee80211_match_bss(struct ieee80211com *ic, struct ieee80211_node *ni)
413 {
414 	u_int8_t rate;
415 	int fail;
416 
417 	fail = 0;
418 	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
419 		fail |= 0x01;
420 	if (ic->ic_des_chan != IEEE80211_CHAN_ANYC &&
421 	    ni->ni_chan != ic->ic_des_chan)
422 		fail |= 0x01;
423 #ifndef IEEE80211_STA_ONLY
424 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
425 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
426 			fail |= 0x02;
427 	} else
428 #endif
429 	{
430 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
431 			fail |= 0x02;
432 	}
433 	if (ic->ic_flags & (IEEE80211_F_WEPON | IEEE80211_F_RSNON)) {
434 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
435 			fail |= 0x04;
436 	} else {
437 		if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
438 			fail |= 0x04;
439 	}
440 
441 	rate = ieee80211_fix_rate(ic, ni, IEEE80211_F_DONEGO);
442 	if (rate & IEEE80211_RATE_BASIC)
443 		fail |= 0x08;
444 	if (ic->ic_des_esslen != 0 &&
445 	    (ni->ni_esslen != ic->ic_des_esslen ||
446 	     memcmp(ni->ni_essid, ic->ic_des_essid, ic->ic_des_esslen) != 0))
447 		fail |= 0x10;
448 	if ((ic->ic_flags & IEEE80211_F_DESBSSID) &&
449 	    !IEEE80211_ADDR_EQ(ic->ic_des_bssid, ni->ni_bssid))
450 		fail |= 0x20;
451 
452 	if (ic->ic_flags & IEEE80211_F_RSNON) {
453 		/*
454 		 * If at least one RSN IE field from the AP's RSN IE fails
455 		 * to overlap with any value the STA supports, the STA shall
456 		 * decline to associate with that AP.
457 		 */
458 		if ((ni->ni_rsnprotos & ic->ic_rsnprotos) == 0)
459 			fail |= 0x40;
460 		if ((ni->ni_rsnakms & ic->ic_rsnakms) == 0)
461 			fail |= 0x40;
462 		if ((ni->ni_rsnakms & ic->ic_rsnakms &
463 		     ~(IEEE80211_AKM_PSK | IEEE80211_AKM_SHA256_PSK)) == 0) {
464 			/* AP only supports PSK AKMPs */
465 			if (!(ic->ic_flags & IEEE80211_F_PSK))
466 				fail |= 0x40;
467 		}
468 		if (ni->ni_rsngroupcipher != IEEE80211_CIPHER_WEP40 &&
469 		    ni->ni_rsngroupcipher != IEEE80211_CIPHER_TKIP &&
470 		    ni->ni_rsngroupcipher != IEEE80211_CIPHER_CCMP &&
471 		    ni->ni_rsngroupcipher != IEEE80211_CIPHER_WEP104)
472 			fail |= 0x40;
473 		if ((ni->ni_rsnciphers & ic->ic_rsnciphers) == 0)
474 			fail |= 0x40;
475 
476 		/* we only support BIP as the IGTK cipher */
477 		if ((ni->ni_rsncaps & IEEE80211_RSNCAP_MFPC) &&
478 		    ni->ni_rsngroupmgmtcipher != IEEE80211_CIPHER_BIP)
479 			fail |= 0x40;
480 
481 		/* we do not support MFP but AP requires it */
482 		if (!(ic->ic_caps & IEEE80211_C_MFP) &&
483 		    (ni->ni_rsncaps & IEEE80211_RSNCAP_MFPR))
484 			fail |= 0x40;
485 
486 		/* we require MFP but AP does not support it */
487 		if ((ic->ic_caps & IEEE80211_C_MFP) &&
488 		    (ic->ic_flags & IEEE80211_F_MFPR) &&
489 		    !(ni->ni_rsncaps & IEEE80211_RSNCAP_MFPC))
490 			fail |= 0x40;
491 	}
492 
493 #ifdef IEEE80211_DEBUG
494 	if (ic->ic_if.if_flags & IFF_DEBUG) {
495 		printf(" %c %s", fail ? '-' : '+',
496 		    ether_sprintf(ni->ni_macaddr));
497 		printf(" %s%c", ether_sprintf(ni->ni_bssid),
498 		    fail & 0x20 ? '!' : ' ');
499 		printf(" %3d%c", ieee80211_chan2ieee(ic, ni->ni_chan),
500 			fail & 0x01 ? '!' : ' ');
501 		printf(" %+4d", ni->ni_rssi);
502 		printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
503 		    fail & 0x08 ? '!' : ' ');
504 		printf(" %4s%c",
505 		    (ni->ni_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
506 		    (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
507 		    "????",
508 		    fail & 0x02 ? '!' : ' ');
509 		printf(" %7s%c ",
510 		    (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) ?
511 		    "privacy" : "no",
512 		    fail & 0x04 ? '!' : ' ');
513 		printf(" %3s%c ",
514 		    (ic->ic_flags & IEEE80211_F_RSNON) ?
515 		    "rsn" : "no",
516 		    fail & 0x40 ? '!' : ' ');
517 		ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
518 		printf("%s\n", fail & 0x10 ? "!" : "");
519 	}
520 #endif
521 	return fail;
522 }
523 
524 /*
525  * Complete a scan of potential channels.
526  */
527 void
528 ieee80211_end_scan(struct ifnet *ifp)
529 {
530 	struct ieee80211com *ic = (void *)ifp;
531 	struct ieee80211_node *ni, *nextbs, *selbs;
532 
533 	if (ifp->if_flags & IFF_DEBUG)
534 		printf("%s: end %s scan\n", ifp->if_xname,
535 			(ic->ic_flags & IEEE80211_F_ASCAN) ?
536 				"active" : "passive");
537 
538 	if (ic->ic_scan_count)
539 		ic->ic_flags &= ~IEEE80211_F_ASCAN;
540 
541 	ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
542 
543 #ifndef IEEE80211_STA_ONLY
544 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
545 		/* XXX off stack? */
546 		u_char occupied[howmany(IEEE80211_CHAN_MAX, NBBY)];
547 		int i, fail;
548 
549 		/*
550 		 * The passive scan to look for existing AP's completed,
551 		 * select a channel to camp on.  Identify the channels
552 		 * that already have one or more AP's and try to locate
553 		 * an unoccupied one.  If that fails, pick a random
554 		 * channel from the active set.
555 		 */
556 		memset(occupied, 0, sizeof(occupied));
557 		RBT_FOREACH(ni, ieee80211_tree, &ic->ic_tree)
558 			setbit(occupied, ieee80211_chan2ieee(ic, ni->ni_chan));
559 		for (i = 0; i < IEEE80211_CHAN_MAX; i++)
560 			if (isset(ic->ic_chan_active, i) && isclr(occupied, i))
561 				break;
562 		if (i == IEEE80211_CHAN_MAX) {
563 			fail = arc4random() & 3;	/* random 0-3 */
564 			for (i = 0; i < IEEE80211_CHAN_MAX; i++)
565 				if (isset(ic->ic_chan_active, i) && fail-- == 0)
566 					break;
567 		}
568 		ieee80211_create_ibss(ic, &ic->ic_channels[i]);
569 		goto wakeup;
570 	}
571 #endif
572 	if (ni == NULL) {
573 		DPRINTF(("no scan candidate\n"));
574  notfound:
575 
576 #ifndef IEEE80211_STA_ONLY
577 		if (ic->ic_opmode == IEEE80211_M_IBSS &&
578 		    (ic->ic_flags & IEEE80211_F_IBSSON) &&
579 		    ic->ic_des_esslen != 0) {
580 			ieee80211_create_ibss(ic, ic->ic_ibss_chan);
581 			goto wakeup;
582 		}
583 #endif
584 		/*
585 		 * Scan the next mode if nothing has been found. This
586 		 * is necessary if the device supports different
587 		 * incompatible modes in the same channel range, like
588 		 * like 11b and "pure" 11G mode.
589 		 * If the device scans all bands in one fell swoop, return
590 		 * current scan results to userspace regardless of mode.
591 		 * This will loop forever except for user-initiated scans.
592 		 */
593 		if (ieee80211_next_mode(ifp) == IEEE80211_MODE_AUTO ||
594 		    (ic->ic_caps & IEEE80211_C_SCANALLBAND)) {
595 			if (ic->ic_scan_lock & IEEE80211_SCAN_REQUEST &&
596 			    ic->ic_scan_lock & IEEE80211_SCAN_RESUME) {
597 				ic->ic_scan_lock = IEEE80211_SCAN_LOCKED;
598 				/* Return from a user-initiated scan. */
599 				wakeup(&ic->ic_scan_lock);
600 			} else if (ic->ic_scan_lock & IEEE80211_SCAN_REQUEST)
601 				goto wakeup;
602 			ic->ic_scan_count++;
603 		}
604 
605 		/*
606 		 * Reset the list of channels to scan and start again.
607 		 */
608 		ieee80211_next_scan(ifp);
609 		return;
610 	}
611 	selbs = NULL;
612 
613 	for (; ni != NULL; ni = nextbs) {
614 		nextbs = RBT_NEXT(ieee80211_tree, ni);
615 		if (ni->ni_fails) {
616 			/*
617 			 * The configuration of the access points may change
618 			 * during my scan.  So delete the entry for the AP
619 			 * and retry to associate if there is another beacon.
620 			 */
621 			if (ni->ni_fails++ > 2)
622 				ieee80211_free_node(ic, ni);
623 			continue;
624 		}
625 		if (ieee80211_match_bss(ic, ni) != 0)
626 			continue;
627 
628 		/* Pick the AP/IBSS match with the best RSSI. */
629 		if (selbs == NULL)
630 			selbs = ni;
631 		else if ((ic->ic_caps & IEEE80211_C_SCANALLBAND) &&
632 		    IEEE80211_IS_CHAN_5GHZ(selbs->ni_chan) &&
633 		    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan) &&
634 		    selbs->ni_rssi >= (ic->ic_max_rssi - (ic->ic_max_rssi / 4)))
635 			/*
636 			 * Prefer 5GHz (with reasonable RSSI) over 2GHz since
637 			 * the 5GHz band is usually less saturated.
638 			 */
639 			continue;
640 		else if (ni->ni_rssi > selbs->ni_rssi)
641 			selbs = ni;
642 	}
643 	if (selbs == NULL)
644 		goto notfound;
645 	(*ic->ic_node_copy)(ic, ic->ic_bss, selbs);
646 	ni = ic->ic_bss;
647 
648 	ic->ic_curmode = ieee80211_chan2mode(ic, ni->ni_chan);
649 
650 	if (ic->ic_flags & IEEE80211_F_RSNON)
651 		ieee80211_choose_rsnparams(ic);
652 	else if (ic->ic_flags & IEEE80211_F_WEPON)
653 		ni->ni_rsncipher = IEEE80211_CIPHER_USEGROUP;
654 
655 	ieee80211_node_newstate(selbs, IEEE80211_STA_BSS);
656 #ifndef IEEE80211_STA_ONLY
657 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
658 		ieee80211_fix_rate(ic, ni, IEEE80211_F_DOFRATE |
659 		    IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
660 		if (ni->ni_rates.rs_nrates == 0)
661 			goto notfound;
662 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
663 	} else
664 #endif
665 		ieee80211_new_state(ic, IEEE80211_S_AUTH, -1);
666 
667  wakeup:
668 	if (ic->ic_scan_lock & IEEE80211_SCAN_REQUEST) {
669 		/* Return from a user-initiated scan. */
670 		wakeup(&ic->ic_scan_lock);
671 	}
672 
673 	ic->ic_scan_lock = IEEE80211_SCAN_UNLOCKED;
674 }
675 
676 /*
677  * Autoselect the best RSN parameters (protocol, AKMP, pairwise cipher...)
678  * that are supported by both peers (STA mode only).
679  */
680 void
681 ieee80211_choose_rsnparams(struct ieee80211com *ic)
682 {
683 	struct ieee80211_node *ni = ic->ic_bss;
684 	struct ieee80211_pmk *pmk;
685 
686 	/* filter out unsupported protocol versions */
687 	ni->ni_rsnprotos &= ic->ic_rsnprotos;
688 	/* prefer RSN (aka WPA2) over WPA */
689 	if (ni->ni_rsnprotos & IEEE80211_PROTO_RSN)
690 		ni->ni_rsnprotos = IEEE80211_PROTO_RSN;
691 	else
692 		ni->ni_rsnprotos = IEEE80211_PROTO_WPA;
693 
694 	/* filter out unsupported AKMPs */
695 	ni->ni_rsnakms &= ic->ic_rsnakms;
696 	/* prefer SHA-256 based AKMPs */
697 	if ((ic->ic_flags & IEEE80211_F_PSK) && (ni->ni_rsnakms &
698 	    (IEEE80211_AKM_PSK | IEEE80211_AKM_SHA256_PSK))) {
699 		/* AP supports PSK AKMP and a PSK is configured */
700 		if (ni->ni_rsnakms & IEEE80211_AKM_SHA256_PSK)
701 			ni->ni_rsnakms = IEEE80211_AKM_SHA256_PSK;
702 		else
703 			ni->ni_rsnakms = IEEE80211_AKM_PSK;
704 	} else {
705 		if (ni->ni_rsnakms & IEEE80211_AKM_SHA256_8021X)
706 			ni->ni_rsnakms = IEEE80211_AKM_SHA256_8021X;
707 		else
708 			ni->ni_rsnakms = IEEE80211_AKM_8021X;
709 		/* check if we have a cached PMK for this AP */
710 		if (ni->ni_rsnprotos == IEEE80211_PROTO_RSN &&
711 		    (pmk = ieee80211_pmksa_find(ic, ni, NULL)) != NULL) {
712 			memcpy(ni->ni_pmkid, pmk->pmk_pmkid,
713 			    IEEE80211_PMKID_LEN);
714 			ni->ni_flags |= IEEE80211_NODE_PMKID;
715 		}
716 	}
717 
718 	/* filter out unsupported pairwise ciphers */
719 	ni->ni_rsnciphers &= ic->ic_rsnciphers;
720 	/* prefer CCMP over TKIP */
721 	if (ni->ni_rsnciphers & IEEE80211_CIPHER_CCMP)
722 		ni->ni_rsnciphers = IEEE80211_CIPHER_CCMP;
723 	else
724 		ni->ni_rsnciphers = IEEE80211_CIPHER_TKIP;
725 	ni->ni_rsncipher = ni->ni_rsnciphers;
726 
727 	/* use MFP if we both support it */
728 	if ((ic->ic_caps & IEEE80211_C_MFP) &&
729 	    (ni->ni_rsncaps & IEEE80211_RSNCAP_MFPC))
730 		ni->ni_flags |= IEEE80211_NODE_MFP;
731 }
732 
733 int
734 ieee80211_get_rate(struct ieee80211com *ic)
735 {
736 	u_int8_t (*rates)[IEEE80211_RATE_MAXSIZE];
737 	int rate;
738 
739 	rates = &ic->ic_bss->ni_rates.rs_rates;
740 
741 	if (ic->ic_fixed_rate != -1)
742 		rate = (*rates)[ic->ic_fixed_rate];
743 	else if (ic->ic_state == IEEE80211_S_RUN)
744 		rate = (*rates)[ic->ic_bss->ni_txrate];
745 	else
746 		rate = 0;
747 
748 	return rate & IEEE80211_RATE_VAL;
749 }
750 
751 struct ieee80211_node *
752 ieee80211_node_alloc(struct ieee80211com *ic)
753 {
754 	return malloc(sizeof(struct ieee80211_node), M_DEVBUF,
755 	    M_NOWAIT | M_ZERO);
756 }
757 
758 void
759 ieee80211_node_cleanup(struct ieee80211com *ic, struct ieee80211_node *ni)
760 {
761 	if (ni->ni_rsnie != NULL) {
762 		free(ni->ni_rsnie, M_DEVBUF, 0);
763 		ni->ni_rsnie = NULL;
764 	}
765 	ieee80211_ba_del(ni);
766 }
767 
768 void
769 ieee80211_node_free(struct ieee80211com *ic, struct ieee80211_node *ni)
770 {
771 	ieee80211_node_cleanup(ic, ni);
772 	free(ni, M_DEVBUF, 0);
773 }
774 
775 void
776 ieee80211_node_copy(struct ieee80211com *ic,
777 	struct ieee80211_node *dst, const struct ieee80211_node *src)
778 {
779 	ieee80211_node_cleanup(ic, dst);
780 	*dst = *src;
781 	dst->ni_rsnie = NULL;
782 	if (src->ni_rsnie != NULL)
783 		ieee80211_save_ie(src->ni_rsnie, &dst->ni_rsnie);
784 }
785 
786 u_int8_t
787 ieee80211_node_getrssi(struct ieee80211com *ic,
788     const struct ieee80211_node *ni)
789 {
790 	return ni->ni_rssi;
791 }
792 
793 void
794 ieee80211_setup_node(struct ieee80211com *ic,
795 	struct ieee80211_node *ni, const u_int8_t *macaddr)
796 {
797 	int s;
798 
799 	DPRINTF(("%s\n", ether_sprintf((u_int8_t *)macaddr)));
800 	IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
801 	ieee80211_node_newstate(ni, IEEE80211_STA_CACHE);
802 
803 	ni->ni_ic = ic;	/* back-pointer */
804 #ifndef IEEE80211_STA_ONLY
805 	mq_init(&ni->ni_savedq, IEEE80211_PS_MAX_QUEUE, IPL_NET);
806 	timeout_set(&ni->ni_eapol_to, ieee80211_eapol_timeout, ni);
807 	timeout_set(&ni->ni_sa_query_to, ieee80211_sa_query_timeout, ni);
808 #endif
809 	s = splnet();
810 	RBT_INSERT(ieee80211_tree, &ic->ic_tree, ni);
811 	ic->ic_nnodes++;
812 	splx(s);
813 }
814 
815 struct ieee80211_node *
816 ieee80211_alloc_node(struct ieee80211com *ic, const u_int8_t *macaddr)
817 {
818 	struct ieee80211_node *ni = ieee80211_alloc_node_helper(ic);
819 	if (ni != NULL)
820 		ieee80211_setup_node(ic, ni, macaddr);
821 	else
822 		ic->ic_stats.is_rx_nodealloc++;
823 	return ni;
824 }
825 
826 struct ieee80211_node *
827 ieee80211_dup_bss(struct ieee80211com *ic, const u_int8_t *macaddr)
828 {
829 	struct ieee80211_node *ni = ieee80211_alloc_node_helper(ic);
830 	if (ni != NULL) {
831 		ieee80211_setup_node(ic, ni, macaddr);
832 		/*
833 		 * Inherit from ic_bss.
834 		 */
835 		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
836 		ni->ni_chan = ic->ic_bss->ni_chan;
837 	} else
838 		ic->ic_stats.is_rx_nodealloc++;
839 	return ni;
840 }
841 
842 struct ieee80211_node *
843 ieee80211_find_node(struct ieee80211com *ic, const u_int8_t *macaddr)
844 {
845 	struct ieee80211_node *ni;
846 	int cmp;
847 
848 	/* similar to RBT_FIND except we compare keys, not nodes */
849 	ni = RBT_ROOT(ieee80211_tree, &ic->ic_tree);
850 	while (ni != NULL) {
851 		cmp = memcmp(macaddr, ni->ni_macaddr, IEEE80211_ADDR_LEN);
852 		if (cmp < 0)
853 			ni = RBT_LEFT(ieee80211_tree, ni);
854 		else if (cmp > 0)
855 			ni = RBT_RIGHT(ieee80211_tree, ni);
856 		else
857 			break;
858 	}
859 	return ni;
860 }
861 
862 /*
863  * Return a reference to the appropriate node for sending
864  * a data frame.  This handles node discovery in adhoc networks.
865  *
866  * Drivers will call this, so increase the reference count before
867  * returning the node.
868  */
869 struct ieee80211_node *
870 ieee80211_find_txnode(struct ieee80211com *ic, const u_int8_t *macaddr)
871 {
872 #ifndef IEEE80211_STA_ONLY
873 	struct ieee80211_node *ni;
874 	int s;
875 #endif
876 
877 	/*
878 	 * The destination address should be in the node table
879 	 * unless we are operating in station mode or this is a
880 	 * multicast/broadcast frame.
881 	 */
882 	if (ic->ic_opmode == IEEE80211_M_STA || IEEE80211_IS_MULTICAST(macaddr))
883 		return ieee80211_ref_node(ic->ic_bss);
884 
885 #ifndef IEEE80211_STA_ONLY
886 	s = splnet();
887 	ni = ieee80211_find_node(ic, macaddr);
888 	splx(s);
889 	if (ni == NULL) {
890 		if (ic->ic_opmode != IEEE80211_M_IBSS &&
891 		    ic->ic_opmode != IEEE80211_M_AHDEMO)
892 			return NULL;
893 
894 		/*
895 		 * Fake up a node; this handles node discovery in
896 		 * adhoc mode.  Note that for the driver's benefit
897 		 * we we treat this like an association so the driver
898 		 * has an opportunity to setup its private state.
899 		 *
900 		 * XXX need better way to handle this; issue probe
901 		 *     request so we can deduce rate set, etc.
902 		 */
903 		if ((ni = ieee80211_dup_bss(ic, macaddr)) == NULL)
904 			return NULL;
905 		/* XXX no rate negotiation; just dup */
906 		ni->ni_rates = ic->ic_bss->ni_rates;
907 		ni->ni_txrate = 0;
908 		if (ic->ic_newassoc)
909 			(*ic->ic_newassoc)(ic, ni, 1);
910 	}
911 	return ieee80211_ref_node(ni);
912 #else
913 	return NULL;	/* can't get there */
914 #endif	/* IEEE80211_STA_ONLY */
915 }
916 
917 /*
918  * It is usually desirable to process a Rx packet using its sender's
919  * node-record instead of the BSS record.
920  *
921  * - AP mode: keep a node-record for every authenticated/associated
922  *   station *in the BSS*. For future use, we also track neighboring
923  *   APs, since they might belong to the same ESS.  APs in the same
924  *   ESS may bridge packets to each other, forming a Wireless
925  *   Distribution System (WDS).
926  *
927  * - IBSS mode: keep a node-record for every station *in the BSS*.
928  *   Also track neighboring stations by their beacons/probe responses.
929  *
930  * - monitor mode: keep a node-record for every sender, regardless
931  *   of BSS.
932  *
933  * - STA mode: the only available node-record is the BSS record,
934  *   ic->ic_bss.
935  *
936  * Of all the 802.11 Control packets, only the node-records for
937  * RTS packets node-record can be looked up.
938  *
939  * Return non-zero if the packet's node-record is kept, zero
940  * otherwise.
941  */
942 static __inline int
943 ieee80211_needs_rxnode(struct ieee80211com *ic,
944     const struct ieee80211_frame *wh, const u_int8_t **bssid)
945 {
946 	int monitor, rc = 0;
947 
948 	monitor = (ic->ic_opmode == IEEE80211_M_MONITOR);
949 
950 	*bssid = NULL;
951 
952 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
953 	case IEEE80211_FC0_TYPE_CTL:
954 		if (!monitor)
955 			break;
956 		return (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
957 		    IEEE80211_FC0_SUBTYPE_RTS;
958 	case IEEE80211_FC0_TYPE_MGT:
959 		*bssid = wh->i_addr3;
960 		switch (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) {
961 		case IEEE80211_FC0_SUBTYPE_BEACON:
962 		case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
963 			break;
964 		default:
965 #ifndef IEEE80211_STA_ONLY
966 			if (ic->ic_opmode == IEEE80211_M_STA)
967 				break;
968 			rc = IEEE80211_ADDR_EQ(*bssid, ic->ic_bss->ni_bssid) ||
969 			     IEEE80211_ADDR_EQ(*bssid, etherbroadcastaddr);
970 #endif
971 			break;
972 		}
973 		break;
974 	case IEEE80211_FC0_TYPE_DATA:
975 		switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
976 		case IEEE80211_FC1_DIR_NODS:
977 			*bssid = wh->i_addr3;
978 #ifndef IEEE80211_STA_ONLY
979 			if (ic->ic_opmode == IEEE80211_M_IBSS ||
980 			    ic->ic_opmode == IEEE80211_M_AHDEMO)
981 				rc = IEEE80211_ADDR_EQ(*bssid,
982 				    ic->ic_bss->ni_bssid);
983 #endif
984 			break;
985 		case IEEE80211_FC1_DIR_TODS:
986 			*bssid = wh->i_addr1;
987 #ifndef IEEE80211_STA_ONLY
988 			if (ic->ic_opmode == IEEE80211_M_HOSTAP)
989 				rc = IEEE80211_ADDR_EQ(*bssid,
990 				    ic->ic_bss->ni_bssid);
991 #endif
992 			break;
993 		case IEEE80211_FC1_DIR_FROMDS:
994 		case IEEE80211_FC1_DIR_DSTODS:
995 			*bssid = wh->i_addr2;
996 #ifndef IEEE80211_STA_ONLY
997 			rc = (ic->ic_opmode == IEEE80211_M_HOSTAP);
998 #endif
999 			break;
1000 		}
1001 		break;
1002 	}
1003 	return monitor || rc;
1004 }
1005 
1006 /*
1007  * Drivers call this, so increase the reference count before returning
1008  * the node.
1009  */
1010 struct ieee80211_node *
1011 ieee80211_find_rxnode(struct ieee80211com *ic,
1012     const struct ieee80211_frame *wh)
1013 {
1014 	static const u_int8_t zero[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1015 	struct ieee80211_node *ni;
1016 	const u_int8_t *bssid;
1017 	int s;
1018 
1019 	if (!ieee80211_needs_rxnode(ic, wh, &bssid))
1020 		return ieee80211_ref_node(ic->ic_bss);
1021 
1022 	s = splnet();
1023 	ni = ieee80211_find_node(ic, wh->i_addr2);
1024 	splx(s);
1025 
1026 	if (ni != NULL)
1027 		return ieee80211_ref_node(ni);
1028 #ifndef IEEE80211_STA_ONLY
1029 	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1030 		return ieee80211_ref_node(ic->ic_bss);
1031 #endif
1032 	/* XXX see remarks in ieee80211_find_txnode */
1033 	/* XXX no rate negotiation; just dup */
1034 	if ((ni = ieee80211_dup_bss(ic, wh->i_addr2)) == NULL)
1035 		return ieee80211_ref_node(ic->ic_bss);
1036 
1037 	IEEE80211_ADDR_COPY(ni->ni_bssid, (bssid != NULL) ? bssid : zero);
1038 
1039 	ni->ni_rates = ic->ic_bss->ni_rates;
1040 	ni->ni_txrate = 0;
1041 	if (ic->ic_newassoc)
1042 		(*ic->ic_newassoc)(ic, ni, 1);
1043 
1044 	DPRINTF(("faked-up node %p for %s\n", ni,
1045 	    ether_sprintf((u_int8_t *)wh->i_addr2)));
1046 
1047 	return ieee80211_ref_node(ni);
1048 }
1049 
1050 struct ieee80211_node *
1051 ieee80211_find_node_for_beacon(struct ieee80211com *ic,
1052     const u_int8_t *macaddr, const struct ieee80211_channel *chan,
1053     const char *ssid, u_int8_t rssi)
1054 {
1055 	struct ieee80211_node *ni, *keep = NULL;
1056 	int s, score = 0;
1057 
1058 	if ((ni = ieee80211_find_node(ic, macaddr)) != NULL) {
1059 		s = splnet();
1060 
1061 		if (ni->ni_chan != chan && ni->ni_rssi >= rssi)
1062 			score++;
1063 		if (ssid[1] == 0 && ni->ni_esslen != 0)
1064 			score++;
1065 		if (score > 0)
1066 			keep = ni;
1067 
1068 		splx(s);
1069 	}
1070 
1071 	return (keep);
1072 }
1073 
1074 void
1075 ieee80211_ba_del(struct ieee80211_node *ni)
1076 {
1077 	int tid;
1078 
1079 	for (tid = 0; tid < nitems(ni->ni_rx_ba); tid++) {
1080 		struct ieee80211_rx_ba *ba = &ni->ni_rx_ba[tid];
1081 		if (ba->ba_state != IEEE80211_BA_INIT) {
1082 			if (timeout_pending(&ba->ba_to))
1083 				timeout_del(&ba->ba_to);
1084 			if (timeout_pending(&ba->ba_gap_to))
1085 				timeout_del(&ba->ba_gap_to);
1086 			ba->ba_state = IEEE80211_BA_INIT;
1087 		}
1088 	}
1089 
1090 	for (tid = 0; tid < nitems(ni->ni_tx_ba); tid++) {
1091 		struct ieee80211_tx_ba *ba = &ni->ni_tx_ba[tid];
1092 		if (ba->ba_state != IEEE80211_BA_INIT) {
1093 			if (timeout_pending(&ba->ba_to))
1094 				timeout_del(&ba->ba_to);
1095 			ba->ba_state = IEEE80211_BA_INIT;
1096 		}
1097 	}
1098 }
1099 
1100 void
1101 ieee80211_free_node(struct ieee80211com *ic, struct ieee80211_node *ni)
1102 {
1103 	if (ni == ic->ic_bss)
1104 		panic("freeing bss node");
1105 
1106 	splassert(IPL_NET);
1107 
1108 	DPRINTF(("%s\n", ether_sprintf(ni->ni_macaddr)));
1109 #ifndef IEEE80211_STA_ONLY
1110 	timeout_del(&ni->ni_eapol_to);
1111 	timeout_del(&ni->ni_sa_query_to);
1112 	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1113 #endif
1114 	ieee80211_ba_del(ni);
1115 	RBT_REMOVE(ieee80211_tree, &ic->ic_tree, ni);
1116 	ic->ic_nnodes--;
1117 #ifndef IEEE80211_STA_ONLY
1118 	if (mq_purge(&ni->ni_savedq) > 0) {
1119 		if (ic->ic_set_tim != NULL)
1120 			(*ic->ic_set_tim)(ic, ni->ni_associd, 0);
1121 	}
1122 #endif
1123 	(*ic->ic_node_free)(ic, ni);
1124 	/* TBD indicate to drivers that a new node can be allocated */
1125 }
1126 
1127 void
1128 ieee80211_release_node(struct ieee80211com *ic, struct ieee80211_node *ni)
1129 {
1130 	int s;
1131 
1132 	DPRINTF(("%s refcnt %u\n", ether_sprintf(ni->ni_macaddr),
1133 	    ni->ni_refcnt));
1134 	s = splnet();
1135 	if (ieee80211_node_decref(ni) == 0 &&
1136 	    ni->ni_state == IEEE80211_STA_COLLECT) {
1137 		ieee80211_free_node(ic, ni);
1138 	}
1139 	splx(s);
1140 }
1141 
1142 void
1143 ieee80211_free_allnodes(struct ieee80211com *ic)
1144 {
1145 	struct ieee80211_node *ni;
1146 	int s;
1147 
1148 	DPRINTF(("freeing all nodes\n"));
1149 	s = splnet();
1150 	while ((ni = RBT_MIN(ieee80211_tree, &ic->ic_tree)) != NULL)
1151 		ieee80211_free_node(ic, ni);
1152 	splx(s);
1153 
1154 	if (ic->ic_bss != NULL)
1155 		ieee80211_node_cleanup(ic, ic->ic_bss);	/* for station mode */
1156 }
1157 
1158 void
1159 ieee80211_clean_cached(struct ieee80211com *ic)
1160 {
1161 	struct ieee80211_node *ni, *next_ni;
1162 	int s;
1163 
1164 	s = splnet();
1165 	for (ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
1166 	    ni != NULL; ni = next_ni) {
1167 		next_ni = RBT_NEXT(ieee80211_tree, ni);
1168 		if (ni->ni_state == IEEE80211_STA_CACHE)
1169 			ieee80211_free_node(ic, ni);
1170 	}
1171 	splx(s);
1172 }
1173 /*
1174  * Timeout inactive nodes.
1175  *
1176  * If called because of a cache timeout, which happens only in hostap and ibss
1177  * modes, clean all inactive cached or authenticated nodes but don't de-auth
1178  * any associated nodes.
1179  *
1180  * Else, this function is called because a new node must be allocated but the
1181  * node cache is full. In this case, return as soon as a free slot was made
1182  * available. If acting as hostap, clean cached nodes regardless of their
1183  * recent activity and also allow de-authing of authenticated nodes older
1184  * than one cache wait interval, and de-authing of inactive associated nodes.
1185  */
1186 void
1187 ieee80211_clean_nodes(struct ieee80211com *ic, int cache_timeout)
1188 {
1189 	struct ieee80211_node *ni, *next_ni;
1190 	u_int gen = ic->ic_scangen++;		/* NB: ok 'cuz single-threaded*/
1191 	int s;
1192 #ifndef IEEE80211_STA_ONLY
1193 	int nnodes = 0;
1194 	struct ifnet *ifp = &ic->ic_if;
1195 #endif
1196 
1197 	s = splnet();
1198 	for (ni = RBT_MIN(ieee80211_tree, &ic->ic_tree);
1199 	    ni != NULL; ni = next_ni) {
1200 		next_ni = RBT_NEXT(ieee80211_tree, ni);
1201 		if (!cache_timeout && ic->ic_nnodes < ic->ic_max_nnodes)
1202 			break;
1203 		if (ni->ni_scangen == gen)	/* previously handled */
1204 			continue;
1205 #ifndef IEEE80211_STA_ONLY
1206 		nnodes++;
1207 #endif
1208 		ni->ni_scangen = gen;
1209 		if (ni->ni_refcnt > 0)
1210 			continue;
1211 #ifndef IEEE80211_STA_ONLY
1212 		if ((ic->ic_opmode == IEEE80211_M_HOSTAP ||
1213 		    ic->ic_opmode == IEEE80211_M_IBSS) &&
1214 		    ic->ic_state == IEEE80211_S_RUN) {
1215 			if (cache_timeout) {
1216 				if (ni->ni_state != IEEE80211_STA_COLLECT &&
1217 				    (ni->ni_state == IEEE80211_STA_ASSOC ||
1218 				    ni->ni_inact < IEEE80211_INACT_MAX))
1219 					continue;
1220 			} else {
1221 				if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
1222 				    ((ni->ni_state == IEEE80211_STA_ASSOC &&
1223 				    ni->ni_inact < IEEE80211_INACT_MAX) ||
1224 				    (ni->ni_state == IEEE80211_STA_AUTH &&
1225 				     ni->ni_inact == 0)))
1226 				    	continue;
1227 
1228 				if (ic->ic_opmode == IEEE80211_M_IBSS &&
1229 				    ni->ni_state != IEEE80211_STA_COLLECT &&
1230 				    ni->ni_state != IEEE80211_STA_CACHE &&
1231 				    ni->ni_inact < IEEE80211_INACT_MAX)
1232 					continue;
1233 			}
1234 		}
1235 		if (ifp->if_flags & IFF_DEBUG)
1236 			printf("%s: station %s purged from node cache\n",
1237 			    ifp->if_xname, ether_sprintf(ni->ni_macaddr));
1238 #endif
1239 		/*
1240 		 * If we're hostap and the node is authenticated, send
1241 		 * a deauthentication frame. The node will be freed when
1242 		 * the driver calls ieee80211_release_node().
1243 		 */
1244 #ifndef IEEE80211_STA_ONLY
1245 		nnodes--;
1246 		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
1247 		    ni->ni_state >= IEEE80211_STA_AUTH &&
1248 		    ni->ni_state != IEEE80211_STA_COLLECT) {
1249 			splx(s);
1250 			IEEE80211_SEND_MGMT(ic, ni,
1251 			    IEEE80211_FC0_SUBTYPE_DEAUTH,
1252 			    IEEE80211_REASON_AUTH_EXPIRE);
1253 			s = splnet();
1254 			ieee80211_node_leave(ic, ni);
1255 		} else
1256 #endif
1257 			ieee80211_free_node(ic, ni);
1258 		ic->ic_stats.is_node_timeout++;
1259 	}
1260 
1261 #ifndef IEEE80211_STA_ONLY
1262 	/*
1263 	 * During a cache timeout we iterate over all nodes.
1264 	 * Check for node leaks by comparing the actual number of cached
1265 	 * nodes with the ic_nnodes count, which is maintained while adding
1266 	 * and removing nodes from the cache.
1267 	 */
1268 	if ((ifp->if_flags & IFF_DEBUG) && cache_timeout &&
1269 	    nnodes != ic->ic_nnodes)
1270 		printf("%s: number of cached nodes is %d, expected %d,"
1271 		    "possible nodes leak\n", ifp->if_xname, nnodes,
1272 		    ic->ic_nnodes);
1273 #endif
1274 	splx(s);
1275 }
1276 
1277 void
1278 ieee80211_iterate_nodes(struct ieee80211com *ic, ieee80211_iter_func *f,
1279     void *arg)
1280 {
1281 	struct ieee80211_node *ni;
1282 	int s;
1283 
1284 	s = splnet();
1285 	RBT_FOREACH(ni, ieee80211_tree, &ic->ic_tree)
1286 		(*f)(arg, ni);
1287 	splx(s);
1288 }
1289 
1290 
1291 /*
1292  * Install received HT caps information in the node's state block.
1293  */
1294 void
1295 ieee80211_setup_htcaps(struct ieee80211_node *ni, const uint8_t *data,
1296     uint8_t len)
1297 {
1298 	uint16_t rxrate;
1299 
1300 	if (len != 26)
1301 		return;
1302 
1303 	ni->ni_htcaps = (data[0] | (data[1] << 8));
1304 	ni->ni_ampdu_param = data[2];
1305 
1306 	memcpy(ni->ni_rxmcs, &data[3], sizeof(ni->ni_rxmcs));
1307 	/* clear reserved bits */
1308 	clrbit(ni->ni_rxmcs, 77);
1309 	clrbit(ni->ni_rxmcs, 78);
1310 	clrbit(ni->ni_rxmcs, 79);
1311 
1312 	/* Max MCS Rx rate in 1Mb/s units (0 means "not specified"). */
1313 	rxrate = ((data[13] | (data[14]) << 8) & IEEE80211_MCS_RX_RATE_HIGH);
1314 	if (rxrate < 1024)
1315 		ni->ni_max_rxrate = rxrate;
1316 
1317 	ni->ni_tx_mcs_set = data[15];
1318 	ni->ni_htxcaps = (data[19] | (data[20] << 8));
1319 	ni->ni_txbfcaps = (data[21] | (data[22] << 8) | (data[23] << 16) |
1320 		(data[24] << 24));
1321 	ni->ni_aselcaps = data[25];
1322 }
1323 
1324 /*
1325  * Install received HT op information in the node's state block.
1326  */
1327 int
1328 ieee80211_setup_htop(struct ieee80211_node *ni, const uint8_t *data,
1329     uint8_t len)
1330 {
1331 	if (len != 22)
1332 		return 0;
1333 
1334 	ni->ni_primary_chan = data[0]; /* XXX corresponds to ni_chan */
1335 
1336 	ni->ni_htop0 = data[1];
1337 	ni->ni_htop1 = (data[2] | (data[3] << 8));
1338 	ni->ni_htop2 = (data[3] | (data[4] << 8));
1339 
1340 	memcpy(ni->ni_basic_mcs, &data[6], sizeof(ni->ni_basic_mcs));
1341 
1342 	return 1;
1343 }
1344 
1345 /*
1346  * Install received rate set information in the node's state block.
1347  */
1348 int
1349 ieee80211_setup_rates(struct ieee80211com *ic, struct ieee80211_node *ni,
1350     const u_int8_t *rates, const u_int8_t *xrates, int flags)
1351 {
1352 	struct ieee80211_rateset *rs = &ni->ni_rates;
1353 
1354 	memset(rs, 0, sizeof(*rs));
1355 	rs->rs_nrates = rates[1];
1356 	memcpy(rs->rs_rates, rates + 2, rs->rs_nrates);
1357 	if (xrates != NULL) {
1358 		u_int8_t nxrates;
1359 		/*
1360 		 * Tack on 11g extended supported rate element.
1361 		 */
1362 		nxrates = xrates[1];
1363 		if (rs->rs_nrates + nxrates > IEEE80211_RATE_MAXSIZE) {
1364 			nxrates = IEEE80211_RATE_MAXSIZE - rs->rs_nrates;
1365 			DPRINTF(("extended rate set too large; "
1366 			    "only using %u of %u rates\n",
1367 			    nxrates, xrates[1]));
1368 			ic->ic_stats.is_rx_rstoobig++;
1369 		}
1370 		memcpy(rs->rs_rates + rs->rs_nrates, xrates+2, nxrates);
1371 		rs->rs_nrates += nxrates;
1372 	}
1373 	return ieee80211_fix_rate(ic, ni, flags);
1374 }
1375 
1376 #ifndef IEEE80211_STA_ONLY
1377 /*
1378  * Check if the specified node supports ERP.
1379  */
1380 int
1381 ieee80211_iserp_sta(const struct ieee80211_node *ni)
1382 {
1383 	static const u_int8_t rates[] = { 2, 4, 11, 22, 12, 24, 48 };
1384 	const struct ieee80211_rateset *rs = &ni->ni_rates;
1385 	int i, j;
1386 
1387 	/*
1388 	 * A STA supports ERP operation if it includes all the Clause 19
1389 	 * mandatory rates in its supported rate set.
1390 	 */
1391 	for (i = 0; i < nitems(rates); i++) {
1392 		for (j = 0; j < rs->rs_nrates; j++) {
1393 			if ((rs->rs_rates[j] & IEEE80211_RATE_VAL) == rates[i])
1394 				break;
1395 		}
1396 		if (j == rs->rs_nrates)
1397 			return 0;
1398 	}
1399 	return 1;
1400 }
1401 
1402 /*
1403  * This function is called to notify the 802.1X PACP machine that a new
1404  * 802.1X port is enabled and must be authenticated. For 802.11, a port
1405  * becomes enabled whenever a STA successfully completes Open System
1406  * authentication with an AP.
1407  */
1408 void
1409 ieee80211_needs_auth(struct ieee80211com *ic, struct ieee80211_node *ni)
1410 {
1411 	/*
1412 	 * XXX this could be done via the route socket of via a dedicated
1413 	 * EAP socket or another kernel->userland notification mechanism.
1414 	 * The notification should include the MAC address (ni_macaddr).
1415 	 */
1416 }
1417 
1418 /*
1419  * Handle an HT STA joining an HT network.
1420  */
1421 void
1422 ieee80211_node_join_ht(struct ieee80211com *ic, struct ieee80211_node *ni)
1423 {
1424 	/* TBD */
1425 }
1426 
1427 /*
1428  * Handle a station joining an RSN network.
1429  */
1430 void
1431 ieee80211_node_join_rsn(struct ieee80211com *ic, struct ieee80211_node *ni)
1432 {
1433 	DPRINTF(("station %s associated using proto %d akm 0x%x "
1434 	    "cipher 0x%x groupcipher 0x%x\n", ether_sprintf(ni->ni_macaddr),
1435 	    ni->ni_rsnprotos, ni->ni_rsnakms, ni->ni_rsnciphers,
1436 	    ni->ni_rsngroupcipher));
1437 
1438 	ni->ni_rsn_state = RSNA_AUTHENTICATION;
1439 	ic->ic_rsnsta++;
1440 
1441 	ni->ni_key_count = 0;
1442 	ni->ni_port_valid = 0;
1443 	ni->ni_flags &= ~IEEE80211_NODE_TXRXPROT;
1444 	ni->ni_replaycnt = -1;	/* XXX */
1445 	ni->ni_rsn_retries = 0;
1446 	ni->ni_rsncipher = ni->ni_rsnciphers;
1447 
1448 	ni->ni_rsn_state = RSNA_AUTHENTICATION_2;
1449 
1450 	/* generate a new authenticator nonce (ANonce) */
1451 	arc4random_buf(ni->ni_nonce, EAPOL_KEY_NONCE_LEN);
1452 
1453 	if (!ieee80211_is_8021x_akm(ni->ni_rsnakms)) {
1454 		memcpy(ni->ni_pmk, ic->ic_psk, IEEE80211_PMK_LEN);
1455 		ni->ni_flags |= IEEE80211_NODE_PMK;
1456 		(void)ieee80211_send_4way_msg1(ic, ni);
1457 	} else if (ni->ni_flags & IEEE80211_NODE_PMK) {
1458 		/* skip 802.1X auth if a cached PMK was found */
1459 		(void)ieee80211_send_4way_msg1(ic, ni);
1460 	} else {
1461 		/* no cached PMK found, needs full 802.1X auth */
1462 		ieee80211_needs_auth(ic, ni);
1463 	}
1464 }
1465 
1466 /*
1467  * Handle a station joining an 11g network.
1468  */
1469 void
1470 ieee80211_node_join_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
1471 {
1472 	if (!(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)) {
1473 		/*
1474 		 * Joining STA doesn't support short slot time.  We must
1475 		 * disable the use of short slot time for all other associated
1476 		 * STAs and give the driver a chance to reconfigure the
1477 		 * hardware.
1478 		 */
1479 		if (++ic->ic_longslotsta == 1) {
1480 			if (ic->ic_caps & IEEE80211_C_SHSLOT)
1481 				ieee80211_set_shortslottime(ic, 0);
1482 		}
1483 		DPRINTF(("[%s] station needs long slot time, count %d\n",
1484 		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta));
1485 	}
1486 
1487 	if (!ieee80211_iserp_sta(ni)) {
1488 		/*
1489 		 * Joining STA is non-ERP.
1490 		 */
1491 		ic->ic_nonerpsta++;
1492 
1493 		DPRINTF(("[%s] station is non-ERP, %d non-ERP "
1494 		    "stations associated\n", ether_sprintf(ni->ni_macaddr),
1495 		    ic->ic_nonerpsta));
1496 
1497 		/* must enable the use of protection */
1498 		if (ic->ic_protmode != IEEE80211_PROT_NONE) {
1499 			DPRINTF(("enable use of protection\n"));
1500 			ic->ic_flags |= IEEE80211_F_USEPROT;
1501 		}
1502 
1503 		if (!(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE))
1504 			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
1505 	} else
1506 		ni->ni_flags |= IEEE80211_NODE_ERP;
1507 }
1508 
1509 void
1510 ieee80211_node_join(struct ieee80211com *ic, struct ieee80211_node *ni,
1511     int resp)
1512 {
1513 	int newassoc = (ni->ni_state != IEEE80211_STA_ASSOC);
1514 
1515 	if (ni->ni_associd == 0) {
1516 		u_int16_t aid;
1517 
1518 		/*
1519 		 * It would be clever to search the bitmap
1520 		 * more efficiently, but this will do for now.
1521 		 */
1522 		for (aid = 1; aid < ic->ic_max_aid; aid++) {
1523 			if (!IEEE80211_AID_ISSET(aid,
1524 			    ic->ic_aid_bitmap))
1525 				break;
1526 		}
1527 		if (aid >= ic->ic_max_aid) {
1528 			IEEE80211_SEND_MGMT(ic, ni, resp,
1529 			    IEEE80211_REASON_ASSOC_TOOMANY);
1530 			ieee80211_node_leave(ic, ni);
1531 			return;
1532 		}
1533 		ni->ni_associd = aid | 0xc000;
1534 		IEEE80211_AID_SET(ni->ni_associd, ic->ic_aid_bitmap);
1535 		if (ic->ic_curmode == IEEE80211_MODE_11G ||
1536 		    (ic->ic_curmode == IEEE80211_MODE_11N &&
1537 		    IEEE80211_IS_CHAN_2GHZ(ic->ic_bss->ni_chan)))
1538 			ieee80211_node_join_11g(ic, ni);
1539 	}
1540 
1541 	DPRINTF(("station %s %s associated at aid %d\n",
1542 	    ether_sprintf(ni->ni_macaddr), newassoc ? "newly" : "already",
1543 	    ni->ni_associd & ~0xc000));
1544 
1545 	/* give driver a chance to setup state like ni_txrate */
1546 	if (ic->ic_newassoc)
1547 		(*ic->ic_newassoc)(ic, ni, newassoc);
1548 	IEEE80211_SEND_MGMT(ic, ni, resp, IEEE80211_STATUS_SUCCESS);
1549 	ieee80211_node_newstate(ni, IEEE80211_STA_ASSOC);
1550 
1551 	if (!(ic->ic_flags & IEEE80211_F_RSNON)) {
1552 		ni->ni_port_valid = 1;
1553 		ni->ni_rsncipher = IEEE80211_CIPHER_USEGROUP;
1554 	} else
1555 		ieee80211_node_join_rsn(ic, ni);
1556 
1557 	ieee80211_ht_negotiate(ic, ni);
1558 	if (ni->ni_flags & IEEE80211_NODE_HT)
1559 		ieee80211_node_join_ht(ic, ni);
1560 
1561 #if NBRIDGE > 0
1562 	/*
1563 	 * If the parent interface is a bridgeport, learn
1564 	 * the node's address dynamically on this interface.
1565 	 */
1566 	if (ic->ic_if.if_bridgeport != NULL)
1567 		bridge_update(&ic->ic_if,
1568 		    (struct ether_addr *)ni->ni_macaddr, 0);
1569 #endif
1570 }
1571 
1572 /*
1573  * Handle an HT STA leaving an HT network.
1574  */
1575 void
1576 ieee80211_node_leave_ht(struct ieee80211com *ic, struct ieee80211_node *ni)
1577 {
1578 	struct ieee80211_rx_ba *ba;
1579 	u_int8_t tid;
1580 	int i;
1581 
1582 	/* free all Block Ack records */
1583 	for (tid = 0; tid < IEEE80211_NUM_TID; tid++) {
1584 		ba = &ni->ni_rx_ba[tid];
1585 		if (ba->ba_buf != NULL) {
1586 			for (i = 0; i < IEEE80211_BA_MAX_WINSZ; i++)
1587 				m_freem(ba->ba_buf[i].m);
1588 			free(ba->ba_buf, M_DEVBUF, 0);
1589 			ba->ba_buf = NULL;
1590 		}
1591 	}
1592 }
1593 
1594 /*
1595  * Handle a station leaving an RSN network.
1596  */
1597 void
1598 ieee80211_node_leave_rsn(struct ieee80211com *ic, struct ieee80211_node *ni)
1599 {
1600 	ni->ni_rsn_state = RSNA_DISCONNECTED;
1601 	ic->ic_rsnsta--;
1602 
1603 	ni->ni_rsn_state = RSNA_INITIALIZE;
1604 	if ((ni->ni_flags & IEEE80211_NODE_REKEY) &&
1605 	    --ic->ic_rsn_keydonesta == 0)
1606 		ieee80211_setkeysdone(ic);
1607 	ni->ni_flags &= ~IEEE80211_NODE_REKEY;
1608 
1609 	ni->ni_flags &= ~IEEE80211_NODE_PMK;
1610 	ni->ni_rsn_gstate = RSNA_IDLE;
1611 
1612 	timeout_del(&ni->ni_eapol_to);
1613 	timeout_del(&ni->ni_sa_query_to);
1614 
1615 	ni->ni_rsn_retries = 0;
1616 	ni->ni_flags &= ~IEEE80211_NODE_TXRXPROT;
1617 	ni->ni_port_valid = 0;
1618 	(*ic->ic_delete_key)(ic, ni, &ni->ni_pairwise_key);
1619 }
1620 
1621 /*
1622  * Handle a station leaving an 11g network.
1623  */
1624 void
1625 ieee80211_node_leave_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
1626 {
1627 	if (!(ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)) {
1628 #ifdef DIAGNOSTIC
1629 		if (ic->ic_longslotsta == 0) {
1630 			panic("bogus long slot station count %d",
1631 			    ic->ic_longslotsta);
1632 		}
1633 #endif
1634 		/* leaving STA did not support short slot time */
1635 		if (--ic->ic_longslotsta == 0) {
1636 			/*
1637 			 * All associated STAs now support short slot time, so
1638 			 * enable this feature and give the driver a chance to
1639 			 * reconfigure the hardware. Notice that IBSS always
1640 			 * use a long slot time.
1641 			 */
1642 			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
1643 			    ic->ic_opmode != IEEE80211_M_IBSS)
1644 				ieee80211_set_shortslottime(ic, 1);
1645 		}
1646 		DPRINTF(("[%s] long slot time station leaves, count %d\n",
1647 		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta));
1648 	}
1649 
1650 	if (!(ni->ni_flags & IEEE80211_NODE_ERP)) {
1651 #ifdef DIAGNOSTIC
1652 		if (ic->ic_nonerpsta == 0) {
1653 			panic("bogus non-ERP station count %d",
1654 			    ic->ic_nonerpsta);
1655 		}
1656 #endif
1657 		/* leaving STA was non-ERP */
1658 		if (--ic->ic_nonerpsta == 0) {
1659 			/*
1660 			 * All associated STAs are now ERP capable, disable use
1661 			 * of protection and re-enable short preamble support.
1662 			 */
1663 			ic->ic_flags &= ~IEEE80211_F_USEPROT;
1664 			if (ic->ic_caps & IEEE80211_C_SHPREAMBLE)
1665 				ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
1666 		}
1667 		DPRINTF(("[%s] non-ERP station leaves, count %d\n",
1668 		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta));
1669 	}
1670 }
1671 
1672 /*
1673  * Handle bookkeeping for station deauthentication/disassociation
1674  * when operating as an ap.
1675  */
1676 void
1677 ieee80211_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
1678 {
1679 	if (ic->ic_opmode != IEEE80211_M_HOSTAP)
1680 		panic("not in ap mode, mode %u", ic->ic_opmode);
1681 	/*
1682 	 * If node wasn't previously associated all we need to do is
1683 	 * reclaim the reference.
1684 	 */
1685 	if (ni->ni_associd == 0) {
1686 		ieee80211_node_newstate(ni, IEEE80211_STA_COLLECT);
1687 		return;
1688 	}
1689 
1690 	if (ni->ni_pwrsave == IEEE80211_PS_DOZE) {
1691 		ic->ic_pssta--;
1692 		ni->ni_pwrsave = IEEE80211_PS_AWAKE;
1693 	}
1694 
1695 	if (mq_purge(&ni->ni_savedq) > 0) {
1696 		if (ic->ic_set_tim != NULL)
1697 			(*ic->ic_set_tim)(ic, ni->ni_associd, 0);
1698 	}
1699 
1700 	if (ic->ic_flags & IEEE80211_F_RSNON)
1701 		ieee80211_node_leave_rsn(ic, ni);
1702 
1703 	if (ic->ic_curmode == IEEE80211_MODE_11G ||
1704 	    (ic->ic_curmode == IEEE80211_MODE_11N &&
1705 	    IEEE80211_IS_CHAN_2GHZ(ic->ic_bss->ni_chan)))
1706 		ieee80211_node_leave_11g(ic, ni);
1707 
1708 	if (ni->ni_flags & IEEE80211_NODE_HT)
1709 		ieee80211_node_leave_ht(ic, ni);
1710 
1711 	if (ic->ic_node_leave != NULL)
1712 		(*ic->ic_node_leave)(ic, ni);
1713 
1714 	ieee80211_node_newstate(ni, IEEE80211_STA_COLLECT);
1715 
1716 #if NBRIDGE > 0
1717 	/*
1718 	 * If the parent interface is a bridgeport, delete
1719 	 * any dynamically learned address for this node.
1720 	 */
1721 	if (ic->ic_if.if_bridgeport != NULL)
1722 		bridge_update(&ic->ic_if,
1723 		    (struct ether_addr *)ni->ni_macaddr, 1);
1724 #endif
1725 }
1726 
1727 static int
1728 ieee80211_do_slow_print(struct ieee80211com *ic, int *did_print)
1729 {
1730 	static const struct timeval merge_print_intvl = {
1731 		.tv_sec = 1, .tv_usec = 0
1732 	};
1733 	if ((ic->ic_if.if_flags & IFF_LINK0) == 0)
1734 		return 0;
1735 	if (!*did_print && (ic->ic_if.if_flags & IFF_DEBUG) == 0 &&
1736 	    !ratecheck(&ic->ic_last_merge_print, &merge_print_intvl))
1737 		return 0;
1738 
1739 	*did_print = 1;
1740 	return 1;
1741 }
1742 
1743 /* ieee80211_ibss_merge helps merge 802.11 ad hoc networks.  The
1744  * convention, set by the Wireless Ethernet Compatibility Alliance
1745  * (WECA), is that an 802.11 station will change its BSSID to match
1746  * the "oldest" 802.11 ad hoc network, on the same channel, that
1747  * has the station's desired SSID.  The "oldest" 802.11 network
1748  * sends beacons with the greatest TSF timestamp.
1749  *
1750  * Return ENETRESET if the BSSID changed, 0 otherwise.
1751  *
1752  * XXX Perhaps we should compensate for the time that elapses
1753  * between the MAC receiving the beacon and the host processing it
1754  * in ieee80211_ibss_merge.
1755  */
1756 int
1757 ieee80211_ibss_merge(struct ieee80211com *ic, struct ieee80211_node *ni,
1758     u_int64_t local_tsft)
1759 {
1760 	u_int64_t beacon_tsft;
1761 	int did_print = 0, sign;
1762 	union {
1763 		u_int64_t	word;
1764 		u_int8_t	tstamp[8];
1765 	} u;
1766 
1767 	/* ensure alignment */
1768 	(void)memcpy(&u, &ni->ni_tstamp[0], sizeof(u));
1769 	beacon_tsft = letoh64(u.word);
1770 
1771 	/* we are faster, let the other guy catch up */
1772 	if (beacon_tsft < local_tsft)
1773 		sign = -1;
1774 	else
1775 		sign = 1;
1776 
1777 	if (IEEE80211_ADDR_EQ(ni->ni_bssid, ic->ic_bss->ni_bssid)) {
1778 		if (!ieee80211_do_slow_print(ic, &did_print))
1779 			return 0;
1780 		printf("%s: tsft offset %s%llu\n", ic->ic_if.if_xname,
1781 		    (sign < 0) ? "-" : "",
1782 		    (sign < 0)
1783 			? (local_tsft - beacon_tsft)
1784 			: (beacon_tsft - local_tsft));
1785 		return 0;
1786 	}
1787 
1788 	if (sign < 0)
1789 		return 0;
1790 
1791 	if (ieee80211_match_bss(ic, ni) != 0)
1792 		return 0;
1793 
1794 	if (ieee80211_do_slow_print(ic, &did_print)) {
1795 		printf("%s: ieee80211_ibss_merge: bssid mismatch %s\n",
1796 		    ic->ic_if.if_xname, ether_sprintf(ni->ni_bssid));
1797 		printf("%s: my tsft %llu beacon tsft %llu\n",
1798 		    ic->ic_if.if_xname, local_tsft, beacon_tsft);
1799 		printf("%s: sync TSF with %s\n",
1800 		    ic->ic_if.if_xname, ether_sprintf(ni->ni_macaddr));
1801 	}
1802 
1803 	ic->ic_flags &= ~IEEE80211_F_SIBSS;
1804 
1805 	/* negotiate rates with new IBSS */
1806 	ieee80211_fix_rate(ic, ni, IEEE80211_F_DOFRATE |
1807 	    IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
1808 	if (ni->ni_rates.rs_nrates == 0) {
1809 		if (ieee80211_do_slow_print(ic, &did_print)) {
1810 			printf("%s: rates mismatch, BSSID %s\n",
1811 			    ic->ic_if.if_xname, ether_sprintf(ni->ni_bssid));
1812 		}
1813 		return 0;
1814 	}
1815 
1816 	if (ieee80211_do_slow_print(ic, &did_print)) {
1817 		printf("%s: sync BSSID %s -> ",
1818 		    ic->ic_if.if_xname, ether_sprintf(ic->ic_bss->ni_bssid));
1819 		printf("%s ", ether_sprintf(ni->ni_bssid));
1820 		printf("(from %s)\n", ether_sprintf(ni->ni_macaddr));
1821 	}
1822 
1823 	ieee80211_node_newstate(ni, IEEE80211_STA_BSS);
1824 	(*ic->ic_node_copy)(ic, ic->ic_bss, ni);
1825 
1826 	return ENETRESET;
1827 }
1828 
1829 void
1830 ieee80211_set_tim(struct ieee80211com *ic, int aid, int set)
1831 {
1832 	if (set)
1833 		setbit(ic->ic_tim_bitmap, aid & ~0xc000);
1834 	else
1835 		clrbit(ic->ic_tim_bitmap, aid & ~0xc000);
1836 }
1837 
1838 /*
1839  * This function shall be called by drivers immediately after every DTIM.
1840  * Transmit all group addressed MSDUs buffered at the AP.
1841  */
1842 void
1843 ieee80211_notify_dtim(struct ieee80211com *ic)
1844 {
1845 	/* NB: group addressed MSDUs are buffered in ic_bss */
1846 	struct ieee80211_node *ni = ic->ic_bss;
1847 	struct ifnet *ifp = &ic->ic_if;
1848 	struct ieee80211_frame *wh;
1849 	struct mbuf *m;
1850 
1851 	KASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP);
1852 
1853 	while ((m = mq_dequeue(&ni->ni_savedq)) != NULL) {
1854 		if (!mq_empty(&ni->ni_savedq)) {
1855 			/* more queued frames, set the more data bit */
1856 			wh = mtod(m, struct ieee80211_frame *);
1857 			wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
1858 		}
1859 		mq_enqueue(&ic->ic_pwrsaveq, m);
1860 		if_start(ifp);
1861 	}
1862 	/* XXX assumes everything has been sent */
1863 	ic->ic_tim_mcast_pending = 0;
1864 }
1865 #endif	/* IEEE80211_STA_ONLY */
1866 
1867 /*
1868  * Compare nodes in the tree by lladdr
1869  */
1870 int
1871 ieee80211_node_cmp(const struct ieee80211_node *b1,
1872     const struct ieee80211_node *b2)
1873 {
1874 	return (memcmp(b1->ni_macaddr, b2->ni_macaddr, IEEE80211_ADDR_LEN));
1875 }
1876 
1877 /*
1878  * Generate red-black tree function logic
1879  */
1880 RBT_GENERATE(ieee80211_tree, ieee80211_node, ni_node, ieee80211_node_cmp);
1881