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