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