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