xref: /freebsd/sys/net80211/ieee80211_node.c (revision 6af83ee0d2941d18880b6aaa2b4facd1d30c6106)
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 static struct ieee80211_node *node_alloc(struct ieee80211_node_table *);
53 static void node_cleanup(struct ieee80211_node *);
54 static void node_free(struct ieee80211_node *);
55 static u_int8_t node_getrssi(const struct ieee80211_node *);
56 
57 static void ieee80211_setup_node(struct ieee80211_node_table *,
58 		struct ieee80211_node *, const u_int8_t *);
59 static void _ieee80211_free_node(struct ieee80211_node *);
60 static void ieee80211_free_allnodes(struct ieee80211_node_table *);
61 
62 static void ieee80211_timeout_scan_candidates(struct ieee80211_node_table *);
63 static void ieee80211_timeout_stations(struct ieee80211_node_table *);
64 
65 static void ieee80211_set_tim(struct ieee80211com *,
66 		struct ieee80211_node *, int set);
67 
68 static void ieee80211_node_table_init(struct ieee80211com *ic,
69 	struct ieee80211_node_table *nt, const char *name, int inact,
70 	void (*timeout)(struct ieee80211_node_table *));
71 static void ieee80211_node_table_cleanup(struct ieee80211_node_table *nt);
72 
73 MALLOC_DEFINE(M_80211_NODE, "80211node", "802.11 node state");
74 
75 void
76 ieee80211_node_attach(struct ieee80211com *ic)
77 {
78 
79 	ieee80211_node_table_init(ic, &ic->ic_sta, "station",
80 		IEEE80211_INACT_INIT, ieee80211_timeout_stations);
81 	ieee80211_node_table_init(ic, &ic->ic_scan, "scan",
82 		IEEE80211_INACT_SCAN, ieee80211_timeout_scan_candidates);
83 
84 	ic->ic_node_alloc = node_alloc;
85 	ic->ic_node_free = node_free;
86 	ic->ic_node_cleanup = node_cleanup;
87 	ic->ic_node_getrssi = node_getrssi;
88 
89 	/* default station inactivity timer setings */
90 	ic->ic_inact_init = IEEE80211_INACT_INIT;
91 	ic->ic_inact_auth = IEEE80211_INACT_AUTH;
92 	ic->ic_inact_run = IEEE80211_INACT_RUN;
93 	ic->ic_inact_probe = IEEE80211_INACT_PROBE;
94 
95 	/* XXX defer */
96 	if (ic->ic_max_aid == 0)
97 		ic->ic_max_aid = IEEE80211_AID_DEF;
98 	else if (ic->ic_max_aid > IEEE80211_AID_MAX)
99 		ic->ic_max_aid = IEEE80211_AID_MAX;
100 	MALLOC(ic->ic_aid_bitmap, u_int32_t *,
101 		howmany(ic->ic_max_aid, 32) * sizeof(u_int32_t),
102 		M_DEVBUF, M_NOWAIT | M_ZERO);
103 	if (ic->ic_aid_bitmap == NULL) {
104 		/* XXX no way to recover */
105 		printf("%s: no memory for AID bitmap!\n", __func__);
106 		ic->ic_max_aid = 0;
107 	}
108 
109 	/* XXX defer until using hostap/ibss mode */
110 	ic->ic_tim_len = howmany(ic->ic_max_aid, 8) * sizeof(u_int8_t);
111 	MALLOC(ic->ic_tim_bitmap, u_int8_t *, ic->ic_tim_len,
112 		M_DEVBUF, M_NOWAIT | M_ZERO);
113 	if (ic->ic_tim_bitmap == NULL) {
114 		/* XXX no way to recover */
115 		printf("%s: no memory for TIM bitmap!\n", __func__);
116 	}
117 	ic->ic_set_tim = ieee80211_set_tim;	/* NB: driver should override */
118 }
119 
120 void
121 ieee80211_node_lateattach(struct ieee80211com *ic)
122 {
123 	struct ieee80211_node *ni;
124 	struct ieee80211_rsnparms *rsn;
125 
126 	ni = ieee80211_alloc_node(&ic->ic_scan, ic->ic_myaddr);
127 	KASSERT(ni != NULL, ("unable to setup inital BSS node"));
128 	/*
129 	 * Setup "global settings" in the bss node so that
130 	 * each new station automatically inherits them.
131 	 */
132 	rsn = &ni->ni_rsn;
133 	/* WEP, TKIP, and AES-CCM are always supported */
134 	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_WEP;
135 	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_TKIP;
136 	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_AES_CCM;
137 	if (ic->ic_caps & IEEE80211_C_AES)
138 		rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_AES_OCB;
139 	if (ic->ic_caps & IEEE80211_C_CKIP)
140 		rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_CKIP;
141 	/*
142 	 * Default unicast cipher to WEP for 802.1x use.  If
143 	 * WPA is enabled the management code will set these
144 	 * values to reflect.
145 	 */
146 	rsn->rsn_ucastcipher = IEEE80211_CIPHER_WEP;
147 	rsn->rsn_ucastkeylen = 104 / NBBY;
148 	/*
149 	 * WPA says the multicast cipher is the lowest unicast
150 	 * cipher supported.  But we skip WEP which would
151 	 * otherwise be used based on this criteria.
152 	 */
153 	rsn->rsn_mcastcipher = IEEE80211_CIPHER_TKIP;
154 	rsn->rsn_mcastkeylen = 128 / NBBY;
155 
156 	/*
157 	 * We support both WPA-PSK and 802.1x; the one used
158 	 * is determined by the authentication mode and the
159 	 * setting of the PSK state.
160 	 */
161 	rsn->rsn_keymgmtset = WPA_ASE_8021X_UNSPEC | WPA_ASE_8021X_PSK;
162 	rsn->rsn_keymgmt = WPA_ASE_8021X_PSK;
163 
164 	ic->ic_bss = ieee80211_ref_node(ni);		/* hold reference */
165 	ic->ic_auth = ieee80211_authenticator_get(ni->ni_authmode);
166 }
167 
168 void
169 ieee80211_node_detach(struct ieee80211com *ic)
170 {
171 
172 	if (ic->ic_bss != NULL) {
173 		ieee80211_free_node(ic->ic_bss);
174 		ic->ic_bss = NULL;
175 	}
176 	ieee80211_node_table_cleanup(&ic->ic_scan);
177 	ieee80211_node_table_cleanup(&ic->ic_sta);
178 	if (ic->ic_aid_bitmap != NULL) {
179 		FREE(ic->ic_aid_bitmap, M_DEVBUF);
180 		ic->ic_aid_bitmap = NULL;
181 	}
182 	if (ic->ic_tim_bitmap != NULL) {
183 		FREE(ic->ic_tim_bitmap, M_DEVBUF);
184 		ic->ic_tim_bitmap = NULL;
185 	}
186 }
187 
188 /*
189  * Port authorize/unauthorize interfaces for use by an authenticator.
190  */
191 
192 void
193 ieee80211_node_authorize(struct ieee80211com *ic, struct ieee80211_node *ni)
194 {
195 	ni->ni_flags |= IEEE80211_NODE_AUTH;
196 	ni->ni_inact_reload = ic->ic_inact_run;
197 }
198 
199 void
200 ieee80211_node_unauthorize(struct ieee80211com *ic, struct ieee80211_node *ni)
201 {
202 	ni->ni_flags &= ~IEEE80211_NODE_AUTH;
203 }
204 
205 /*
206  * Set/change the channel.  The rate set is also updated as
207  * to insure a consistent view by drivers.
208  */
209 static __inline void
210 ieee80211_set_chan(struct ieee80211com *ic,
211 	struct ieee80211_node *ni, struct ieee80211_channel *chan)
212 {
213 	ni->ni_chan = chan;
214 	ni->ni_rates = ic->ic_sup_rates[ieee80211_chan2mode(ic, chan)];
215 }
216 
217 /*
218  * AP scanning support.
219  */
220 
221 #ifdef IEEE80211_DEBUG
222 static void
223 dump_chanlist(const u_char chans[])
224 {
225 	const char *sep;
226 	int i;
227 
228 	sep = " ";
229 	for (i = 0; i < IEEE80211_CHAN_MAX; i++)
230 		if (isset(chans, i)) {
231 			printf("%s%u", sep, i);
232 			sep = ", ";
233 		}
234 }
235 #endif /* IEEE80211_DEBUG */
236 
237 /*
238  * Initialize the channel set to scan based on the
239  * of available channels and the current PHY mode.
240  */
241 static void
242 ieee80211_reset_scan(struct ieee80211com *ic)
243 {
244 
245 	/* XXX ic_des_chan should be handled with ic_chan_active */
246 	if (ic->ic_des_chan != IEEE80211_CHAN_ANYC) {
247 		memset(ic->ic_chan_scan, 0, sizeof(ic->ic_chan_scan));
248 		setbit(ic->ic_chan_scan,
249 			ieee80211_chan2ieee(ic, ic->ic_des_chan));
250 	} else
251 		memcpy(ic->ic_chan_scan, ic->ic_chan_active,
252 			sizeof(ic->ic_chan_active));
253 	/* NB: hack, setup so next_scan starts with the first channel */
254 	if (ic->ic_bss->ni_chan == IEEE80211_CHAN_ANYC)
255 		ieee80211_set_chan(ic, ic->ic_bss,
256 			&ic->ic_channels[IEEE80211_CHAN_MAX]);
257 #ifdef IEEE80211_DEBUG
258 	if (ieee80211_msg_scan(ic)) {
259 		printf("%s: scan set:", __func__);
260 		dump_chanlist(ic->ic_chan_scan);
261 		printf(" start chan %u\n",
262 			ieee80211_chan2ieee(ic, ic->ic_bss->ni_chan));
263 	}
264 #endif /* IEEE80211_DEBUG */
265 }
266 
267 /*
268  * Begin an active scan.
269  */
270 void
271 ieee80211_begin_scan(struct ieee80211com *ic, int reset)
272 {
273 
274 	ic->ic_scan.nt_scangen++;
275 	/*
276 	 * In all but hostap mode scanning starts off in
277 	 * an active mode before switching to passive.
278 	 */
279 	if (ic->ic_opmode != IEEE80211_M_HOSTAP) {
280 		ic->ic_flags |= IEEE80211_F_ASCAN;
281 		ic->ic_stats.is_scan_active++;
282 	} else
283 		ic->ic_stats.is_scan_passive++;
284 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
285 		"begin %s scan in %s mode, scangen %u\n",
286 		(ic->ic_flags & IEEE80211_F_ASCAN) ?  "active" : "passive",
287 		ieee80211_phymode_name[ic->ic_curmode], ic->ic_scan.nt_scangen);
288 	/*
289 	 * Clear scan state and flush any previously seen AP's.
290 	 */
291 	ieee80211_reset_scan(ic);
292 	if (reset)
293 		ieee80211_free_allnodes(&ic->ic_scan);
294 
295 	ic->ic_flags |= IEEE80211_F_SCAN;
296 
297 	/* Scan the next channel. */
298 	ieee80211_next_scan(ic);
299 }
300 
301 /*
302  * Switch to the next channel marked for scanning.
303  */
304 int
305 ieee80211_next_scan(struct ieee80211com *ic)
306 {
307 	struct ieee80211_channel *chan;
308 
309 	/*
310 	 * Insure any previous mgt frame timeouts don't fire.
311 	 * This assumes the driver does the right thing in
312 	 * flushing anything queued in the driver and below.
313 	 */
314 	ic->ic_mgt_timer = 0;
315 
316 	chan = ic->ic_bss->ni_chan;
317 	do {
318 		if (++chan > &ic->ic_channels[IEEE80211_CHAN_MAX])
319 			chan = &ic->ic_channels[0];
320 		if (isset(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan))) {
321 			clrbit(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan));
322 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
323 			    "%s: chan %d->%d\n", __func__,
324 			    ieee80211_chan2ieee(ic, ic->ic_bss->ni_chan),
325 			    ieee80211_chan2ieee(ic, chan));
326 			ieee80211_set_chan(ic, ic->ic_bss, chan);
327 #ifdef notyet
328 			/* XXX driver state change */
329 			/*
330 			 * Scan next channel. If doing an active scan
331 			 * and the channel is not marked passive-only
332 			 * then send a probe request.  Otherwise just
333 			 * listen for beacons on the channel.
334 			 */
335 			if ((ic->ic_flags & IEEE80211_F_ASCAN) &&
336 			    (ni->ni_chan->ic_flags & IEEE80211_CHAN_PASSIVE) == 0) {
337 				IEEE80211_SEND_MGMT(ic, ni,
338 				    IEEE80211_FC0_SUBTYPE_PROBE_REQ, 0);
339 			}
340 #else
341 			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
342 #endif
343 			return 1;
344 		}
345 	} while (chan != ic->ic_bss->ni_chan);
346 	ieee80211_end_scan(ic);
347 	return 0;
348 }
349 
350 static __inline void
351 copy_bss(struct ieee80211_node *nbss, const struct ieee80211_node *obss)
352 {
353 	/* propagate useful state */
354 	nbss->ni_authmode = obss->ni_authmode;
355 	nbss->ni_txpower = obss->ni_txpower;
356 	nbss->ni_vlan = obss->ni_vlan;
357 	nbss->ni_rsn = obss->ni_rsn;
358 	/* XXX statistics? */
359 }
360 
361 void
362 ieee80211_create_ibss(struct ieee80211com* ic, struct ieee80211_channel *chan)
363 {
364 	struct ieee80211_node_table *nt;
365 	struct ieee80211_node *ni;
366 
367 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
368 		"%s: creating ibss\n", __func__);
369 
370 	/*
371 	 * Create the station/neighbor table.  Note that for adhoc
372 	 * mode we make the initial inactivity timer longer since
373 	 * we create nodes only through discovery and they typically
374 	 * are long-lived associations.
375 	 */
376 	nt = &ic->ic_sta;
377 	IEEE80211_NODE_LOCK(nt);
378 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
379 		nt->nt_name = "station";
380 		nt->nt_inact_init = ic->ic_inact_init;
381 	} else {
382 		nt->nt_name = "neighbor";
383 		nt->nt_inact_init = ic->ic_inact_run;
384 	}
385 	IEEE80211_NODE_UNLOCK(nt);
386 
387 	ni = ieee80211_alloc_node(nt, ic->ic_myaddr);
388 	if (ni == NULL) {
389 		/* XXX recovery? */
390 		return;
391 	}
392 	IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_myaddr);
393 	ni->ni_esslen = ic->ic_des_esslen;
394 	memcpy(ni->ni_essid, ic->ic_des_essid, ni->ni_esslen);
395 	copy_bss(ni, ic->ic_bss);
396 	ni->ni_intval = ic->ic_lintval;
397 	if (ic->ic_flags & IEEE80211_F_PRIVACY)
398 		ni->ni_capinfo |= IEEE80211_CAPINFO_PRIVACY;
399 	if (ic->ic_phytype == IEEE80211_T_FH) {
400 		ni->ni_fhdwell = 200;	/* XXX */
401 		ni->ni_fhindex = 1;
402 	}
403 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
404 		ic->ic_flags |= IEEE80211_F_SIBSS;
405 		ni->ni_capinfo |= IEEE80211_CAPINFO_IBSS;	/* XXX */
406 		ni->ni_bssid[0] |= 0x02;	/* local bit for IBSS */
407 	}
408 	/*
409 	 * Fix the channel and related attributes.
410 	 */
411 	ieee80211_set_chan(ic, ni, chan);
412 	ic->ic_curmode = ieee80211_chan2mode(ic, chan);
413 	/*
414 	 * Do mode-specific rate setup.
415 	 */
416 	if (ic->ic_curmode == IEEE80211_MODE_11G) {
417 		/*
418 		 * Use a mixed 11b/11g rate set.
419 		 */
420 		ieee80211_set11gbasicrates(&ni->ni_rates, IEEE80211_MODE_11G);
421 	} else if (ic->ic_curmode == IEEE80211_MODE_11B) {
422 		/*
423 		 * Force pure 11b rate set.
424 		 */
425 		ieee80211_set11gbasicrates(&ni->ni_rates, IEEE80211_MODE_11B);
426 	}
427 
428 	(void) ieee80211_sta_join(ic, ieee80211_ref_node(ni));
429 }
430 
431 void
432 ieee80211_reset_bss(struct ieee80211com *ic)
433 {
434 	struct ieee80211_node *ni, *obss;
435 
436 	ieee80211_node_table_reset(&ic->ic_scan);
437 	ieee80211_node_table_reset(&ic->ic_sta);
438 
439 	ni = ieee80211_alloc_node(&ic->ic_scan, ic->ic_myaddr);
440 	KASSERT(ni != NULL, ("unable to setup inital BSS node"));
441 	obss = ic->ic_bss;
442 	ic->ic_bss = ieee80211_ref_node(ni);
443 	if (obss != NULL) {
444 		copy_bss(ni, obss);
445 		ni->ni_intval = ic->ic_lintval;
446 		ieee80211_free_node(obss);
447 	}
448 }
449 
450 static int
451 ieee80211_match_bss(struct ieee80211com *ic, struct ieee80211_node *ni)
452 {
453         u_int8_t rate;
454         int fail;
455 
456 	fail = 0;
457 	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
458 		fail |= 0x01;
459 	if (ic->ic_des_chan != IEEE80211_CHAN_ANYC &&
460 	    ni->ni_chan != ic->ic_des_chan)
461 		fail |= 0x01;
462 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
463 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
464 			fail |= 0x02;
465 	} else {
466 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
467 			fail |= 0x02;
468 	}
469 	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
470 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
471 			fail |= 0x04;
472 	} else {
473 		/* XXX does this mean privacy is supported or required? */
474 		if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
475 			fail |= 0x04;
476 	}
477 	rate = ieee80211_fix_rate(ic, ni,
478 			IEEE80211_F_DONEGO | IEEE80211_F_DOFRATE);
479 	if (rate & IEEE80211_RATE_BASIC)
480 		fail |= 0x08;
481 	if (ic->ic_des_esslen != 0 &&
482 	    (ni->ni_esslen != ic->ic_des_esslen ||
483 	     memcmp(ni->ni_essid, ic->ic_des_essid, ic->ic_des_esslen) != 0))
484 		fail |= 0x10;
485 	if ((ic->ic_flags & IEEE80211_F_DESBSSID) &&
486 	    !IEEE80211_ADDR_EQ(ic->ic_des_bssid, ni->ni_bssid))
487 		fail |= 0x20;
488 #ifdef IEEE80211_DEBUG
489 	if (ieee80211_msg_scan(ic)) {
490 		printf(" %c %s", fail ? '-' : '+',
491 		    ether_sprintf(ni->ni_macaddr));
492 		printf(" %s%c", ether_sprintf(ni->ni_bssid),
493 		    fail & 0x20 ? '!' : ' ');
494 		printf(" %3d%c", ieee80211_chan2ieee(ic, ni->ni_chan),
495 			fail & 0x01 ? '!' : ' ');
496 		printf(" %+4d", ni->ni_rssi);
497 		printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
498 		    fail & 0x08 ? '!' : ' ');
499 		printf(" %4s%c",
500 		    (ni->ni_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
501 		    (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
502 		    "????",
503 		    fail & 0x02 ? '!' : ' ');
504 		printf(" %3s%c ",
505 		    (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) ?
506 		    "wep" : "no",
507 		    fail & 0x04 ? '!' : ' ');
508 		ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
509 		printf("%s\n", fail & 0x10 ? "!" : "");
510 	}
511 #endif
512 	return fail;
513 }
514 
515 static __inline u_int8_t
516 maxrate(const struct ieee80211_node *ni)
517 {
518 	const struct ieee80211_rateset *rs = &ni->ni_rates;
519 	/* NB: assumes rate set is sorted (happens on frame receive) */
520 	return rs->rs_rates[rs->rs_nrates-1] & IEEE80211_RATE_VAL;
521 }
522 
523 /*
524  * Compare the capabilities of two nodes and decide which is
525  * more desirable (return >0 if a is considered better).  Note
526  * that we assume compatibility/usability has already been checked
527  * so we don't need to (e.g. validate whether privacy is supported).
528  * Used to select the best scan candidate for association in a BSS.
529  */
530 static int
531 ieee80211_node_compare(struct ieee80211com *ic,
532 		       const struct ieee80211_node *a,
533 		       const struct ieee80211_node *b)
534 {
535 	u_int8_t maxa, maxb;
536 	u_int8_t rssia, rssib;
537 
538 	/* privacy support preferred */
539 	if ((a->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) &&
540 	    (b->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
541 		return 1;
542 	if ((a->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0 &&
543 	    (b->ni_capinfo & IEEE80211_CAPINFO_PRIVACY))
544 		return -1;
545 
546 	rssia = ic->ic_node_getrssi(a);
547 	rssib = ic->ic_node_getrssi(b);
548 	if (abs(rssib - rssia) < 5) {
549 		/* best/max rate preferred if signal level close enough XXX */
550 		maxa = maxrate(a);
551 		maxb = maxrate(b);
552 		if (maxa != maxb)
553 			return maxa - maxb;
554 		/* XXX use freq for channel preference */
555 		/* for now just prefer 5Ghz band to all other bands */
556 		if (IEEE80211_IS_CHAN_5GHZ(a->ni_chan) &&
557 		   !IEEE80211_IS_CHAN_5GHZ(b->ni_chan))
558 			return 1;
559 		if (!IEEE80211_IS_CHAN_5GHZ(a->ni_chan) &&
560 		     IEEE80211_IS_CHAN_5GHZ(b->ni_chan))
561 			return -1;
562 	}
563 	/* all things being equal, use signal level */
564 	return rssia - rssib;
565 }
566 
567 /*
568  * Mark an ongoing scan stopped.
569  */
570 void
571 ieee80211_cancel_scan(struct ieee80211com *ic)
572 {
573 
574 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN, "%s: end %s scan\n",
575 		__func__,
576 		(ic->ic_flags & IEEE80211_F_ASCAN) ?  "active" : "passive");
577 
578 	ic->ic_flags &= ~(IEEE80211_F_SCAN | IEEE80211_F_ASCAN);
579 }
580 
581 /*
582  * Complete a scan of potential channels.
583  */
584 void
585 ieee80211_end_scan(struct ieee80211com *ic)
586 {
587 	struct ieee80211_node_table *nt = &ic->ic_scan;
588 	struct ieee80211_node *ni, *selbs;
589 
590 	ieee80211_cancel_scan(ic);
591 	ieee80211_notify_scan_done(ic);
592 
593 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
594 		u_int8_t maxrssi[IEEE80211_CHAN_MAX];	/* XXX off stack? */
595 		int i, bestchan;
596 		u_int8_t rssi;
597 
598 		/*
599 		 * The passive scan to look for existing AP's completed,
600 		 * select a channel to camp on.  Identify the channels
601 		 * that already have one or more AP's and try to locate
602 		 * an unoccupied one.  If that fails, pick a channel that
603 		 * looks to be quietest.
604 		 */
605 		memset(maxrssi, 0, sizeof(maxrssi));
606 		IEEE80211_NODE_LOCK(nt);
607 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
608 			rssi = ic->ic_node_getrssi(ni);
609 			i = ieee80211_chan2ieee(ic, ni->ni_chan);
610 			if (rssi > maxrssi[i])
611 				maxrssi[i] = rssi;
612 		}
613 		IEEE80211_NODE_UNLOCK(nt);
614 		/* XXX select channel more intelligently */
615 		bestchan = -1;
616 		for (i = 0; i < IEEE80211_CHAN_MAX; i++)
617 			if (isset(ic->ic_chan_active, i)) {
618 				/*
619 				 * If the channel is unoccupied the max rssi
620 				 * should be zero; just take it.  Otherwise
621 				 * track the channel with the lowest rssi and
622 				 * use that when all channels appear occupied.
623 				 */
624 				if (maxrssi[i] == 0) {
625 					bestchan = i;
626 					break;
627 				}
628 				if (maxrssi[i] < maxrssi[bestchan])
629 					bestchan = i;
630 			}
631 		if (bestchan != -1) {
632 			ieee80211_create_ibss(ic, &ic->ic_channels[bestchan]);
633 			return;
634 		}
635 		/* no suitable channel, should not happen */
636 	}
637 
638 	/*
639 	 * When manually sequencing the state machine; scan just once
640 	 * regardless of whether we have a candidate or not.  The
641 	 * controlling application is expected to setup state and
642 	 * initiate an association.
643 	 */
644 	if (ic->ic_roaming == IEEE80211_ROAMING_MANUAL)
645 		return;
646 	/*
647 	 * Automatic sequencing; look for a candidate and
648 	 * if found join the network.
649 	 */
650 	/* NB: unlocked read should be ok */
651 	if (TAILQ_FIRST(&nt->nt_node) == NULL) {
652 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
653 			"%s: no scan candidate\n", __func__);
654   notfound:
655 		if (ic->ic_opmode == IEEE80211_M_IBSS &&
656 		    (ic->ic_flags & IEEE80211_F_IBSSON) &&
657 		    ic->ic_des_esslen != 0) {
658 			ieee80211_create_ibss(ic, ic->ic_ibss_chan);
659 			return;
660 		}
661 		/*
662 		 * Reset the list of channels to scan and start again.
663 		 */
664 		ieee80211_reset_scan(ic);
665 		ic->ic_flags |= IEEE80211_F_SCAN;
666 		ieee80211_next_scan(ic);
667 		return;
668 	}
669 	selbs = NULL;
670 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN, "\t%s\n",
671 	    "macaddr          bssid         chan  rssi rate flag  wep  essid");
672 	IEEE80211_NODE_LOCK(nt);
673 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
674 		if (ni->ni_fails) {
675 			/*
676 			 * The configuration of the access points may change
677 			 * during my scan.  So delete the entry for the AP
678 			 * and retry to associate if there is another beacon.
679 			 */
680 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
681 				"%s: skip scan candidate %s, fails %u\n",
682 				__func__, ether_sprintf(ni->ni_macaddr),
683 				ni->ni_fails);
684 			ni->ni_fails++;
685 #if 0
686 			if (ni->ni_fails++ > 2)
687 				ieee80211_free_node(ni);
688 #endif
689 			continue;
690 		}
691 		if (ieee80211_match_bss(ic, ni) == 0) {
692 			if (selbs == NULL)
693 				selbs = ni;
694 			else if (ieee80211_node_compare(ic, ni, selbs) > 0)
695 				selbs = ni;
696 		}
697 	}
698 	if (selbs != NULL)		/* NB: grab ref while dropping lock */
699 		(void) ieee80211_ref_node(selbs);
700 	IEEE80211_NODE_UNLOCK(nt);
701 	if (selbs == NULL)
702 		goto notfound;
703 	if (!ieee80211_sta_join(ic, selbs)) {
704 		ieee80211_free_node(selbs);
705 		goto notfound;
706 	}
707 }
708 
709 /*
710  * Handle 802.11 ad hoc network merge.  The
711  * convention, set by the Wireless Ethernet Compatibility Alliance
712  * (WECA), is that an 802.11 station will change its BSSID to match
713  * the "oldest" 802.11 ad hoc network, on the same channel, that
714  * has the station's desired SSID.  The "oldest" 802.11 network
715  * sends beacons with the greatest TSF timestamp.
716  *
717  * The caller is assumed to validate TSF's before attempting a merge.
718  *
719  * Return !0 if the BSSID changed, 0 otherwise.
720  */
721 int
722 ieee80211_ibss_merge(struct ieee80211com *ic, struct ieee80211_node *ni)
723 {
724 
725 	if (ni == ic->ic_bss ||
726 	    IEEE80211_ADDR_EQ(ni->ni_bssid, ic->ic_bss->ni_bssid)) {
727 		/* unchanged, nothing to do */
728 		return 0;
729 	}
730 	if (ieee80211_match_bss(ic, ni) != 0) {	/* capabilities mismatch */
731 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
732 		    "%s: merge failed, capabilities mismatch\n", __func__);
733 		ic->ic_stats.is_ibss_capmismatch++;
734 		return 0;
735 	}
736 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
737 		"%s: new bssid %s: %s preamble, %s slot time%s\n", __func__,
738 		ether_sprintf(ni->ni_bssid),
739 		ic->ic_flags&IEEE80211_F_SHPREAMBLE ? "short" : "long",
740 		ic->ic_flags&IEEE80211_F_SHSLOT ? "short" : "long",
741 		ic->ic_flags&IEEE80211_F_USEPROT ? ", protection" : ""
742 	);
743 	return ieee80211_sta_join(ic, ieee80211_ref_node(ni));
744 }
745 
746 /*
747  * Join the specified IBSS/BSS network.  The node is assumed to
748  * be passed in with a held reference.
749  */
750 int
751 ieee80211_sta_join(struct ieee80211com *ic, struct ieee80211_node *selbs)
752 {
753 	struct ieee80211_node *obss;
754 
755 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
756 		struct ieee80211_node_table *nt;
757 		/*
758 		 * Delete unusable rates; we've already checked
759 		 * that the negotiated rate set is acceptable.
760 		 */
761 		ieee80211_fix_rate(ic, selbs, IEEE80211_F_DODEL);
762 		/*
763 		 * Fillin the neighbor table; it will already
764 		 * exist if we are simply switching mastership.
765 		 * XXX ic_sta always setup so this is unnecessary?
766 		 */
767 		nt = &ic->ic_sta;
768 		IEEE80211_NODE_LOCK(nt);
769 		nt->nt_name = "neighbor";
770 		nt->nt_inact_init = ic->ic_inact_run;
771 		IEEE80211_NODE_UNLOCK(nt);
772 	}
773 
774 	/*
775 	 * Committed to selbs, setup state.
776 	 */
777 	obss = ic->ic_bss;
778 	ic->ic_bss = selbs;		/* NB: caller assumed to bump refcnt */
779 	if (obss != NULL)
780 		ieee80211_free_node(obss);
781 	/*
782 	 * Set the erp state (mostly the slot time) to deal with
783 	 * the auto-select case; this should be redundant if the
784 	 * mode is locked.
785 	 */
786 	ic->ic_curmode = ieee80211_chan2mode(ic, selbs->ni_chan);
787 	ieee80211_reset_erp(ic);
788 	ieee80211_wme_initparams(ic);
789 
790 	if (ic->ic_opmode == IEEE80211_M_STA)
791 		ieee80211_new_state(ic, IEEE80211_S_AUTH, -1);
792 	else
793 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
794 	return 1;
795 }
796 
797 /*
798  * Leave the specified IBSS/BSS network.  The node is assumed to
799  * be passed in with a held reference.
800  */
801 void
802 ieee80211_sta_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
803 {
804 	ic->ic_node_cleanup(ni);
805 	ieee80211_notify_node_leave(ic, ni);
806 }
807 
808 static struct ieee80211_node *
809 node_alloc(struct ieee80211_node_table *nt)
810 {
811 	struct ieee80211_node *ni;
812 
813 	MALLOC(ni, struct ieee80211_node *, sizeof(struct ieee80211_node),
814 		M_80211_NODE, M_NOWAIT | M_ZERO);
815 	return ni;
816 }
817 
818 /*
819  * Reclaim any resources in a node and reset any critical
820  * state.  Typically nodes are free'd immediately after,
821  * but in some cases the storage may be reused so we need
822  * to insure consistent state (should probably fix that).
823  */
824 static void
825 node_cleanup(struct ieee80211_node *ni)
826 {
827 #define	N(a)	(sizeof(a)/sizeof(a[0]))
828 	struct ieee80211com *ic = ni->ni_ic;
829 	int i, qlen;
830 
831 	/* NB: preserve ni_table */
832 	if (ni->ni_flags & IEEE80211_NODE_PWR_MGT) {
833 		ic->ic_ps_sta--;
834 		ni->ni_flags &= ~IEEE80211_NODE_PWR_MGT;
835 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
836 		    "[%s] power save mode off, %u sta's in ps mode\n",
837 		    ether_sprintf(ni->ni_macaddr), ic->ic_ps_sta);
838 	}
839 
840 	/*
841 	 * Drain power save queue and, if needed, clear TIM.
842 	 */
843 	IEEE80211_NODE_SAVEQ_DRAIN(ni, qlen);
844 	if (qlen != 0 && ic->ic_set_tim != NULL)
845 		ic->ic_set_tim(ic, ni, 0);
846 
847 	ni->ni_associd = 0;
848 	if (ni->ni_challenge != NULL) {
849 		FREE(ni->ni_challenge, M_DEVBUF);
850 		ni->ni_challenge = NULL;
851 	}
852 	/*
853 	 * Preserve SSID, WPA, and WME ie's so the bss node is
854 	 * reusable during a re-auth/re-assoc state transition.
855 	 * If we remove these data they will not be recreated
856 	 * because they come from a probe-response or beacon frame
857 	 * which cannot be expected prior to the association-response.
858 	 * This should not be an issue when operating in other modes
859 	 * as stations leaving always go through a full state transition
860 	 * which will rebuild this state.
861 	 *
862 	 * XXX does this leave us open to inheriting old state?
863 	 */
864 	for (i = 0; i < N(ni->ni_rxfrag); i++)
865 		if (ni->ni_rxfrag[i] != NULL) {
866 			m_freem(ni->ni_rxfrag[i]);
867 			ni->ni_rxfrag[i] = NULL;
868 		}
869 	ieee80211_crypto_delkey(ic, &ni->ni_ucastkey);
870 #undef N
871 }
872 
873 static void
874 node_free(struct ieee80211_node *ni)
875 {
876 	struct ieee80211com *ic = ni->ni_ic;
877 
878 	ic->ic_node_cleanup(ni);
879 	if (ni->ni_wpa_ie != NULL)
880 		FREE(ni->ni_wpa_ie, M_DEVBUF);
881 	if (ni->ni_wme_ie != NULL)
882 		FREE(ni->ni_wme_ie, M_DEVBUF);
883 	IEEE80211_NODE_SAVEQ_DESTROY(ni);
884 	FREE(ni, M_80211_NODE);
885 }
886 
887 static u_int8_t
888 node_getrssi(const struct ieee80211_node *ni)
889 {
890 	return ni->ni_rssi;
891 }
892 
893 static void
894 ieee80211_setup_node(struct ieee80211_node_table *nt,
895 	struct ieee80211_node *ni, const u_int8_t *macaddr)
896 {
897 	struct ieee80211com *ic = nt->nt_ic;
898 	int hash;
899 
900 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
901 		"%s %p<%s> in %s table\n", __func__, ni,
902 		ether_sprintf(macaddr), nt->nt_name);
903 
904 	IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
905 	hash = IEEE80211_NODE_HASH(macaddr);
906 	ieee80211_node_initref(ni);		/* mark referenced */
907 	ni->ni_chan = IEEE80211_CHAN_ANYC;
908 	ni->ni_authmode = IEEE80211_AUTH_OPEN;
909 	ni->ni_txpower = ic->ic_txpowlimit;	/* max power */
910 	ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey, IEEE80211_KEYIX_NONE);
911 	ni->ni_inact_reload = nt->nt_inact_init;
912 	ni->ni_inact = ni->ni_inact_reload;
913 	IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
914 
915 	IEEE80211_NODE_LOCK(nt);
916 	TAILQ_INSERT_TAIL(&nt->nt_node, ni, ni_list);
917 	LIST_INSERT_HEAD(&nt->nt_hash[hash], ni, ni_hash);
918 	ni->ni_table = nt;
919 	ni->ni_ic = ic;
920 	IEEE80211_NODE_UNLOCK(nt);
921 }
922 
923 struct ieee80211_node *
924 ieee80211_alloc_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
925 {
926 	struct ieee80211com *ic = nt->nt_ic;
927 	struct ieee80211_node *ni;
928 
929 	ni = ic->ic_node_alloc(nt);
930 	if (ni != NULL)
931 		ieee80211_setup_node(nt, ni, macaddr);
932 	else
933 		ic->ic_stats.is_rx_nodealloc++;
934 	return ni;
935 }
936 
937 struct ieee80211_node *
938 ieee80211_dup_bss(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
939 {
940 	struct ieee80211com *ic = nt->nt_ic;
941 	struct ieee80211_node *ni;
942 
943 	ni = ic->ic_node_alloc(nt);
944 	if (ni != NULL) {
945 		ieee80211_setup_node(nt, ni, macaddr);
946 		/*
947 		 * Inherit from ic_bss.
948 		 */
949 		ni->ni_authmode = ic->ic_bss->ni_authmode;
950 		ni->ni_txpower = ic->ic_bss->ni_txpower;
951 		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
952 		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
953 		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
954 		ni->ni_rsn = ic->ic_bss->ni_rsn;
955 	} else
956 		ic->ic_stats.is_rx_nodealloc++;
957 	return ni;
958 }
959 
960 static struct ieee80211_node *
961 #ifdef IEEE80211_DEBUG_REFCNT
962 _ieee80211_find_node_debug(struct ieee80211_node_table *nt,
963 	const u_int8_t *macaddr, const char *func, int line)
964 #else
965 _ieee80211_find_node(struct ieee80211_node_table *nt,
966 	const u_int8_t *macaddr)
967 #endif
968 {
969 	struct ieee80211_node *ni;
970 	int hash;
971 
972 	IEEE80211_NODE_LOCK_ASSERT(nt);
973 
974 	hash = IEEE80211_NODE_HASH(macaddr);
975 	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
976 		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
977 			ieee80211_ref_node(ni);	/* mark referenced */
978 #ifdef IEEE80211_DEBUG_REFCNT
979 			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
980 			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
981 			    func, line,
982 			    ni, ether_sprintf(ni->ni_macaddr),
983 			    ieee80211_node_refcnt(ni));
984 #endif
985 			return ni;
986 		}
987 	}
988 	return NULL;
989 }
990 #ifdef IEEE80211_DEBUG_REFCNT
991 #define	_ieee80211_find_node(nt, mac) \
992 	_ieee80211_find_node_debug(nt, mac, func, line)
993 #endif
994 
995 struct ieee80211_node *
996 #ifdef IEEE80211_DEBUG_REFCNT
997 ieee80211_find_node_debug(struct ieee80211_node_table *nt,
998 	const u_int8_t *macaddr, const char *func, int line)
999 #else
1000 ieee80211_find_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
1001 #endif
1002 {
1003 	struct ieee80211_node *ni;
1004 
1005 	IEEE80211_NODE_LOCK(nt);
1006 	ni = _ieee80211_find_node(nt, macaddr);
1007 	IEEE80211_NODE_UNLOCK(nt);
1008 	return ni;
1009 }
1010 
1011 /*
1012  * Fake up a node; this handles node discovery in adhoc mode.
1013  * Note that for the driver's benefit we we treat this like
1014  * an association so the driver has an opportunity to setup
1015  * it's private state.
1016  */
1017 struct ieee80211_node *
1018 ieee80211_fakeup_adhoc_node(struct ieee80211_node_table *nt,
1019 	const u_int8_t macaddr[IEEE80211_ADDR_LEN])
1020 {
1021 	struct ieee80211com *ic = nt->nt_ic;
1022 	struct ieee80211_node *ni;
1023 
1024 	ni = ieee80211_dup_bss(nt, macaddr);
1025 	if (ni != NULL) {
1026 		/* XXX no rate negotiation; just dup */
1027 		ni->ni_rates = ic->ic_bss->ni_rates;
1028 		if (ic->ic_newassoc != NULL)
1029 			ic->ic_newassoc(ic, ni, 1);
1030 		/* XXX not right for 802.1x/WPA */
1031 		ieee80211_node_authorize(ic, ni);
1032 	}
1033 	return ni;
1034 }
1035 
1036 /*
1037  * Locate the node for sender, track state, and then pass the
1038  * (referenced) node up to the 802.11 layer for its use.  We
1039  * are required to pass some node so we fall back to ic_bss
1040  * when this frame is from an unknown sender.  The 802.11 layer
1041  * knows this means the sender wasn't in the node table and
1042  * acts accordingly.
1043  */
1044 struct ieee80211_node *
1045 #ifdef IEEE80211_DEBUG_REFCNT
1046 ieee80211_find_rxnode_debug(struct ieee80211com *ic,
1047 	const struct ieee80211_frame_min *wh, const char *func, int line)
1048 #else
1049 ieee80211_find_rxnode(struct ieee80211com *ic,
1050 	const struct ieee80211_frame_min *wh)
1051 #endif
1052 {
1053 #define	IS_CTL(wh) \
1054 	((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_CTL)
1055 #define	IS_PSPOLL(wh) \
1056 	((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_PS_POLL)
1057 	struct ieee80211_node_table *nt;
1058 	struct ieee80211_node *ni;
1059 
1060 	/* XXX may want scanned nodes in the neighbor table for adhoc */
1061 	if (ic->ic_opmode == IEEE80211_M_STA ||
1062 	    ic->ic_opmode == IEEE80211_M_MONITOR ||
1063 	    (ic->ic_flags & IEEE80211_F_SCAN))
1064 		nt = &ic->ic_scan;
1065 	else
1066 		nt = &ic->ic_sta;
1067 	/* XXX check ic_bss first in station mode */
1068 	/* XXX 4-address frames? */
1069 	IEEE80211_NODE_LOCK(nt);
1070 	if (IS_CTL(wh) && !IS_PSPOLL(wh) /*&& !IS_RTS(ah)*/)
1071 		ni = _ieee80211_find_node(nt, wh->i_addr1);
1072 	else
1073 		ni = _ieee80211_find_node(nt, wh->i_addr2);
1074 	IEEE80211_NODE_UNLOCK(nt);
1075 
1076 	return (ni != NULL ? ni : ieee80211_ref_node(ic->ic_bss));
1077 #undef IS_PSPOLL
1078 #undef IS_CTL
1079 }
1080 
1081 /*
1082  * Return a reference to the appropriate node for sending
1083  * a data frame.  This handles node discovery in adhoc networks.
1084  */
1085 struct ieee80211_node *
1086 #ifdef IEEE80211_DEBUG_REFCNT
1087 ieee80211_find_txnode_debug(struct ieee80211com *ic, const u_int8_t *macaddr,
1088 	const char *func, int line)
1089 #else
1090 ieee80211_find_txnode(struct ieee80211com *ic, const u_int8_t *macaddr)
1091 #endif
1092 {
1093 	struct ieee80211_node_table *nt = &ic->ic_sta;
1094 	struct ieee80211_node *ni;
1095 
1096 	/*
1097 	 * The destination address should be in the node table
1098 	 * unless we are operating in station mode or this is a
1099 	 * multicast/broadcast frame.
1100 	 */
1101 	if (ic->ic_opmode == IEEE80211_M_STA || IEEE80211_IS_MULTICAST(macaddr))
1102 		return ieee80211_ref_node(ic->ic_bss);
1103 
1104 	/* XXX can't hold lock across dup_bss 'cuz of recursive locking */
1105 	IEEE80211_NODE_LOCK(nt);
1106 	ni = _ieee80211_find_node(nt, macaddr);
1107 	IEEE80211_NODE_UNLOCK(nt);
1108 
1109 	if (ni == NULL) {
1110 		if (ic->ic_opmode == IEEE80211_M_IBSS ||
1111 		    ic->ic_opmode == IEEE80211_M_AHDEMO) {
1112 			/*
1113 			 * In adhoc mode cons up a node for the destination.
1114 			 * Note that we need an additional reference for the
1115 			 * caller to be consistent with _ieee80211_find_node.
1116 			 */
1117 			ni = ieee80211_fakeup_adhoc_node(nt, macaddr);
1118 			if (ni != NULL)
1119 				(void) ieee80211_ref_node(ni);
1120 		} else {
1121 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
1122 				"[%s] no node, discard frame (%s)\n",
1123 				ether_sprintf(macaddr), __func__);
1124 			ic->ic_stats.is_tx_nonode++;
1125 		}
1126 	}
1127 	return ni;
1128 }
1129 
1130 /*
1131  * Like find but search based on the channel too.
1132  */
1133 struct ieee80211_node *
1134 #ifdef IEEE80211_DEBUG_REFCNT
1135 ieee80211_find_node_with_channel_debug(struct ieee80211_node_table *nt,
1136 	const u_int8_t *macaddr, struct ieee80211_channel *chan,
1137 	const char *func, int line)
1138 #else
1139 ieee80211_find_node_with_channel(struct ieee80211_node_table *nt,
1140 	const u_int8_t *macaddr, struct ieee80211_channel *chan)
1141 #endif
1142 {
1143 	struct ieee80211_node *ni;
1144 	int hash;
1145 
1146 	hash = IEEE80211_NODE_HASH(macaddr);
1147 	IEEE80211_NODE_LOCK(nt);
1148 	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1149 		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1150 		    ni->ni_chan == chan) {
1151 			ieee80211_ref_node(ni);		/* mark referenced */
1152 			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1153 #ifdef IEEE80211_DEBUG_REFCNT
1154 			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1155 			    func, line,
1156 #else
1157 			    "%s %p<%s> refcnt %d\n", __func__,
1158 #endif
1159 			    ni, ether_sprintf(ni->ni_macaddr),
1160 			    ieee80211_node_refcnt(ni));
1161 			break;
1162 		}
1163 	}
1164 	IEEE80211_NODE_UNLOCK(nt);
1165 	return ni;
1166 }
1167 
1168 /*
1169  * Like find but search based on the ssid too.
1170  */
1171 struct ieee80211_node *
1172 #ifdef IEEE80211_DEBUG_REFCNT
1173 ieee80211_find_node_with_ssid_debug(struct ieee80211_node_table *nt,
1174 	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid,
1175 	const char *func, int line)
1176 #else
1177 ieee80211_find_node_with_ssid(struct ieee80211_node_table *nt,
1178 	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid)
1179 #endif
1180 {
1181 	struct ieee80211com *ic = nt->nt_ic;
1182 	struct ieee80211_node *ni;
1183 	int hash;
1184 
1185 	hash = IEEE80211_NODE_HASH(macaddr);
1186 	IEEE80211_NODE_LOCK(nt);
1187 	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1188 		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1189 		    ni->ni_esslen == ic->ic_des_esslen &&
1190 		    memcmp(ni->ni_essid, ic->ic_des_essid, ni->ni_esslen) == 0) {
1191 			ieee80211_ref_node(ni);		/* mark referenced */
1192 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1193 #ifdef IEEE80211_DEBUG_REFCNT
1194 			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1195 			    func, line,
1196 #else
1197 			    "%s %p<%s> refcnt %d\n", __func__,
1198 #endif
1199 			     ni, ether_sprintf(ni->ni_macaddr),
1200 			     ieee80211_node_refcnt(ni));
1201 			break;
1202 		}
1203 	}
1204 	IEEE80211_NODE_UNLOCK(nt);
1205 	return ni;
1206 }
1207 
1208 static void
1209 _ieee80211_free_node(struct ieee80211_node *ni)
1210 {
1211 	struct ieee80211com *ic = ni->ni_ic;
1212 	struct ieee80211_node_table *nt = ni->ni_table;
1213 
1214 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1215 		"%s %p<%s> in %s table\n", __func__, ni,
1216 		ether_sprintf(ni->ni_macaddr),
1217 		nt != NULL ? nt->nt_name : "<gone>");
1218 
1219 	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1220 	if (nt != NULL) {
1221 		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1222 		LIST_REMOVE(ni, ni_hash);
1223 	}
1224 	ic->ic_node_free(ni);
1225 }
1226 
1227 void
1228 #ifdef IEEE80211_DEBUG_REFCNT
1229 ieee80211_free_node_debug(struct ieee80211_node *ni, const char *func, int line)
1230 #else
1231 ieee80211_free_node(struct ieee80211_node *ni)
1232 #endif
1233 {
1234 	struct ieee80211_node_table *nt = ni->ni_table;
1235 
1236 #ifdef IEEE80211_DEBUG_REFCNT
1237 	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1238 		"%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line, ni,
1239 		 ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)-1);
1240 #endif
1241 	if (ieee80211_node_dectestref(ni)) {
1242 		/*
1243 		 * Beware; if the node is marked gone then it's already
1244 		 * been removed from the table and we cannot assume the
1245 		 * table still exists.  Regardless, there's no need to lock
1246 		 * the table.
1247 		 */
1248 		if (ni->ni_table != NULL) {
1249 			IEEE80211_NODE_LOCK(nt);
1250 			_ieee80211_free_node(ni);
1251 			IEEE80211_NODE_UNLOCK(nt);
1252 		} else
1253 			_ieee80211_free_node(ni);
1254 	}
1255 }
1256 
1257 /*
1258  * Reclaim a node.  If this is the last reference count then
1259  * do the normal free work.  Otherwise remove it from the node
1260  * table and mark it gone by clearing the back-reference.
1261  */
1262 static void
1263 node_reclaim(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1264 {
1265 
1266 	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1267 		"%s: remove %p<%s> from %s table, refcnt %d\n",
1268 		__func__, ni, ether_sprintf(ni->ni_macaddr),
1269 		nt->nt_name, ieee80211_node_refcnt(ni)-1);
1270 	if (!ieee80211_node_dectestref(ni)) {
1271 		/*
1272 		 * Other references are present, just remove the
1273 		 * node from the table so it cannot be found.  When
1274 		 * the references are dropped storage will be
1275 		 * reclaimed.
1276 		 */
1277 		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1278 		LIST_REMOVE(ni, ni_hash);
1279 		ni->ni_table = NULL;		/* clear reference */
1280 	} else
1281 		_ieee80211_free_node(ni);
1282 }
1283 
1284 static void
1285 ieee80211_free_allnodes_locked(struct ieee80211_node_table *nt)
1286 {
1287 	struct ieee80211com *ic = nt->nt_ic;
1288 	struct ieee80211_node *ni;
1289 
1290 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1291 		"%s: free all nodes in %s table\n", __func__, nt->nt_name);
1292 
1293 	while ((ni = TAILQ_FIRST(&nt->nt_node)) != NULL) {
1294 		if (ni->ni_associd != 0) {
1295 			if (ic->ic_auth->ia_node_leave != NULL)
1296 				ic->ic_auth->ia_node_leave(ic, ni);
1297 			IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1298 		}
1299 		node_reclaim(nt, ni);
1300 	}
1301 	ieee80211_reset_erp(ic);
1302 }
1303 
1304 static void
1305 ieee80211_free_allnodes(struct ieee80211_node_table *nt)
1306 {
1307 
1308 	IEEE80211_NODE_LOCK(nt);
1309 	ieee80211_free_allnodes_locked(nt);
1310 	IEEE80211_NODE_UNLOCK(nt);
1311 }
1312 
1313 /*
1314  * Timeout entries in the scan cache.
1315  */
1316 static void
1317 ieee80211_timeout_scan_candidates(struct ieee80211_node_table *nt)
1318 {
1319 	struct ieee80211com *ic = nt->nt_ic;
1320 	struct ieee80211_node *ni, *tni;
1321 
1322 	IEEE80211_NODE_LOCK(nt);
1323 	ni = ic->ic_bss;
1324 	/* XXX belongs elsewhere */
1325 	if (ni->ni_rxfrag[0] != NULL && ticks > ni->ni_rxfragstamp + hz) {
1326 		m_freem(ni->ni_rxfrag[0]);
1327 		ni->ni_rxfrag[0] = NULL;
1328 	}
1329 	TAILQ_FOREACH_SAFE(ni, &nt->nt_node, ni_list, tni) {
1330 		if (ni->ni_inact && --ni->ni_inact == 0) {
1331 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1332 			    "[%s] scan candidate purged from cache "
1333 			    "(refcnt %u)\n", ether_sprintf(ni->ni_macaddr),
1334 			    ieee80211_node_refcnt(ni));
1335 			node_reclaim(nt, ni);
1336 		}
1337 	}
1338 	IEEE80211_NODE_UNLOCK(nt);
1339 
1340 	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
1341 }
1342 
1343 /*
1344  * Timeout inactive stations and do related housekeeping.
1345  * Note that we cannot hold the node lock while sending a
1346  * frame as this would lead to a LOR.  Instead we use a
1347  * generation number to mark nodes that we've scanned and
1348  * drop the lock and restart a scan if we have to time out
1349  * a node.  Since we are single-threaded by virtue of
1350  * controlling the inactivity timer we can be sure this will
1351  * process each node only once.
1352  */
1353 static void
1354 ieee80211_timeout_stations(struct ieee80211_node_table *nt)
1355 {
1356 	struct ieee80211com *ic = nt->nt_ic;
1357 	struct ieee80211_node *ni;
1358 	u_int gen;
1359 
1360 	IEEE80211_SCAN_LOCK(nt);
1361 	gen = nt->nt_scangen++;
1362 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1363 		"%s: %s scangen %u\n", __func__, nt->nt_name, gen);
1364 restart:
1365 	IEEE80211_NODE_LOCK(nt);
1366 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1367 		if (ni->ni_scangen == gen)	/* previously handled */
1368 			continue;
1369 		ni->ni_scangen = gen;
1370 		/*
1371 		 * Free fragment if not needed anymore
1372 		 * (last fragment older than 1s).
1373 		 * XXX doesn't belong here
1374 		 */
1375 		if (ni->ni_rxfrag[0] != NULL &&
1376 		    ticks > ni->ni_rxfragstamp + hz) {
1377 			m_freem(ni->ni_rxfrag[0]);
1378 			ni->ni_rxfrag[0] = NULL;
1379 		}
1380 		/*
1381 		 * Special case ourself; we may be idle for extended periods
1382 		 * of time and regardless reclaiming our state is wrong.
1383 		 */
1384 		if (ni == ic->ic_bss)
1385 			continue;
1386 		ni->ni_inact--;
1387 		if (ni->ni_associd != 0) {
1388 			/*
1389 			 * Age frames on the power save queue. The
1390 			 * aging interval is 4 times the listen
1391 			 * interval specified by the station.  This
1392 			 * number is factored into the age calculations
1393 			 * when the frame is placed on the queue.  We
1394 			 * store ages as time differences we can check
1395 			 * and/or adjust only the head of the list.
1396 			 */
1397 			if (IEEE80211_NODE_SAVEQ_QLEN(ni) != 0) {
1398 				struct mbuf *m;
1399 				int discard = 0;
1400 
1401 				IEEE80211_NODE_SAVEQ_LOCK(ni);
1402 				while (IF_POLL(&ni->ni_savedq, m) != NULL &&
1403 				     M_AGE_GET(m) < IEEE80211_INACT_WAIT) {
1404 IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER, "[%s] discard frame, age %u\n", ether_sprintf(ni->ni_macaddr), M_AGE_GET(m));/*XXX*/
1405 					_IEEE80211_NODE_SAVEQ_DEQUEUE_HEAD(ni, m);
1406 					m_freem(m);
1407 					discard++;
1408 				}
1409 				if (m != NULL)
1410 					M_AGE_SUB(m, IEEE80211_INACT_WAIT);
1411 				IEEE80211_NODE_SAVEQ_UNLOCK(ni);
1412 
1413 				if (discard != 0) {
1414 					IEEE80211_DPRINTF(ic,
1415 					    IEEE80211_MSG_POWER,
1416 					    "[%s] discard %u frames for age\n",
1417 					    ether_sprintf(ni->ni_macaddr),
1418 					    discard);
1419 					IEEE80211_NODE_STAT_ADD(ni,
1420 						ps_discard, discard);
1421 					if (IEEE80211_NODE_SAVEQ_QLEN(ni) == 0)
1422 						ic->ic_set_tim(ic, ni, 0);
1423 				}
1424 			}
1425 			/*
1426 			 * Probe the station before time it out.  We
1427 			 * send a null data frame which may not be
1428 			 * universally supported by drivers (need it
1429 			 * for ps-poll support so it should be...).
1430 			 */
1431 			if (0 < ni->ni_inact &&
1432 			    ni->ni_inact <= ic->ic_inact_probe) {
1433 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1434 				    "[%s] probe station due to inactivity\n",
1435 				    ether_sprintf(ni->ni_macaddr));
1436 				IEEE80211_NODE_UNLOCK(nt);
1437 				ieee80211_send_nulldata(ic, ni);
1438 				/* XXX stat? */
1439 				goto restart;
1440 			}
1441 		}
1442 		if (ni->ni_inact <= 0) {
1443 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1444 			    "[%s] station timed out due to inactivity "
1445 			    "(refcnt %u)\n", ether_sprintf(ni->ni_macaddr),
1446 			    ieee80211_node_refcnt(ni));
1447 			/*
1448 			 * Send a deauthenticate frame and drop the station.
1449 			 * This is somewhat complicated due to reference counts
1450 			 * and locking.  At this point a station will typically
1451 			 * have a reference count of 1.  ieee80211_node_leave
1452 			 * will do a "free" of the node which will drop the
1453 			 * reference count.  But in the meantime a reference
1454 			 * wil be held by the deauth frame.  The actual reclaim
1455 			 * of the node will happen either after the tx is
1456 			 * completed or by ieee80211_node_leave.
1457 			 *
1458 			 * Separately we must drop the node lock before sending
1459 			 * in case the driver takes a lock, as this will result
1460 			 * in  LOR between the node lock and the driver lock.
1461 			 */
1462 			IEEE80211_NODE_UNLOCK(nt);
1463 			if (ni->ni_associd != 0) {
1464 				IEEE80211_SEND_MGMT(ic, ni,
1465 				    IEEE80211_FC0_SUBTYPE_DEAUTH,
1466 				    IEEE80211_REASON_AUTH_EXPIRE);
1467 			}
1468 			ieee80211_node_leave(ic, ni);
1469 			ic->ic_stats.is_node_timeout++;
1470 			goto restart;
1471 		}
1472 	}
1473 	IEEE80211_NODE_UNLOCK(nt);
1474 
1475 	IEEE80211_SCAN_UNLOCK(nt);
1476 
1477 	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
1478 }
1479 
1480 void
1481 ieee80211_iterate_nodes(struct ieee80211_node_table *nt, ieee80211_iter_func *f, void *arg)
1482 {
1483 	struct ieee80211_node *ni;
1484 	u_int gen;
1485 
1486 	IEEE80211_SCAN_LOCK(nt);
1487 	gen = nt->nt_scangen++;
1488 restart:
1489 	IEEE80211_NODE_LOCK(nt);
1490 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1491 		if (ni->ni_scangen != gen) {
1492 			ni->ni_scangen = gen;
1493 			(void) ieee80211_ref_node(ni);
1494 			IEEE80211_NODE_UNLOCK(nt);
1495 			(*f)(arg, ni);
1496 			ieee80211_free_node(ni);
1497 			goto restart;
1498 		}
1499 	}
1500 	IEEE80211_NODE_UNLOCK(nt);
1501 
1502 	IEEE80211_SCAN_UNLOCK(nt);
1503 }
1504 
1505 void
1506 ieee80211_dump_node(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1507 {
1508 	printf("0x%p: mac %s refcnt %d\n", ni,
1509 		ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni));
1510 	printf("\tscangen %u authmode %u flags 0x%x\n",
1511 		ni->ni_scangen, ni->ni_authmode, ni->ni_flags);
1512 	printf("\tassocid 0x%x txpower %u vlan %u\n",
1513 		ni->ni_associd, ni->ni_txpower, ni->ni_vlan);
1514 	printf("\ttxseq %u rxseq %u fragno %u rxfragstamp %u\n",
1515 		ni->ni_txseqs[0],
1516 		ni->ni_rxseqs[0] >> IEEE80211_SEQ_SEQ_SHIFT,
1517 		ni->ni_rxseqs[0] & IEEE80211_SEQ_FRAG_MASK,
1518 		ni->ni_rxfragstamp);
1519 	printf("\trstamp %u rssi %u intval %u capinfo 0x%x\n",
1520 		ni->ni_rstamp, ni->ni_rssi, ni->ni_intval, ni->ni_capinfo);
1521 	printf("\tbssid %s essid \"%.*s\" channel %u:0x%x\n",
1522 		ether_sprintf(ni->ni_bssid),
1523 		ni->ni_esslen, ni->ni_essid,
1524 		ni->ni_chan->ic_freq, ni->ni_chan->ic_flags);
1525 	printf("\tfails %u inact %u txrate %u\n",
1526 		ni->ni_fails, ni->ni_inact, ni->ni_txrate);
1527 }
1528 
1529 void
1530 ieee80211_dump_nodes(struct ieee80211_node_table *nt)
1531 {
1532 	ieee80211_iterate_nodes(nt,
1533 		(ieee80211_iter_func *) ieee80211_dump_node, nt);
1534 }
1535 
1536 /*
1537  * Handle a station joining an 11g network.
1538  */
1539 static void
1540 ieee80211_node_join_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
1541 {
1542 
1543 	/*
1544 	 * Station isn't capable of short slot time.  Bump
1545 	 * the count of long slot time stations and disable
1546 	 * use of short slot time.  Note that the actual switch
1547 	 * over to long slot time use may not occur until the
1548 	 * next beacon transmission (per sec. 7.3.1.4 of 11g).
1549 	 */
1550 	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
1551 		ic->ic_longslotsta++;
1552 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1553 		    "[%s] station needs long slot time, count %d\n",
1554 		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
1555 		/* XXX vap's w/ conflicting needs won't work */
1556 		ieee80211_set_shortslottime(ic, 0);
1557 	}
1558 	/*
1559 	 * If the new station is not an ERP station
1560 	 * then bump the counter and enable protection
1561 	 * if configured.
1562 	 */
1563 	if (!ieee80211_iserp_rateset(ic, &ni->ni_rates)) {
1564 		ic->ic_nonerpsta++;
1565 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1566 		    "[%s] station is !ERP, %d non-ERP stations associated\n",
1567 		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
1568 		/*
1569 		 * If protection is configured, enable it.
1570 		 */
1571 		if (ic->ic_protmode != IEEE80211_PROT_NONE) {
1572 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1573 			    "%s: enable use of protection\n", __func__);
1574 			ic->ic_flags |= IEEE80211_F_USEPROT;
1575 		}
1576 		/*
1577 		 * If station does not support short preamble
1578 		 * then we must enable use of Barker preamble.
1579 		 */
1580 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE) == 0) {
1581 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1582 			    "[%s] station needs long preamble\n",
1583 			    ether_sprintf(ni->ni_macaddr));
1584 			ic->ic_flags |= IEEE80211_F_USEBARKER;
1585 			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
1586 		}
1587 	} else
1588 		ni->ni_flags |= IEEE80211_NODE_ERP;
1589 }
1590 
1591 void
1592 ieee80211_node_join(struct ieee80211com *ic, struct ieee80211_node *ni, int resp)
1593 {
1594 	int newassoc;
1595 
1596 	if (ni->ni_associd == 0) {
1597 		u_int16_t aid;
1598 
1599 		/*
1600 		 * It would be good to search the bitmap
1601 		 * more efficiently, but this will do for now.
1602 		 */
1603 		for (aid = 1; aid < ic->ic_max_aid; aid++) {
1604 			if (!IEEE80211_AID_ISSET(aid,
1605 			    ic->ic_aid_bitmap))
1606 				break;
1607 		}
1608 		if (aid >= ic->ic_max_aid) {
1609 			IEEE80211_SEND_MGMT(ic, ni, resp,
1610 			    IEEE80211_REASON_ASSOC_TOOMANY);
1611 			ieee80211_node_leave(ic, ni);
1612 			return;
1613 		}
1614 		ni->ni_associd = aid | 0xc000;
1615 		IEEE80211_AID_SET(ni->ni_associd, ic->ic_aid_bitmap);
1616 		ic->ic_sta_assoc++;
1617 		newassoc = 1;
1618 		if (ic->ic_curmode == IEEE80211_MODE_11G ||
1619 		    ic->ic_curmode == IEEE80211_MODE_TURBO_G)
1620 			ieee80211_node_join_11g(ic, ni);
1621 	} else
1622 		newassoc = 0;
1623 
1624 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
1625 	    "[%s] station %sassociated at aid %d: %s preamble, %s slot time%s%s\n",
1626 	    ether_sprintf(ni->ni_macaddr), newassoc ? "" : "re",
1627 	    IEEE80211_NODE_AID(ni),
1628 	    ic->ic_flags & IEEE80211_F_SHPREAMBLE ? "short" : "long",
1629 	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long",
1630 	    ic->ic_flags & IEEE80211_F_USEPROT ? ", protection" : "",
1631 	    ni->ni_flags & IEEE80211_NODE_QOS ? ", QoS" : ""
1632 	);
1633 
1634 	/* give driver a chance to setup state like ni_txrate */
1635 	if (ic->ic_newassoc != NULL)
1636 		ic->ic_newassoc(ic, ni, newassoc);
1637 	ni->ni_inact_reload = ic->ic_inact_auth;
1638 	ni->ni_inact = ni->ni_inact_reload;
1639 	IEEE80211_SEND_MGMT(ic, ni, resp, IEEE80211_STATUS_SUCCESS);
1640 	/* tell the authenticator about new station */
1641 	if (ic->ic_auth->ia_node_join != NULL)
1642 		ic->ic_auth->ia_node_join(ic, ni);
1643 	ieee80211_notify_node_join(ic, ni, newassoc);
1644 }
1645 
1646 /*
1647  * Handle a station leaving an 11g network.
1648  */
1649 static void
1650 ieee80211_node_leave_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
1651 {
1652 
1653 	KASSERT(ic->ic_curmode == IEEE80211_MODE_11G ||
1654 		ic->ic_curmode == IEEE80211_MODE_TURBO_G,
1655 		("not in 11g, curmode %x", ic->ic_curmode));
1656 
1657 	/*
1658 	 * If a long slot station do the slot time bookkeeping.
1659 	 */
1660 	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
1661 		KASSERT(ic->ic_longslotsta > 0,
1662 		    ("bogus long slot station count %d", ic->ic_longslotsta));
1663 		ic->ic_longslotsta--;
1664 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1665 		    "[%s] long slot time station leaves, count now %d\n",
1666 		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
1667 		if (ic->ic_longslotsta == 0) {
1668 			/*
1669 			 * Re-enable use of short slot time if supported
1670 			 * and not operating in IBSS mode (per spec).
1671 			 */
1672 			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
1673 			    ic->ic_opmode != IEEE80211_M_IBSS) {
1674 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1675 				    "%s: re-enable use of short slot time\n",
1676 				    __func__);
1677 				ieee80211_set_shortslottime(ic, 1);
1678 			}
1679 		}
1680 	}
1681 	/*
1682 	 * If a non-ERP station do the protection-related bookkeeping.
1683 	 */
1684 	if ((ni->ni_flags & IEEE80211_NODE_ERP) == 0) {
1685 		KASSERT(ic->ic_nonerpsta > 0,
1686 		    ("bogus non-ERP station count %d", ic->ic_nonerpsta));
1687 		ic->ic_nonerpsta--;
1688 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1689 		    "[%s] non-ERP station leaves, count now %d\n",
1690 		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
1691 		if (ic->ic_nonerpsta == 0) {
1692 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1693 				"%s: disable use of protection\n", __func__);
1694 			ic->ic_flags &= ~IEEE80211_F_USEPROT;
1695 			/* XXX verify mode? */
1696 			if (ic->ic_caps & IEEE80211_C_SHPREAMBLE) {
1697 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1698 				    "%s: re-enable use of short preamble\n",
1699 				    __func__);
1700 				ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
1701 				ic->ic_flags &= ~IEEE80211_F_USEBARKER;
1702 			}
1703 		}
1704 	}
1705 }
1706 
1707 /*
1708  * Handle bookkeeping for station deauthentication/disassociation
1709  * when operating as an ap.
1710  */
1711 void
1712 ieee80211_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
1713 {
1714 	struct ieee80211_node_table *nt = ni->ni_table;
1715 
1716 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
1717 	    "[%s] station with aid %d leaves\n",
1718 	    ether_sprintf(ni->ni_macaddr), IEEE80211_NODE_AID(ni));
1719 
1720 	KASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
1721 		ic->ic_opmode == IEEE80211_M_IBSS ||
1722 		ic->ic_opmode == IEEE80211_M_AHDEMO,
1723 		("unexpected operating mode %u", ic->ic_opmode));
1724 	/*
1725 	 * If node wasn't previously associated all
1726 	 * we need to do is reclaim the reference.
1727 	 */
1728 	/* XXX ibss mode bypasses 11g and notification */
1729 	if (ni->ni_associd == 0)
1730 		goto done;
1731 	/*
1732 	 * Tell the authenticator the station is leaving.
1733 	 * Note that we must do this before yanking the
1734 	 * association id as the authenticator uses the
1735 	 * associd to locate it's state block.
1736 	 */
1737 	if (ic->ic_auth->ia_node_leave != NULL)
1738 		ic->ic_auth->ia_node_leave(ic, ni);
1739 	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1740 	ni->ni_associd = 0;
1741 	ic->ic_sta_assoc--;
1742 
1743 	if (ic->ic_curmode == IEEE80211_MODE_11G ||
1744 	    ic->ic_curmode == IEEE80211_MODE_TURBO_G)
1745 		ieee80211_node_leave_11g(ic, ni);
1746 	/*
1747 	 * Cleanup station state.  In particular clear various
1748 	 * state that might otherwise be reused if the node
1749 	 * is reused before the reference count goes to zero
1750 	 * (and memory is reclaimed).
1751 	 */
1752 	ieee80211_sta_leave(ic, ni);
1753 done:
1754 	/*
1755 	 * Remove the node from any table it's recorded in and
1756 	 * drop the caller's reference.  Removal from the table
1757 	 * is important to insure the node is not reprocessed
1758 	 * for inactivity.
1759 	 */
1760 	if (nt != NULL) {
1761 		IEEE80211_NODE_LOCK(nt);
1762 		node_reclaim(nt, ni);
1763 		IEEE80211_NODE_UNLOCK(nt);
1764 	} else
1765 		ieee80211_free_node(ni);
1766 }
1767 
1768 u_int8_t
1769 ieee80211_getrssi(struct ieee80211com *ic)
1770 {
1771 #define	NZ(x)	((x) == 0 ? 1 : (x))
1772 	struct ieee80211_node_table *nt = &ic->ic_sta;
1773 	u_int32_t rssi_samples, rssi_total;
1774 	struct ieee80211_node *ni;
1775 
1776 	rssi_total = 0;
1777 	rssi_samples = 0;
1778 	switch (ic->ic_opmode) {
1779 	case IEEE80211_M_IBSS:		/* average of all ibss neighbors */
1780 		/* XXX locking */
1781 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
1782 			if (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) {
1783 				rssi_samples++;
1784 				rssi_total += ic->ic_node_getrssi(ni);
1785 			}
1786 		break;
1787 	case IEEE80211_M_AHDEMO:	/* average of all neighbors */
1788 		/* XXX locking */
1789 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1790 			rssi_samples++;
1791 			rssi_total += ic->ic_node_getrssi(ni);
1792 		}
1793 		break;
1794 	case IEEE80211_M_HOSTAP:	/* average of all associated stations */
1795 		/* XXX locking */
1796 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
1797 			if (IEEE80211_AID(ni->ni_associd) != 0) {
1798 				rssi_samples++;
1799 				rssi_total += ic->ic_node_getrssi(ni);
1800 			}
1801 		break;
1802 	case IEEE80211_M_MONITOR:	/* XXX */
1803 	case IEEE80211_M_STA:		/* use stats from associated ap */
1804 	default:
1805 		if (ic->ic_bss != NULL)
1806 			rssi_total = ic->ic_node_getrssi(ic->ic_bss);
1807 		rssi_samples = 1;
1808 		break;
1809 	}
1810 	return rssi_total / NZ(rssi_samples);
1811 #undef NZ
1812 }
1813 
1814 /*
1815  * Indicate whether there are frames queued for a station in power-save mode.
1816  */
1817 static void
1818 ieee80211_set_tim(struct ieee80211com *ic, struct ieee80211_node *ni, int set)
1819 {
1820 	u_int16_t aid;
1821 
1822 	KASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
1823 		ic->ic_opmode == IEEE80211_M_IBSS,
1824 		("operating mode %u", ic->ic_opmode));
1825 
1826 	aid = IEEE80211_AID(ni->ni_associd);
1827 	KASSERT(aid < ic->ic_max_aid,
1828 		("bogus aid %u, max %u", aid, ic->ic_max_aid));
1829 
1830 	IEEE80211_BEACON_LOCK(ic);
1831 	if (set != (isset(ic->ic_tim_bitmap, aid) != 0)) {
1832 		if (set) {
1833 			setbit(ic->ic_tim_bitmap, aid);
1834 			ic->ic_ps_pending++;
1835 		} else {
1836 			clrbit(ic->ic_tim_bitmap, aid);
1837 			ic->ic_ps_pending--;
1838 		}
1839 		ic->ic_flags |= IEEE80211_F_TIMUPDATE;
1840 	}
1841 	IEEE80211_BEACON_UNLOCK(ic);
1842 }
1843 
1844 /*
1845  * Node table support.
1846  */
1847 
1848 static void
1849 ieee80211_node_table_init(struct ieee80211com *ic,
1850 	struct ieee80211_node_table *nt,
1851 	const char *name, int inact,
1852 	void (*timeout)(struct ieee80211_node_table *))
1853 {
1854 
1855 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1856 		"%s %s table, inact %u\n", __func__, name, inact);
1857 
1858 	nt->nt_ic = ic;
1859 	/* XXX need unit */
1860 	IEEE80211_NODE_LOCK_INIT(nt, ic->ic_ifp->if_xname);
1861 	IEEE80211_SCAN_LOCK_INIT(nt, ic->ic_ifp->if_xname);
1862 	TAILQ_INIT(&nt->nt_node);
1863 	nt->nt_name = name;
1864 	nt->nt_scangen = 1;
1865 	nt->nt_inact_init = inact;
1866 	nt->nt_timeout = timeout;
1867 }
1868 
1869 void
1870 ieee80211_node_table_reset(struct ieee80211_node_table *nt)
1871 {
1872 
1873 	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1874 		"%s %s table\n", __func__, nt->nt_name);
1875 
1876 	IEEE80211_NODE_LOCK(nt);
1877 	nt->nt_inact_timer = 0;
1878 	ieee80211_free_allnodes_locked(nt);
1879 	IEEE80211_NODE_UNLOCK(nt);
1880 }
1881 
1882 static void
1883 ieee80211_node_table_cleanup(struct ieee80211_node_table *nt)
1884 {
1885 
1886 	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1887 		"%s %s table\n", __func__, nt->nt_name);
1888 
1889 	ieee80211_free_allnodes_locked(nt);
1890 	IEEE80211_SCAN_LOCK_DESTROY(nt);
1891 	IEEE80211_NODE_LOCK_DESTROY(nt);
1892 }
1893