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