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