xref: /netbsd-src/sys/net80211/ieee80211_node.c (revision d9ac053afa92f3d7a493f791e10558f738234217)
1 /*	$NetBSD: ieee80211_node.c,v 1.56 2006/05/03 16:50:58 seanb 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.56 2006/05/03 16:50:58 seanb 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 	ic->ic_aid_bitmap = malloc(howmany(ic->ic_max_aid, 32) *
134 	    sizeof(u_int32_t), M_DEVBUF, M_NOWAIT | M_ZERO);
135 	if (ic->ic_aid_bitmap == NULL) {
136 		/* XXX no way to recover */
137 		printf("%s: no memory for AID bitmap!\n", __func__);
138 		ic->ic_max_aid = 0;
139 	}
140 
141 	/* XXX defer until using hostap/ibss mode */
142 	ic->ic_tim_len = howmany(ic->ic_max_aid, 8) * sizeof(u_int8_t);
143 	ic->ic_tim_bitmap = malloc(ic->ic_tim_len, M_DEVBUF, M_NOWAIT | M_ZERO);
144 	if (ic->ic_tim_bitmap == NULL) {
145 		/* XXX no way to recover */
146 		printf("%s: no memory for TIM bitmap!\n", __func__);
147 	}
148 
149 	ieee80211_node_table_init(ic, &ic->ic_sta, "station",
150 		IEEE80211_INACT_INIT, ic->ic_crypto.cs_max_keyix,
151 		ieee80211_timeout_stations);
152 	ieee80211_node_table_init(ic, &ic->ic_scan, "scan",
153 		IEEE80211_INACT_SCAN, 0,
154 		ieee80211_timeout_scan_candidates);
155 
156 	ieee80211_reset_bss(ic);
157 	/*
158 	 * Setup "global settings" in the bss node so that
159 	 * each new station automatically inherits them.
160 	 */
161 	rsn = &ic->ic_bss->ni_rsn;
162 	/* WEP, TKIP, and AES-CCM are always supported */
163 	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_WEP;
164 	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_TKIP;
165 	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_AES_CCM;
166 	if (ic->ic_caps & IEEE80211_C_AES)
167 		rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_AES_OCB;
168 	if (ic->ic_caps & IEEE80211_C_CKIP)
169 		rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_CKIP;
170 	/*
171 	 * Default unicast cipher to WEP for 802.1x use.  If
172 	 * WPA is enabled the management code will set these
173 	 * values to reflect.
174 	 */
175 	rsn->rsn_ucastcipher = IEEE80211_CIPHER_WEP;
176 	rsn->rsn_ucastkeylen = 104 / NBBY;
177 	/*
178 	 * WPA says the multicast cipher is the lowest unicast
179 	 * cipher supported.  But we skip WEP which would
180 	 * otherwise be used based on this criteria.
181 	 */
182 	rsn->rsn_mcastcipher = IEEE80211_CIPHER_TKIP;
183 	rsn->rsn_mcastkeylen = 128 / NBBY;
184 
185 	/*
186 	 * We support both WPA-PSK and 802.1x; the one used
187 	 * is determined by the authentication mode and the
188 	 * setting of the PSK state.
189 	 */
190 	rsn->rsn_keymgmtset = WPA_ASE_8021X_UNSPEC | WPA_ASE_8021X_PSK;
191 	rsn->rsn_keymgmt = WPA_ASE_8021X_PSK;
192 
193 	ic->ic_auth = ieee80211_authenticator_get(ic->ic_bss->ni_authmode);
194 }
195 
196 void
197 ieee80211_node_detach(struct ieee80211com *ic)
198 {
199 
200 	if (ic->ic_bss != NULL) {
201 		ieee80211_free_node(ic->ic_bss);
202 		ic->ic_bss = NULL;
203 	}
204 	ieee80211_node_table_cleanup(&ic->ic_scan);
205 	ieee80211_node_table_cleanup(&ic->ic_sta);
206 	if (ic->ic_aid_bitmap != NULL) {
207 		FREE(ic->ic_aid_bitmap, M_DEVBUF);
208 		ic->ic_aid_bitmap = NULL;
209 	}
210 	if (ic->ic_tim_bitmap != NULL) {
211 		FREE(ic->ic_tim_bitmap, M_DEVBUF);
212 		ic->ic_tim_bitmap = NULL;
213 	}
214 }
215 
216 /*
217  * Port authorize/unauthorize interfaces for use by an authenticator.
218  */
219 
220 void
221 ieee80211_node_authorize(struct ieee80211_node *ni)
222 {
223 	struct ieee80211com *ic = ni->ni_ic;
224 
225 	ni->ni_flags |= IEEE80211_NODE_AUTH;
226 	ni->ni_inact_reload = ic->ic_inact_run;
227 }
228 
229 void
230 ieee80211_node_unauthorize(struct ieee80211_node *ni)
231 {
232 	ni->ni_flags &= ~IEEE80211_NODE_AUTH;
233 }
234 
235 /*
236  * Set/change the channel.  The rate set is also updated as
237  * to insure a consistent view by drivers.
238  */
239 static void
240 ieee80211_set_chan(struct ieee80211com *ic,
241 	struct ieee80211_node *ni, struct ieee80211_channel *chan)
242 {
243 	if (chan == IEEE80211_CHAN_ANYC)	/* XXX while scanning */
244 		chan = ic->ic_curchan;
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 5 GHz 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 		copy_bss(selbs, obss);
816 		ieee80211_free_node(obss);
817 	}
818 	/*
819 	 * Set the erp state (mostly the slot time) to deal with
820 	 * the auto-select case; this should be redundant if the
821 	 * mode is locked.
822 	 */
823 	ic->ic_curmode = ieee80211_chan2mode(ic, selbs->ni_chan);
824 	ic->ic_curchan = selbs->ni_chan;
825 	ieee80211_reset_erp(ic);
826 	ieee80211_wme_initparams(ic);
827 
828 	if (ic->ic_opmode == IEEE80211_M_STA)
829 		ieee80211_new_state(ic, IEEE80211_S_AUTH, -1);
830 	else
831 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
832 	return 1;
833 }
834 
835 /*
836  * Leave the specified IBSS/BSS network.  The node is assumed to
837  * be passed in with a held reference.
838  */
839 void
840 ieee80211_sta_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
841 {
842 	ic->ic_node_cleanup(ni);
843 	ieee80211_notify_node_leave(ic, ni);
844 }
845 
846 int
847 ieee80211_get_rate(const struct ieee80211_node * const ni)
848 {
849 #define	RATE(_ix)	(ni->ni_rates.rs_rates[(_ix)] & IEEE80211_RATE_VAL)
850 	int ix, rate;
851 	struct ieee80211com *ic = ni->ni_ic;
852 	const struct ieee80211_rateset *rs;
853 
854 	IASSERT(ni != NULL, ("ni != NULL"));
855 	IASSERT(ieee80211_node_refcnt(ni) > 0,
856 	    ("refcnt(ni) == %d", ieee80211_node_refcnt(ni)));
857 	IASSERT(ic != NULL, ("ic != NULL"));
858 	if (ic->ic_fixed_rate != IEEE80211_FIXED_RATE_NONE) {
859 		rs = &ic->ic_sup_rates[ic->ic_curmode];
860 		rate = rs->rs_rates[ic->ic_fixed_rate] & IEEE80211_RATE_VAL;
861 		for (ix = ni->ni_rates.rs_nrates - 1;
862 		     ix >= 0 && RATE(ix) != rate; ix--)
863 			;
864 		if (ix < 0) {
865 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG,
866 			    "%s: fixed rate %d (%d.%d Mb/s) not in rate set",
867 			    __func__, ic->ic_fixed_rate, (rate * 5) / 10,
868 			    (rate * 5) % 10);
869 			goto no_rate;
870 		}
871 	} else if (ic->ic_state == IEEE80211_S_RUN)
872 		rate = ni->ni_rates.rs_rates[ni->ni_txrate];
873 	else {
874 no_rate:
875 		rs = &ni->ni_rates;
876 		/* Choose node's lowest basic rate, or else its lowest rate. */
877 		for (ix = 0; ix < rs->rs_nrates; ix++) {
878 			if (rs->rs_rates[ix] & IEEE80211_RATE_BASIC)
879 				return rs->rs_rates[ix] & IEEE80211_RATE_VAL;
880 		}
881 		return ni->ni_rates.rs_rates[0] & IEEE80211_RATE_VAL;
882 	}
883 	return rate & IEEE80211_RATE_VAL;
884 }
885 
886 static struct ieee80211_node *
887 node_alloc(struct ieee80211_node_table *nt)
888 {
889 	struct ieee80211_node *ni;
890 
891 	MALLOC(ni, struct ieee80211_node *, sizeof(struct ieee80211_node),
892 		M_80211_NODE, M_NOWAIT | M_ZERO);
893 	return ni;
894 }
895 
896 /*
897  * Reclaim any resources in a node and reset any critical
898  * state.  Typically nodes are free'd immediately after,
899  * but in some cases the storage may be reused so we need
900  * to insure consistent state (should probably fix that).
901  */
902 static void
903 node_cleanup(struct ieee80211_node *ni)
904 {
905 #define	N(a)	(sizeof(a)/sizeof(a[0]))
906 	struct ieee80211com *ic = ni->ni_ic;
907 	int i, qlen;
908 
909 	/* NB: preserve ni_table */
910 	if (ni->ni_flags & IEEE80211_NODE_PWR_MGT) {
911 		ic->ic_ps_sta--;
912 		ni->ni_flags &= ~IEEE80211_NODE_PWR_MGT;
913 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
914 		    "[%s] power save mode off, %u sta's in ps mode\n",
915 		    ether_sprintf(ni->ni_macaddr), ic->ic_ps_sta);
916 	}
917 	/*
918 	 * Clear AREF flag that marks the authorization refcnt bump
919 	 * has happened.  This is probably not needed as the node
920 	 * should always be removed from the table so not found but
921 	 * do it just in case.
922 	 */
923 	ni->ni_flags &= ~IEEE80211_NODE_AREF;
924 
925 	/*
926 	 * Drain power save queue and, if needed, clear TIM.
927 	 */
928 	IEEE80211_NODE_SAVEQ_DRAIN(ni, qlen);
929 	if (qlen != 0 && ic->ic_set_tim != NULL)
930 		ic->ic_set_tim(ni, 0);
931 
932 	ni->ni_associd = 0;
933 	if (ni->ni_challenge != NULL) {
934 		FREE(ni->ni_challenge, M_DEVBUF);
935 		ni->ni_challenge = NULL;
936 	}
937 	/*
938 	 * Preserve SSID, WPA, and WME ie's so the bss node is
939 	 * reusable during a re-auth/re-assoc state transition.
940 	 * If we remove these data they will not be recreated
941 	 * because they come from a probe-response or beacon frame
942 	 * which cannot be expected prior to the association-response.
943 	 * This should not be an issue when operating in other modes
944 	 * as stations leaving always go through a full state transition
945 	 * which will rebuild this state.
946 	 *
947 	 * XXX does this leave us open to inheriting old state?
948 	 */
949 	for (i = 0; i < N(ni->ni_rxfrag); i++)
950 		if (ni->ni_rxfrag[i] != NULL) {
951 			m_freem(ni->ni_rxfrag[i]);
952 			ni->ni_rxfrag[i] = NULL;
953 		}
954 	/*
955 	 * Must be careful here to remove any key map entry w/o a LOR.
956 	 */
957 	ieee80211_node_delucastkey(ni);
958 #undef N
959 }
960 
961 static void
962 node_free(struct ieee80211_node *ni)
963 {
964 	struct ieee80211com *ic = ni->ni_ic;
965 
966 	ic->ic_node_cleanup(ni);
967 	if (ni->ni_wpa_ie != NULL)
968 		FREE(ni->ni_wpa_ie, M_DEVBUF);
969 	if (ni->ni_wme_ie != NULL)
970 		FREE(ni->ni_wme_ie, M_DEVBUF);
971 	IEEE80211_NODE_SAVEQ_DESTROY(ni);
972 	FREE(ni, M_80211_NODE);
973 }
974 
975 static u_int8_t
976 node_getrssi(const struct ieee80211_node *ni)
977 {
978 	return ni->ni_rssi;
979 }
980 
981 static void
982 ieee80211_setup_node(struct ieee80211_node_table *nt,
983 	struct ieee80211_node *ni, const u_int8_t *macaddr)
984 {
985 	struct ieee80211com *ic = nt->nt_ic;
986 	int hash;
987 
988 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
989 		"%s %p<%s> in %s table\n", __func__, ni,
990 		ether_sprintf(macaddr), nt->nt_name);
991 
992 	IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
993 	hash = IEEE80211_NODE_HASH(macaddr);
994 	ieee80211_node_initref(ni);		/* mark referenced */
995 	ni->ni_chan = IEEE80211_CHAN_ANYC;
996 	ni->ni_authmode = IEEE80211_AUTH_OPEN;
997 	ni->ni_txpower = ic->ic_txpowlimit;	/* max power */
998 	ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey, IEEE80211_KEYIX_NONE);
999 	ni->ni_inact_reload = nt->nt_inact_init;
1000 	ni->ni_inact = ni->ni_inact_reload;
1001 	IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
1002 
1003 	IEEE80211_NODE_LOCK(nt);
1004 	TAILQ_INSERT_TAIL(&nt->nt_node, ni, ni_list);
1005 	LIST_INSERT_HEAD(&nt->nt_hash[hash], ni, ni_hash);
1006 	ni->ni_table = nt;
1007 	ni->ni_ic = ic;
1008 	IEEE80211_NODE_UNLOCK(nt);
1009 }
1010 
1011 struct ieee80211_node *
1012 ieee80211_alloc_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
1013 {
1014 	struct ieee80211com *ic = nt->nt_ic;
1015 	struct ieee80211_node *ni;
1016 
1017 	ni = ic->ic_node_alloc(nt);
1018 	if (ni != NULL)
1019 		ieee80211_setup_node(nt, ni, macaddr);
1020 	else
1021 		ic->ic_stats.is_rx_nodealloc++;
1022 	return ni;
1023 }
1024 
1025 /*
1026  * Craft a temporary node suitable for sending a management frame
1027  * to the specified station.  We craft only as much state as we
1028  * need to do the work since the node will be immediately reclaimed
1029  * once the send completes.
1030  */
1031 struct ieee80211_node *
1032 ieee80211_tmp_node(struct ieee80211com *ic, const u_int8_t *macaddr)
1033 {
1034 	struct ieee80211_node *ni;
1035 
1036 	ni = ic->ic_node_alloc(&ic->ic_sta);
1037 	if (ni != NULL) {
1038 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1039 			"%s %p<%s>\n", __func__, ni, ether_sprintf(macaddr));
1040 
1041 		IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
1042 		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
1043 		ieee80211_node_initref(ni);		/* mark referenced */
1044 		ni->ni_txpower = ic->ic_bss->ni_txpower;
1045 		/* NB: required by ieee80211_fix_rate */
1046 		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
1047 		ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey,
1048 			IEEE80211_KEYIX_NONE);
1049 		/* XXX optimize away */
1050 		IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
1051 
1052 		ni->ni_table = NULL;		/* NB: pedantic */
1053 		ni->ni_ic = ic;
1054 	} else {
1055 		/* XXX msg */
1056 		ic->ic_stats.is_rx_nodealloc++;
1057 	}
1058 	return ni;
1059 }
1060 
1061 struct ieee80211_node *
1062 ieee80211_dup_bss(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
1063 {
1064 	struct ieee80211com *ic = nt->nt_ic;
1065 	struct ieee80211_node *ni;
1066 
1067 	ni = ic->ic_node_alloc(nt);
1068 	if (ni != NULL) {
1069 		ieee80211_setup_node(nt, ni, macaddr);
1070 		/*
1071 		 * Inherit from ic_bss.
1072 		 */
1073 		ni->ni_authmode = ic->ic_bss->ni_authmode;
1074 		ni->ni_txpower = ic->ic_bss->ni_txpower;
1075 		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
1076 		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
1077 		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
1078 		ni->ni_rsn = ic->ic_bss->ni_rsn;
1079 	} else
1080 		ic->ic_stats.is_rx_nodealloc++;
1081 	return ni;
1082 }
1083 
1084 static struct ieee80211_node *
1085 #ifdef IEEE80211_DEBUG_REFCNT
1086 _ieee80211_find_node_debug(struct ieee80211_node_table *nt,
1087 	const u_int8_t *macaddr, const char *func, int line)
1088 #else
1089 _ieee80211_find_node(struct ieee80211_node_table *nt,
1090 	const u_int8_t *macaddr)
1091 #endif
1092 {
1093 	struct ieee80211_node *ni;
1094 	int hash;
1095 
1096 	IEEE80211_NODE_LOCK_ASSERT(nt);
1097 
1098 	hash = IEEE80211_NODE_HASH(macaddr);
1099 	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1100 		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
1101 			ieee80211_ref_node(ni);	/* mark referenced */
1102 #ifdef IEEE80211_DEBUG_REFCNT
1103 			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1104 			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1105 			    func, line,
1106 			    ni, ether_sprintf(ni->ni_macaddr),
1107 			    ieee80211_node_refcnt(ni));
1108 #endif
1109 			return ni;
1110 		}
1111 	}
1112 	return NULL;
1113 }
1114 #ifdef IEEE80211_DEBUG_REFCNT
1115 #define	_ieee80211_find_node(nt, mac) \
1116 	_ieee80211_find_node_debug(nt, mac, func, line)
1117 #endif
1118 
1119 struct ieee80211_node *
1120 #ifdef IEEE80211_DEBUG_REFCNT
1121 ieee80211_find_node_debug(struct ieee80211_node_table *nt,
1122 	const u_int8_t *macaddr, const char *func, int line)
1123 #else
1124 ieee80211_find_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
1125 #endif
1126 {
1127 	struct ieee80211_node *ni;
1128 
1129 	IEEE80211_NODE_LOCK(nt);
1130 	ni = _ieee80211_find_node(nt, macaddr);
1131 	IEEE80211_NODE_UNLOCK(nt);
1132 	return ni;
1133 }
1134 
1135 /*
1136  * Fake up a node; this handles node discovery in adhoc mode.
1137  * Note that for the driver's benefit we we treat this like
1138  * an association so the driver has an opportunity to setup
1139  * it's private state.
1140  */
1141 struct ieee80211_node *
1142 ieee80211_fakeup_adhoc_node(struct ieee80211_node_table *nt,
1143 	const u_int8_t macaddr[IEEE80211_ADDR_LEN])
1144 {
1145 	struct ieee80211com *ic = nt->nt_ic;
1146 	struct ieee80211_node *ni;
1147 
1148 	ni = ieee80211_dup_bss(nt, macaddr);
1149 	if (ni != NULL) {
1150 		/* XXX no rate negotiation; just dup */
1151 		ni->ni_rates = ic->ic_bss->ni_rates;
1152 		if (ic->ic_newassoc != NULL)
1153 			ic->ic_newassoc(ni, 1);
1154 		/* XXX not right for 802.1x/WPA */
1155 		ieee80211_node_authorize(ni);
1156 	}
1157 	return ni;
1158 }
1159 
1160 #ifdef IEEE80211_DEBUG
1161 static void
1162 dump_probe_beacon(u_int8_t subtype, int isnew,
1163 	const u_int8_t mac[IEEE80211_ADDR_LEN],
1164 	const struct ieee80211_scanparams *sp)
1165 {
1166 
1167 	printf("[%s] %s%s on chan %u (bss chan %u) ",
1168 	    ether_sprintf(mac), isnew ? "new " : "",
1169 	    ieee80211_mgt_subtype_name[subtype >> IEEE80211_FC0_SUBTYPE_SHIFT],
1170 	    sp->chan, sp->bchan);
1171 	ieee80211_print_essid(sp->ssid + 2, sp->ssid[1]);
1172 	printf("\n");
1173 
1174 	if (isnew) {
1175 		printf("[%s] caps 0x%x bintval %u erp 0x%x",
1176 			ether_sprintf(mac), sp->capinfo, sp->bintval, sp->erp);
1177 		if (sp->country != NULL) {
1178 #ifdef __FreeBSD__
1179 			printf(" country info %*D",
1180 				sp->country[1], sp->country+2, " ");
1181 #else
1182 			int i;
1183 			printf(" country info");
1184 			for (i = 0; i < sp->country[1]; i++)
1185 				printf(" %02x", sp->country[i+2]);
1186 #endif
1187 		}
1188 		printf("\n");
1189 	}
1190 }
1191 #endif /* IEEE80211_DEBUG */
1192 
1193 static void
1194 saveie(u_int8_t **iep, const u_int8_t *ie)
1195 {
1196 
1197 	if (ie == NULL)
1198 		*iep = NULL;
1199 	else
1200 		ieee80211_saveie(iep, ie);
1201 }
1202 
1203 /*
1204  * Process a beacon or probe response frame.
1205  */
1206 void
1207 ieee80211_add_scan(struct ieee80211com *ic,
1208 	const struct ieee80211_scanparams *sp,
1209 	const struct ieee80211_frame *wh,
1210 	int subtype, int rssi, int rstamp)
1211 {
1212 #define	ISPROBE(_st)	((_st) == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1213 	struct ieee80211_node_table *nt = &ic->ic_scan;
1214 	struct ieee80211_node *ni;
1215 	int newnode = 0;
1216 
1217 	ni = ieee80211_find_node(nt, wh->i_addr2);
1218 	if (ni == NULL) {
1219 		/*
1220 		 * Create a new entry.
1221 		 */
1222 		ni = ic->ic_node_alloc(nt);
1223 		if (ni == NULL) {
1224 			ic->ic_stats.is_rx_nodealloc++;
1225 			return;
1226 		}
1227 		ieee80211_setup_node(nt, ni, wh->i_addr2);
1228 		/*
1229 		 * XXX inherit from ic_bss.
1230 		 */
1231 		ni->ni_authmode = ic->ic_bss->ni_authmode;
1232 		ni->ni_txpower = ic->ic_bss->ni_txpower;
1233 		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
1234 		ieee80211_set_chan(ic, ni, ic->ic_curchan);
1235 		ni->ni_rsn = ic->ic_bss->ni_rsn;
1236 		newnode = 1;
1237 	}
1238 #ifdef IEEE80211_DEBUG
1239 	if (ieee80211_msg_scan(ic) && (ic->ic_flags & IEEE80211_F_SCAN))
1240 		dump_probe_beacon(subtype, newnode, wh->i_addr2, sp);
1241 #endif
1242 	/* XXX ap beaconing multiple ssid w/ same bssid */
1243 	if (sp->ssid[1] != 0 &&
1244 	    (ISPROBE(subtype) || ni->ni_esslen == 0)) {
1245 		ni->ni_esslen = sp->ssid[1];
1246 		memset(ni->ni_essid, 0, sizeof(ni->ni_essid));
1247 		memcpy(ni->ni_essid, sp->ssid + 2, sp->ssid[1]);
1248 	}
1249 	ni->ni_scangen = ic->ic_scan.nt_scangen;
1250 	IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
1251 	ni->ni_rssi = rssi;
1252 	ni->ni_rstamp = rstamp;
1253 	memcpy(ni->ni_tstamp.data, sp->tstamp, sizeof(ni->ni_tstamp));
1254 	ni->ni_intval = sp->bintval;
1255 	ni->ni_capinfo = sp->capinfo;
1256 	ni->ni_chan = &ic->ic_channels[sp->chan];
1257 	ni->ni_fhdwell = sp->fhdwell;
1258 	ni->ni_fhindex = sp->fhindex;
1259 	ni->ni_erp = sp->erp;
1260 	if (sp->tim != NULL) {
1261 		struct ieee80211_tim_ie *ie =
1262 		    (struct ieee80211_tim_ie *) sp->tim;
1263 
1264 		ni->ni_dtim_count = ie->tim_count;
1265 		ni->ni_dtim_period = ie->tim_period;
1266 	}
1267 	/*
1268 	 * Record the byte offset from the mac header to
1269 	 * the start of the TIM information element for
1270 	 * use by hardware and/or to speedup software
1271 	 * processing of beacon frames.
1272 	 */
1273 	ni->ni_timoff = sp->timoff;
1274 	/*
1275 	 * Record optional information elements that might be
1276 	 * used by applications or drivers.
1277 	 */
1278 	saveie(&ni->ni_wme_ie, sp->wme);
1279 	saveie(&ni->ni_wpa_ie, sp->wpa);
1280 
1281 	/* NB: must be after ni_chan is setup */
1282 	ieee80211_setup_rates(ni, sp->rates, sp->xrates, IEEE80211_F_DOSORT);
1283 
1284 	if (!newnode)
1285 		ieee80211_free_node(ni);
1286 #undef ISPROBE
1287 }
1288 
1289 void
1290 ieee80211_init_neighbor(struct ieee80211com *ic, struct ieee80211_node *ni,
1291     const struct ieee80211_frame *wh, const struct ieee80211_scanparams *sp,
1292     int isnew)
1293 {
1294 	ni->ni_esslen = sp->ssid[1];
1295 	memcpy(ni->ni_essid, sp->ssid + 2, sp->ssid[1]);
1296 	IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
1297 	memcpy(ni->ni_tstamp.data, sp->tstamp, sizeof(ni->ni_tstamp));
1298 	ni->ni_intval = sp->bintval;
1299 	ni->ni_capinfo = sp->capinfo;
1300 	ni->ni_chan = ic->ic_bss->ni_chan;
1301 	ni->ni_fhdwell = sp->fhdwell;
1302 	ni->ni_fhindex = sp->fhindex;
1303 	ni->ni_erp = sp->erp;
1304 	ni->ni_timoff = sp->timoff;
1305 	if (sp->wme != NULL)
1306 		ieee80211_saveie(&ni->ni_wme_ie, sp->wme);
1307 	if (sp->wpa != NULL)
1308 		ieee80211_saveie(&ni->ni_wpa_ie, sp->wpa);
1309 
1310 	/* NB: must be after ni_chan is setup */
1311 	ieee80211_setup_rates(ni, sp->rates, sp->xrates,
1312 	    IEEE80211_F_DODEL | IEEE80211_F_DONEGO | IEEE80211_F_DOSORT);
1313 
1314 	if (ic->ic_newassoc != NULL)
1315 		ic->ic_newassoc(ni, isnew);
1316 }
1317 
1318 /*
1319  * Do node discovery in adhoc mode on receipt of a beacon
1320  * or probe response frame.  Note that for the driver's
1321  * benefit we we treat this like an association so the
1322  * driver has an opportunity to setup it's private state.
1323  */
1324 struct ieee80211_node *
1325 ieee80211_add_neighbor(struct ieee80211com *ic,
1326 	const struct ieee80211_frame *wh,
1327 	const struct ieee80211_scanparams *sp)
1328 {
1329 	struct ieee80211_node *ni;
1330 
1331 	ni = ieee80211_dup_bss(&ic->ic_sta, wh->i_addr2);/* XXX alloc_node? */
1332 	if (ni != NULL) {
1333 		ieee80211_init_neighbor(ic, ni, wh, sp, 1);
1334 		/* XXX not right for 802.1x/WPA */
1335 		ieee80211_node_authorize(ni);
1336 	}
1337 	return ni;
1338 }
1339 
1340 #define	IS_CTL(wh) \
1341 	((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_CTL)
1342 #define	IS_PSPOLL(wh) \
1343 	((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_PS_POLL)
1344 /*
1345  * Locate the node for sender, track state, and then pass the
1346  * (referenced) node up to the 802.11 layer for its use.  We
1347  * are required to pass some node so we fall back to ic_bss
1348  * when this frame is from an unknown sender.  The 802.11 layer
1349  * knows this means the sender wasn't in the node table and
1350  * acts accordingly.
1351  */
1352 struct ieee80211_node *
1353 #ifdef IEEE80211_DEBUG_REFCNT
1354 ieee80211_find_rxnode_debug(struct ieee80211com *ic,
1355 	const struct ieee80211_frame_min *wh, const char *func, int line)
1356 #else
1357 ieee80211_find_rxnode(struct ieee80211com *ic,
1358 	const struct ieee80211_frame_min *wh)
1359 #endif
1360 {
1361 	struct ieee80211_node_table *nt;
1362 	struct ieee80211_node *ni;
1363 
1364 	/* XXX may want scanned nodes in the neighbor table for adhoc */
1365 	if (ic->ic_opmode == IEEE80211_M_STA ||
1366 	    ic->ic_opmode == IEEE80211_M_MONITOR ||
1367 	    (ic->ic_flags & IEEE80211_F_SCAN))
1368 		nt = &ic->ic_scan;
1369 	else
1370 		nt = &ic->ic_sta;
1371 	/* XXX check ic_bss first in station mode */
1372 	/* XXX 4-address frames? */
1373 	IEEE80211_NODE_LOCK(nt);
1374 	if (IS_CTL(wh) && !IS_PSPOLL(wh) /*&& !IS_RTS(ah)*/)
1375 		ni = _ieee80211_find_node(nt, wh->i_addr1);
1376 	else
1377 		ni = _ieee80211_find_node(nt, wh->i_addr2);
1378 	if (ni == NULL)
1379 		ni = ieee80211_ref_node(ic->ic_bss);
1380 	IEEE80211_NODE_UNLOCK(nt);
1381 
1382 	return ni;
1383 }
1384 
1385 /*
1386  * Like ieee80211_find_rxnode but use the supplied h/w
1387  * key index as a hint to locate the node in the key
1388  * mapping table.  If an entry is present at the key
1389  * index we return it; otherwise do a normal lookup and
1390  * update the mapping table if the station has a unicast
1391  * key assigned to it.
1392  */
1393 struct ieee80211_node *
1394 #ifdef IEEE80211_DEBUG_REFCNT
1395 ieee80211_find_rxnode_withkey_debug(struct ieee80211com *ic,
1396 	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix,
1397 	const char *func, int line)
1398 #else
1399 ieee80211_find_rxnode_withkey(struct ieee80211com *ic,
1400 	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix)
1401 #endif
1402 {
1403 	struct ieee80211_node_table *nt;
1404 	struct ieee80211_node *ni;
1405 
1406 	if (ic->ic_opmode == IEEE80211_M_STA ||
1407 	    ic->ic_opmode == IEEE80211_M_MONITOR ||
1408 	    (ic->ic_flags & IEEE80211_F_SCAN))
1409 		nt = &ic->ic_scan;
1410 	else
1411 		nt = &ic->ic_sta;
1412 	IEEE80211_NODE_LOCK(nt);
1413 	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax)
1414 		ni = nt->nt_keyixmap[keyix];
1415 	else
1416 		ni = NULL;
1417 	if (ni == NULL) {
1418 		if (IS_CTL(wh) && !IS_PSPOLL(wh) /*&& !IS_RTS(ah)*/)
1419 			ni = _ieee80211_find_node(nt, wh->i_addr1);
1420 		else
1421 			ni = _ieee80211_find_node(nt, wh->i_addr2);
1422 		if (ni == NULL)
1423 			ni = ieee80211_ref_node(ic->ic_bss);
1424 		if (nt->nt_keyixmap != NULL) {
1425 			/*
1426 			 * If the station has a unicast key cache slot
1427 			 * assigned update the key->node mapping table.
1428 			 */
1429 			keyix = ni->ni_ucastkey.wk_rxkeyix;
1430 			/* XXX can keyixmap[keyix] != NULL? */
1431 			if (keyix < nt->nt_keyixmax &&
1432 			    nt->nt_keyixmap[keyix] == NULL) {
1433 				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1434 				    "%s: add key map entry %p<%s> refcnt %d\n",
1435 				    __func__, ni, ether_sprintf(ni->ni_macaddr),
1436 				    ieee80211_node_refcnt(ni)+1);
1437 				nt->nt_keyixmap[keyix] = ieee80211_ref_node(ni);
1438 			}
1439 		}
1440 	} else {
1441 		ieee80211_ref_node(ni);
1442 	}
1443 	IEEE80211_NODE_UNLOCK(nt);
1444 
1445 	return ni;
1446 }
1447 #undef IS_PSPOLL
1448 #undef IS_CTL
1449 
1450 /*
1451  * Return a reference to the appropriate node for sending
1452  * a data frame.  This handles node discovery in adhoc networks.
1453  */
1454 struct ieee80211_node *
1455 #ifdef IEEE80211_DEBUG_REFCNT
1456 ieee80211_find_txnode_debug(struct ieee80211com *ic, const u_int8_t *macaddr,
1457 	const char *func, int line)
1458 #else
1459 ieee80211_find_txnode(struct ieee80211com *ic, const u_int8_t *macaddr)
1460 #endif
1461 {
1462 	struct ieee80211_node_table *nt = &ic->ic_sta;
1463 	struct ieee80211_node *ni;
1464 
1465 	/*
1466 	 * The destination address should be in the node table
1467 	 * unless this is a multicast/broadcast frame.  We can
1468 	 * also optimize station mode operation, all frames go
1469 	 * to the bss node.
1470 	 */
1471 	/* XXX can't hold lock across dup_bss 'cuz of recursive locking */
1472 	IEEE80211_NODE_LOCK(nt);
1473 	if (ic->ic_opmode == IEEE80211_M_STA || IEEE80211_IS_MULTICAST(macaddr))
1474 		ni = ieee80211_ref_node(ic->ic_bss);
1475 	else
1476 		ni = _ieee80211_find_node(nt, macaddr);
1477 	IEEE80211_NODE_UNLOCK(nt);
1478 
1479 	if (ni == NULL) {
1480 		if (ic->ic_opmode == IEEE80211_M_IBSS ||
1481 		    ic->ic_opmode == IEEE80211_M_AHDEMO) {
1482 			/*
1483 			 * In adhoc mode cons up a node for the destination.
1484 			 * Note that we need an additional reference for the
1485 			 * caller to be consistent with _ieee80211_find_node.
1486 			 */
1487 			ni = ieee80211_fakeup_adhoc_node(nt, macaddr);
1488 			if (ni != NULL)
1489 				(void) ieee80211_ref_node(ni);
1490 		} else {
1491 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
1492 				"[%s] no node, discard frame (%s)\n",
1493 				ether_sprintf(macaddr), __func__);
1494 			ic->ic_stats.is_tx_nonode++;
1495 		}
1496 	}
1497 	return ni;
1498 }
1499 
1500 /*
1501  * Like find but search based on the channel too.
1502  */
1503 struct ieee80211_node *
1504 #ifdef IEEE80211_DEBUG_REFCNT
1505 ieee80211_find_node_with_channel_debug(struct ieee80211_node_table *nt,
1506 	const u_int8_t *macaddr, struct ieee80211_channel *chan,
1507 	const char *func, int line)
1508 #else
1509 ieee80211_find_node_with_channel(struct ieee80211_node_table *nt,
1510 	const u_int8_t *macaddr, struct ieee80211_channel *chan)
1511 #endif
1512 {
1513 	struct ieee80211_node *ni;
1514 	int hash;
1515 
1516 	hash = IEEE80211_NODE_HASH(macaddr);
1517 	IEEE80211_NODE_LOCK(nt);
1518 	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1519 		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1520 		    ni->ni_chan == chan) {
1521 			ieee80211_ref_node(ni);		/* mark referenced */
1522 			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1523 #ifdef IEEE80211_DEBUG_REFCNT
1524 			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1525 			    func, line,
1526 #else
1527 			    "%s %p<%s> refcnt %d\n", __func__,
1528 #endif
1529 			    ni, ether_sprintf(ni->ni_macaddr),
1530 			    ieee80211_node_refcnt(ni));
1531 			break;
1532 		}
1533 	}
1534 	IEEE80211_NODE_UNLOCK(nt);
1535 	return ni;
1536 }
1537 
1538 struct ieee80211_node *
1539 ieee80211_refine_node_for_beacon(struct ieee80211com *ic,
1540 	struct ieee80211_node *ni0, struct ieee80211_channel *chan,
1541 	const u_int8_t *ssid)
1542 {
1543 	struct ieee80211_node_table *nt = ni0->ni_table;
1544 	struct ieee80211_node *best, *ni;
1545 	int best_score = 0, score;
1546 
1547 	if (nt == NULL)
1548 		return ni0;
1549 
1550 	best = ni0;
1551 	if (ssid[1] == 0 || best->ni_esslen == 0)
1552 		best_score = 1;
1553 	else if (ssid[1] == best->ni_esslen &&
1554 		 memcmp(ssid + 2, best->ni_essid, ssid[1]) == 0)
1555 		best_score = 2;
1556 	else
1557 		best_score = 0;
1558 
1559 	IEEE80211_NODE_LOCK(nt);
1560 	for (ni = LIST_NEXT(ni0, ni_hash); ni != NULL;
1561 	     ni = LIST_NEXT(ni, ni_hash)) {
1562 		if (!IEEE80211_ADDR_EQ(ni->ni_macaddr, best->ni_macaddr) ||
1563 		    ni->ni_ic != best->ni_ic || ni->ni_chan != chan)
1564 			continue;
1565 
1566 		if (ssid[1] == 0 || ni->ni_esslen == 0)
1567 			score = 1;
1568 		else if (ssid[1] == ni->ni_esslen &&
1569 			 memcmp(ssid + 2, ni->ni_essid, ssid[1]) == 0)
1570 			score = 2;
1571 		else
1572 			continue;
1573 
1574 		if (score > best_score) {
1575 			best = ni;
1576 			best_score = score;
1577 		}
1578 	}
1579 	IEEE80211_NODE_UNLOCK(nt);
1580 	return best;
1581 }
1582 
1583 /*
1584  * Like find but search based on the ssid too.
1585  */
1586 struct ieee80211_node *
1587 #ifdef IEEE80211_DEBUG_REFCNT
1588 ieee80211_find_node_with_ssid_debug(struct ieee80211_node_table *nt,
1589 	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid,
1590 	const char *func, int line)
1591 #else
1592 ieee80211_find_node_with_ssid(struct ieee80211_node_table *nt,
1593 	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid)
1594 #endif
1595 {
1596 #define	MATCH_SSID(ni, ssid, ssidlen) \
1597 	(ni->ni_esslen == ssidlen && memcmp(ni->ni_essid, ssid, ssidlen) == 0)
1598 	static const u_int8_t zeromac[IEEE80211_ADDR_LEN];
1599 	struct ieee80211com *ic = nt->nt_ic;
1600 	struct ieee80211_node *ni;
1601 	int hash;
1602 
1603 	IEEE80211_NODE_LOCK(nt);
1604 	/*
1605 	 * A mac address that is all zero means match only the ssid;
1606 	 * otherwise we must match both.
1607 	 */
1608 	if (IEEE80211_ADDR_EQ(macaddr, zeromac)) {
1609 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1610 			if (MATCH_SSID(ni, ssid, ssidlen))
1611 				break;
1612 		}
1613 	} else {
1614 		hash = IEEE80211_NODE_HASH(macaddr);
1615 		LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1616 			if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1617 			    MATCH_SSID(ni, ssid, ssidlen))
1618 				break;
1619 		}
1620 	}
1621 	if (ni != NULL) {
1622 		ieee80211_ref_node(ni);	/* mark referenced */
1623 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1624 #ifdef IEEE80211_DEBUG_REFCNT
1625 		    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1626 		    func, line,
1627 #else
1628 		    "%s %p<%s> refcnt %d\n", __func__,
1629 #endif
1630 		     ni, ether_sprintf(ni->ni_macaddr),
1631 		     ieee80211_node_refcnt(ni));
1632 	}
1633 	IEEE80211_NODE_UNLOCK(nt);
1634 	return ni;
1635 #undef MATCH_SSID
1636 }
1637 
1638 static void
1639 _ieee80211_free_node(struct ieee80211_node *ni)
1640 {
1641 	struct ieee80211com *ic = ni->ni_ic;
1642 	struct ieee80211_node_table *nt = ni->ni_table;
1643 
1644 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1645 		"%s %p<%s> in %s table\n", __func__, ni,
1646 		ether_sprintf(ni->ni_macaddr),
1647 		nt != NULL ? nt->nt_name : "<gone>");
1648 
1649 	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1650 	if (nt != NULL) {
1651 		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1652 		LIST_REMOVE(ni, ni_hash);
1653 	}
1654 	ic->ic_node_free(ni);
1655 }
1656 
1657 void
1658 #ifdef IEEE80211_DEBUG_REFCNT
1659 ieee80211_free_node_debug(struct ieee80211_node *ni, const char *func, int line)
1660 #else
1661 ieee80211_free_node(struct ieee80211_node *ni)
1662 #endif
1663 {
1664 	struct ieee80211_node_table *nt = ni->ni_table;
1665 
1666 #ifdef IEEE80211_DEBUG_REFCNT
1667 	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1668 		"%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line, ni,
1669 		 ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)-1);
1670 #endif
1671 	if (nt != NULL) {
1672 		IEEE80211_NODE_LOCK(nt);
1673 		if (ieee80211_node_dectestref(ni)) {
1674 			/*
1675 			 * Last reference, reclaim state.
1676 			 */
1677 			_ieee80211_free_node(ni);
1678 		} else if (ieee80211_node_refcnt(ni) == 1 &&
1679 		    nt->nt_keyixmap != NULL) {
1680 			ieee80211_keyix keyix;
1681 			/*
1682 			 * Check for a last reference in the key mapping table.
1683 			 */
1684 			keyix = ni->ni_ucastkey.wk_rxkeyix;
1685 			if (keyix < nt->nt_keyixmax &&
1686 			    nt->nt_keyixmap[keyix] == ni) {
1687 				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1688 				    "%s: %p<%s> clear key map entry", __func__,
1689 				    ni, ether_sprintf(ni->ni_macaddr));
1690 				nt->nt_keyixmap[keyix] = NULL;
1691 				ieee80211_node_decref(ni); /* XXX needed? */
1692 				_ieee80211_free_node(ni);
1693 			}
1694 		}
1695 		IEEE80211_NODE_UNLOCK(nt);
1696 	} else {
1697 		if (ieee80211_node_dectestref(ni))
1698 			_ieee80211_free_node(ni);
1699 	}
1700 }
1701 
1702 /*
1703  * Reclaim a unicast key and clear any key cache state.
1704  */
1705 int
1706 ieee80211_node_delucastkey(struct ieee80211_node *ni)
1707 {
1708 	struct ieee80211com *ic = ni->ni_ic;
1709 	struct ieee80211_node_table *nt = &ic->ic_sta;
1710 	struct ieee80211_node *nikey;
1711 	ieee80211_keyix keyix;
1712 	int isowned, status;
1713 
1714 	/*
1715 	 * NB: We must beware of LOR here; deleting the key
1716 	 * can cause the crypto layer to block traffic updates
1717 	 * which can generate a LOR against the node table lock;
1718 	 * grab it here and stash the key index for our use below.
1719 	 *
1720 	 * Must also beware of recursion on the node table lock.
1721 	 * When called from node_cleanup we may already have
1722 	 * the node table lock held.  Unfortunately there's no
1723 	 * way to separate out this path so we must do this
1724 	 * conditionally.
1725 	 */
1726 	isowned = IEEE80211_NODE_IS_LOCKED(nt);
1727 	if (!isowned)
1728 		IEEE80211_NODE_LOCK(nt);
1729 	keyix = ni->ni_ucastkey.wk_rxkeyix;
1730 	status = ieee80211_crypto_delkey(ic, &ni->ni_ucastkey);
1731 	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax) {
1732 		nikey = nt->nt_keyixmap[keyix];
1733 		nt->nt_keyixmap[keyix] = NULL;;
1734 	} else
1735 		nikey = NULL;
1736 	if (!isowned)
1737 		IEEE80211_NODE_UNLOCK(&ic->ic_sta);
1738 
1739 	if (nikey != NULL) {
1740 		IASSERT(nikey == ni,
1741 			("key map out of sync, ni %p nikey %p", ni, nikey));
1742 		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1743 			"%s: delete key map entry %p<%s> refcnt %d\n",
1744 			__func__, ni, ether_sprintf(ni->ni_macaddr),
1745 			ieee80211_node_refcnt(ni)-1);
1746 		ieee80211_free_node(ni);
1747 	}
1748 	return status;
1749 }
1750 
1751 /*
1752  * Reclaim a node.  If this is the last reference count then
1753  * do the normal free work.  Otherwise remove it from the node
1754  * table and mark it gone by clearing the back-reference.
1755  */
1756 static void
1757 node_reclaim(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1758 {
1759 	ieee80211_keyix keyix;
1760 
1761 	IEEE80211_NODE_LOCK_ASSERT(nt);
1762 
1763 	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1764 		"%s: remove %p<%s> from %s table, refcnt %d\n",
1765 		__func__, ni, ether_sprintf(ni->ni_macaddr),
1766 		nt->nt_name, ieee80211_node_refcnt(ni)-1);
1767 	/*
1768 	 * Clear any entry in the unicast key mapping table.
1769 	 * We need to do it here so rx lookups don't find it
1770 	 * in the mapping table even if it's not in the hash
1771 	 * table.  We cannot depend on the mapping table entry
1772 	 * being cleared because the node may not be free'd.
1773 	 */
1774 	keyix = ni->ni_ucastkey.wk_rxkeyix;
1775 	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax &&
1776 	    nt->nt_keyixmap[keyix] == ni) {
1777 		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1778 			"%s: %p<%s> clear key map entry\n",
1779 			__func__, ni, ether_sprintf(ni->ni_macaddr));
1780 		nt->nt_keyixmap[keyix] = NULL;
1781 		ieee80211_node_decref(ni);	/* NB: don't need free */
1782 	}
1783 	if (!ieee80211_node_dectestref(ni)) {
1784 		/*
1785 		 * Other references are present, just remove the
1786 		 * node from the table so it cannot be found.  When
1787 		 * the references are dropped storage will be
1788 		 * reclaimed.
1789 		 */
1790 		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1791 		LIST_REMOVE(ni, ni_hash);
1792 		ni->ni_table = NULL;		/* clear reference */
1793 	} else
1794 		_ieee80211_free_node(ni);
1795 }
1796 
1797 static void
1798 ieee80211_free_allnodes_locked(struct ieee80211_node_table *nt)
1799 {
1800 	struct ieee80211com *ic = nt->nt_ic;
1801 	struct ieee80211_node *ni;
1802 
1803 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1804 		"%s: free all nodes in %s table\n", __func__, nt->nt_name);
1805 
1806 	while ((ni = TAILQ_FIRST(&nt->nt_node)) != NULL) {
1807 		if (ni->ni_associd != 0) {
1808 			if (ic->ic_auth->ia_node_leave != NULL)
1809 				ic->ic_auth->ia_node_leave(ic, ni);
1810 			IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1811 		}
1812 		node_reclaim(nt, ni);
1813 	}
1814 	ieee80211_reset_erp(ic);
1815 }
1816 
1817 static void
1818 ieee80211_free_allnodes(struct ieee80211_node_table *nt)
1819 {
1820 
1821 	IEEE80211_NODE_LOCK(nt);
1822 	ieee80211_free_allnodes_locked(nt);
1823 	IEEE80211_NODE_UNLOCK(nt);
1824 }
1825 
1826 /*
1827  * Timeout entries in the scan cache.
1828  */
1829 static void
1830 ieee80211_timeout_scan_candidates(struct ieee80211_node_table *nt)
1831 {
1832 	struct ieee80211com *ic = nt->nt_ic;
1833 	struct ieee80211_node *ni, *tni;
1834 
1835 	IEEE80211_NODE_LOCK(nt);
1836 	ni = ic->ic_bss;
1837 	/* XXX belongs elsewhere */
1838 	if (ni->ni_rxfrag[0] != NULL && ticks > ni->ni_rxfragstamp + hz) {
1839 		m_freem(ni->ni_rxfrag[0]);
1840 		ni->ni_rxfrag[0] = NULL;
1841 	}
1842 	TAILQ_FOREACH_SAFE(ni, &nt->nt_node, ni_list, tni) {
1843 		if (ni->ni_inact && --ni->ni_inact == 0) {
1844 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1845 			    "[%s] scan candidate purged from cache "
1846 			    "(refcnt %u)\n", ether_sprintf(ni->ni_macaddr),
1847 			    ieee80211_node_refcnt(ni));
1848 			node_reclaim(nt, ni);
1849 		}
1850 	}
1851 	IEEE80211_NODE_UNLOCK(nt);
1852 
1853 	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
1854 }
1855 
1856 /*
1857  * Timeout inactive stations and do related housekeeping.
1858  * Note that we cannot hold the node lock while sending a
1859  * frame as this would lead to a LOR.  Instead we use a
1860  * generation number to mark nodes that we've scanned and
1861  * drop the lock and restart a scan if we have to time out
1862  * a node.  Since we are single-threaded by virtue of
1863  * controlling the inactivity timer we can be sure this will
1864  * process each node only once.
1865  */
1866 static void
1867 ieee80211_timeout_stations(struct ieee80211_node_table *nt)
1868 {
1869 	struct ieee80211com *ic = nt->nt_ic;
1870 	struct ieee80211_node *ni;
1871 	u_int gen;
1872 	int isadhoc;
1873 
1874 	isadhoc = (ic->ic_opmode == IEEE80211_M_IBSS ||
1875 		   ic->ic_opmode == IEEE80211_M_AHDEMO);
1876 	IEEE80211_SCAN_LOCK(nt);
1877 	gen = ++nt->nt_scangen;
1878 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1879 		"%s: %s scangen %u\n", __func__, nt->nt_name, gen);
1880 restart:
1881 	IEEE80211_NODE_LOCK(nt);
1882 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1883 		if (ni->ni_scangen == gen)	/* previously handled */
1884 			continue;
1885 		ni->ni_scangen = gen;
1886 		/*
1887 		 * Ignore entries for which have yet to receive an
1888 		 * authentication frame.  These are transient and
1889 		 * will be reclaimed when the last reference to them
1890 		 * goes away (when frame xmits complete).
1891 		 */
1892 		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
1893 		    (ni->ni_flags & IEEE80211_NODE_AREF) == 0)
1894 			continue;
1895 		/*
1896 		 * Free fragment if not needed anymore
1897 		 * (last fragment older than 1s).
1898 		 * XXX doesn't belong here
1899 		 */
1900 		if (ni->ni_rxfrag[0] != NULL &&
1901 		    ticks > ni->ni_rxfragstamp + hz) {
1902 			m_freem(ni->ni_rxfrag[0]);
1903 			ni->ni_rxfrag[0] = NULL;
1904 		}
1905 		/*
1906 		 * Special case ourself; we may be idle for extended periods
1907 		 * of time and regardless reclaiming our state is wrong.
1908 		 */
1909 		if (ni == ic->ic_bss)
1910 			continue;
1911 		ni->ni_inact--;
1912 		if (ni->ni_associd != 0 || isadhoc) {
1913 			/*
1914 			 * Age frames on the power save queue. The
1915 			 * aging interval is 4 times the listen
1916 			 * interval specified by the station.  This
1917 			 * number is factored into the age calculations
1918 			 * when the frame is placed on the queue.  We
1919 			 * store ages as time differences we can check
1920 			 * and/or adjust only the head of the list.
1921 			 */
1922 			if (IEEE80211_NODE_SAVEQ_QLEN(ni) != 0) {
1923 				struct mbuf *m;
1924 				int discard = 0;
1925 
1926 				IEEE80211_NODE_SAVEQ_LOCK(ni);
1927 				while (IF_POLL(&ni->ni_savedq, m) != NULL &&
1928 				     M_AGE_GET(m) < IEEE80211_INACT_WAIT) {
1929 IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER, "[%s] discard frame, age %u\n", ether_sprintf(ni->ni_macaddr), M_AGE_GET(m));/*XXX*/
1930 					_IEEE80211_NODE_SAVEQ_DEQUEUE_HEAD(ni, m);
1931 					m_freem(m);
1932 					discard++;
1933 				}
1934 				if (m != NULL)
1935 					M_AGE_SUB(m, IEEE80211_INACT_WAIT);
1936 				IEEE80211_NODE_SAVEQ_UNLOCK(ni);
1937 
1938 				if (discard != 0) {
1939 					IEEE80211_DPRINTF(ic,
1940 					    IEEE80211_MSG_POWER,
1941 					    "[%s] discard %u frames for age\n",
1942 					    ether_sprintf(ni->ni_macaddr),
1943 					    discard);
1944 					IEEE80211_NODE_STAT_ADD(ni,
1945 						ps_discard, discard);
1946 					if (IEEE80211_NODE_SAVEQ_QLEN(ni) == 0)
1947 						ic->ic_set_tim(ni, 0);
1948 				}
1949 			}
1950 			/*
1951 			 * Probe the station before time it out.  We
1952 			 * send a null data frame which may not be
1953 			 * universally supported by drivers (need it
1954 			 * for ps-poll support so it should be...).
1955 			 */
1956 			if (0 < ni->ni_inact &&
1957 			    ni->ni_inact <= ic->ic_inact_probe) {
1958 				IEEE80211_NOTE(ic,
1959 				    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE,
1960 				    ni, "%s",
1961 				    "probe station due to inactivity");
1962 				/*
1963 				 * Grab a reference before unlocking the table
1964 				 * so the node cannot be reclaimed before we
1965 				 * send the frame. ieee80211_send_nulldata
1966 				 * understands we've done this and reclaims the
1967 				 * ref for us as needed.
1968 				 */
1969 				ieee80211_ref_node(ni);
1970 				IEEE80211_NODE_UNLOCK(nt);
1971 				ieee80211_send_nulldata(ni);
1972 				/* XXX stat? */
1973 				goto restart;
1974 			}
1975 		}
1976 		if (ni->ni_inact <= 0) {
1977 			IEEE80211_NOTE(ic,
1978 			    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE, ni,
1979 			    "station timed out due to inactivity "
1980 			    "(refcnt %u)", ieee80211_node_refcnt(ni));
1981 			/*
1982 			 * Send a deauthenticate frame and drop the station.
1983 			 * This is somewhat complicated due to reference counts
1984 			 * and locking.  At this point a station will typically
1985 			 * have a reference count of 1.  ieee80211_node_leave
1986 			 * will do a "free" of the node which will drop the
1987 			 * reference count.  But in the meantime a reference
1988 			 * will be held by the deauth frame.  The actual reclaim
1989 			 * of the node will happen either after the tx is
1990 			 * completed or by ieee80211_node_leave.
1991 			 *
1992 			 * Separately we must drop the node lock before sending
1993 			 * in case the driver takes a lock, as this will result
1994 			 * in  LOR between the node lock and the driver lock.
1995 			 */
1996 			IEEE80211_NODE_UNLOCK(nt);
1997 			if (ni->ni_associd != 0) {
1998 				IEEE80211_SEND_MGMT(ic, ni,
1999 				    IEEE80211_FC0_SUBTYPE_DEAUTH,
2000 				    IEEE80211_REASON_AUTH_EXPIRE);
2001 			}
2002 			ieee80211_node_leave(ic, ni);
2003 			ic->ic_stats.is_node_timeout++;
2004 			goto restart;
2005 		}
2006 	}
2007 	IEEE80211_NODE_UNLOCK(nt);
2008 
2009 	IEEE80211_SCAN_UNLOCK(nt);
2010 
2011 	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
2012 }
2013 
2014 void
2015 ieee80211_iterate_nodes(struct ieee80211_node_table *nt, ieee80211_iter_func *f, void *arg)
2016 {
2017 	struct ieee80211_node *ni;
2018 	u_int gen;
2019 
2020 	IEEE80211_SCAN_LOCK(nt);
2021 	gen = ++nt->nt_scangen;
2022 restart:
2023 	IEEE80211_NODE_LOCK(nt);
2024 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
2025 		if (ni->ni_scangen != gen) {
2026 			ni->ni_scangen = gen;
2027 			(void) ieee80211_ref_node(ni);
2028 			IEEE80211_NODE_UNLOCK(nt);
2029 			(*f)(arg, ni);
2030 			ieee80211_free_node(ni);
2031 			goto restart;
2032 		}
2033 	}
2034 	IEEE80211_NODE_UNLOCK(nt);
2035 
2036 	IEEE80211_SCAN_UNLOCK(nt);
2037 }
2038 
2039 void
2040 ieee80211_dump_node(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
2041 {
2042 	printf("0x%p: mac %s refcnt %d\n", ni,
2043 		ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni));
2044 	printf("\tscangen %u authmode %u flags 0x%x\n",
2045 		ni->ni_scangen, ni->ni_authmode, ni->ni_flags);
2046 	printf("\tassocid 0x%x txpower %u vlan %u\n",
2047 		ni->ni_associd, ni->ni_txpower, ni->ni_vlan);
2048 	printf("\ttxseq %u rxseq %u fragno %u rxfragstamp %u\n",
2049 		ni->ni_txseqs[0],
2050 		ni->ni_rxseqs[0] >> IEEE80211_SEQ_SEQ_SHIFT,
2051 		ni->ni_rxseqs[0] & IEEE80211_SEQ_FRAG_MASK,
2052 		ni->ni_rxfragstamp);
2053 	printf("\trstamp %u rssi %u intval %u capinfo 0x%x\n",
2054 		ni->ni_rstamp, ni->ni_rssi, ni->ni_intval, ni->ni_capinfo);
2055 	printf("\tbssid %s essid \"%.*s\" channel %u:0x%x\n",
2056 		ether_sprintf(ni->ni_bssid),
2057 		ni->ni_esslen, ni->ni_essid,
2058 		ni->ni_chan->ic_freq, ni->ni_chan->ic_flags);
2059 	printf("\tfails %u inact %u txrate %u\n",
2060 		ni->ni_fails, ni->ni_inact, ni->ni_txrate);
2061 }
2062 
2063 void
2064 ieee80211_dump_nodes(struct ieee80211_node_table *nt)
2065 {
2066 	ieee80211_iterate_nodes(nt,
2067 		(ieee80211_iter_func *) ieee80211_dump_node, nt);
2068 }
2069 
2070 /*
2071  * Handle a station joining an 11g network.
2072  */
2073 static void
2074 ieee80211_node_join_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
2075 {
2076 
2077 	/*
2078 	 * Station isn't capable of short slot time.  Bump
2079 	 * the count of long slot time stations and disable
2080 	 * use of short slot time.  Note that the actual switch
2081 	 * over to long slot time use may not occur until the
2082 	 * next beacon transmission (per sec. 7.3.1.4 of 11g).
2083 	 */
2084 	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
2085 		ic->ic_longslotsta++;
2086 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2087 		    "[%s] station needs long slot time, count %d\n",
2088 		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
2089 		/* XXX vap's w/ conflicting needs won't work */
2090 		ieee80211_set_shortslottime(ic, 0);
2091 	}
2092 	/*
2093 	 * If the new station is not an ERP station
2094 	 * then bump the counter and enable protection
2095 	 * if configured.
2096 	 */
2097 	if (!ieee80211_iserp_rateset(ic, &ni->ni_rates)) {
2098 		ic->ic_nonerpsta++;
2099 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2100 		    "[%s] station is !ERP, %d non-ERP stations associated\n",
2101 		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
2102 		/*
2103 		 * If protection is configured, enable it.
2104 		 */
2105 		if (ic->ic_protmode != IEEE80211_PROT_NONE) {
2106 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2107 			    "%s: enable use of protection\n", __func__);
2108 			ic->ic_flags |= IEEE80211_F_USEPROT;
2109 		}
2110 		/*
2111 		 * If station does not support short preamble
2112 		 * then we must enable use of Barker preamble.
2113 		 */
2114 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE) == 0) {
2115 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2116 			    "[%s] station needs long preamble\n",
2117 			    ether_sprintf(ni->ni_macaddr));
2118 			ic->ic_flags |= IEEE80211_F_USEBARKER;
2119 			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
2120 		}
2121 	} else
2122 		ni->ni_flags |= IEEE80211_NODE_ERP;
2123 }
2124 
2125 void
2126 ieee80211_node_join(struct ieee80211com *ic, struct ieee80211_node *ni, int resp)
2127 {
2128 	int newassoc;
2129 
2130 	if (ni->ni_associd == 0) {
2131 		u_int16_t aid;
2132 
2133 		/*
2134 		 * It would be good to search the bitmap
2135 		 * more efficiently, but this will do for now.
2136 		 */
2137 		for (aid = 1; aid < ic->ic_max_aid; aid++) {
2138 			if (!IEEE80211_AID_ISSET(aid,
2139 			    ic->ic_aid_bitmap))
2140 				break;
2141 		}
2142 		if (aid >= ic->ic_max_aid) {
2143 			IEEE80211_SEND_MGMT(ic, ni, resp,
2144 			    IEEE80211_REASON_ASSOC_TOOMANY);
2145 			ieee80211_node_leave(ic, ni);
2146 			return;
2147 		}
2148 		ni->ni_associd = aid | 0xc000;
2149 		IEEE80211_AID_SET(ni->ni_associd, ic->ic_aid_bitmap);
2150 		ic->ic_sta_assoc++;
2151 		newassoc = 1;
2152 		if (ic->ic_curmode == IEEE80211_MODE_11G)
2153 			ieee80211_node_join_11g(ic, ni);
2154 	} else
2155 		newassoc = 0;
2156 
2157 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
2158 	    "[%s] station %sassociated at aid %d: %s preamble, %s slot time%s%s\n",
2159 	    ether_sprintf(ni->ni_macaddr), newassoc ? "" : "re",
2160 	    IEEE80211_NODE_AID(ni),
2161 	    ic->ic_flags & IEEE80211_F_SHPREAMBLE ? "short" : "long",
2162 	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long",
2163 	    ic->ic_flags & IEEE80211_F_USEPROT ? ", protection" : "",
2164 	    ni->ni_flags & IEEE80211_NODE_QOS ? ", QoS" : ""
2165 	);
2166 
2167 	/* give driver a chance to setup state like ni_txrate */
2168 	if (ic->ic_newassoc != NULL)
2169 		ic->ic_newassoc(ni, newassoc);
2170 	ni->ni_inact_reload = ic->ic_inact_auth;
2171 	ni->ni_inact = ni->ni_inact_reload;
2172 	IEEE80211_SEND_MGMT(ic, ni, resp, IEEE80211_STATUS_SUCCESS);
2173 	/* tell the authenticator about new station */
2174 	if (ic->ic_auth->ia_node_join != NULL)
2175 		ic->ic_auth->ia_node_join(ic, ni);
2176 	ieee80211_notify_node_join(ic, ni, newassoc);
2177 }
2178 
2179 /*
2180  * Handle a station leaving an 11g network.
2181  */
2182 static void
2183 ieee80211_node_leave_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
2184 {
2185 
2186 	IASSERT(ic->ic_curmode == IEEE80211_MODE_11G,
2187 	     ("not in 11g, bss %u:0x%x, curmode %u", ni->ni_chan->ic_freq,
2188 	      ni->ni_chan->ic_flags, ic->ic_curmode));
2189 
2190 	/*
2191 	 * If a long slot station do the slot time bookkeeping.
2192 	 */
2193 	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
2194 		IASSERT(ic->ic_longslotsta > 0,
2195 		    ("bogus long slot station count %d", ic->ic_longslotsta));
2196 		ic->ic_longslotsta--;
2197 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2198 		    "[%s] long slot time station leaves, count now %d\n",
2199 		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
2200 		if (ic->ic_longslotsta == 0) {
2201 			/*
2202 			 * Re-enable use of short slot time if supported
2203 			 * and not operating in IBSS mode (per spec).
2204 			 */
2205 			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
2206 			    ic->ic_opmode != IEEE80211_M_IBSS) {
2207 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2208 				    "%s: re-enable use of short slot time\n",
2209 				    __func__);
2210 				ieee80211_set_shortslottime(ic, 1);
2211 			}
2212 		}
2213 	}
2214 	/*
2215 	 * If a non-ERP station do the protection-related bookkeeping.
2216 	 */
2217 	if ((ni->ni_flags & IEEE80211_NODE_ERP) == 0) {
2218 		IASSERT(ic->ic_nonerpsta > 0,
2219 		    ("bogus non-ERP station count %d", ic->ic_nonerpsta));
2220 		ic->ic_nonerpsta--;
2221 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2222 		    "[%s] non-ERP station leaves, count now %d\n",
2223 		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
2224 		if (ic->ic_nonerpsta == 0) {
2225 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2226 				"%s: disable use of protection\n", __func__);
2227 			ic->ic_flags &= ~IEEE80211_F_USEPROT;
2228 			/* XXX verify mode? */
2229 			if (ic->ic_caps & IEEE80211_C_SHPREAMBLE) {
2230 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2231 				    "%s: re-enable use of short preamble\n",
2232 				    __func__);
2233 				ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
2234 				ic->ic_flags &= ~IEEE80211_F_USEBARKER;
2235 			}
2236 		}
2237 	}
2238 }
2239 
2240 /*
2241  * Handle bookkeeping for station deauthentication/disassociation
2242  * when operating as an ap.
2243  */
2244 void
2245 ieee80211_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
2246 {
2247 	struct ieee80211_node_table *nt = ni->ni_table;
2248 
2249 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
2250 	    "[%s] station with aid %d leaves\n",
2251 	    ether_sprintf(ni->ni_macaddr), IEEE80211_NODE_AID(ni));
2252 
2253 	IASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
2254 		ic->ic_opmode == IEEE80211_M_IBSS ||
2255 		ic->ic_opmode == IEEE80211_M_AHDEMO,
2256 		("unexpected operating mode %u", ic->ic_opmode));
2257 	/*
2258 	 * If node wasn't previously associated all
2259 	 * we need to do is reclaim the reference.
2260 	 */
2261 	/* XXX ibss mode bypasses 11g and notification */
2262 	if (ni->ni_associd == 0)
2263 		goto done;
2264 	/*
2265 	 * Tell the authenticator the station is leaving.
2266 	 * Note that we must do this before yanking the
2267 	 * association id as the authenticator uses the
2268 	 * associd to locate it's state block.
2269 	 */
2270 	if (ic->ic_auth->ia_node_leave != NULL)
2271 		ic->ic_auth->ia_node_leave(ic, ni);
2272 	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
2273 	ni->ni_associd = 0;
2274 	ic->ic_sta_assoc--;
2275 
2276 	if (ic->ic_curmode == IEEE80211_MODE_11G)
2277 		ieee80211_node_leave_11g(ic, ni);
2278 	/*
2279 	 * Cleanup station state.  In particular clear various
2280 	 * state that might otherwise be reused if the node
2281 	 * is reused before the reference count goes to zero
2282 	 * (and memory is reclaimed).
2283 	 */
2284 	ieee80211_sta_leave(ic, ni);
2285 done:
2286 	/*
2287 	 * Remove the node from any table it's recorded in and
2288 	 * drop the caller's reference.  Removal from the table
2289 	 * is important to insure the node is not reprocessed
2290 	 * for inactivity.
2291 	 */
2292 	if (nt != NULL) {
2293 		IEEE80211_NODE_LOCK(nt);
2294 		node_reclaim(nt, ni);
2295 		IEEE80211_NODE_UNLOCK(nt);
2296 	} else
2297 		ieee80211_free_node(ni);
2298 }
2299 
2300 u_int8_t
2301 ieee80211_getrssi(struct ieee80211com *ic)
2302 {
2303 #define	NZ(x)	((x) == 0 ? 1 : (x))
2304 	struct ieee80211_node_table *nt = &ic->ic_sta;
2305 	u_int32_t rssi_samples, rssi_total;
2306 	struct ieee80211_node *ni;
2307 
2308 	rssi_total = 0;
2309 	rssi_samples = 0;
2310 	switch (ic->ic_opmode) {
2311 	case IEEE80211_M_IBSS:		/* average of all ibss neighbors */
2312 		/* XXX locking */
2313 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
2314 			if (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) {
2315 				rssi_samples++;
2316 				rssi_total += ic->ic_node_getrssi(ni);
2317 			}
2318 		break;
2319 	case IEEE80211_M_AHDEMO:	/* average of all neighbors */
2320 		/* XXX locking */
2321 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
2322 			rssi_samples++;
2323 			rssi_total += ic->ic_node_getrssi(ni);
2324 		}
2325 		break;
2326 	case IEEE80211_M_HOSTAP:	/* average of all associated stations */
2327 #ifndef IEEE80211_NO_HOSTAP
2328 		/* XXX locking */
2329 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
2330 			if (IEEE80211_AID(ni->ni_associd) != 0) {
2331 				rssi_samples++;
2332 				rssi_total += ic->ic_node_getrssi(ni);
2333 			}
2334 #endif /* !IEEE80211_NO_HOSTAP */
2335 		break;
2336 	case IEEE80211_M_MONITOR:	/* XXX */
2337 	case IEEE80211_M_STA:		/* use stats from associated ap */
2338 	default:
2339 		if (ic->ic_bss != NULL)
2340 			rssi_total = ic->ic_node_getrssi(ic->ic_bss);
2341 		rssi_samples = 1;
2342 		break;
2343 	}
2344 	return rssi_total / NZ(rssi_samples);
2345 #undef NZ
2346 }
2347 
2348 /*
2349  * Indicate whether there are frames queued for a station in power-save mode.
2350  */
2351 static void
2352 ieee80211_set_tim(struct ieee80211_node *ni, int set)
2353 {
2354 	struct ieee80211com *ic = ni->ni_ic;
2355 	u_int16_t aid;
2356 
2357 	IASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
2358 		ic->ic_opmode == IEEE80211_M_IBSS,
2359 		("operating mode %u", ic->ic_opmode));
2360 
2361 	aid = IEEE80211_AID(ni->ni_associd);
2362 	IASSERT(aid < ic->ic_max_aid,
2363 		("bogus aid %u, max %u", aid, ic->ic_max_aid));
2364 
2365 	IEEE80211_BEACON_LOCK(ic);
2366 	if (set != (isset(ic->ic_tim_bitmap, aid) != 0)) {
2367 		if (set) {
2368 			setbit(ic->ic_tim_bitmap, aid);
2369 			ic->ic_ps_pending++;
2370 		} else {
2371 			clrbit(ic->ic_tim_bitmap, aid);
2372 			ic->ic_ps_pending--;
2373 		}
2374 		ic->ic_flags |= IEEE80211_F_TIMUPDATE;
2375 	}
2376 	IEEE80211_BEACON_UNLOCK(ic);
2377 }
2378 
2379 /*
2380  * Node table support.
2381  */
2382 
2383 static void
2384 ieee80211_node_table_init(struct ieee80211com *ic,
2385 	struct ieee80211_node_table *nt,
2386 	const char *name, int inact, int keyixmax,
2387 	void (*timeout)(struct ieee80211_node_table *))
2388 {
2389 
2390 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
2391 		"%s %s table, inact %u\n", __func__, name, inact);
2392 
2393 	nt->nt_ic = ic;
2394 	/* XXX need unit */
2395 	IEEE80211_NODE_LOCK_INIT(nt, ic->ic_ifp->if_xname);
2396 	IEEE80211_SCAN_LOCK_INIT(nt, ic->ic_ifp->if_xname);
2397 	TAILQ_INIT(&nt->nt_node);
2398 	nt->nt_name = name;
2399 	nt->nt_scangen = 1;
2400 	nt->nt_inact_init = inact;
2401 	nt->nt_timeout = timeout;
2402 	nt->nt_keyixmax = keyixmax;
2403 	if (nt->nt_keyixmax > 0) {
2404 		nt->nt_keyixmap = malloc(keyixmax *
2405 		    sizeof(struct ieee80211_node *), M_80211_NODE,
2406 		    M_NOWAIT | M_ZERO);
2407 		if (nt->nt_keyixmap == NULL)
2408 			if_printf(ic->ic_ifp,
2409 			    "Cannot allocate key index map with %u entries\n",
2410 			    keyixmax);
2411 	} else
2412 		nt->nt_keyixmap = NULL;
2413 }
2414 
2415 void
2416 ieee80211_node_table_reset(struct ieee80211_node_table *nt)
2417 {
2418 
2419 	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
2420 		"%s %s table\n", __func__, nt->nt_name);
2421 
2422 	IEEE80211_NODE_LOCK(nt);
2423 	nt->nt_inact_timer = 0;
2424 	ieee80211_free_allnodes_locked(nt);
2425 	IEEE80211_NODE_UNLOCK(nt);
2426 }
2427 
2428 static void
2429 ieee80211_node_table_cleanup(struct ieee80211_node_table *nt)
2430 {
2431 
2432 	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
2433 		"%s %s table\n", __func__, nt->nt_name);
2434 
2435 	IEEE80211_NODE_LOCK(nt);
2436 	ieee80211_free_allnodes_locked(nt);
2437 	if (nt->nt_keyixmap != NULL) {
2438 		/* XXX verify all entries are NULL */
2439 		int i;
2440 		for (i = 0; i < nt->nt_keyixmax; i++)
2441 			if (nt->nt_keyixmap[i] != NULL)
2442 				printf("%s: %s[%u] still active\n", __func__,
2443 					nt->nt_name, i);
2444 		FREE(nt->nt_keyixmap, M_80211_NODE);
2445 		nt->nt_keyixmap = NULL;
2446 	}
2447 	IEEE80211_SCAN_LOCK_DESTROY(nt);
2448 	IEEE80211_NODE_LOCK_DESTROY(nt);
2449 }
2450