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