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