xref: /netbsd-src/sys/net80211/ieee80211_node.c (revision aaf4ece63a859a04e37cf3a7229b5fab0157cc06)
1 /*	$NetBSD: ieee80211_node.c,v 1.50 2006/01/13 08:43:11 skrll Exp $	*/
2 /*-
3  * Copyright (c) 2001 Atsushi Onoe
4  * Copyright (c) 2002-2005 Sam Leffler, Errno Consulting
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. The name of the author may not be used to endorse or promote products
16  *    derived from this software without specific prior written permission.
17  *
18  * Alternatively, this software may be distributed under the terms of the
19  * GNU General Public License ("GPL") version 2 as published by the Free
20  * Software Foundation.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
23  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 #include <sys/cdefs.h>
35 #ifdef __FreeBSD__
36 __FBSDID("$FreeBSD: src/sys/net80211/ieee80211_node.c,v 1.65 2005/08/13 17:50:21 sam Exp $");
37 #endif
38 #ifdef __NetBSD__
39 __KERNEL_RCSID(0, "$NetBSD: ieee80211_node.c,v 1.50 2006/01/13 08:43:11 skrll Exp $");
40 #endif
41 
42 #include "opt_inet.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/mbuf.h>
47 #include <sys/malloc.h>
48 #include <sys/kernel.h>
49 
50 #include <sys/socket.h>
51 #include <sys/sockio.h>
52 #include <sys/endian.h>
53 #include <sys/errno.h>
54 #include <sys/proc.h>
55 #include <sys/sysctl.h>
56 
57 #include <net/if.h>
58 #include <net/if_media.h>
59 #include <net/if_arp.h>
60 #include <net/if_ether.h>
61 #include <net/if_llc.h>
62 
63 #include <net80211/ieee80211_netbsd.h>
64 #include <net80211/ieee80211_var.h>
65 
66 #include <net/bpf.h>
67 
68 #ifdef INET
69 #include <netinet/in.h>
70 #include <net/if_ether.h>
71 #endif
72 
73 /*
74  * Association id's are managed with a bit vector.
75  */
76 #define	IEEE80211_AID_SET(b, w) \
77 	((w)[IEEE80211_AID(b) / 32] |= (1 << (IEEE80211_AID(b) % 32)))
78 #define	IEEE80211_AID_CLR(b, w) \
79 	((w)[IEEE80211_AID(b) / 32] &= ~(1 << (IEEE80211_AID(b) % 32)))
80 #define	IEEE80211_AID_ISSET(b, w) \
81 	((w)[IEEE80211_AID(b) / 32] & (1 << (IEEE80211_AID(b) % 32)))
82 
83 static struct ieee80211_node *node_alloc(struct ieee80211_node_table *);
84 static void node_cleanup(struct ieee80211_node *);
85 static void node_free(struct ieee80211_node *);
86 static u_int8_t node_getrssi(const struct ieee80211_node *);
87 
88 static void ieee80211_setup_node(struct ieee80211_node_table *,
89 		struct ieee80211_node *, const u_int8_t *);
90 static void _ieee80211_free_node(struct ieee80211_node *);
91 static void ieee80211_free_allnodes(struct ieee80211_node_table *);
92 
93 static void ieee80211_timeout_scan_candidates(struct ieee80211_node_table *);
94 static void ieee80211_timeout_stations(struct ieee80211_node_table *);
95 
96 static void ieee80211_set_tim(struct ieee80211_node *, int set);
97 
98 static void ieee80211_node_table_init(struct ieee80211com *ic,
99 	struct ieee80211_node_table *nt, const char *name,
100 	int inact, int keyixmax,
101 	void (*timeout)(struct ieee80211_node_table *));
102 static void ieee80211_node_table_cleanup(struct ieee80211_node_table *nt);
103 
104 MALLOC_DEFINE(M_80211_NODE, "80211node", "802.11 node state");
105 
106 void
107 ieee80211_node_attach(struct ieee80211com *ic)
108 {
109 
110 	ic->ic_node_alloc = node_alloc;
111 	ic->ic_node_free = node_free;
112 	ic->ic_node_cleanup = node_cleanup;
113 	ic->ic_node_getrssi = node_getrssi;
114 
115 	/* default station inactivity timer setings */
116 	ic->ic_inact_init = IEEE80211_INACT_INIT;
117 	ic->ic_inact_auth = IEEE80211_INACT_AUTH;
118 	ic->ic_inact_run = IEEE80211_INACT_RUN;
119 	ic->ic_inact_probe = IEEE80211_INACT_PROBE;
120 
121 	/* NB: driver should override */
122 	ic->ic_max_aid = IEEE80211_AID_DEF;
123 	ic->ic_set_tim = ieee80211_set_tim;
124 }
125 
126 void
127 ieee80211_node_lateattach(struct ieee80211com *ic)
128 {
129 	struct ieee80211_rsnparms *rsn;
130 
131 	if (ic->ic_max_aid > IEEE80211_AID_MAX)
132 		ic->ic_max_aid = IEEE80211_AID_MAX;
133 	MALLOC(ic->ic_aid_bitmap, u_int32_t *,
134 		howmany(ic->ic_max_aid, 32) * sizeof(u_int32_t),
135 		M_DEVBUF, M_NOWAIT | M_ZERO);
136 	if (ic->ic_aid_bitmap == NULL) {
137 		/* XXX no way to recover */
138 		printf("%s: no memory for AID bitmap!\n", __func__);
139 		ic->ic_max_aid = 0;
140 	}
141 
142 	/* XXX defer until using hostap/ibss mode */
143 	ic->ic_tim_len = howmany(ic->ic_max_aid, 8) * sizeof(u_int8_t);
144 	MALLOC(ic->ic_tim_bitmap, u_int8_t *, ic->ic_tim_len,
145 		M_DEVBUF, M_NOWAIT | M_ZERO);
146 	if (ic->ic_tim_bitmap == NULL) {
147 		/* XXX no way to recover */
148 		printf("%s: no memory for TIM bitmap!\n", __func__);
149 	}
150 
151 	ieee80211_node_table_init(ic, &ic->ic_sta, "station",
152 		IEEE80211_INACT_INIT, ic->ic_crypto.cs_max_keyix,
153 		ieee80211_timeout_stations);
154 	ieee80211_node_table_init(ic, &ic->ic_scan, "scan",
155 		IEEE80211_INACT_SCAN, 0,
156 		ieee80211_timeout_scan_candidates);
157 
158 	ieee80211_reset_bss(ic);
159 	/*
160 	 * Setup "global settings" in the bss node so that
161 	 * each new station automatically inherits them.
162 	 */
163 	rsn = &ic->ic_bss->ni_rsn;
164 	/* WEP, TKIP, and AES-CCM are always supported */
165 	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_WEP;
166 	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_TKIP;
167 	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_AES_CCM;
168 	if (ic->ic_caps & IEEE80211_C_AES)
169 		rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_AES_OCB;
170 	if (ic->ic_caps & IEEE80211_C_CKIP)
171 		rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_CKIP;
172 	/*
173 	 * Default unicast cipher to WEP for 802.1x use.  If
174 	 * WPA is enabled the management code will set these
175 	 * values to reflect.
176 	 */
177 	rsn->rsn_ucastcipher = IEEE80211_CIPHER_WEP;
178 	rsn->rsn_ucastkeylen = 104 / NBBY;
179 	/*
180 	 * WPA says the multicast cipher is the lowest unicast
181 	 * cipher supported.  But we skip WEP which would
182 	 * otherwise be used based on this criteria.
183 	 */
184 	rsn->rsn_mcastcipher = IEEE80211_CIPHER_TKIP;
185 	rsn->rsn_mcastkeylen = 128 / NBBY;
186 
187 	/*
188 	 * We support both WPA-PSK and 802.1x; the one used
189 	 * is determined by the authentication mode and the
190 	 * setting of the PSK state.
191 	 */
192 	rsn->rsn_keymgmtset = WPA_ASE_8021X_UNSPEC | WPA_ASE_8021X_PSK;
193 	rsn->rsn_keymgmt = WPA_ASE_8021X_PSK;
194 
195 	ic->ic_auth = ieee80211_authenticator_get(ic->ic_bss->ni_authmode);
196 }
197 
198 void
199 ieee80211_node_detach(struct ieee80211com *ic)
200 {
201 
202 	if (ic->ic_bss != NULL) {
203 		ieee80211_free_node(ic->ic_bss);
204 		ic->ic_bss = NULL;
205 	}
206 	ieee80211_node_table_cleanup(&ic->ic_scan);
207 	ieee80211_node_table_cleanup(&ic->ic_sta);
208 	if (ic->ic_aid_bitmap != NULL) {
209 		FREE(ic->ic_aid_bitmap, M_DEVBUF);
210 		ic->ic_aid_bitmap = NULL;
211 	}
212 	if (ic->ic_tim_bitmap != NULL) {
213 		FREE(ic->ic_tim_bitmap, M_DEVBUF);
214 		ic->ic_tim_bitmap = NULL;
215 	}
216 }
217 
218 /*
219  * Port authorize/unauthorize interfaces for use by an authenticator.
220  */
221 
222 void
223 ieee80211_node_authorize(struct ieee80211_node *ni)
224 {
225 	struct ieee80211com *ic = ni->ni_ic;
226 
227 	ni->ni_flags |= IEEE80211_NODE_AUTH;
228 	ni->ni_inact_reload = ic->ic_inact_run;
229 }
230 
231 void
232 ieee80211_node_unauthorize(struct ieee80211_node *ni)
233 {
234 	ni->ni_flags &= ~IEEE80211_NODE_AUTH;
235 }
236 
237 /*
238  * Set/change the channel.  The rate set is also updated as
239  * to insure a consistent view by drivers.
240  */
241 static __inline void
242 ieee80211_set_chan(struct ieee80211com *ic,
243 	struct ieee80211_node *ni, struct ieee80211_channel *chan)
244 {
245 	ni->ni_chan = chan;
246 	ni->ni_rates = ic->ic_sup_rates[ieee80211_chan2mode(ic, chan)];
247 }
248 
249 /*
250  * AP scanning support.
251  */
252 
253 #ifdef IEEE80211_DEBUG
254 static void
255 dump_chanlist(const u_char chans[])
256 {
257 	const char *sep;
258 	int i;
259 
260 	sep = " ";
261 	for (i = 0; i < IEEE80211_CHAN_MAX; i++)
262 		if (isset(chans, i)) {
263 			printf("%s%u", sep, i);
264 			sep = ", ";
265 		}
266 }
267 #endif /* IEEE80211_DEBUG */
268 
269 /*
270  * Initialize the channel set to scan based on the
271  * of available channels and the current PHY mode.
272  */
273 static void
274 ieee80211_reset_scan(struct ieee80211com *ic)
275 {
276 
277 	/* XXX ic_des_chan should be handled with ic_chan_active */
278 	if (ic->ic_des_chan != IEEE80211_CHAN_ANYC) {
279 		memset(ic->ic_chan_scan, 0, sizeof(ic->ic_chan_scan));
280 		setbit(ic->ic_chan_scan,
281 			ieee80211_chan2ieee(ic, ic->ic_des_chan));
282 	} else
283 		memcpy(ic->ic_chan_scan, ic->ic_chan_active,
284 			sizeof(ic->ic_chan_active));
285 #ifdef IEEE80211_DEBUG
286 	if (ieee80211_msg_scan(ic)) {
287 		printf("%s: scan set:", __func__);
288 		dump_chanlist(ic->ic_chan_scan);
289 		printf(" start chan %u\n",
290 			ieee80211_chan2ieee(ic, ic->ic_curchan));
291 	}
292 #endif /* IEEE80211_DEBUG */
293 }
294 
295 /*
296  * Begin an active scan.
297  */
298 void
299 ieee80211_begin_scan(struct ieee80211com *ic, int reset)
300 {
301 
302 	ic->ic_scan.nt_scangen++;
303 	/*
304 	 * In all but hostap mode scanning starts off in
305 	 * an active mode before switching to passive.
306 	 */
307 	if (ic->ic_opmode != IEEE80211_M_HOSTAP) {
308 		ic->ic_flags |= IEEE80211_F_ASCAN;
309 		ic->ic_stats.is_scan_active++;
310 	} else
311 		ic->ic_stats.is_scan_passive++;
312 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
313 		"begin %s scan in %s mode, scangen %u\n",
314 		(ic->ic_flags & IEEE80211_F_ASCAN) ?  "active" : "passive",
315 		ieee80211_phymode_name[ic->ic_curmode], ic->ic_scan.nt_scangen);
316 	/*
317 	 * Clear scan state and flush any previously seen AP's.
318 	 */
319 	ieee80211_reset_scan(ic);
320 	if (reset)
321 		ieee80211_free_allnodes(&ic->ic_scan);
322 
323 	ic->ic_flags |= IEEE80211_F_SCAN;
324 
325 	/* Scan the next channel. */
326 	ieee80211_next_scan(ic);
327 }
328 
329 /*
330  * Switch to the next channel marked for scanning.
331  */
332 int
333 ieee80211_next_scan(struct ieee80211com *ic)
334 {
335 	struct ieee80211_channel *chan;
336 
337 	/*
338 	 * Insure any previous mgt frame timeouts don't fire.
339 	 * This assumes the driver does the right thing in
340 	 * flushing anything queued in the driver and below.
341 	 */
342 	ic->ic_mgt_timer = 0;
343 
344 	chan = ic->ic_curchan;
345 	do {
346 		if (++chan > &ic->ic_channels[IEEE80211_CHAN_MAX])
347 			chan = &ic->ic_channels[0];
348 		if (isset(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan))) {
349 			clrbit(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan));
350 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
351 			    "%s: chan %d->%d\n", __func__,
352 			    ieee80211_chan2ieee(ic, ic->ic_curchan),
353 			    ieee80211_chan2ieee(ic, chan));
354 			ic->ic_curchan = chan;
355 			/*
356 			 * XXX drivers should do this as needed,
357 			 * XXX for now maintain compatibility
358 			 */
359 			ic->ic_bss->ni_rates =
360 				ic->ic_sup_rates[ieee80211_chan2mode(ic, chan)];
361 			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
362 			return 1;
363 		}
364 	} while (chan != ic->ic_curchan);
365 	ieee80211_end_scan(ic);
366 	return 0;
367 }
368 
369 static __inline void
370 copy_bss(struct ieee80211_node *nbss, const struct ieee80211_node *obss)
371 {
372 	/* propagate useful state */
373 	nbss->ni_authmode = obss->ni_authmode;
374 	nbss->ni_txpower = obss->ni_txpower;
375 	nbss->ni_vlan = obss->ni_vlan;
376 	nbss->ni_rsn = obss->ni_rsn;
377 	/* XXX statistics? */
378 }
379 
380 void
381 ieee80211_create_ibss(struct ieee80211com* ic, struct ieee80211_channel *chan)
382 {
383 	struct ieee80211_node_table *nt;
384 	struct ieee80211_node *ni;
385 
386 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
387 		"%s: creating ibss\n", __func__);
388 
389 	/*
390 	 * Create the station/neighbor table.  Note that for adhoc
391 	 * mode we make the initial inactivity timer longer since
392 	 * we create nodes only through discovery and they typically
393 	 * are long-lived associations.
394 	 */
395 	nt = &ic->ic_sta;
396 	IEEE80211_NODE_LOCK(nt);
397 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
398 		nt->nt_name = "station";
399 		nt->nt_inact_init = ic->ic_inact_init;
400 	} else {
401 		nt->nt_name = "neighbor";
402 		nt->nt_inact_init = ic->ic_inact_run;
403 	}
404 	IEEE80211_NODE_UNLOCK(nt);
405 
406 	ni = ieee80211_alloc_node(&ic->ic_sta, ic->ic_myaddr);
407 	if (ni == NULL) {
408 		/* XXX recovery? */
409 		return;
410 	}
411 	IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_myaddr);
412 	ni->ni_esslen = ic->ic_des_esslen;
413 	memcpy(ni->ni_essid, ic->ic_des_essid, ni->ni_esslen);
414 	copy_bss(ni, ic->ic_bss);
415 	ni->ni_intval = ic->ic_bintval;
416 	if (ic->ic_flags & IEEE80211_F_PRIVACY)
417 		ni->ni_capinfo |= IEEE80211_CAPINFO_PRIVACY;
418 	if (ic->ic_phytype == IEEE80211_T_FH) {
419 		ni->ni_fhdwell = 200;	/* XXX */
420 		ni->ni_fhindex = 1;
421 	}
422 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
423 		ic->ic_flags |= IEEE80211_F_SIBSS;
424 		ni->ni_capinfo |= IEEE80211_CAPINFO_IBSS;	/* XXX */
425 		if (ic->ic_flags & IEEE80211_F_DESBSSID)
426 			IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_des_bssid);
427 		else
428 			ni->ni_bssid[0] |= 0x02;	/* local bit for IBSS */
429 	}
430 	/*
431 	 * Fix the channel and related attributes.
432 	 */
433 	ieee80211_set_chan(ic, ni, chan);
434 	ic->ic_curchan = chan;
435 	ic->ic_curmode = ieee80211_chan2mode(ic, chan);
436 	/*
437 	 * Do mode-specific rate setup.
438 	 */
439 	if (ic->ic_curmode == IEEE80211_MODE_11G) {
440 		/*
441 		 * Use a mixed 11b/11g rate set.
442 		 */
443 		ieee80211_set11gbasicrates(&ni->ni_rates, IEEE80211_MODE_11G);
444 	} else if (ic->ic_curmode == IEEE80211_MODE_11B) {
445 		/*
446 		 * Force pure 11b rate set.
447 		 */
448 		ieee80211_set11gbasicrates(&ni->ni_rates, IEEE80211_MODE_11B);
449 	}
450 
451 	(void) ieee80211_sta_join(ic, ieee80211_ref_node(ni));
452 }
453 
454 void
455 ieee80211_reset_bss(struct ieee80211com *ic)
456 {
457 	struct ieee80211_node *ni, *obss;
458 
459 	ieee80211_node_table_reset(&ic->ic_scan);
460 	ieee80211_node_table_reset(&ic->ic_sta);
461 
462 	ni = ieee80211_alloc_node(&ic->ic_scan, ic->ic_myaddr);
463 	IASSERT(ni != NULL, ("unable to setup inital BSS node"));
464 	obss = ic->ic_bss;
465 	ic->ic_bss = ieee80211_ref_node(ni);
466 	if (obss != NULL) {
467 		copy_bss(ni, obss);
468 		ni->ni_intval = ic->ic_bintval;
469 		ieee80211_free_node(obss);
470 	}
471 }
472 
473 /* XXX tunable */
474 #define	STA_FAILS_MAX	2		/* assoc failures before ignored */
475 
476 static int
477 ieee80211_match_bss(struct ieee80211com *ic, struct ieee80211_node *ni)
478 {
479         u_int8_t rate;
480         int fail;
481 
482 	fail = 0;
483 	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
484 		fail |= 0x01;
485 	if (ic->ic_des_chan != IEEE80211_CHAN_ANYC &&
486 	    ni->ni_chan != ic->ic_des_chan)
487 		fail |= 0x01;
488 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
489 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
490 			fail |= 0x02;
491 	} else {
492 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
493 			fail |= 0x02;
494 	}
495 	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
496 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
497 			fail |= 0x04;
498 	} else {
499 		/* XXX does this mean privacy is supported or required? */
500 		if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
501 			fail |= 0x04;
502 	}
503 	rate = ieee80211_fix_rate(ni, IEEE80211_F_DONEGO | IEEE80211_F_DOFRATE);
504 	if (rate & IEEE80211_RATE_BASIC)
505 		fail |= 0x08;
506 	if (ic->ic_des_esslen != 0 &&
507 	    (ni->ni_esslen != ic->ic_des_esslen ||
508 	     memcmp(ni->ni_essid, ic->ic_des_essid, ic->ic_des_esslen) != 0))
509 		fail |= 0x10;
510 	if ((ic->ic_flags & IEEE80211_F_DESBSSID) &&
511 	    !IEEE80211_ADDR_EQ(ic->ic_des_bssid, ni->ni_bssid))
512 		fail |= 0x20;
513 	if (ni->ni_fails >= STA_FAILS_MAX)
514 		fail |= 0x40;
515 #ifdef IEEE80211_DEBUG
516 	if (ieee80211_msg_scan(ic)) {
517 		printf(" %c %s",
518 		    fail & 0x40 ? '=' : fail & 0x80 ? '^' : fail ? '-' : '+',
519 		    ether_sprintf(ni->ni_macaddr));
520 		printf(" %s%c", ether_sprintf(ni->ni_bssid),
521 		    fail & 0x20 ? '!' : ' ');
522 		printf(" %3d%c", ieee80211_chan2ieee(ic, ni->ni_chan),
523 			fail & 0x01 ? '!' : ' ');
524 		printf(" %+4d", ni->ni_rssi);
525 		printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
526 		    fail & 0x08 ? '!' : ' ');
527 		printf(" %4s%c",
528 		    (ni->ni_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
529 		    (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
530 		    "????",
531 		    fail & 0x02 ? '!' : ' ');
532 		printf(" %3s%c ",
533 		    (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) ?
534 		    "wep" : "no",
535 		    fail & 0x04 ? '!' : ' ');
536 		ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
537 		printf("%s\n", fail & 0x10 ? "!" : "");
538 	}
539 #endif
540 	return fail;
541 }
542 
543 static __inline u_int8_t
544 maxrate(const struct ieee80211_node *ni)
545 {
546 	const struct ieee80211_rateset *rs = &ni->ni_rates;
547 	/* NB: assumes rate set is sorted (happens on frame receive) */
548 	return rs->rs_rates[rs->rs_nrates-1] & IEEE80211_RATE_VAL;
549 }
550 
551 /*
552  * Compare the capabilities of two nodes and decide which is
553  * more desirable (return >0 if a is considered better).  Note
554  * that we assume compatibility/usability has already been checked
555  * so we don't need to (e.g. validate whether privacy is supported).
556  * Used to select the best scan candidate for association in a BSS.
557  */
558 static int
559 ieee80211_node_compare(struct ieee80211com *ic,
560 		       const struct ieee80211_node *a,
561 		       const struct ieee80211_node *b)
562 {
563 	u_int8_t maxa, maxb;
564 	u_int8_t rssia, rssib;
565 	int weight;
566 
567 	/* privacy support preferred */
568 	if ((a->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) &&
569 	    (b->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
570 		return 1;
571 	if ((a->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0 &&
572 	    (b->ni_capinfo & IEEE80211_CAPINFO_PRIVACY))
573 		return -1;
574 
575 	/* compare count of previous failures */
576 	weight = b->ni_fails - a->ni_fails;
577 	if (abs(weight) > 1)
578 		return weight;
579 
580 	rssia = ic->ic_node_getrssi(a);
581 	rssib = ic->ic_node_getrssi(b);
582 	if (abs(rssib - rssia) < 5) {
583 		/* best/max rate preferred if signal level close enough XXX */
584 		maxa = maxrate(a);
585 		maxb = maxrate(b);
586 		if (maxa != maxb)
587 			return maxa - maxb;
588 		/* XXX use freq for channel preference */
589 		/* for now just prefer 5Ghz band to all other bands */
590 		if (IEEE80211_IS_CHAN_5GHZ(a->ni_chan) &&
591 		   !IEEE80211_IS_CHAN_5GHZ(b->ni_chan))
592 			return 1;
593 		if (!IEEE80211_IS_CHAN_5GHZ(a->ni_chan) &&
594 		     IEEE80211_IS_CHAN_5GHZ(b->ni_chan))
595 			return -1;
596 	}
597 	/* all things being equal, use signal level */
598 	return rssia - rssib;
599 }
600 
601 /*
602  * Mark an ongoing scan stopped.
603  */
604 void
605 ieee80211_cancel_scan(struct ieee80211com *ic)
606 {
607 
608 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN, "%s: end %s scan\n",
609 		__func__,
610 		(ic->ic_flags & IEEE80211_F_ASCAN) ?  "active" : "passive");
611 
612 	ic->ic_flags &= ~(IEEE80211_F_SCAN | IEEE80211_F_ASCAN);
613 }
614 
615 /*
616  * Complete a scan of potential channels.
617  */
618 void
619 ieee80211_end_scan(struct ieee80211com *ic)
620 {
621 	struct ieee80211_node_table *nt = &ic->ic_scan;
622 	struct ieee80211_node *ni, *selbs;
623 
624 	ieee80211_cancel_scan(ic);
625 	ieee80211_notify_scan_done(ic);
626 
627 #ifndef IEEE80211_NO_HOSTAP
628 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
629 		u_int8_t maxrssi[IEEE80211_CHAN_MAX];	/* XXX off stack? */
630 		int i, bestchan;
631 		u_int8_t rssi;
632 
633 		/*
634 		 * The passive scan to look for existing AP's completed,
635 		 * select a channel to camp on.  Identify the channels
636 		 * that already have one or more AP's and try to locate
637 		 * an unoccupied one.  If that fails, pick a channel that
638 		 * looks to be quietest.
639 		 */
640 		memset(maxrssi, 0, sizeof(maxrssi));
641 		IEEE80211_NODE_LOCK(nt);
642 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
643 			rssi = ic->ic_node_getrssi(ni);
644 			i = ieee80211_chan2ieee(ic, ni->ni_chan);
645 			if (rssi > maxrssi[i])
646 				maxrssi[i] = rssi;
647 		}
648 		IEEE80211_NODE_UNLOCK(nt);
649 		/* XXX select channel more intelligently */
650 		bestchan = -1;
651 		for (i = 0; i < IEEE80211_CHAN_MAX; i++)
652 			if (isset(ic->ic_chan_active, i)) {
653 				/*
654 				 * If the channel is unoccupied the max rssi
655 				 * should be zero; just take it.  Otherwise
656 				 * track the channel with the lowest rssi and
657 				 * use that when all channels appear occupied.
658 				 */
659 				if (maxrssi[i] == 0) {
660 					bestchan = i;
661 					break;
662 				}
663 				if (bestchan == -1 ||
664 				    maxrssi[i] < maxrssi[bestchan])
665 					bestchan = i;
666 			}
667 		if (bestchan != -1) {
668 			ieee80211_create_ibss(ic, &ic->ic_channels[bestchan]);
669 			return;
670 		}
671 		/* no suitable channel, should not happen */
672 	}
673 #endif /* !IEEE80211_NO_HOSTAP */
674 
675 	/*
676 	 * When manually sequencing the state machine; scan just once
677 	 * regardless of whether we have a candidate or not.  The
678 	 * controlling application is expected to setup state and
679 	 * initiate an association.
680 	 */
681 	if (ic->ic_roaming == IEEE80211_ROAMING_MANUAL)
682 		return;
683 	/*
684 	 * Automatic sequencing; look for a candidate and
685 	 * if found join the network.
686 	 */
687 	/* NB: unlocked read should be ok */
688 	if (TAILQ_FIRST(&nt->nt_node) == NULL) {
689 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
690 			"%s: no scan candidate\n", __func__);
691   notfound:
692 		if (ic->ic_opmode == IEEE80211_M_IBSS &&
693 		    (ic->ic_flags & IEEE80211_F_IBSSON) &&
694 		    ic->ic_des_esslen != 0) {
695 			ieee80211_create_ibss(ic, ic->ic_ibss_chan);
696 			return;
697 		}
698 		/*
699 		 * Decrement the failure counts so entries will be
700 		 * reconsidered the next time around.  We really want
701 		 * to do this only for sta's where we've previously
702 		 * had some success.
703 		 */
704 		IEEE80211_NODE_LOCK(nt);
705 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
706 			if (ni->ni_fails)
707 				ni->ni_fails--;
708 		IEEE80211_NODE_UNLOCK(nt);
709 		/*
710 		 * Reset the list of channels to scan and start again.
711 		 */
712 		ieee80211_reset_scan(ic);
713 		ic->ic_flags |= IEEE80211_F_SCAN;
714 		ieee80211_next_scan(ic);
715 		return;
716 	}
717 	selbs = NULL;
718 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN, "\t%s\n",
719 	    "macaddr          bssid         chan  rssi rate flag  wep  essid");
720 	IEEE80211_NODE_LOCK(nt);
721 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
722 		if (ieee80211_match_bss(ic, ni) == 0) {
723 			if (selbs == NULL)
724 				selbs = ni;
725 			else if (ieee80211_node_compare(ic, ni, selbs) > 0)
726 				selbs = ni;
727 		}
728 	}
729 	if (selbs != NULL)		/* NB: grab ref while dropping lock */
730 		(void) ieee80211_ref_node(selbs);
731 	IEEE80211_NODE_UNLOCK(nt);
732 	if (selbs == NULL)
733 		goto notfound;
734 	if (!ieee80211_sta_join(ic, selbs)) {
735 		ieee80211_free_node(selbs);
736 		goto notfound;
737 	}
738 }
739 
740 /*
741  * Handle 802.11 ad hoc network merge.  The
742  * convention, set by the Wireless Ethernet Compatibility Alliance
743  * (WECA), is that an 802.11 station will change its BSSID to match
744  * the "oldest" 802.11 ad hoc network, on the same channel, that
745  * has the station's desired SSID.  The "oldest" 802.11 network
746  * sends beacons with the greatest TSF timestamp.
747  *
748  * The caller is assumed to validate TSF's before attempting a merge.
749  *
750  * Return !0 if the BSSID changed, 0 otherwise.
751  */
752 int
753 ieee80211_ibss_merge(struct ieee80211_node *ni)
754 {
755 	struct ieee80211com *ic = ni->ni_ic;
756 
757 	if (ni == ic->ic_bss ||
758 	    IEEE80211_ADDR_EQ(ni->ni_bssid, ic->ic_bss->ni_bssid)) {
759 		/* unchanged, nothing to do */
760 		return 0;
761 	}
762 	if (ieee80211_match_bss(ic, ni) != 0) {	/* capabilities mismatch */
763 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
764 		    "%s: merge failed, capabilities mismatch\n", __func__);
765 		ic->ic_stats.is_ibss_capmismatch++;
766 		return 0;
767 	}
768 	if (!ieee80211_sta_join(ic, ieee80211_ref_node(ni)))
769 		return 0;
770 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
771 		"%s: new bssid %s: %s preamble, %s slot time%s\n", __func__,
772 		ether_sprintf(ni->ni_bssid),
773 		ic->ic_flags&IEEE80211_F_SHPREAMBLE ? "short" : "long",
774 		ic->ic_flags&IEEE80211_F_SHSLOT ? "short" : "long",
775 		ic->ic_flags&IEEE80211_F_USEPROT ? ", protection" : ""
776 	);
777 	ic->ic_flags &= ~IEEE80211_F_SIBSS;
778 	return 1;
779 }
780 
781 /*
782  * Join the specified IBSS/BSS network.  The node is assumed to
783  * be passed in with a held reference.
784  */
785 int
786 ieee80211_sta_join(struct ieee80211com *ic, struct ieee80211_node *selbs)
787 {
788 	struct ieee80211_node *obss;
789 
790 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
791 		struct ieee80211_node_table *nt;
792 		/*
793 		 * Delete unusable rates; we've already checked
794 		 * that the negotiated rate set is acceptable.
795 		 */
796 		ieee80211_fix_rate(selbs, IEEE80211_F_DODEL);
797 		/*
798 		 * Fillin the neighbor table; it will already
799 		 * exist if we are simply switching mastership.
800 		 * XXX ic_sta always setup so this is unnecessary?
801 		 */
802 		nt = &ic->ic_sta;
803 		IEEE80211_NODE_LOCK(nt);
804 		nt->nt_name = "neighbor";
805 		nt->nt_inact_init = ic->ic_inact_run;
806 		IEEE80211_NODE_UNLOCK(nt);
807 	}
808 
809 	/*
810 	 * Committed to selbs, setup state.
811 	 */
812 	obss = ic->ic_bss;
813 	ic->ic_bss = selbs;		/* NB: caller assumed to bump refcnt */
814 	if (obss != NULL)
815 		ieee80211_free_node(obss);
816 	/*
817 	 * Set the erp state (mostly the slot time) to deal with
818 	 * the auto-select case; this should be redundant if the
819 	 * mode is locked.
820 	 */
821 	ic->ic_curmode = ieee80211_chan2mode(ic, selbs->ni_chan);
822 	ic->ic_curchan = selbs->ni_chan;
823 	ieee80211_reset_erp(ic);
824 	ieee80211_wme_initparams(ic);
825 
826 	if (ic->ic_opmode == IEEE80211_M_STA)
827 		ieee80211_new_state(ic, IEEE80211_S_AUTH, -1);
828 	else
829 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
830 	return 1;
831 }
832 
833 /*
834  * Leave the specified IBSS/BSS network.  The node is assumed to
835  * be passed in with a held reference.
836  */
837 void
838 ieee80211_sta_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
839 {
840 	ic->ic_node_cleanup(ni);
841 	ieee80211_notify_node_leave(ic, ni);
842 }
843 
844 int
845 ieee80211_get_rate(struct ieee80211com *ic)
846 {
847 #define	RATE(_ix)	(ni->ni_rates.rs_rates[(_ix)] & IEEE80211_RATE_VAL)
848 	int ix, rate;
849 	const struct ieee80211_node *ni;
850 	const struct ieee80211_rateset *rs;
851 
852 	ni = ic->ic_bss;
853 
854 	if (ic->ic_fixed_rate != IEEE80211_FIXED_RATE_NONE) {
855 		rs = &ic->ic_sup_rates[ic->ic_curmode];
856 		rate = rs->rs_rates[ic->ic_fixed_rate] & IEEE80211_RATE_VAL;
857 		for (ix = ni->ni_rates.rs_nrates - 1;
858 		     ix >= 0 && RATE(ix) != rate; ix--)
859 			;
860 		IASSERT(ix >= 0,
861 			("fixed rate %d not in rate set", ic->ic_fixed_rate));
862 	} else if (ic->ic_state == IEEE80211_S_RUN)
863 		rate = ni->ni_rates.rs_rates[ni->ni_txrate];
864 	else
865 		rate = 0;
866 
867 	return rate & IEEE80211_RATE_VAL;
868 }
869 
870 static struct ieee80211_node *
871 node_alloc(struct ieee80211_node_table *nt)
872 {
873 	struct ieee80211_node *ni;
874 
875 	MALLOC(ni, struct ieee80211_node *, sizeof(struct ieee80211_node),
876 		M_80211_NODE, M_NOWAIT | M_ZERO);
877 	return ni;
878 }
879 
880 /*
881  * Reclaim any resources in a node and reset any critical
882  * state.  Typically nodes are free'd immediately after,
883  * but in some cases the storage may be reused so we need
884  * to insure consistent state (should probably fix that).
885  */
886 static void
887 node_cleanup(struct ieee80211_node *ni)
888 {
889 #define	N(a)	(sizeof(a)/sizeof(a[0]))
890 	struct ieee80211com *ic = ni->ni_ic;
891 	int i, qlen;
892 
893 	/* NB: preserve ni_table */
894 	if (ni->ni_flags & IEEE80211_NODE_PWR_MGT) {
895 		ic->ic_ps_sta--;
896 		ni->ni_flags &= ~IEEE80211_NODE_PWR_MGT;
897 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
898 		    "[%s] power save mode off, %u sta's in ps mode\n",
899 		    ether_sprintf(ni->ni_macaddr), ic->ic_ps_sta);
900 	}
901 	/*
902 	 * Clear AREF flag that marks the authorization refcnt bump
903 	 * has happened.  This is probably not needed as the node
904 	 * should always be removed from the table so not found but
905 	 * do it just in case.
906 	 */
907 	ni->ni_flags &= ~IEEE80211_NODE_AREF;
908 
909 	/*
910 	 * Drain power save queue and, if needed, clear TIM.
911 	 */
912 	IEEE80211_NODE_SAVEQ_DRAIN(ni, qlen);
913 	if (qlen != 0 && ic->ic_set_tim != NULL)
914 		ic->ic_set_tim(ni, 0);
915 
916 	ni->ni_associd = 0;
917 	if (ni->ni_challenge != NULL) {
918 		FREE(ni->ni_challenge, M_DEVBUF);
919 		ni->ni_challenge = NULL;
920 	}
921 	/*
922 	 * Preserve SSID, WPA, and WME ie's so the bss node is
923 	 * reusable during a re-auth/re-assoc state transition.
924 	 * If we remove these data they will not be recreated
925 	 * because they come from a probe-response or beacon frame
926 	 * which cannot be expected prior to the association-response.
927 	 * This should not be an issue when operating in other modes
928 	 * as stations leaving always go through a full state transition
929 	 * which will rebuild this state.
930 	 *
931 	 * XXX does this leave us open to inheriting old state?
932 	 */
933 	for (i = 0; i < N(ni->ni_rxfrag); i++)
934 		if (ni->ni_rxfrag[i] != NULL) {
935 			m_freem(ni->ni_rxfrag[i]);
936 			ni->ni_rxfrag[i] = NULL;
937 		}
938 	/*
939 	 * Must be careful here to remove any key map entry w/o a LOR.
940 	 */
941 	ieee80211_node_delucastkey(ni);
942 #undef N
943 }
944 
945 static void
946 node_free(struct ieee80211_node *ni)
947 {
948 	struct ieee80211com *ic = ni->ni_ic;
949 
950 	ic->ic_node_cleanup(ni);
951 	if (ni->ni_wpa_ie != NULL)
952 		FREE(ni->ni_wpa_ie, M_DEVBUF);
953 	if (ni->ni_wme_ie != NULL)
954 		FREE(ni->ni_wme_ie, M_DEVBUF);
955 	IEEE80211_NODE_SAVEQ_DESTROY(ni);
956 	FREE(ni, M_80211_NODE);
957 }
958 
959 static u_int8_t
960 node_getrssi(const struct ieee80211_node *ni)
961 {
962 	return ni->ni_rssi;
963 }
964 
965 static void
966 ieee80211_setup_node(struct ieee80211_node_table *nt,
967 	struct ieee80211_node *ni, const u_int8_t *macaddr)
968 {
969 	struct ieee80211com *ic = nt->nt_ic;
970 	int hash;
971 
972 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
973 		"%s %p<%s> in %s table\n", __func__, ni,
974 		ether_sprintf(macaddr), nt->nt_name);
975 
976 	IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
977 	hash = IEEE80211_NODE_HASH(macaddr);
978 	ieee80211_node_initref(ni);		/* mark referenced */
979 	ni->ni_chan = IEEE80211_CHAN_ANYC;
980 	ni->ni_authmode = IEEE80211_AUTH_OPEN;
981 	ni->ni_txpower = ic->ic_txpowlimit;	/* max power */
982 	ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey, IEEE80211_KEYIX_NONE);
983 	ni->ni_inact_reload = nt->nt_inact_init;
984 	ni->ni_inact = ni->ni_inact_reload;
985 	IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
986 
987 	IEEE80211_NODE_LOCK(nt);
988 	TAILQ_INSERT_TAIL(&nt->nt_node, ni, ni_list);
989 	LIST_INSERT_HEAD(&nt->nt_hash[hash], ni, ni_hash);
990 	ni->ni_table = nt;
991 	ni->ni_ic = ic;
992 	IEEE80211_NODE_UNLOCK(nt);
993 }
994 
995 struct ieee80211_node *
996 ieee80211_alloc_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
997 {
998 	struct ieee80211com *ic = nt->nt_ic;
999 	struct ieee80211_node *ni;
1000 
1001 	ni = ic->ic_node_alloc(nt);
1002 	if (ni != NULL)
1003 		ieee80211_setup_node(nt, ni, macaddr);
1004 	else
1005 		ic->ic_stats.is_rx_nodealloc++;
1006 	return ni;
1007 }
1008 
1009 /*
1010  * Craft a temporary node suitable for sending a management frame
1011  * to the specified station.  We craft only as much state as we
1012  * need to do the work since the node will be immediately reclaimed
1013  * once the send completes.
1014  */
1015 struct ieee80211_node *
1016 ieee80211_tmp_node(struct ieee80211com *ic, const u_int8_t *macaddr)
1017 {
1018 	struct ieee80211_node *ni;
1019 
1020 	ni = ic->ic_node_alloc(&ic->ic_sta);
1021 	if (ni != NULL) {
1022 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1023 			"%s %p<%s>\n", __func__, ni, ether_sprintf(macaddr));
1024 
1025 		IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
1026 		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
1027 		ieee80211_node_initref(ni);		/* mark referenced */
1028 		ni->ni_txpower = ic->ic_bss->ni_txpower;
1029 		/* NB: required by ieee80211_fix_rate */
1030 		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
1031 		ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey,
1032 			IEEE80211_KEYIX_NONE);
1033 		/* XXX optimize away */
1034 		IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
1035 
1036 		ni->ni_table = NULL;		/* NB: pedantic */
1037 		ni->ni_ic = ic;
1038 	} else {
1039 		/* XXX msg */
1040 		ic->ic_stats.is_rx_nodealloc++;
1041 	}
1042 	return ni;
1043 }
1044 
1045 struct ieee80211_node *
1046 ieee80211_dup_bss(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
1047 {
1048 	struct ieee80211com *ic = nt->nt_ic;
1049 	struct ieee80211_node *ni;
1050 
1051 	ni = ic->ic_node_alloc(nt);
1052 	if (ni != NULL) {
1053 		ieee80211_setup_node(nt, ni, macaddr);
1054 		/*
1055 		 * Inherit from ic_bss.
1056 		 */
1057 		ni->ni_authmode = ic->ic_bss->ni_authmode;
1058 		ni->ni_txpower = ic->ic_bss->ni_txpower;
1059 		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
1060 		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
1061 		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
1062 		ni->ni_rsn = ic->ic_bss->ni_rsn;
1063 	} else
1064 		ic->ic_stats.is_rx_nodealloc++;
1065 	return ni;
1066 }
1067 
1068 static struct ieee80211_node *
1069 #ifdef IEEE80211_DEBUG_REFCNT
1070 _ieee80211_find_node_debug(struct ieee80211_node_table *nt,
1071 	const u_int8_t *macaddr, const char *func, int line)
1072 #else
1073 _ieee80211_find_node(struct ieee80211_node_table *nt,
1074 	const u_int8_t *macaddr)
1075 #endif
1076 {
1077 	struct ieee80211_node *ni;
1078 	int hash;
1079 
1080 	IEEE80211_NODE_LOCK_ASSERT(nt);
1081 
1082 	hash = IEEE80211_NODE_HASH(macaddr);
1083 	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1084 		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
1085 			ieee80211_ref_node(ni);	/* mark referenced */
1086 #ifdef IEEE80211_DEBUG_REFCNT
1087 			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1088 			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1089 			    func, line,
1090 			    ni, ether_sprintf(ni->ni_macaddr),
1091 			    ieee80211_node_refcnt(ni));
1092 #endif
1093 			return ni;
1094 		}
1095 	}
1096 	return NULL;
1097 }
1098 #ifdef IEEE80211_DEBUG_REFCNT
1099 #define	_ieee80211_find_node(nt, mac) \
1100 	_ieee80211_find_node_debug(nt, mac, func, line)
1101 #endif
1102 
1103 struct ieee80211_node *
1104 #ifdef IEEE80211_DEBUG_REFCNT
1105 ieee80211_find_node_debug(struct ieee80211_node_table *nt,
1106 	const u_int8_t *macaddr, const char *func, int line)
1107 #else
1108 ieee80211_find_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
1109 #endif
1110 {
1111 	struct ieee80211_node *ni;
1112 
1113 	IEEE80211_NODE_LOCK(nt);
1114 	ni = _ieee80211_find_node(nt, macaddr);
1115 	IEEE80211_NODE_UNLOCK(nt);
1116 	return ni;
1117 }
1118 
1119 /*
1120  * Fake up a node; this handles node discovery in adhoc mode.
1121  * Note that for the driver's benefit we we treat this like
1122  * an association so the driver has an opportunity to setup
1123  * it's private state.
1124  */
1125 struct ieee80211_node *
1126 ieee80211_fakeup_adhoc_node(struct ieee80211_node_table *nt,
1127 	const u_int8_t macaddr[IEEE80211_ADDR_LEN])
1128 {
1129 	struct ieee80211com *ic = nt->nt_ic;
1130 	struct ieee80211_node *ni;
1131 
1132 	ni = ieee80211_dup_bss(nt, macaddr);
1133 	if (ni != NULL) {
1134 		/* XXX no rate negotiation; just dup */
1135 		ni->ni_rates = ic->ic_bss->ni_rates;
1136 		if (ic->ic_newassoc != NULL)
1137 			ic->ic_newassoc(ni, 1);
1138 		/* XXX not right for 802.1x/WPA */
1139 		ieee80211_node_authorize(ni);
1140 	}
1141 	return ni;
1142 }
1143 
1144 #ifdef IEEE80211_DEBUG
1145 static void
1146 dump_probe_beacon(u_int8_t subtype, int isnew,
1147 	const u_int8_t mac[IEEE80211_ADDR_LEN],
1148 	const struct ieee80211_scanparams *sp)
1149 {
1150 
1151 	printf("[%s] %s%s on chan %u (bss chan %u) ",
1152 	    ether_sprintf(mac), isnew ? "new " : "",
1153 	    ieee80211_mgt_subtype_name[subtype >> IEEE80211_FC0_SUBTYPE_SHIFT],
1154 	    sp->chan, sp->bchan);
1155 	ieee80211_print_essid(sp->ssid + 2, sp->ssid[1]);
1156 	printf("\n");
1157 
1158 	if (isnew) {
1159 		printf("[%s] caps 0x%x bintval %u erp 0x%x",
1160 			ether_sprintf(mac), sp->capinfo, sp->bintval, sp->erp);
1161 		if (sp->country != NULL) {
1162 #ifdef __FreeBSD__
1163 			printf(" country info %*D",
1164 				sp->country[1], sp->country+2, " ");
1165 #else
1166 			int i;
1167 			printf(" country info");
1168 			for (i = 0; i < sp->country[1]; i++)
1169 				printf(" %02x", sp->country[i+2]);
1170 #endif
1171 		}
1172 		printf("\n");
1173 	}
1174 }
1175 #endif /* IEEE80211_DEBUG */
1176 
1177 static void
1178 saveie(u_int8_t **iep, const u_int8_t *ie)
1179 {
1180 
1181 	if (ie == NULL)
1182 		*iep = NULL;
1183 	else
1184 		ieee80211_saveie(iep, ie);
1185 }
1186 
1187 /*
1188  * Process a beacon or probe response frame.
1189  */
1190 void
1191 ieee80211_add_scan(struct ieee80211com *ic,
1192 	const struct ieee80211_scanparams *sp,
1193 	const struct ieee80211_frame *wh,
1194 	int subtype, int rssi, int rstamp)
1195 {
1196 #define	ISPROBE(_st)	((_st) == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1197 	struct ieee80211_node_table *nt = &ic->ic_scan;
1198 	struct ieee80211_node *ni;
1199 	int newnode = 0;
1200 
1201 	ni = ieee80211_find_node(nt, wh->i_addr2);
1202 	if (ni == NULL) {
1203 		/*
1204 		 * Create a new entry.
1205 		 */
1206 		ni = ic->ic_node_alloc(nt);
1207 		if (ni == NULL) {
1208 			ic->ic_stats.is_rx_nodealloc++;
1209 			return;
1210 		}
1211 		ieee80211_setup_node(nt, ni, wh->i_addr2);
1212 		/*
1213 		 * XXX inherit from ic_bss.
1214 		 */
1215 		ni->ni_authmode = ic->ic_bss->ni_authmode;
1216 		ni->ni_txpower = ic->ic_bss->ni_txpower;
1217 		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
1218 		ieee80211_set_chan(ic, ni, ic->ic_curchan);
1219 		ni->ni_rsn = ic->ic_bss->ni_rsn;
1220 		newnode = 1;
1221 	}
1222 #ifdef IEEE80211_DEBUG
1223 	if (ieee80211_msg_scan(ic) && (ic->ic_flags & IEEE80211_F_SCAN))
1224 		dump_probe_beacon(subtype, newnode, wh->i_addr2, sp);
1225 #endif
1226 	/* XXX ap beaconing multiple ssid w/ same bssid */
1227 	if (sp->ssid[1] != 0 &&
1228 	    (ISPROBE(subtype) || ni->ni_esslen == 0)) {
1229 		ni->ni_esslen = sp->ssid[1];
1230 		memset(ni->ni_essid, 0, sizeof(ni->ni_essid));
1231 		memcpy(ni->ni_essid, sp->ssid + 2, sp->ssid[1]);
1232 	}
1233 	ni->ni_scangen = ic->ic_scan.nt_scangen;
1234 	IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
1235 	ni->ni_rssi = rssi;
1236 	ni->ni_rstamp = rstamp;
1237 	memcpy(ni->ni_tstamp.data, sp->tstamp, sizeof(ni->ni_tstamp));
1238 	ni->ni_intval = sp->bintval;
1239 	ni->ni_capinfo = sp->capinfo;
1240 	ni->ni_chan = &ic->ic_channels[sp->chan];
1241 	ni->ni_fhdwell = sp->fhdwell;
1242 	ni->ni_fhindex = sp->fhindex;
1243 	ni->ni_erp = sp->erp;
1244 	if (sp->tim != NULL) {
1245 		struct ieee80211_tim_ie *ie =
1246 		    (struct ieee80211_tim_ie *) sp->tim;
1247 
1248 		ni->ni_dtim_count = ie->tim_count;
1249 		ni->ni_dtim_period = ie->tim_period;
1250 	}
1251 	/*
1252 	 * Record the byte offset from the mac header to
1253 	 * the start of the TIM information element for
1254 	 * use by hardware and/or to speedup software
1255 	 * processing of beacon frames.
1256 	 */
1257 	ni->ni_timoff = sp->timoff;
1258 	/*
1259 	 * Record optional information elements that might be
1260 	 * used by applications or drivers.
1261 	 */
1262 	saveie(&ni->ni_wme_ie, sp->wme);
1263 	saveie(&ni->ni_wpa_ie, sp->wpa);
1264 
1265 	/* NB: must be after ni_chan is setup */
1266 	ieee80211_setup_rates(ni, sp->rates, sp->xrates, IEEE80211_F_DOSORT);
1267 
1268 	if (!newnode)
1269 		ieee80211_free_node(ni);
1270 #undef ISPROBE
1271 }
1272 
1273 void
1274 ieee80211_init_neighbor(struct ieee80211com *ic, struct ieee80211_node *ni,
1275     const struct ieee80211_frame *wh, const struct ieee80211_scanparams *sp,
1276     int isnew)
1277 {
1278 	ni->ni_esslen = sp->ssid[1];
1279 	memcpy(ni->ni_essid, sp->ssid + 2, sp->ssid[1]);
1280 	IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
1281 	memcpy(ni->ni_tstamp.data, sp->tstamp, sizeof(ni->ni_tstamp));
1282 	ni->ni_intval = sp->bintval;
1283 	ni->ni_capinfo = sp->capinfo;
1284 	ni->ni_chan = ic->ic_bss->ni_chan;
1285 	ni->ni_fhdwell = sp->fhdwell;
1286 	ni->ni_fhindex = sp->fhindex;
1287 	ni->ni_erp = sp->erp;
1288 	ni->ni_timoff = sp->timoff;
1289 	if (sp->wme != NULL)
1290 		ieee80211_saveie(&ni->ni_wme_ie, sp->wme);
1291 	if (sp->wpa != NULL)
1292 		ieee80211_saveie(&ni->ni_wpa_ie, sp->wpa);
1293 
1294 	/* NB: must be after ni_chan is setup */
1295 	ieee80211_setup_rates(ni, sp->rates, sp->xrates,
1296 	    IEEE80211_F_DODEL | IEEE80211_F_DONEGO | IEEE80211_F_DOSORT);
1297 
1298 	if (ic->ic_newassoc != NULL)
1299 		ic->ic_newassoc(ni, isnew);
1300 }
1301 
1302 /*
1303  * Do node discovery in adhoc mode on receipt of a beacon
1304  * or probe response frame.  Note that for the driver's
1305  * benefit we we treat this like an association so the
1306  * driver has an opportunity to setup it's private state.
1307  */
1308 struct ieee80211_node *
1309 ieee80211_add_neighbor(struct ieee80211com *ic,
1310 	const struct ieee80211_frame *wh,
1311 	const struct ieee80211_scanparams *sp)
1312 {
1313 	struct ieee80211_node *ni;
1314 
1315 	ni = ieee80211_dup_bss(&ic->ic_sta, wh->i_addr2);/* XXX alloc_node? */
1316 	if (ni != NULL) {
1317 		ieee80211_init_neighbor(ic, ni, wh, sp, 1);
1318 		/* XXX not right for 802.1x/WPA */
1319 		ieee80211_node_authorize(ni);
1320 	}
1321 	return ni;
1322 }
1323 
1324 #define	IS_CTL(wh) \
1325 	((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_CTL)
1326 #define	IS_PSPOLL(wh) \
1327 	((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_PS_POLL)
1328 /*
1329  * Locate the node for sender, track state, and then pass the
1330  * (referenced) node up to the 802.11 layer for its use.  We
1331  * are required to pass some node so we fall back to ic_bss
1332  * when this frame is from an unknown sender.  The 802.11 layer
1333  * knows this means the sender wasn't in the node table and
1334  * acts accordingly.
1335  */
1336 struct ieee80211_node *
1337 #ifdef IEEE80211_DEBUG_REFCNT
1338 ieee80211_find_rxnode_debug(struct ieee80211com *ic,
1339 	const struct ieee80211_frame_min *wh, const char *func, int line)
1340 #else
1341 ieee80211_find_rxnode(struct ieee80211com *ic,
1342 	const struct ieee80211_frame_min *wh)
1343 #endif
1344 {
1345 	struct ieee80211_node_table *nt;
1346 	struct ieee80211_node *ni;
1347 
1348 	/* XXX may want scanned nodes in the neighbor table for adhoc */
1349 	if (ic->ic_opmode == IEEE80211_M_STA ||
1350 	    ic->ic_opmode == IEEE80211_M_MONITOR ||
1351 	    (ic->ic_flags & IEEE80211_F_SCAN))
1352 		nt = &ic->ic_scan;
1353 	else
1354 		nt = &ic->ic_sta;
1355 	/* XXX check ic_bss first in station mode */
1356 	/* XXX 4-address frames? */
1357 	IEEE80211_NODE_LOCK(nt);
1358 	if (IS_CTL(wh) && !IS_PSPOLL(wh) /*&& !IS_RTS(ah)*/)
1359 		ni = _ieee80211_find_node(nt, wh->i_addr1);
1360 	else
1361 		ni = _ieee80211_find_node(nt, wh->i_addr2);
1362 	if (ni == NULL)
1363 		ni = ieee80211_ref_node(ic->ic_bss);
1364 	IEEE80211_NODE_UNLOCK(nt);
1365 
1366 	return ni;
1367 }
1368 
1369 /*
1370  * Like ieee80211_find_rxnode but use the supplied h/w
1371  * key index as a hint to locate the node in the key
1372  * mapping table.  If an entry is present at the key
1373  * index we return it; otherwise do a normal lookup and
1374  * update the mapping table if the station has a unicast
1375  * key assigned to it.
1376  */
1377 struct ieee80211_node *
1378 #ifdef IEEE80211_DEBUG_REFCNT
1379 ieee80211_find_rxnode_withkey_debug(struct ieee80211com *ic,
1380 	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix,
1381 	const char *func, int line)
1382 #else
1383 ieee80211_find_rxnode_withkey(struct ieee80211com *ic,
1384 	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix)
1385 #endif
1386 {
1387 	struct ieee80211_node_table *nt;
1388 	struct ieee80211_node *ni;
1389 
1390 	if (ic->ic_opmode == IEEE80211_M_STA ||
1391 	    ic->ic_opmode == IEEE80211_M_MONITOR ||
1392 	    (ic->ic_flags & IEEE80211_F_SCAN))
1393 		nt = &ic->ic_scan;
1394 	else
1395 		nt = &ic->ic_sta;
1396 	IEEE80211_NODE_LOCK(nt);
1397 	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax)
1398 		ni = nt->nt_keyixmap[keyix];
1399 	else
1400 		ni = NULL;
1401 	if (ni == NULL) {
1402 		if (IS_CTL(wh) && !IS_PSPOLL(wh) /*&& !IS_RTS(ah)*/)
1403 			ni = _ieee80211_find_node(nt, wh->i_addr1);
1404 		else
1405 			ni = _ieee80211_find_node(nt, wh->i_addr2);
1406 		if (ni == NULL)
1407 			ni = ieee80211_ref_node(ic->ic_bss);
1408 		if (nt->nt_keyixmap != NULL) {
1409 			/*
1410 			 * If the station has a unicast key cache slot
1411 			 * assigned update the key->node mapping table.
1412 			 */
1413 			keyix = ni->ni_ucastkey.wk_rxkeyix;
1414 			/* XXX can keyixmap[keyix] != NULL? */
1415 			if (keyix < nt->nt_keyixmax &&
1416 			    nt->nt_keyixmap[keyix] == NULL) {
1417 				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1418 				    "%s: add key map entry %p<%s> refcnt %d\n",
1419 				    __func__, ni, ether_sprintf(ni->ni_macaddr),
1420 				    ieee80211_node_refcnt(ni)+1);
1421 				nt->nt_keyixmap[keyix] = ieee80211_ref_node(ni);
1422 			}
1423 		}
1424 	} else {
1425 		ieee80211_ref_node(ni);
1426 	}
1427 	IEEE80211_NODE_UNLOCK(nt);
1428 
1429 	return ni;
1430 }
1431 #undef IS_PSPOLL
1432 #undef IS_CTL
1433 
1434 /*
1435  * Return a reference to the appropriate node for sending
1436  * a data frame.  This handles node discovery in adhoc networks.
1437  */
1438 struct ieee80211_node *
1439 #ifdef IEEE80211_DEBUG_REFCNT
1440 ieee80211_find_txnode_debug(struct ieee80211com *ic, const u_int8_t *macaddr,
1441 	const char *func, int line)
1442 #else
1443 ieee80211_find_txnode(struct ieee80211com *ic, const u_int8_t *macaddr)
1444 #endif
1445 {
1446 	struct ieee80211_node_table *nt = &ic->ic_sta;
1447 	struct ieee80211_node *ni;
1448 
1449 	/*
1450 	 * The destination address should be in the node table
1451 	 * unless this is a multicast/broadcast frame.  We can
1452 	 * also optimize station mode operation, all frames go
1453 	 * to the bss node.
1454 	 */
1455 	/* XXX can't hold lock across dup_bss 'cuz of recursive locking */
1456 	IEEE80211_NODE_LOCK(nt);
1457 	if (ic->ic_opmode == IEEE80211_M_STA || IEEE80211_IS_MULTICAST(macaddr))
1458 		ni = ieee80211_ref_node(ic->ic_bss);
1459 	else
1460 		ni = _ieee80211_find_node(nt, macaddr);
1461 	IEEE80211_NODE_UNLOCK(nt);
1462 
1463 	if (ni == NULL) {
1464 		if (ic->ic_opmode == IEEE80211_M_IBSS ||
1465 		    ic->ic_opmode == IEEE80211_M_AHDEMO) {
1466 			/*
1467 			 * In adhoc mode cons up a node for the destination.
1468 			 * Note that we need an additional reference for the
1469 			 * caller to be consistent with _ieee80211_find_node.
1470 			 */
1471 			ni = ieee80211_fakeup_adhoc_node(nt, macaddr);
1472 			if (ni != NULL)
1473 				(void) ieee80211_ref_node(ni);
1474 		} else {
1475 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
1476 				"[%s] no node, discard frame (%s)\n",
1477 				ether_sprintf(macaddr), __func__);
1478 			ic->ic_stats.is_tx_nonode++;
1479 		}
1480 	}
1481 	return ni;
1482 }
1483 
1484 /*
1485  * Like find but search based on the channel too.
1486  */
1487 struct ieee80211_node *
1488 #ifdef IEEE80211_DEBUG_REFCNT
1489 ieee80211_find_node_with_channel_debug(struct ieee80211_node_table *nt,
1490 	const u_int8_t *macaddr, struct ieee80211_channel *chan,
1491 	const char *func, int line)
1492 #else
1493 ieee80211_find_node_with_channel(struct ieee80211_node_table *nt,
1494 	const u_int8_t *macaddr, struct ieee80211_channel *chan)
1495 #endif
1496 {
1497 	struct ieee80211_node *ni;
1498 	int hash;
1499 
1500 	hash = IEEE80211_NODE_HASH(macaddr);
1501 	IEEE80211_NODE_LOCK(nt);
1502 	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1503 		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1504 		    ni->ni_chan == chan) {
1505 			ieee80211_ref_node(ni);		/* mark referenced */
1506 			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1507 #ifdef IEEE80211_DEBUG_REFCNT
1508 			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1509 			    func, line,
1510 #else
1511 			    "%s %p<%s> refcnt %d\n", __func__,
1512 #endif
1513 			    ni, ether_sprintf(ni->ni_macaddr),
1514 			    ieee80211_node_refcnt(ni));
1515 			break;
1516 		}
1517 	}
1518 	IEEE80211_NODE_UNLOCK(nt);
1519 	return ni;
1520 }
1521 
1522 struct ieee80211_node *
1523 ieee80211_refine_node_for_beacon(struct ieee80211com *ic,
1524 	struct ieee80211_node *ni0, struct ieee80211_channel *chan,
1525 	const u_int8_t *ssid)
1526 {
1527 	struct ieee80211_node_table *nt = ni0->ni_table;
1528 	struct ieee80211_node *best, *ni;
1529 	int best_score = 0, score;
1530 
1531 	if (nt == NULL)
1532 		return ni0;
1533 
1534 	best = ni0;
1535 	if (ssid[1] == 0 || best->ni_esslen == 0)
1536 		best_score = 1;
1537 	else if (ssid[1] == best->ni_esslen &&
1538 		 memcmp(ssid + 2, best->ni_essid, ssid[1]) == 0)
1539 		best_score = 2;
1540 	else
1541 		best_score = 0;
1542 
1543 	IEEE80211_NODE_LOCK(nt);
1544 	for (ni = LIST_NEXT(ni0, ni_hash); ni != NULL;
1545 	     ni = LIST_NEXT(ni, ni_hash)) {
1546 		if (!IEEE80211_ADDR_EQ(ni->ni_macaddr, best->ni_macaddr) ||
1547 		    ni->ni_ic != best->ni_ic || ni->ni_chan != chan)
1548 			continue;
1549 
1550 		if (ssid[1] == 0 || ni->ni_esslen == 0)
1551 			score = 1;
1552 		else if (ssid[1] == ni->ni_esslen &&
1553 			 memcmp(ssid + 2, ni->ni_essid, ssid[1]) == 0)
1554 			score = 2;
1555 		else
1556 			continue;
1557 
1558 		if (score > best_score) {
1559 			best = ni;
1560 			best_score = score;
1561 		}
1562 	}
1563 	IEEE80211_NODE_UNLOCK(nt);
1564 	return best;
1565 }
1566 
1567 /*
1568  * Like find but search based on the ssid too.
1569  */
1570 struct ieee80211_node *
1571 #ifdef IEEE80211_DEBUG_REFCNT
1572 ieee80211_find_node_with_ssid_debug(struct ieee80211_node_table *nt,
1573 	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid,
1574 	const char *func, int line)
1575 #else
1576 ieee80211_find_node_with_ssid(struct ieee80211_node_table *nt,
1577 	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid)
1578 #endif
1579 {
1580 #define	MATCH_SSID(ni, ssid, ssidlen) \
1581 	(ni->ni_esslen == ssidlen && memcmp(ni->ni_essid, ssid, ssidlen) == 0)
1582 	static const u_int8_t zeromac[IEEE80211_ADDR_LEN];
1583 	struct ieee80211com *ic = nt->nt_ic;
1584 	struct ieee80211_node *ni;
1585 	int hash;
1586 
1587 	IEEE80211_NODE_LOCK(nt);
1588 	/*
1589 	 * A mac address that is all zero means match only the ssid;
1590 	 * otherwise we must match both.
1591 	 */
1592 	if (IEEE80211_ADDR_EQ(macaddr, zeromac)) {
1593 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1594 			if (MATCH_SSID(ni, ssid, ssidlen))
1595 				break;
1596 		}
1597 	} else {
1598 		hash = IEEE80211_NODE_HASH(macaddr);
1599 		LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1600 			if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1601 			    MATCH_SSID(ni, ssid, ssidlen))
1602 				break;
1603 		}
1604 	}
1605 	if (ni != NULL) {
1606 		ieee80211_ref_node(ni);	/* mark referenced */
1607 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1608 #ifdef IEEE80211_DEBUG_REFCNT
1609 		    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1610 		    func, line,
1611 #else
1612 		    "%s %p<%s> refcnt %d\n", __func__,
1613 #endif
1614 		     ni, ether_sprintf(ni->ni_macaddr),
1615 		     ieee80211_node_refcnt(ni));
1616 	}
1617 	IEEE80211_NODE_UNLOCK(nt);
1618 	return ni;
1619 #undef MATCH_SSID
1620 }
1621 
1622 static void
1623 _ieee80211_free_node(struct ieee80211_node *ni)
1624 {
1625 	struct ieee80211com *ic = ni->ni_ic;
1626 	struct ieee80211_node_table *nt = ni->ni_table;
1627 
1628 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1629 		"%s %p<%s> in %s table\n", __func__, ni,
1630 		ether_sprintf(ni->ni_macaddr),
1631 		nt != NULL ? nt->nt_name : "<gone>");
1632 
1633 	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1634 	if (nt != NULL) {
1635 		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1636 		LIST_REMOVE(ni, ni_hash);
1637 	}
1638 	ic->ic_node_free(ni);
1639 }
1640 
1641 void
1642 #ifdef IEEE80211_DEBUG_REFCNT
1643 ieee80211_free_node_debug(struct ieee80211_node *ni, const char *func, int line)
1644 #else
1645 ieee80211_free_node(struct ieee80211_node *ni)
1646 #endif
1647 {
1648 	struct ieee80211_node_table *nt = ni->ni_table;
1649 
1650 #ifdef IEEE80211_DEBUG_REFCNT
1651 	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1652 		"%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line, ni,
1653 		 ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)-1);
1654 #endif
1655 	if (nt != NULL) {
1656 		IEEE80211_NODE_LOCK(nt);
1657 		if (ieee80211_node_dectestref(ni)) {
1658 			/*
1659 			 * Last reference, reclaim state.
1660 			 */
1661 			_ieee80211_free_node(ni);
1662 		} else if (ieee80211_node_refcnt(ni) == 1 &&
1663 		    nt->nt_keyixmap != NULL) {
1664 			ieee80211_keyix keyix;
1665 			/*
1666 			 * Check for a last reference in the key mapping table.
1667 			 */
1668 			keyix = ni->ni_ucastkey.wk_rxkeyix;
1669 			if (keyix < nt->nt_keyixmax &&
1670 			    nt->nt_keyixmap[keyix] == ni) {
1671 				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1672 				    "%s: %p<%s> clear key map entry", __func__,
1673 				    ni, ether_sprintf(ni->ni_macaddr));
1674 				nt->nt_keyixmap[keyix] = NULL;
1675 				ieee80211_node_decref(ni); /* XXX needed? */
1676 				_ieee80211_free_node(ni);
1677 			}
1678 		}
1679 		IEEE80211_NODE_UNLOCK(nt);
1680 	} else {
1681 		if (ieee80211_node_dectestref(ni))
1682 			_ieee80211_free_node(ni);
1683 	}
1684 }
1685 
1686 /*
1687  * Reclaim a unicast key and clear any key cache state.
1688  */
1689 int
1690 ieee80211_node_delucastkey(struct ieee80211_node *ni)
1691 {
1692 	struct ieee80211com *ic = ni->ni_ic;
1693 	struct ieee80211_node_table *nt = &ic->ic_sta;
1694 	struct ieee80211_node *nikey;
1695 	ieee80211_keyix keyix;
1696 	int isowned, status;
1697 
1698 	/*
1699 	 * NB: We must beware of LOR here; deleting the key
1700 	 * can cause the crypto layer to block traffic updates
1701 	 * which can generate a LOR against the node table lock;
1702 	 * grab it here and stash the key index for our use below.
1703 	 *
1704 	 * Must also beware of recursion on the node table lock.
1705 	 * When called from node_cleanup we may already have
1706 	 * the node table lock held.  Unfortunately there's no
1707 	 * way to separate out this path so we must do this
1708 	 * conditionally.
1709 	 */
1710 	isowned = IEEE80211_NODE_IS_LOCKED(nt);
1711 	if (!isowned)
1712 		IEEE80211_NODE_LOCK(nt);
1713 	keyix = ni->ni_ucastkey.wk_rxkeyix;
1714 	status = ieee80211_crypto_delkey(ic, &ni->ni_ucastkey);
1715 	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax) {
1716 		nikey = nt->nt_keyixmap[keyix];
1717 		nt->nt_keyixmap[keyix] = NULL;;
1718 	} else
1719 		nikey = NULL;
1720 	if (!isowned)
1721 		IEEE80211_NODE_UNLOCK(&ic->ic_sta);
1722 
1723 	if (nikey != NULL) {
1724 		IASSERT(nikey == ni,
1725 			("key map out of sync, ni %p nikey %p", ni, nikey));
1726 		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1727 			"%s: delete key map entry %p<%s> refcnt %d\n",
1728 			__func__, ni, ether_sprintf(ni->ni_macaddr),
1729 			ieee80211_node_refcnt(ni)-1);
1730 		ieee80211_free_node(ni);
1731 	}
1732 	return status;
1733 }
1734 
1735 /*
1736  * Reclaim a node.  If this is the last reference count then
1737  * do the normal free work.  Otherwise remove it from the node
1738  * table and mark it gone by clearing the back-reference.
1739  */
1740 static void
1741 node_reclaim(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1742 {
1743 	ieee80211_keyix keyix;
1744 
1745 	IEEE80211_NODE_LOCK_ASSERT(nt);
1746 
1747 	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1748 		"%s: remove %p<%s> from %s table, refcnt %d\n",
1749 		__func__, ni, ether_sprintf(ni->ni_macaddr),
1750 		nt->nt_name, ieee80211_node_refcnt(ni)-1);
1751 	/*
1752 	 * Clear any entry in the unicast key mapping table.
1753 	 * We need to do it here so rx lookups don't find it
1754 	 * in the mapping table even if it's not in the hash
1755 	 * table.  We cannot depend on the mapping table entry
1756 	 * being cleared because the node may not be free'd.
1757 	 */
1758 	keyix = ni->ni_ucastkey.wk_rxkeyix;
1759 	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax &&
1760 	    nt->nt_keyixmap[keyix] == ni) {
1761 		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1762 			"%s: %p<%s> clear key map entry\n",
1763 			__func__, ni, ether_sprintf(ni->ni_macaddr));
1764 		nt->nt_keyixmap[keyix] = NULL;
1765 		ieee80211_node_decref(ni);	/* NB: don't need free */
1766 	}
1767 	if (!ieee80211_node_dectestref(ni)) {
1768 		/*
1769 		 * Other references are present, just remove the
1770 		 * node from the table so it cannot be found.  When
1771 		 * the references are dropped storage will be
1772 		 * reclaimed.
1773 		 */
1774 		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1775 		LIST_REMOVE(ni, ni_hash);
1776 		ni->ni_table = NULL;		/* clear reference */
1777 	} else
1778 		_ieee80211_free_node(ni);
1779 }
1780 
1781 static void
1782 ieee80211_free_allnodes_locked(struct ieee80211_node_table *nt)
1783 {
1784 	struct ieee80211com *ic = nt->nt_ic;
1785 	struct ieee80211_node *ni;
1786 
1787 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1788 		"%s: free all nodes in %s table\n", __func__, nt->nt_name);
1789 
1790 	while ((ni = TAILQ_FIRST(&nt->nt_node)) != NULL) {
1791 		if (ni->ni_associd != 0) {
1792 			if (ic->ic_auth->ia_node_leave != NULL)
1793 				ic->ic_auth->ia_node_leave(ic, ni);
1794 			IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1795 		}
1796 		node_reclaim(nt, ni);
1797 	}
1798 	ieee80211_reset_erp(ic);
1799 }
1800 
1801 static void
1802 ieee80211_free_allnodes(struct ieee80211_node_table *nt)
1803 {
1804 
1805 	IEEE80211_NODE_LOCK(nt);
1806 	ieee80211_free_allnodes_locked(nt);
1807 	IEEE80211_NODE_UNLOCK(nt);
1808 }
1809 
1810 /*
1811  * Timeout entries in the scan cache.
1812  */
1813 static void
1814 ieee80211_timeout_scan_candidates(struct ieee80211_node_table *nt)
1815 {
1816 	struct ieee80211com *ic = nt->nt_ic;
1817 	struct ieee80211_node *ni, *tni;
1818 
1819 	IEEE80211_NODE_LOCK(nt);
1820 	ni = ic->ic_bss;
1821 	/* XXX belongs elsewhere */
1822 	if (ni->ni_rxfrag[0] != NULL && ticks > ni->ni_rxfragstamp + hz) {
1823 		m_freem(ni->ni_rxfrag[0]);
1824 		ni->ni_rxfrag[0] = NULL;
1825 	}
1826 	TAILQ_FOREACH_SAFE(ni, &nt->nt_node, ni_list, tni) {
1827 		if (ni->ni_inact && --ni->ni_inact == 0) {
1828 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1829 			    "[%s] scan candidate purged from cache "
1830 			    "(refcnt %u)\n", ether_sprintf(ni->ni_macaddr),
1831 			    ieee80211_node_refcnt(ni));
1832 			node_reclaim(nt, ni);
1833 		}
1834 	}
1835 	IEEE80211_NODE_UNLOCK(nt);
1836 
1837 	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
1838 }
1839 
1840 /*
1841  * Timeout inactive stations and do related housekeeping.
1842  * Note that we cannot hold the node lock while sending a
1843  * frame as this would lead to a LOR.  Instead we use a
1844  * generation number to mark nodes that we've scanned and
1845  * drop the lock and restart a scan if we have to time out
1846  * a node.  Since we are single-threaded by virtue of
1847  * controlling the inactivity timer we can be sure this will
1848  * process each node only once.
1849  */
1850 static void
1851 ieee80211_timeout_stations(struct ieee80211_node_table *nt)
1852 {
1853 	struct ieee80211com *ic = nt->nt_ic;
1854 	struct ieee80211_node *ni;
1855 	u_int gen;
1856 	int isadhoc;
1857 
1858 	isadhoc = (ic->ic_opmode == IEEE80211_M_IBSS ||
1859 		   ic->ic_opmode == IEEE80211_M_AHDEMO);
1860 	IEEE80211_SCAN_LOCK(nt);
1861 	gen = nt->nt_scangen++;
1862 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1863 		"%s: %s scangen %u\n", __func__, nt->nt_name, gen);
1864 restart:
1865 	IEEE80211_NODE_LOCK(nt);
1866 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1867 		if (ni->ni_scangen == gen)	/* previously handled */
1868 			continue;
1869 		ni->ni_scangen = gen;
1870 		/*
1871 		 * Ignore entries for which have yet to receive an
1872 		 * authentication frame.  These are transient and
1873 		 * will be reclaimed when the last reference to them
1874 		 * goes away (when frame xmits complete).
1875 		 */
1876 		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
1877 		    (ni->ni_flags & IEEE80211_NODE_AREF) == 0)
1878 			continue;
1879 		/*
1880 		 * Free fragment if not needed anymore
1881 		 * (last fragment older than 1s).
1882 		 * XXX doesn't belong here
1883 		 */
1884 		if (ni->ni_rxfrag[0] != NULL &&
1885 		    ticks > ni->ni_rxfragstamp + hz) {
1886 			m_freem(ni->ni_rxfrag[0]);
1887 			ni->ni_rxfrag[0] = NULL;
1888 		}
1889 		/*
1890 		 * Special case ourself; we may be idle for extended periods
1891 		 * of time and regardless reclaiming our state is wrong.
1892 		 */
1893 		if (ni == ic->ic_bss)
1894 			continue;
1895 		ni->ni_inact--;
1896 		if (ni->ni_associd != 0 || isadhoc) {
1897 			/*
1898 			 * Age frames on the power save queue. The
1899 			 * aging interval is 4 times the listen
1900 			 * interval specified by the station.  This
1901 			 * number is factored into the age calculations
1902 			 * when the frame is placed on the queue.  We
1903 			 * store ages as time differences we can check
1904 			 * and/or adjust only the head of the list.
1905 			 */
1906 			if (IEEE80211_NODE_SAVEQ_QLEN(ni) != 0) {
1907 				struct mbuf *m;
1908 				int discard = 0;
1909 
1910 				IEEE80211_NODE_SAVEQ_LOCK(ni);
1911 				while (IF_POLL(&ni->ni_savedq, m) != NULL &&
1912 				     M_AGE_GET(m) < IEEE80211_INACT_WAIT) {
1913 IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER, "[%s] discard frame, age %u\n", ether_sprintf(ni->ni_macaddr), M_AGE_GET(m));/*XXX*/
1914 					_IEEE80211_NODE_SAVEQ_DEQUEUE_HEAD(ni, m);
1915 					m_freem(m);
1916 					discard++;
1917 				}
1918 				if (m != NULL)
1919 					M_AGE_SUB(m, IEEE80211_INACT_WAIT);
1920 				IEEE80211_NODE_SAVEQ_UNLOCK(ni);
1921 
1922 				if (discard != 0) {
1923 					IEEE80211_DPRINTF(ic,
1924 					    IEEE80211_MSG_POWER,
1925 					    "[%s] discard %u frames for age\n",
1926 					    ether_sprintf(ni->ni_macaddr),
1927 					    discard);
1928 					IEEE80211_NODE_STAT_ADD(ni,
1929 						ps_discard, discard);
1930 					if (IEEE80211_NODE_SAVEQ_QLEN(ni) == 0)
1931 						ic->ic_set_tim(ni, 0);
1932 				}
1933 			}
1934 			/*
1935 			 * Probe the station before time it out.  We
1936 			 * send a null data frame which may not be
1937 			 * universally supported by drivers (need it
1938 			 * for ps-poll support so it should be...).
1939 			 */
1940 			if (0 < ni->ni_inact &&
1941 			    ni->ni_inact <= ic->ic_inact_probe) {
1942 				IEEE80211_NOTE(ic,
1943 				    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE,
1944 				    ni, "%s",
1945 				    "probe station due to inactivity");
1946 				/*
1947 				 * Grab a reference before unlocking the table
1948 				 * so the node cannot be reclaimed before we
1949 				 * send the frame. ieee80211_send_nulldata
1950 				 * understands we've done this and reclaims the
1951 				 * ref for us as needed.
1952 				 */
1953 				ieee80211_ref_node(ni);
1954 				IEEE80211_NODE_UNLOCK(nt);
1955 				ieee80211_send_nulldata(ni);
1956 				/* XXX stat? */
1957 				goto restart;
1958 			}
1959 		}
1960 		if (ni->ni_inact <= 0) {
1961 			IEEE80211_NOTE(ic,
1962 			    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE, ni,
1963 			    "station timed out due to inactivity "
1964 			    "(refcnt %u)", ieee80211_node_refcnt(ni));
1965 			/*
1966 			 * Send a deauthenticate frame and drop the station.
1967 			 * This is somewhat complicated due to reference counts
1968 			 * and locking.  At this point a station will typically
1969 			 * have a reference count of 1.  ieee80211_node_leave
1970 			 * will do a "free" of the node which will drop the
1971 			 * reference count.  But in the meantime a reference
1972 			 * wil be held by the deauth frame.  The actual reclaim
1973 			 * of the node will happen either after the tx is
1974 			 * completed or by ieee80211_node_leave.
1975 			 *
1976 			 * Separately we must drop the node lock before sending
1977 			 * in case the driver takes a lock, as this will result
1978 			 * in  LOR between the node lock and the driver lock.
1979 			 */
1980 			IEEE80211_NODE_UNLOCK(nt);
1981 			if (ni->ni_associd != 0) {
1982 				IEEE80211_SEND_MGMT(ic, ni,
1983 				    IEEE80211_FC0_SUBTYPE_DEAUTH,
1984 				    IEEE80211_REASON_AUTH_EXPIRE);
1985 			}
1986 			ieee80211_node_leave(ic, ni);
1987 			ic->ic_stats.is_node_timeout++;
1988 			goto restart;
1989 		}
1990 	}
1991 	IEEE80211_NODE_UNLOCK(nt);
1992 
1993 	IEEE80211_SCAN_UNLOCK(nt);
1994 
1995 	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
1996 }
1997 
1998 void
1999 ieee80211_iterate_nodes(struct ieee80211_node_table *nt, ieee80211_iter_func *f, void *arg)
2000 {
2001 	struct ieee80211_node *ni;
2002 	u_int gen;
2003 
2004 	IEEE80211_SCAN_LOCK(nt);
2005 	gen = nt->nt_scangen++;
2006 restart:
2007 	IEEE80211_NODE_LOCK(nt);
2008 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
2009 		if (ni->ni_scangen != gen) {
2010 			ni->ni_scangen = gen;
2011 			(void) ieee80211_ref_node(ni);
2012 			IEEE80211_NODE_UNLOCK(nt);
2013 			(*f)(arg, ni);
2014 			ieee80211_free_node(ni);
2015 			goto restart;
2016 		}
2017 	}
2018 	IEEE80211_NODE_UNLOCK(nt);
2019 
2020 	IEEE80211_SCAN_UNLOCK(nt);
2021 }
2022 
2023 void
2024 ieee80211_dump_node(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
2025 {
2026 	printf("0x%p: mac %s refcnt %d\n", ni,
2027 		ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni));
2028 	printf("\tscangen %u authmode %u flags 0x%x\n",
2029 		ni->ni_scangen, ni->ni_authmode, ni->ni_flags);
2030 	printf("\tassocid 0x%x txpower %u vlan %u\n",
2031 		ni->ni_associd, ni->ni_txpower, ni->ni_vlan);
2032 	printf("\ttxseq %u rxseq %u fragno %u rxfragstamp %u\n",
2033 		ni->ni_txseqs[0],
2034 		ni->ni_rxseqs[0] >> IEEE80211_SEQ_SEQ_SHIFT,
2035 		ni->ni_rxseqs[0] & IEEE80211_SEQ_FRAG_MASK,
2036 		ni->ni_rxfragstamp);
2037 	printf("\trstamp %u rssi %u intval %u capinfo 0x%x\n",
2038 		ni->ni_rstamp, ni->ni_rssi, ni->ni_intval, ni->ni_capinfo);
2039 	printf("\tbssid %s essid \"%.*s\" channel %u:0x%x\n",
2040 		ether_sprintf(ni->ni_bssid),
2041 		ni->ni_esslen, ni->ni_essid,
2042 		ni->ni_chan->ic_freq, ni->ni_chan->ic_flags);
2043 	printf("\tfails %u inact %u txrate %u\n",
2044 		ni->ni_fails, ni->ni_inact, ni->ni_txrate);
2045 }
2046 
2047 void
2048 ieee80211_dump_nodes(struct ieee80211_node_table *nt)
2049 {
2050 	ieee80211_iterate_nodes(nt,
2051 		(ieee80211_iter_func *) ieee80211_dump_node, nt);
2052 }
2053 
2054 /*
2055  * Handle a station joining an 11g network.
2056  */
2057 static void
2058 ieee80211_node_join_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
2059 {
2060 
2061 	/*
2062 	 * Station isn't capable of short slot time.  Bump
2063 	 * the count of long slot time stations and disable
2064 	 * use of short slot time.  Note that the actual switch
2065 	 * over to long slot time use may not occur until the
2066 	 * next beacon transmission (per sec. 7.3.1.4 of 11g).
2067 	 */
2068 	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
2069 		ic->ic_longslotsta++;
2070 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2071 		    "[%s] station needs long slot time, count %d\n",
2072 		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
2073 		/* XXX vap's w/ conflicting needs won't work */
2074 		ieee80211_set_shortslottime(ic, 0);
2075 	}
2076 	/*
2077 	 * If the new station is not an ERP station
2078 	 * then bump the counter and enable protection
2079 	 * if configured.
2080 	 */
2081 	if (!ieee80211_iserp_rateset(ic, &ni->ni_rates)) {
2082 		ic->ic_nonerpsta++;
2083 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2084 		    "[%s] station is !ERP, %d non-ERP stations associated\n",
2085 		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
2086 		/*
2087 		 * If protection is configured, enable it.
2088 		 */
2089 		if (ic->ic_protmode != IEEE80211_PROT_NONE) {
2090 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2091 			    "%s: enable use of protection\n", __func__);
2092 			ic->ic_flags |= IEEE80211_F_USEPROT;
2093 		}
2094 		/*
2095 		 * If station does not support short preamble
2096 		 * then we must enable use of Barker preamble.
2097 		 */
2098 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE) == 0) {
2099 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2100 			    "[%s] station needs long preamble\n",
2101 			    ether_sprintf(ni->ni_macaddr));
2102 			ic->ic_flags |= IEEE80211_F_USEBARKER;
2103 			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
2104 		}
2105 	} else
2106 		ni->ni_flags |= IEEE80211_NODE_ERP;
2107 }
2108 
2109 void
2110 ieee80211_node_join(struct ieee80211com *ic, struct ieee80211_node *ni, int resp)
2111 {
2112 	int newassoc;
2113 
2114 	if (ni->ni_associd == 0) {
2115 		u_int16_t aid;
2116 
2117 		/*
2118 		 * It would be good to search the bitmap
2119 		 * more efficiently, but this will do for now.
2120 		 */
2121 		for (aid = 1; aid < ic->ic_max_aid; aid++) {
2122 			if (!IEEE80211_AID_ISSET(aid,
2123 			    ic->ic_aid_bitmap))
2124 				break;
2125 		}
2126 		if (aid >= ic->ic_max_aid) {
2127 			IEEE80211_SEND_MGMT(ic, ni, resp,
2128 			    IEEE80211_REASON_ASSOC_TOOMANY);
2129 			ieee80211_node_leave(ic, ni);
2130 			return;
2131 		}
2132 		ni->ni_associd = aid | 0xc000;
2133 		IEEE80211_AID_SET(ni->ni_associd, ic->ic_aid_bitmap);
2134 		ic->ic_sta_assoc++;
2135 		newassoc = 1;
2136 		if (ic->ic_curmode == IEEE80211_MODE_11G)
2137 			ieee80211_node_join_11g(ic, ni);
2138 	} else
2139 		newassoc = 0;
2140 
2141 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
2142 	    "[%s] station %sassociated at aid %d: %s preamble, %s slot time%s%s\n",
2143 	    ether_sprintf(ni->ni_macaddr), newassoc ? "" : "re",
2144 	    IEEE80211_NODE_AID(ni),
2145 	    ic->ic_flags & IEEE80211_F_SHPREAMBLE ? "short" : "long",
2146 	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long",
2147 	    ic->ic_flags & IEEE80211_F_USEPROT ? ", protection" : "",
2148 	    ni->ni_flags & IEEE80211_NODE_QOS ? ", QoS" : ""
2149 	);
2150 
2151 	/* give driver a chance to setup state like ni_txrate */
2152 	if (ic->ic_newassoc != NULL)
2153 		ic->ic_newassoc(ni, newassoc);
2154 	ni->ni_inact_reload = ic->ic_inact_auth;
2155 	ni->ni_inact = ni->ni_inact_reload;
2156 	IEEE80211_SEND_MGMT(ic, ni, resp, IEEE80211_STATUS_SUCCESS);
2157 	/* tell the authenticator about new station */
2158 	if (ic->ic_auth->ia_node_join != NULL)
2159 		ic->ic_auth->ia_node_join(ic, ni);
2160 	ieee80211_notify_node_join(ic, ni, newassoc);
2161 }
2162 
2163 /*
2164  * Handle a station leaving an 11g network.
2165  */
2166 static void
2167 ieee80211_node_leave_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
2168 {
2169 
2170 	IASSERT(ic->ic_curmode == IEEE80211_MODE_11G,
2171 	     ("not in 11g, bss %u:0x%x, curmode %u", ni->ni_chan->ic_freq,
2172 	      ni->ni_chan->ic_flags, ic->ic_curmode));
2173 
2174 	/*
2175 	 * If a long slot station do the slot time bookkeeping.
2176 	 */
2177 	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
2178 		IASSERT(ic->ic_longslotsta > 0,
2179 		    ("bogus long slot station count %d", ic->ic_longslotsta));
2180 		ic->ic_longslotsta--;
2181 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2182 		    "[%s] long slot time station leaves, count now %d\n",
2183 		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
2184 		if (ic->ic_longslotsta == 0) {
2185 			/*
2186 			 * Re-enable use of short slot time if supported
2187 			 * and not operating in IBSS mode (per spec).
2188 			 */
2189 			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
2190 			    ic->ic_opmode != IEEE80211_M_IBSS) {
2191 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2192 				    "%s: re-enable use of short slot time\n",
2193 				    __func__);
2194 				ieee80211_set_shortslottime(ic, 1);
2195 			}
2196 		}
2197 	}
2198 	/*
2199 	 * If a non-ERP station do the protection-related bookkeeping.
2200 	 */
2201 	if ((ni->ni_flags & IEEE80211_NODE_ERP) == 0) {
2202 		IASSERT(ic->ic_nonerpsta > 0,
2203 		    ("bogus non-ERP station count %d", ic->ic_nonerpsta));
2204 		ic->ic_nonerpsta--;
2205 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2206 		    "[%s] non-ERP station leaves, count now %d\n",
2207 		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
2208 		if (ic->ic_nonerpsta == 0) {
2209 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2210 				"%s: disable use of protection\n", __func__);
2211 			ic->ic_flags &= ~IEEE80211_F_USEPROT;
2212 			/* XXX verify mode? */
2213 			if (ic->ic_caps & IEEE80211_C_SHPREAMBLE) {
2214 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2215 				    "%s: re-enable use of short preamble\n",
2216 				    __func__);
2217 				ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
2218 				ic->ic_flags &= ~IEEE80211_F_USEBARKER;
2219 			}
2220 		}
2221 	}
2222 }
2223 
2224 /*
2225  * Handle bookkeeping for station deauthentication/disassociation
2226  * when operating as an ap.
2227  */
2228 void
2229 ieee80211_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
2230 {
2231 	struct ieee80211_node_table *nt = ni->ni_table;
2232 
2233 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
2234 	    "[%s] station with aid %d leaves\n",
2235 	    ether_sprintf(ni->ni_macaddr), IEEE80211_NODE_AID(ni));
2236 
2237 	IASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
2238 		ic->ic_opmode == IEEE80211_M_IBSS ||
2239 		ic->ic_opmode == IEEE80211_M_AHDEMO,
2240 		("unexpected operating mode %u", ic->ic_opmode));
2241 	/*
2242 	 * If node wasn't previously associated all
2243 	 * we need to do is reclaim the reference.
2244 	 */
2245 	/* XXX ibss mode bypasses 11g and notification */
2246 	if (ni->ni_associd == 0)
2247 		goto done;
2248 	/*
2249 	 * Tell the authenticator the station is leaving.
2250 	 * Note that we must do this before yanking the
2251 	 * association id as the authenticator uses the
2252 	 * associd to locate it's state block.
2253 	 */
2254 	if (ic->ic_auth->ia_node_leave != NULL)
2255 		ic->ic_auth->ia_node_leave(ic, ni);
2256 	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
2257 	ni->ni_associd = 0;
2258 	ic->ic_sta_assoc--;
2259 
2260 	if (ic->ic_curmode == IEEE80211_MODE_11G)
2261 		ieee80211_node_leave_11g(ic, ni);
2262 	/*
2263 	 * Cleanup station state.  In particular clear various
2264 	 * state that might otherwise be reused if the node
2265 	 * is reused before the reference count goes to zero
2266 	 * (and memory is reclaimed).
2267 	 */
2268 	ieee80211_sta_leave(ic, ni);
2269 done:
2270 	/*
2271 	 * Remove the node from any table it's recorded in and
2272 	 * drop the caller's reference.  Removal from the table
2273 	 * is important to insure the node is not reprocessed
2274 	 * for inactivity.
2275 	 */
2276 	if (nt != NULL) {
2277 		IEEE80211_NODE_LOCK(nt);
2278 		node_reclaim(nt, ni);
2279 		IEEE80211_NODE_UNLOCK(nt);
2280 	} else
2281 		ieee80211_free_node(ni);
2282 }
2283 
2284 u_int8_t
2285 ieee80211_getrssi(struct ieee80211com *ic)
2286 {
2287 #define	NZ(x)	((x) == 0 ? 1 : (x))
2288 	struct ieee80211_node_table *nt = &ic->ic_sta;
2289 	u_int32_t rssi_samples, rssi_total;
2290 	struct ieee80211_node *ni;
2291 
2292 	rssi_total = 0;
2293 	rssi_samples = 0;
2294 	switch (ic->ic_opmode) {
2295 	case IEEE80211_M_IBSS:		/* average of all ibss neighbors */
2296 		/* XXX locking */
2297 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
2298 			if (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) {
2299 				rssi_samples++;
2300 				rssi_total += ic->ic_node_getrssi(ni);
2301 			}
2302 		break;
2303 	case IEEE80211_M_AHDEMO:	/* average of all neighbors */
2304 		/* XXX locking */
2305 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
2306 			rssi_samples++;
2307 			rssi_total += ic->ic_node_getrssi(ni);
2308 		}
2309 		break;
2310 	case IEEE80211_M_HOSTAP:	/* average of all associated stations */
2311 #ifndef IEEE80211_NO_HOSTAP
2312 		/* XXX locking */
2313 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
2314 			if (IEEE80211_AID(ni->ni_associd) != 0) {
2315 				rssi_samples++;
2316 				rssi_total += ic->ic_node_getrssi(ni);
2317 			}
2318 #endif /* !IEEE80211_NO_HOSTAP */
2319 		break;
2320 	case IEEE80211_M_MONITOR:	/* XXX */
2321 	case IEEE80211_M_STA:		/* use stats from associated ap */
2322 	default:
2323 		if (ic->ic_bss != NULL)
2324 			rssi_total = ic->ic_node_getrssi(ic->ic_bss);
2325 		rssi_samples = 1;
2326 		break;
2327 	}
2328 	return rssi_total / NZ(rssi_samples);
2329 #undef NZ
2330 }
2331 
2332 /*
2333  * Indicate whether there are frames queued for a station in power-save mode.
2334  */
2335 static void
2336 ieee80211_set_tim(struct ieee80211_node *ni, int set)
2337 {
2338 	struct ieee80211com *ic = ni->ni_ic;
2339 	u_int16_t aid;
2340 
2341 	IASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
2342 		ic->ic_opmode == IEEE80211_M_IBSS,
2343 		("operating mode %u", ic->ic_opmode));
2344 
2345 	aid = IEEE80211_AID(ni->ni_associd);
2346 	IASSERT(aid < ic->ic_max_aid,
2347 		("bogus aid %u, max %u", aid, ic->ic_max_aid));
2348 
2349 	IEEE80211_BEACON_LOCK(ic);
2350 	if (set != (isset(ic->ic_tim_bitmap, aid) != 0)) {
2351 		if (set) {
2352 			setbit(ic->ic_tim_bitmap, aid);
2353 			ic->ic_ps_pending++;
2354 		} else {
2355 			clrbit(ic->ic_tim_bitmap, aid);
2356 			ic->ic_ps_pending--;
2357 		}
2358 		ic->ic_flags |= IEEE80211_F_TIMUPDATE;
2359 	}
2360 	IEEE80211_BEACON_UNLOCK(ic);
2361 }
2362 
2363 /*
2364  * Node table support.
2365  */
2366 
2367 static void
2368 ieee80211_node_table_init(struct ieee80211com *ic,
2369 	struct ieee80211_node_table *nt,
2370 	const char *name, int inact, int keyixmax,
2371 	void (*timeout)(struct ieee80211_node_table *))
2372 {
2373 
2374 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
2375 		"%s %s table, inact %u\n", __func__, name, inact);
2376 
2377 	nt->nt_ic = ic;
2378 	/* XXX need unit */
2379 	IEEE80211_NODE_LOCK_INIT(nt, ic->ic_ifp->if_xname);
2380 	IEEE80211_SCAN_LOCK_INIT(nt, ic->ic_ifp->if_xname);
2381 	TAILQ_INIT(&nt->nt_node);
2382 	nt->nt_name = name;
2383 	nt->nt_scangen = 1;
2384 	nt->nt_inact_init = inact;
2385 	nt->nt_timeout = timeout;
2386 	nt->nt_keyixmax = keyixmax;
2387 	if (nt->nt_keyixmax > 0) {
2388 		MALLOC(nt->nt_keyixmap, struct ieee80211_node **,
2389 			keyixmax * sizeof(struct ieee80211_node *),
2390 			M_80211_NODE, M_NOWAIT | M_ZERO);
2391 		if (nt->nt_keyixmap == NULL)
2392 			if_printf(ic->ic_ifp,
2393 			    "Cannot allocate key index map with %u entries\n",
2394 			    keyixmax);
2395 	} else
2396 		nt->nt_keyixmap = NULL;
2397 }
2398 
2399 void
2400 ieee80211_node_table_reset(struct ieee80211_node_table *nt)
2401 {
2402 
2403 	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
2404 		"%s %s table\n", __func__, nt->nt_name);
2405 
2406 	IEEE80211_NODE_LOCK(nt);
2407 	nt->nt_inact_timer = 0;
2408 	ieee80211_free_allnodes_locked(nt);
2409 	IEEE80211_NODE_UNLOCK(nt);
2410 }
2411 
2412 static void
2413 ieee80211_node_table_cleanup(struct ieee80211_node_table *nt)
2414 {
2415 
2416 	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
2417 		"%s %s table\n", __func__, nt->nt_name);
2418 
2419 	IEEE80211_NODE_LOCK(nt);
2420 	ieee80211_free_allnodes_locked(nt);
2421 	if (nt->nt_keyixmap != NULL) {
2422 		/* XXX verify all entries are NULL */
2423 		int i;
2424 		for (i = 0; i < nt->nt_keyixmax; i++)
2425 			if (nt->nt_keyixmap[i] != NULL)
2426 				printf("%s: %s[%u] still active\n", __func__,
2427 					nt->nt_name, i);
2428 		FREE(nt->nt_keyixmap, M_80211_NODE);
2429 		nt->nt_keyixmap = NULL;
2430 	}
2431 	IEEE80211_SCAN_LOCK_DESTROY(nt);
2432 	IEEE80211_NODE_LOCK_DESTROY(nt);
2433 }
2434