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