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