xref: /freebsd/sys/net80211/ieee80211_node.c (revision 7cc1fde083b1fe9d55388045ba3df7d770d4f3bf)
1 /*-
2  * Copyright (c) 2001 Atsushi Onoe
3  * Copyright (c) 2002-2009 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  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include "opt_wlan.h"
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/mbuf.h>
35 #include <sys/malloc.h>
36 #include <sys/kernel.h>
37 
38 #include <sys/socket.h>
39 
40 #include <net/if.h>
41 #include <net/if_media.h>
42 #include <net/ethernet.h>
43 
44 #include <net80211/ieee80211_var.h>
45 #include <net80211/ieee80211_input.h>
46 #ifdef IEEE80211_SUPPORT_SUPERG
47 #include <net80211/ieee80211_superg.h>
48 #endif
49 #ifdef IEEE80211_SUPPORT_TDMA
50 #include <net80211/ieee80211_tdma.h>
51 #endif
52 #include <net80211/ieee80211_wds.h>
53 #include <net80211/ieee80211_mesh.h>
54 #include <net80211/ieee80211_ratectl.h>
55 
56 #include <net/bpf.h>
57 
58 /*
59  * IEEE80211_NODE_HASHSIZE must be a power of 2.
60  */
61 CTASSERT((IEEE80211_NODE_HASHSIZE & (IEEE80211_NODE_HASHSIZE-1)) == 0);
62 
63 /*
64  * Association id's are managed with a bit vector.
65  */
66 #define	IEEE80211_AID_SET(_vap, b) \
67 	((_vap)->iv_aid_bitmap[IEEE80211_AID(b) / 32] |= \
68 		(1 << (IEEE80211_AID(b) % 32)))
69 #define	IEEE80211_AID_CLR(_vap, b) \
70 	((_vap)->iv_aid_bitmap[IEEE80211_AID(b) / 32] &= \
71 		~(1 << (IEEE80211_AID(b) % 32)))
72 #define	IEEE80211_AID_ISSET(_vap, b) \
73 	((_vap)->iv_aid_bitmap[IEEE80211_AID(b) / 32] & (1 << (IEEE80211_AID(b) % 32)))
74 
75 #ifdef IEEE80211_DEBUG_REFCNT
76 #define REFCNT_LOC "%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line
77 #else
78 #define REFCNT_LOC "%s %p<%s> refcnt %d\n", __func__
79 #endif
80 
81 static int ieee80211_sta_join1(struct ieee80211_node *);
82 
83 static struct ieee80211_node *node_alloc(struct ieee80211vap *,
84 	const uint8_t [IEEE80211_ADDR_LEN]);
85 static void node_cleanup(struct ieee80211_node *);
86 static void node_free(struct ieee80211_node *);
87 static void node_age(struct ieee80211_node *);
88 static int8_t node_getrssi(const struct ieee80211_node *);
89 static void node_getsignal(const struct ieee80211_node *, int8_t *, int8_t *);
90 static void node_getmimoinfo(const struct ieee80211_node *,
91 	struct ieee80211_mimo_info *);
92 
93 static void _ieee80211_free_node(struct ieee80211_node *);
94 
95 static void ieee80211_node_table_init(struct ieee80211com *ic,
96 	struct ieee80211_node_table *nt, const char *name,
97 	int inact, int keymaxix);
98 static void ieee80211_node_table_reset(struct ieee80211_node_table *,
99 	struct ieee80211vap *);
100 static void ieee80211_node_table_cleanup(struct ieee80211_node_table *nt);
101 static void ieee80211_erp_timeout(struct ieee80211com *);
102 
103 MALLOC_DEFINE(M_80211_NODE, "80211node", "802.11 node state");
104 MALLOC_DEFINE(M_80211_NODE_IE, "80211nodeie", "802.11 node ie");
105 
106 void
107 ieee80211_node_attach(struct ieee80211com *ic)
108 {
109 	/* XXX really want maxlen enforced per-sta */
110 	ieee80211_ageq_init(&ic->ic_stageq, ic->ic_max_keyix * 8,
111 	    "802.11 staging q");
112 	ieee80211_node_table_init(ic, &ic->ic_sta, "station",
113 		IEEE80211_INACT_INIT, ic->ic_max_keyix);
114 	callout_init(&ic->ic_inact, CALLOUT_MPSAFE);
115 	callout_reset(&ic->ic_inact, IEEE80211_INACT_WAIT*hz,
116 		ieee80211_node_timeout, ic);
117 
118 	ic->ic_node_alloc = node_alloc;
119 	ic->ic_node_free = node_free;
120 	ic->ic_node_cleanup = node_cleanup;
121 	ic->ic_node_age = node_age;
122 	ic->ic_node_drain = node_age;		/* NB: same as age */
123 	ic->ic_node_getrssi = node_getrssi;
124 	ic->ic_node_getsignal = node_getsignal;
125 	ic->ic_node_getmimoinfo = node_getmimoinfo;
126 
127 	/*
128 	 * Set flags to be propagated to all vap's;
129 	 * these define default behaviour/configuration.
130 	 */
131 	ic->ic_flags_ext |= IEEE80211_FEXT_INACT; /* inactivity processing */
132 }
133 
134 void
135 ieee80211_node_detach(struct ieee80211com *ic)
136 {
137 
138 	callout_drain(&ic->ic_inact);
139 	ieee80211_node_table_cleanup(&ic->ic_sta);
140 	ieee80211_ageq_cleanup(&ic->ic_stageq);
141 }
142 
143 void
144 ieee80211_node_vattach(struct ieee80211vap *vap)
145 {
146 	/* NB: driver can override */
147 	vap->iv_max_aid = IEEE80211_AID_DEF;
148 
149 	/* default station inactivity timer setings */
150 	vap->iv_inact_init = IEEE80211_INACT_INIT;
151 	vap->iv_inact_auth = IEEE80211_INACT_AUTH;
152 	vap->iv_inact_run = IEEE80211_INACT_RUN;
153 	vap->iv_inact_probe = IEEE80211_INACT_PROBE;
154 
155 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_INACT,
156 	    "%s: init %u auth %u run %u probe %u\n", __func__,
157 	    vap->iv_inact_init, vap->iv_inact_auth,
158 	    vap->iv_inact_run, vap->iv_inact_probe);
159 }
160 
161 void
162 ieee80211_node_latevattach(struct ieee80211vap *vap)
163 {
164 	if (vap->iv_opmode == IEEE80211_M_HOSTAP) {
165 		/* XXX should we allow max aid to be zero? */
166 		if (vap->iv_max_aid < IEEE80211_AID_MIN) {
167 			vap->iv_max_aid = IEEE80211_AID_MIN;
168 			if_printf(vap->iv_ifp,
169 			    "WARNING: max aid too small, changed to %d\n",
170 			    vap->iv_max_aid);
171 		}
172 		vap->iv_aid_bitmap = (uint32_t *) malloc(
173 			howmany(vap->iv_max_aid, 32) * sizeof(uint32_t),
174 			M_80211_NODE, M_NOWAIT | M_ZERO);
175 		if (vap->iv_aid_bitmap == NULL) {
176 			/* XXX no way to recover */
177 			printf("%s: no memory for AID bitmap, max aid %d!\n",
178 			    __func__, vap->iv_max_aid);
179 			vap->iv_max_aid = 0;
180 		}
181 	}
182 
183 	ieee80211_reset_bss(vap);
184 
185 	vap->iv_auth = ieee80211_authenticator_get(vap->iv_bss->ni_authmode);
186 }
187 
188 void
189 ieee80211_node_vdetach(struct ieee80211vap *vap)
190 {
191 	struct ieee80211com *ic = vap->iv_ic;
192 
193 	ieee80211_node_table_reset(&ic->ic_sta, vap);
194 	if (vap->iv_bss != NULL) {
195 		ieee80211_free_node(vap->iv_bss);
196 		vap->iv_bss = NULL;
197 	}
198 	if (vap->iv_aid_bitmap != NULL) {
199 		free(vap->iv_aid_bitmap, M_80211_NODE);
200 		vap->iv_aid_bitmap = NULL;
201 	}
202 }
203 
204 /*
205  * Port authorize/unauthorize interfaces for use by an authenticator.
206  */
207 
208 void
209 ieee80211_node_authorize(struct ieee80211_node *ni)
210 {
211 	struct ieee80211vap *vap = ni->ni_vap;
212 
213 	ni->ni_flags |= IEEE80211_NODE_AUTH;
214 	ni->ni_inact_reload = vap->iv_inact_run;
215 	ni->ni_inact = ni->ni_inact_reload;
216 
217 	IEEE80211_NOTE(vap, IEEE80211_MSG_INACT, ni,
218 	    "%s: inact_reload %u", __func__, ni->ni_inact_reload);
219 }
220 
221 void
222 ieee80211_node_unauthorize(struct ieee80211_node *ni)
223 {
224 	struct ieee80211vap *vap = ni->ni_vap;
225 
226 	ni->ni_flags &= ~IEEE80211_NODE_AUTH;
227 	ni->ni_inact_reload = vap->iv_inact_auth;
228 	if (ni->ni_inact > ni->ni_inact_reload)
229 		ni->ni_inact = ni->ni_inact_reload;
230 
231 	IEEE80211_NOTE(vap, IEEE80211_MSG_INACT, ni,
232 	    "%s: inact_reload %u inact %u", __func__,
233 	    ni->ni_inact_reload, ni->ni_inact);
234 }
235 
236 /*
237  * Fix tx parameters for a node according to ``association state''.
238  */
239 void
240 ieee80211_node_setuptxparms(struct ieee80211_node *ni)
241 {
242 	struct ieee80211vap *vap = ni->ni_vap;
243 	enum ieee80211_phymode mode;
244 
245 	if (ni->ni_flags & IEEE80211_NODE_HT) {
246 		if (IEEE80211_IS_CHAN_5GHZ(ni->ni_chan))
247 			mode = IEEE80211_MODE_11NA;
248 		else
249 			mode = IEEE80211_MODE_11NG;
250 	} else {				/* legacy rate handling */
251 		if (IEEE80211_IS_CHAN_ST(ni->ni_chan))
252 			mode = IEEE80211_MODE_STURBO_A;
253 		else if (IEEE80211_IS_CHAN_HALF(ni->ni_chan))
254 			mode = IEEE80211_MODE_HALF;
255 		else if (IEEE80211_IS_CHAN_QUARTER(ni->ni_chan))
256 			mode = IEEE80211_MODE_QUARTER;
257 		/* NB: 108A should be handled as 11a */
258 		else if (IEEE80211_IS_CHAN_A(ni->ni_chan))
259 			mode = IEEE80211_MODE_11A;
260 		else if (IEEE80211_IS_CHAN_108G(ni->ni_chan) ||
261 		    (ni->ni_flags & IEEE80211_NODE_ERP))
262 			mode = IEEE80211_MODE_11G;
263 		else
264 			mode = IEEE80211_MODE_11B;
265 	}
266 	ni->ni_txparms = &vap->iv_txparms[mode];
267 }
268 
269 /*
270  * Set/change the channel.  The rate set is also updated as
271  * to insure a consistent view by drivers.
272  * XXX should be private but hostap needs it to deal with CSA
273  */
274 void
275 ieee80211_node_set_chan(struct ieee80211_node *ni,
276 	struct ieee80211_channel *chan)
277 {
278 	struct ieee80211com *ic = ni->ni_ic;
279 	struct ieee80211vap *vap = ni->ni_vap;
280 	enum ieee80211_phymode mode;
281 
282 	KASSERT(chan != IEEE80211_CHAN_ANYC, ("no channel"));
283 
284 	ni->ni_chan = chan;
285 	mode = ieee80211_chan2mode(chan);
286 	if (IEEE80211_IS_CHAN_HT(chan)) {
287 		/*
288 		 * XXX Gotta be careful here; the rate set returned by
289 		 * ieee80211_get_suprates is actually any HT rate
290 		 * set so blindly copying it will be bad.  We must
291 		 * install the legacy rate est in ni_rates and the
292 		 * HT rate set in ni_htrates.
293 		 */
294 		ni->ni_htrates = *ieee80211_get_suphtrates(ic, chan);
295 		/*
296 		 * Setup bss tx parameters based on operating mode.  We
297 		 * use legacy rates when operating in a mixed HT+non-HT bss
298 		 * and non-ERP rates in 11g for mixed ERP+non-ERP bss.
299 		 */
300 		if (mode == IEEE80211_MODE_11NA &&
301 		    (vap->iv_flags_ht & IEEE80211_FHT_PUREN) == 0)
302 			mode = IEEE80211_MODE_11A;
303 		else if (mode == IEEE80211_MODE_11NG &&
304 		    (vap->iv_flags_ht & IEEE80211_FHT_PUREN) == 0)
305 			mode = IEEE80211_MODE_11G;
306 		if (mode == IEEE80211_MODE_11G &&
307 		    (vap->iv_flags & IEEE80211_F_PUREG) == 0)
308 			mode = IEEE80211_MODE_11B;
309 	}
310 	ni->ni_txparms = &vap->iv_txparms[mode];
311 	ni->ni_rates = *ieee80211_get_suprates(ic, chan);
312 }
313 
314 static __inline void
315 copy_bss(struct ieee80211_node *nbss, const struct ieee80211_node *obss)
316 {
317 	/* propagate useful state */
318 	nbss->ni_authmode = obss->ni_authmode;
319 	nbss->ni_txpower = obss->ni_txpower;
320 	nbss->ni_vlan = obss->ni_vlan;
321 	/* XXX statistics? */
322 	/* XXX legacy WDS bssid? */
323 }
324 
325 void
326 ieee80211_create_ibss(struct ieee80211vap* vap, struct ieee80211_channel *chan)
327 {
328 	struct ieee80211com *ic = vap->iv_ic;
329 	struct ieee80211_node *ni;
330 
331 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
332 		"%s: creating %s on channel %u\n", __func__,
333 		ieee80211_opmode_name[vap->iv_opmode],
334 		ieee80211_chan2ieee(ic, chan));
335 
336 	ni = ieee80211_alloc_node(&ic->ic_sta, vap, vap->iv_myaddr);
337 	if (ni == NULL) {
338 		/* XXX recovery? */
339 		return;
340 	}
341 	IEEE80211_ADDR_COPY(ni->ni_bssid, vap->iv_myaddr);
342 	ni->ni_esslen = vap->iv_des_ssid[0].len;
343 	memcpy(ni->ni_essid, vap->iv_des_ssid[0].ssid, ni->ni_esslen);
344 	if (vap->iv_bss != NULL)
345 		copy_bss(ni, vap->iv_bss);
346 	ni->ni_intval = ic->ic_bintval;
347 	if (vap->iv_flags & IEEE80211_F_PRIVACY)
348 		ni->ni_capinfo |= IEEE80211_CAPINFO_PRIVACY;
349 	if (ic->ic_phytype == IEEE80211_T_FH) {
350 		ni->ni_fhdwell = 200;	/* XXX */
351 		ni->ni_fhindex = 1;
352 	}
353 	if (vap->iv_opmode == IEEE80211_M_IBSS) {
354 		vap->iv_flags |= IEEE80211_F_SIBSS;
355 		ni->ni_capinfo |= IEEE80211_CAPINFO_IBSS;	/* XXX */
356 		if (vap->iv_flags & IEEE80211_F_DESBSSID)
357 			IEEE80211_ADDR_COPY(ni->ni_bssid, vap->iv_des_bssid);
358 		else {
359 			get_random_bytes(ni->ni_bssid, IEEE80211_ADDR_LEN);
360 			/* clear group bit, add local bit */
361 			ni->ni_bssid[0] = (ni->ni_bssid[0] &~ 0x01) | 0x02;
362 		}
363 	} else if (vap->iv_opmode == IEEE80211_M_AHDEMO) {
364 		if (vap->iv_flags & IEEE80211_F_DESBSSID)
365 			IEEE80211_ADDR_COPY(ni->ni_bssid, vap->iv_des_bssid);
366 		else
367 #ifdef IEEE80211_SUPPORT_TDMA
368 		if ((vap->iv_caps & IEEE80211_C_TDMA) == 0)
369 #endif
370 			memset(ni->ni_bssid, 0, IEEE80211_ADDR_LEN);
371 #ifdef IEEE80211_SUPPORT_MESH
372 	} else if (vap->iv_opmode == IEEE80211_M_MBSS) {
373 		ni->ni_meshidlen = vap->iv_mesh->ms_idlen;
374 		memcpy(ni->ni_meshid, vap->iv_mesh->ms_id, ni->ni_meshidlen);
375 #endif
376 	}
377 	/*
378 	 * Fix the channel and related attributes.
379 	 */
380 	/* clear DFS CAC state on previous channel */
381 	if (ic->ic_bsschan != IEEE80211_CHAN_ANYC &&
382 	    ic->ic_bsschan->ic_freq != chan->ic_freq &&
383 	    IEEE80211_IS_CHAN_CACDONE(ic->ic_bsschan))
384 		ieee80211_dfs_cac_clear(ic, ic->ic_bsschan);
385 	ic->ic_bsschan = chan;
386 	ieee80211_node_set_chan(ni, chan);
387 	ic->ic_curmode = ieee80211_chan2mode(chan);
388 	/*
389 	 * Do mode-specific setup.
390 	 */
391 	if (IEEE80211_IS_CHAN_FULL(chan)) {
392 		if (IEEE80211_IS_CHAN_ANYG(chan)) {
393 			/*
394 			 * Use a mixed 11b/11g basic rate set.
395 			 */
396 			ieee80211_setbasicrates(&ni->ni_rates,
397 			    IEEE80211_MODE_11G);
398 			if (vap->iv_flags & IEEE80211_F_PUREG) {
399 				/*
400 				 * Also mark OFDM rates basic so 11b
401 				 * stations do not join (WiFi compliance).
402 				 */
403 				ieee80211_addbasicrates(&ni->ni_rates,
404 				    IEEE80211_MODE_11A);
405 			}
406 		} else if (IEEE80211_IS_CHAN_B(chan)) {
407 			/*
408 			 * Force pure 11b rate set.
409 			 */
410 			ieee80211_setbasicrates(&ni->ni_rates,
411 				IEEE80211_MODE_11B);
412 		}
413 	}
414 
415 	(void) ieee80211_sta_join1(ieee80211_ref_node(ni));
416 }
417 
418 /*
419  * Reset bss state on transition to the INIT state.
420  * Clear any stations from the table (they have been
421  * deauth'd) and reset the bss node (clears key, rate
422  * etc. state).
423  */
424 void
425 ieee80211_reset_bss(struct ieee80211vap *vap)
426 {
427 	struct ieee80211com *ic = vap->iv_ic;
428 	struct ieee80211_node *ni, *obss;
429 
430 	ieee80211_node_table_reset(&ic->ic_sta, vap);
431 	/* XXX multi-bss: wrong */
432 	ieee80211_reset_erp(ic);
433 
434 	ni = ieee80211_alloc_node(&ic->ic_sta, vap, vap->iv_myaddr);
435 	KASSERT(ni != NULL, ("unable to setup initial BSS node"));
436 	obss = vap->iv_bss;
437 	vap->iv_bss = ieee80211_ref_node(ni);
438 	if (obss != NULL) {
439 		copy_bss(ni, obss);
440 		ni->ni_intval = ic->ic_bintval;
441 		ieee80211_free_node(obss);
442 	} else
443 		IEEE80211_ADDR_COPY(ni->ni_bssid, vap->iv_myaddr);
444 }
445 
446 static int
447 match_ssid(const struct ieee80211_node *ni,
448 	int nssid, const struct ieee80211_scan_ssid ssids[])
449 {
450 	int i;
451 
452 	for (i = 0; i < nssid; i++) {
453 		if (ni->ni_esslen == ssids[i].len &&
454 		     memcmp(ni->ni_essid, ssids[i].ssid, ni->ni_esslen) == 0)
455 			return 1;
456 	}
457 	return 0;
458 }
459 
460 /*
461  * Test a node for suitability/compatibility.
462  */
463 static int
464 check_bss(struct ieee80211vap *vap, struct ieee80211_node *ni)
465 {
466 	struct ieee80211com *ic = ni->ni_ic;
467         uint8_t rate;
468 
469 	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
470 		return 0;
471 	if (vap->iv_opmode == IEEE80211_M_IBSS) {
472 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
473 			return 0;
474 	} else {
475 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
476 			return 0;
477 	}
478 	if (vap->iv_flags & IEEE80211_F_PRIVACY) {
479 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
480 			return 0;
481 	} else {
482 		/* XXX does this mean privacy is supported or required? */
483 		if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
484 			return 0;
485 	}
486 	rate = ieee80211_fix_rate(ni, &ni->ni_rates,
487 	    IEEE80211_F_JOIN | IEEE80211_F_DONEGO | IEEE80211_F_DOFRATE);
488 	if (rate & IEEE80211_RATE_BASIC)
489 		return 0;
490 	if (vap->iv_des_nssid != 0 &&
491 	    !match_ssid(ni, vap->iv_des_nssid, vap->iv_des_ssid))
492 		return 0;
493 	if ((vap->iv_flags & IEEE80211_F_DESBSSID) &&
494 	    !IEEE80211_ADDR_EQ(vap->iv_des_bssid, ni->ni_bssid))
495 		return 0;
496 	return 1;
497 }
498 
499 #ifdef IEEE80211_DEBUG
500 /*
501  * Display node suitability/compatibility.
502  */
503 static void
504 check_bss_debug(struct ieee80211vap *vap, struct ieee80211_node *ni)
505 {
506 	struct ieee80211com *ic = ni->ni_ic;
507         uint8_t rate;
508         int fail;
509 
510 	fail = 0;
511 	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
512 		fail |= 0x01;
513 	if (vap->iv_opmode == IEEE80211_M_IBSS) {
514 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
515 			fail |= 0x02;
516 	} else {
517 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
518 			fail |= 0x02;
519 	}
520 	if (vap->iv_flags & IEEE80211_F_PRIVACY) {
521 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
522 			fail |= 0x04;
523 	} else {
524 		/* XXX does this mean privacy is supported or required? */
525 		if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
526 			fail |= 0x04;
527 	}
528 	rate = ieee80211_fix_rate(ni, &ni->ni_rates,
529 	     IEEE80211_F_JOIN | IEEE80211_F_DONEGO | IEEE80211_F_DOFRATE);
530 	if (rate & IEEE80211_RATE_BASIC)
531 		fail |= 0x08;
532 	if (vap->iv_des_nssid != 0 &&
533 	    !match_ssid(ni, vap->iv_des_nssid, vap->iv_des_ssid))
534 		fail |= 0x10;
535 	if ((vap->iv_flags & IEEE80211_F_DESBSSID) &&
536 	    !IEEE80211_ADDR_EQ(vap->iv_des_bssid, ni->ni_bssid))
537 		fail |= 0x20;
538 
539 	printf(" %c %s", fail ? '-' : '+', ether_sprintf(ni->ni_macaddr));
540 	printf(" %s%c", ether_sprintf(ni->ni_bssid), fail & 0x20 ? '!' : ' ');
541 	printf(" %3d%c",
542 	    ieee80211_chan2ieee(ic, ni->ni_chan), fail & 0x01 ? '!' : ' ');
543 	printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
544 	    fail & 0x08 ? '!' : ' ');
545 	printf(" %4s%c",
546 	    (ni->ni_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
547 	    (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
548 	    "????",
549 	    fail & 0x02 ? '!' : ' ');
550 	printf(" %3s%c ",
551 	    (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) ?  "wep" : "no",
552 	    fail & 0x04 ? '!' : ' ');
553 	ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
554 	printf("%s\n", fail & 0x10 ? "!" : "");
555 }
556 #endif /* IEEE80211_DEBUG */
557 
558 /*
559  * Handle 802.11 ad hoc network merge.  The
560  * convention, set by the Wireless Ethernet Compatibility Alliance
561  * (WECA), is that an 802.11 station will change its BSSID to match
562  * the "oldest" 802.11 ad hoc network, on the same channel, that
563  * has the station's desired SSID.  The "oldest" 802.11 network
564  * sends beacons with the greatest TSF timestamp.
565  *
566  * The caller is assumed to validate TSF's before attempting a merge.
567  *
568  * Return !0 if the BSSID changed, 0 otherwise.
569  */
570 int
571 ieee80211_ibss_merge(struct ieee80211_node *ni)
572 {
573 	struct ieee80211vap *vap = ni->ni_vap;
574 #ifdef IEEE80211_DEBUG
575 	struct ieee80211com *ic = ni->ni_ic;
576 #endif
577 
578 	if (ni == vap->iv_bss ||
579 	    IEEE80211_ADDR_EQ(ni->ni_bssid, vap->iv_bss->ni_bssid)) {
580 		/* unchanged, nothing to do */
581 		return 0;
582 	}
583 	if (!check_bss(vap, ni)) {
584 		/* capabilities mismatch */
585 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_ASSOC,
586 		    "%s: merge failed, capabilities mismatch\n", __func__);
587 #ifdef IEEE80211_DEBUG
588 		if (ieee80211_msg_assoc(vap))
589 			check_bss_debug(vap, ni);
590 #endif
591 		vap->iv_stats.is_ibss_capmismatch++;
592 		return 0;
593 	}
594 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_ASSOC,
595 		"%s: new bssid %s: %s preamble, %s slot time%s\n", __func__,
596 		ether_sprintf(ni->ni_bssid),
597 		ic->ic_flags&IEEE80211_F_SHPREAMBLE ? "short" : "long",
598 		ic->ic_flags&IEEE80211_F_SHSLOT ? "short" : "long",
599 		ic->ic_flags&IEEE80211_F_USEPROT ? ", protection" : ""
600 	);
601 	return ieee80211_sta_join1(ieee80211_ref_node(ni));
602 }
603 
604 /*
605  * Calculate HT channel promotion flags for all vaps.
606  * This assumes ni_chan have been setup for each vap.
607  */
608 static int
609 gethtadjustflags(struct ieee80211com *ic)
610 {
611 	struct ieee80211vap *vap;
612 	int flags;
613 
614 	flags = 0;
615 	/* XXX locking */
616 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
617 		if (vap->iv_state < IEEE80211_S_RUN)
618 			continue;
619 		switch (vap->iv_opmode) {
620 		case IEEE80211_M_WDS:
621 		case IEEE80211_M_STA:
622 		case IEEE80211_M_AHDEMO:
623 		case IEEE80211_M_HOSTAP:
624 		case IEEE80211_M_IBSS:
625 		case IEEE80211_M_MBSS:
626 			flags |= ieee80211_htchanflags(vap->iv_bss->ni_chan);
627 			break;
628 		default:
629 			break;
630 		}
631 	}
632 	return flags;
633 }
634 
635 /*
636  * Check if the current channel needs to change based on whether
637  * any vap's are using HT20/HT40.  This is used to sync the state
638  * of ic_curchan after a channel width change on a running vap.
639  */
640 void
641 ieee80211_sync_curchan(struct ieee80211com *ic)
642 {
643 	struct ieee80211_channel *c;
644 
645 	c = ieee80211_ht_adjust_channel(ic, ic->ic_curchan, gethtadjustflags(ic));
646 	if (c != ic->ic_curchan) {
647 		ic->ic_curchan = c;
648 		ic->ic_curmode = ieee80211_chan2mode(ic->ic_curchan);
649 		ic->ic_rt = ieee80211_get_ratetable(ic->ic_curchan);
650 		IEEE80211_UNLOCK(ic);
651 		ic->ic_set_channel(ic);
652 		ieee80211_radiotap_chan_change(ic);
653 		IEEE80211_LOCK(ic);
654 	}
655 }
656 
657 /*
658  * Setup the current channel.  The request channel may be
659  * promoted if other vap's are operating with HT20/HT40.
660  */
661 void
662 ieee80211_setupcurchan(struct ieee80211com *ic, struct ieee80211_channel *c)
663 {
664 	if (ic->ic_htcaps & IEEE80211_HTC_HT) {
665 		int flags = gethtadjustflags(ic);
666 		/*
667 		 * Check for channel promotion required to support the
668 		 * set of running vap's.  This assumes we are called
669 		 * after ni_chan is setup for each vap.
670 		 */
671 		/* NB: this assumes IEEE80211_FHT_USEHT40 > IEEE80211_FHT_HT */
672 		if (flags > ieee80211_htchanflags(c))
673 			c = ieee80211_ht_adjust_channel(ic, c, flags);
674 	}
675 	ic->ic_bsschan = ic->ic_curchan = c;
676 	ic->ic_curmode = ieee80211_chan2mode(ic->ic_curchan);
677 	ic->ic_rt = ieee80211_get_ratetable(ic->ic_curchan);
678 }
679 
680 /*
681  * Change the current channel.  The channel change is guaranteed to have
682  * happened before the next state change.
683  */
684 void
685 ieee80211_setcurchan(struct ieee80211com *ic, struct ieee80211_channel *c)
686 {
687 	ieee80211_setupcurchan(ic, c);
688 	ieee80211_runtask(ic, &ic->ic_chan_task);
689 }
690 
691 /*
692  * Join the specified IBSS/BSS network.  The node is assumed to
693  * be passed in with a held reference.
694  */
695 static int
696 ieee80211_sta_join1(struct ieee80211_node *selbs)
697 {
698 	struct ieee80211vap *vap = selbs->ni_vap;
699 	struct ieee80211com *ic = selbs->ni_ic;
700 	struct ieee80211_node *obss;
701 	int canreassoc;
702 
703 	/*
704 	 * Committed to selbs, setup state.
705 	 */
706 	obss = vap->iv_bss;
707 	/*
708 	 * Check if old+new node have the same address in which
709 	 * case we can reassociate when operating in sta mode.
710 	 */
711 	canreassoc = (obss != NULL &&
712 		vap->iv_state == IEEE80211_S_RUN &&
713 		IEEE80211_ADDR_EQ(obss->ni_macaddr, selbs->ni_macaddr));
714 	vap->iv_bss = selbs;		/* NB: caller assumed to bump refcnt */
715 	if (obss != NULL) {
716 		copy_bss(selbs, obss);
717 		ieee80211_node_decref(obss);	/* iv_bss reference */
718 		ieee80211_free_node(obss);	/* station table reference */
719 		obss = NULL;		/* NB: guard against later use */
720 	}
721 
722 	/*
723 	 * Delete unusable rates; we've already checked
724 	 * that the negotiated rate set is acceptable.
725 	 */
726 	ieee80211_fix_rate(vap->iv_bss, &vap->iv_bss->ni_rates,
727 		IEEE80211_F_DODEL | IEEE80211_F_JOIN);
728 
729 	ieee80211_setcurchan(ic, selbs->ni_chan);
730 	/*
731 	 * Set the erp state (mostly the slot time) to deal with
732 	 * the auto-select case; this should be redundant if the
733 	 * mode is locked.
734 	 */
735 	ieee80211_reset_erp(ic);
736 	ieee80211_wme_initparams(vap);
737 
738 	if (vap->iv_opmode == IEEE80211_M_STA) {
739 		if (canreassoc) {
740 			/* Reassociate */
741 			ieee80211_new_state(vap, IEEE80211_S_ASSOC, 1);
742 		} else {
743 			/*
744 			 * Act as if we received a DEAUTH frame in case we
745 			 * are invoked from the RUN state.  This will cause
746 			 * us to try to re-authenticate if we are operating
747 			 * as a station.
748 			 */
749 			ieee80211_new_state(vap, IEEE80211_S_AUTH,
750 				IEEE80211_FC0_SUBTYPE_DEAUTH);
751 		}
752 	} else
753 		ieee80211_new_state(vap, IEEE80211_S_RUN, -1);
754 	return 1;
755 }
756 
757 int
758 ieee80211_sta_join(struct ieee80211vap *vap, struct ieee80211_channel *chan,
759 	const struct ieee80211_scan_entry *se)
760 {
761 	struct ieee80211com *ic = vap->iv_ic;
762 	struct ieee80211_node *ni;
763 
764 	ni = ieee80211_alloc_node(&ic->ic_sta, vap, se->se_macaddr);
765 	if (ni == NULL) {
766 		/* XXX msg */
767 		return 0;
768 	}
769 	/*
770 	 * Expand scan state into node's format.
771 	 * XXX may not need all this stuff
772 	 */
773 	IEEE80211_ADDR_COPY(ni->ni_bssid, se->se_bssid);
774 	ni->ni_esslen = se->se_ssid[1];
775 	memcpy(ni->ni_essid, se->se_ssid+2, ni->ni_esslen);
776 	ni->ni_tstamp.tsf = se->se_tstamp.tsf;
777 	ni->ni_intval = se->se_intval;
778 	ni->ni_capinfo = se->se_capinfo;
779 	ni->ni_chan = chan;
780 	ni->ni_timoff = se->se_timoff;
781 	ni->ni_fhdwell = se->se_fhdwell;
782 	ni->ni_fhindex = se->se_fhindex;
783 	ni->ni_erp = se->se_erp;
784 	IEEE80211_RSSI_LPF(ni->ni_avgrssi, se->se_rssi);
785 	ni->ni_noise = se->se_noise;
786 	if (vap->iv_opmode == IEEE80211_M_STA) {
787 		/* NB: only infrastructure mode requires an associd */
788 		ni->ni_flags |= IEEE80211_NODE_ASSOCID;
789 	}
790 
791 	if (ieee80211_ies_init(&ni->ni_ies, se->se_ies.data, se->se_ies.len)) {
792 		ieee80211_ies_expand(&ni->ni_ies);
793 #ifdef IEEE80211_SUPPORT_SUPERG
794 		if (ni->ni_ies.ath_ie != NULL)
795 			ieee80211_parse_ath(ni, ni->ni_ies.ath_ie);
796 #endif
797 		if (ni->ni_ies.htcap_ie != NULL)
798 			ieee80211_parse_htcap(ni, ni->ni_ies.htcap_ie);
799 		if (ni->ni_ies.htinfo_ie != NULL)
800 			ieee80211_parse_htinfo(ni, ni->ni_ies.htinfo_ie);
801 #ifdef IEEE80211_SUPPORT_MESH
802 		if (ni->ni_ies.meshid_ie != NULL)
803 			ieee80211_parse_meshid(ni, ni->ni_ies.meshid_ie);
804 #endif
805 #ifdef IEEE80211_SUPPORT_TDMA
806 		if (ni->ni_ies.tdma_ie != NULL)
807 			ieee80211_parse_tdma(ni, ni->ni_ies.tdma_ie);
808 #endif
809 	}
810 
811 	vap->iv_dtim_period = se->se_dtimperiod;
812 	vap->iv_dtim_count = 0;
813 
814 	/* NB: must be after ni_chan is setup */
815 	ieee80211_setup_rates(ni, se->se_rates, se->se_xrates,
816 		IEEE80211_F_DOSORT);
817 	if (ieee80211_iserp_rateset(&ni->ni_rates))
818 		ni->ni_flags |= IEEE80211_NODE_ERP;
819 	ieee80211_node_setuptxparms(ni);
820 	if (vap->iv_caps & IEEE80211_C_RATECTL)
821 		ieee80211_ratectl_node_init(ni);
822 
823 	return ieee80211_sta_join1(ieee80211_ref_node(ni));
824 }
825 
826 /*
827  * Leave the specified IBSS/BSS network.  The node is assumed to
828  * be passed in with a held reference.
829  */
830 void
831 ieee80211_sta_leave(struct ieee80211_node *ni)
832 {
833 	struct ieee80211com *ic = ni->ni_ic;
834 
835 	ic->ic_node_cleanup(ni);
836 	ieee80211_notify_node_leave(ni);
837 }
838 
839 /*
840  * Send a deauthenticate frame and drop the station.
841  */
842 void
843 ieee80211_node_deauth(struct ieee80211_node *ni, int reason)
844 {
845 	/* NB: bump the refcnt to be sure temporay nodes are not reclaimed */
846 	ieee80211_ref_node(ni);
847 	if (ni->ni_associd != 0)
848 		IEEE80211_SEND_MGMT(ni, IEEE80211_FC0_SUBTYPE_DEAUTH, reason);
849 	ieee80211_node_leave(ni);
850 	ieee80211_free_node(ni);
851 }
852 
853 static struct ieee80211_node *
854 node_alloc(struct ieee80211vap *vap, const uint8_t macaddr[IEEE80211_ADDR_LEN])
855 {
856 	struct ieee80211_node *ni;
857 
858 	ni = (struct ieee80211_node *) malloc(sizeof(struct ieee80211_node),
859 		M_80211_NODE, M_NOWAIT | M_ZERO);
860 	return ni;
861 }
862 
863 /*
864  * Initialize an ie blob with the specified data.  If previous
865  * data exists re-use the data block.  As a side effect we clear
866  * all references to specific ie's; the caller is required to
867  * recalculate them.
868  */
869 int
870 ieee80211_ies_init(struct ieee80211_ies *ies, const uint8_t *data, int len)
871 {
872 	/* NB: assumes data+len are the last fields */
873 	memset(ies, 0, offsetof(struct ieee80211_ies, data));
874 	if (ies->data != NULL && ies->len != len) {
875 		/* data size changed */
876 		free(ies->data, M_80211_NODE_IE);
877 		ies->data = NULL;
878 	}
879 	if (ies->data == NULL) {
880 		ies->data = (uint8_t *) malloc(len, M_80211_NODE_IE, M_NOWAIT);
881 		if (ies->data == NULL) {
882 			ies->len = 0;
883 			/* NB: pointers have already been zero'd above */
884 			return 0;
885 		}
886 	}
887 	memcpy(ies->data, data, len);
888 	ies->len = len;
889 	return 1;
890 }
891 
892 /*
893  * Reclaim storage for an ie blob.
894  */
895 void
896 ieee80211_ies_cleanup(struct ieee80211_ies *ies)
897 {
898 	if (ies->data != NULL)
899 		free(ies->data, M_80211_NODE_IE);
900 }
901 
902 /*
903  * Expand an ie blob data contents and to fillin individual
904  * ie pointers.  The data blob is assumed to be well-formed;
905  * we don't do any validity checking of ie lengths.
906  */
907 void
908 ieee80211_ies_expand(struct ieee80211_ies *ies)
909 {
910 	uint8_t *ie;
911 	int ielen;
912 
913 	ie = ies->data;
914 	ielen = ies->len;
915 	while (ielen > 0) {
916 		switch (ie[0]) {
917 		case IEEE80211_ELEMID_VENDOR:
918 			if (iswpaoui(ie))
919 				ies->wpa_ie = ie;
920 			else if (iswmeoui(ie))
921 				ies->wme_ie = ie;
922 #ifdef IEEE80211_SUPPORT_SUPERG
923 			else if (isatherosoui(ie))
924 				ies->ath_ie = ie;
925 #endif
926 #ifdef IEEE80211_SUPPORT_TDMA
927 			else if (istdmaoui(ie))
928 				ies->tdma_ie = ie;
929 #endif
930 			break;
931 		case IEEE80211_ELEMID_RSN:
932 			ies->rsn_ie = ie;
933 			break;
934 		case IEEE80211_ELEMID_HTCAP:
935 			ies->htcap_ie = ie;
936 			break;
937 #ifdef IEEE80211_SUPPORT_MESH
938 		case IEEE80211_ELEMID_MESHID:
939 			ies->meshid_ie = ie;
940 			break;
941 #endif
942 		}
943 		ielen -= 2 + ie[1];
944 		ie += 2 + ie[1];
945 	}
946 }
947 
948 /*
949  * Reclaim any resources in a node and reset any critical
950  * state.  Typically nodes are free'd immediately after,
951  * but in some cases the storage may be reused so we need
952  * to insure consistent state (should probably fix that).
953  */
954 static void
955 node_cleanup(struct ieee80211_node *ni)
956 {
957 #define	N(a)	(sizeof(a)/sizeof(a[0]))
958 	struct ieee80211vap *vap = ni->ni_vap;
959 	struct ieee80211com *ic = ni->ni_ic;
960 	int i;
961 
962 	/* NB: preserve ni_table */
963 	if (ni->ni_flags & IEEE80211_NODE_PWR_MGT) {
964 		if (vap->iv_opmode != IEEE80211_M_STA)
965 			vap->iv_ps_sta--;
966 		ni->ni_flags &= ~IEEE80211_NODE_PWR_MGT;
967 		IEEE80211_NOTE(vap, IEEE80211_MSG_POWER, ni,
968 		    "power save mode off, %u sta's in ps mode", vap->iv_ps_sta);
969 	}
970 	/*
971 	 * Cleanup any HT-related state.
972 	 */
973 	if (ni->ni_flags & IEEE80211_NODE_HT)
974 		ieee80211_ht_node_cleanup(ni);
975 #ifdef IEEE80211_SUPPORT_SUPERG
976 	else if (ni->ni_ath_flags & IEEE80211_NODE_ATH)
977 		ieee80211_ff_node_cleanup(ni);
978 #endif
979 #ifdef IEEE80211_SUPPORT_MESH
980 	/*
981 	 * Cleanup any mesh-related state.
982 	 */
983 	if (vap->iv_opmode == IEEE80211_M_MBSS)
984 		ieee80211_mesh_node_cleanup(ni);
985 #endif
986 	/*
987 	 * Clear any staging queue entries.
988 	 */
989 	ieee80211_ageq_drain_node(&ic->ic_stageq, ni);
990 
991 	/*
992 	 * Clear AREF flag that marks the authorization refcnt bump
993 	 * has happened.  This is probably not needed as the node
994 	 * should always be removed from the table so not found but
995 	 * do it just in case.
996 	 * Likewise clear the ASSOCID flag as these flags are intended
997 	 * to be managed in tandem.
998 	 */
999 	ni->ni_flags &= ~(IEEE80211_NODE_AREF | IEEE80211_NODE_ASSOCID);
1000 
1001 	/*
1002 	 * Drain power save queue and, if needed, clear TIM.
1003 	 */
1004 	if (ieee80211_node_psq_drain(ni) != 0 && vap->iv_set_tim != NULL)
1005 		vap->iv_set_tim(ni, 0);
1006 
1007 	ni->ni_associd = 0;
1008 	if (ni->ni_challenge != NULL) {
1009 		free(ni->ni_challenge, M_80211_NODE);
1010 		ni->ni_challenge = NULL;
1011 	}
1012 	/*
1013 	 * Preserve SSID, WPA, and WME ie's so the bss node is
1014 	 * reusable during a re-auth/re-assoc state transition.
1015 	 * If we remove these data they will not be recreated
1016 	 * because they come from a probe-response or beacon frame
1017 	 * which cannot be expected prior to the association-response.
1018 	 * This should not be an issue when operating in other modes
1019 	 * as stations leaving always go through a full state transition
1020 	 * which will rebuild this state.
1021 	 *
1022 	 * XXX does this leave us open to inheriting old state?
1023 	 */
1024 	for (i = 0; i < N(ni->ni_rxfrag); i++)
1025 		if (ni->ni_rxfrag[i] != NULL) {
1026 			m_freem(ni->ni_rxfrag[i]);
1027 			ni->ni_rxfrag[i] = NULL;
1028 		}
1029 	/*
1030 	 * Must be careful here to remove any key map entry w/o a LOR.
1031 	 */
1032 	ieee80211_node_delucastkey(ni);
1033 #undef N
1034 }
1035 
1036 static void
1037 node_free(struct ieee80211_node *ni)
1038 {
1039 	struct ieee80211com *ic = ni->ni_ic;
1040 
1041 	if (ni->ni_vap->iv_caps & IEEE80211_C_RATECTL)
1042 		ieee80211_ratectl_node_deinit(ni);
1043 	ic->ic_node_cleanup(ni);
1044 	ieee80211_ies_cleanup(&ni->ni_ies);
1045 	ieee80211_psq_cleanup(&ni->ni_psq);
1046 	free(ni, M_80211_NODE);
1047 }
1048 
1049 static void
1050 node_age(struct ieee80211_node *ni)
1051 {
1052 	struct ieee80211vap *vap = ni->ni_vap;
1053 
1054 	IEEE80211_NODE_LOCK_ASSERT(&vap->iv_ic->ic_sta);
1055 
1056 	/*
1057 	 * Age frames on the power save queue.
1058 	 */
1059 	if (ieee80211_node_psq_age(ni) != 0 &&
1060 	    ni->ni_psq.psq_len == 0 && vap->iv_set_tim != NULL)
1061 		vap->iv_set_tim(ni, 0);
1062 	/*
1063 	 * Age out HT resources (e.g. frames on the
1064 	 * A-MPDU reorder queues).
1065 	 */
1066 	if (ni->ni_associd != 0 && (ni->ni_flags & IEEE80211_NODE_HT))
1067 		ieee80211_ht_node_age(ni);
1068 }
1069 
1070 static int8_t
1071 node_getrssi(const struct ieee80211_node *ni)
1072 {
1073 	uint32_t avgrssi = ni->ni_avgrssi;
1074 	int32_t rssi;
1075 
1076 	if (avgrssi == IEEE80211_RSSI_DUMMY_MARKER)
1077 		return 0;
1078 	rssi = IEEE80211_RSSI_GET(avgrssi);
1079 	return rssi < 0 ? 0 : rssi > 127 ? 127 : rssi;
1080 }
1081 
1082 static void
1083 node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
1084 {
1085 	*rssi = node_getrssi(ni);
1086 	*noise = ni->ni_noise;
1087 }
1088 
1089 static void
1090 node_getmimoinfo(const struct ieee80211_node *ni,
1091 	struct ieee80211_mimo_info *info)
1092 {
1093 	/* XXX zero data? */
1094 }
1095 
1096 struct ieee80211_node *
1097 ieee80211_alloc_node(struct ieee80211_node_table *nt,
1098 	struct ieee80211vap *vap, const uint8_t macaddr[IEEE80211_ADDR_LEN])
1099 {
1100 	struct ieee80211com *ic = nt->nt_ic;
1101 	struct ieee80211_node *ni;
1102 	int hash;
1103 
1104 	ni = ic->ic_node_alloc(vap, macaddr);
1105 	if (ni == NULL) {
1106 		vap->iv_stats.is_rx_nodealloc++;
1107 		return NULL;
1108 	}
1109 
1110 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1111 		"%s %p<%s> in %s table\n", __func__, ni,
1112 		ether_sprintf(macaddr), nt->nt_name);
1113 
1114 	IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
1115 	hash = IEEE80211_NODE_HASH(ic, macaddr);
1116 	ieee80211_node_initref(ni);		/* mark referenced */
1117 	ni->ni_chan = IEEE80211_CHAN_ANYC;
1118 	ni->ni_authmode = IEEE80211_AUTH_OPEN;
1119 	ni->ni_txpower = ic->ic_txpowlimit;	/* max power */
1120 	ni->ni_txparms = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
1121 	ieee80211_crypto_resetkey(vap, &ni->ni_ucastkey, IEEE80211_KEYIX_NONE);
1122 	ni->ni_avgrssi = IEEE80211_RSSI_DUMMY_MARKER;
1123 	ni->ni_inact_reload = nt->nt_inact_init;
1124 	ni->ni_inact = ni->ni_inact_reload;
1125 	ni->ni_ath_defkeyix = 0x7fff;
1126 	ieee80211_psq_init(&ni->ni_psq, "unknown");
1127 #ifdef IEEE80211_SUPPORT_MESH
1128 	if (vap->iv_opmode == IEEE80211_M_MBSS)
1129 		ieee80211_mesh_node_init(vap, ni);
1130 #endif
1131 	IEEE80211_NODE_LOCK(nt);
1132 	TAILQ_INSERT_TAIL(&nt->nt_node, ni, ni_list);
1133 	LIST_INSERT_HEAD(&nt->nt_hash[hash], ni, ni_hash);
1134 	ni->ni_table = nt;
1135 	ni->ni_vap = vap;
1136 	ni->ni_ic = ic;
1137 	IEEE80211_NODE_UNLOCK(nt);
1138 
1139 	IEEE80211_NOTE(vap, IEEE80211_MSG_INACT, ni,
1140 	    "%s: inact_reload %u", __func__, ni->ni_inact_reload);
1141 
1142 	return ni;
1143 }
1144 
1145 /*
1146  * Craft a temporary node suitable for sending a management frame
1147  * to the specified station.  We craft only as much state as we
1148  * need to do the work since the node will be immediately reclaimed
1149  * once the send completes.
1150  */
1151 struct ieee80211_node *
1152 ieee80211_tmp_node(struct ieee80211vap *vap,
1153 	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1154 {
1155 	struct ieee80211com *ic = vap->iv_ic;
1156 	struct ieee80211_node *ni;
1157 
1158 	ni = ic->ic_node_alloc(vap, macaddr);
1159 	if (ni != NULL) {
1160 		struct ieee80211_node *bss = vap->iv_bss;
1161 
1162 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1163 			"%s %p<%s>\n", __func__, ni, ether_sprintf(macaddr));
1164 
1165 		ni->ni_table = NULL;		/* NB: pedantic */
1166 		ni->ni_ic = ic;			/* NB: needed to set channel */
1167 		ni->ni_vap = vap;
1168 
1169 		IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
1170 		IEEE80211_ADDR_COPY(ni->ni_bssid, bss->ni_bssid);
1171 		ieee80211_node_initref(ni);		/* mark referenced */
1172 		/* NB: required by ieee80211_fix_rate */
1173 		ieee80211_node_set_chan(ni, bss->ni_chan);
1174 		ieee80211_crypto_resetkey(vap, &ni->ni_ucastkey,
1175 			IEEE80211_KEYIX_NONE);
1176 		ni->ni_txpower = bss->ni_txpower;
1177 		/* XXX optimize away */
1178 		ieee80211_psq_init(&ni->ni_psq, "unknown");
1179 	} else {
1180 		/* XXX msg */
1181 		vap->iv_stats.is_rx_nodealloc++;
1182 	}
1183 	return ni;
1184 }
1185 
1186 struct ieee80211_node *
1187 ieee80211_dup_bss(struct ieee80211vap *vap,
1188 	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1189 {
1190 	struct ieee80211com *ic = vap->iv_ic;
1191 	struct ieee80211_node *ni;
1192 
1193 	ni = ieee80211_alloc_node(&ic->ic_sta, vap, macaddr);
1194 	if (ni != NULL) {
1195 		struct ieee80211_node *bss = vap->iv_bss;
1196 		/*
1197 		 * Inherit from iv_bss.
1198 		 */
1199 		copy_bss(ni, bss);
1200 		IEEE80211_ADDR_COPY(ni->ni_bssid, bss->ni_bssid);
1201 		ieee80211_node_set_chan(ni, bss->ni_chan);
1202 	}
1203 	return ni;
1204 }
1205 
1206 /*
1207  * Create a bss node for a legacy WDS vap.  The far end does
1208  * not associate so we just create create a new node and
1209  * simulate an association.  The caller is responsible for
1210  * installing the node as the bss node and handling any further
1211  * setup work like authorizing the port.
1212  */
1213 struct ieee80211_node *
1214 ieee80211_node_create_wds(struct ieee80211vap *vap,
1215 	const uint8_t bssid[IEEE80211_ADDR_LEN], struct ieee80211_channel *chan)
1216 {
1217 	struct ieee80211com *ic = vap->iv_ic;
1218 	struct ieee80211_node *ni;
1219 
1220 	/* XXX check if node already in sta table? */
1221 	ni = ieee80211_alloc_node(&ic->ic_sta, vap, bssid);
1222 	if (ni != NULL) {
1223 		ni->ni_wdsvap = vap;
1224 		IEEE80211_ADDR_COPY(ni->ni_bssid, bssid);
1225 		/*
1226 		 * Inherit any manually configured settings.
1227 		 */
1228 		copy_bss(ni, vap->iv_bss);
1229 		ieee80211_node_set_chan(ni, chan);
1230 		/* NB: propagate ssid so available to WPA supplicant */
1231 		ni->ni_esslen = vap->iv_des_ssid[0].len;
1232 		memcpy(ni->ni_essid, vap->iv_des_ssid[0].ssid, ni->ni_esslen);
1233 		/* NB: no associd for peer */
1234 		/*
1235 		 * There are no management frames to use to
1236 		 * discover neighbor capabilities, so blindly
1237 		 * propagate the local configuration.
1238 		 */
1239 		if (vap->iv_flags & IEEE80211_F_WME)
1240 			ni->ni_flags |= IEEE80211_NODE_QOS;
1241 #ifdef IEEE80211_SUPPORT_SUPERG
1242 		if (vap->iv_flags & IEEE80211_F_FF)
1243 			ni->ni_flags |= IEEE80211_NODE_FF;
1244 #endif
1245 		if ((ic->ic_htcaps & IEEE80211_HTC_HT) &&
1246 		    (vap->iv_flags_ht & IEEE80211_FHT_HT)) {
1247 			/*
1248 			 * Device is HT-capable and HT is enabled for
1249 			 * the vap; setup HT operation.  On return
1250 			 * ni_chan will be adjusted to an HT channel.
1251 			 */
1252 			ieee80211_ht_wds_init(ni);
1253 		} else {
1254 			struct ieee80211_channel *c = ni->ni_chan;
1255 			/*
1256 			 * Force a legacy channel to be used.
1257 			 */
1258 			c = ieee80211_find_channel(ic,
1259 			    c->ic_freq, c->ic_flags &~ IEEE80211_CHAN_HT);
1260 			KASSERT(c != NULL, ("no legacy channel, %u/%x",
1261 			    ni->ni_chan->ic_freq, ni->ni_chan->ic_flags));
1262 			ni->ni_chan = c;
1263 		}
1264 	}
1265 	return ni;
1266 }
1267 
1268 struct ieee80211_node *
1269 #ifdef IEEE80211_DEBUG_REFCNT
1270 ieee80211_find_node_locked_debug(struct ieee80211_node_table *nt,
1271 	const uint8_t macaddr[IEEE80211_ADDR_LEN], const char *func, int line)
1272 #else
1273 ieee80211_find_node_locked(struct ieee80211_node_table *nt,
1274 	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1275 #endif
1276 {
1277 	struct ieee80211_node *ni;
1278 	int hash;
1279 
1280 	IEEE80211_NODE_LOCK_ASSERT(nt);
1281 
1282 	hash = IEEE80211_NODE_HASH(nt->nt_ic, macaddr);
1283 	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1284 		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
1285 			ieee80211_ref_node(ni);	/* mark referenced */
1286 #ifdef IEEE80211_DEBUG_REFCNT
1287 			IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_NODE,
1288 			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1289 			    func, line,
1290 			    ni, ether_sprintf(ni->ni_macaddr),
1291 			    ieee80211_node_refcnt(ni));
1292 #endif
1293 			return ni;
1294 		}
1295 	}
1296 	return NULL;
1297 }
1298 
1299 struct ieee80211_node *
1300 #ifdef IEEE80211_DEBUG_REFCNT
1301 ieee80211_find_node_debug(struct ieee80211_node_table *nt,
1302 	const uint8_t macaddr[IEEE80211_ADDR_LEN], const char *func, int line)
1303 #else
1304 ieee80211_find_node(struct ieee80211_node_table *nt,
1305 	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1306 #endif
1307 {
1308 	struct ieee80211_node *ni;
1309 
1310 	IEEE80211_NODE_LOCK(nt);
1311 	ni = ieee80211_find_node_locked(nt, macaddr);
1312 	IEEE80211_NODE_UNLOCK(nt);
1313 	return ni;
1314 }
1315 
1316 struct ieee80211_node *
1317 #ifdef IEEE80211_DEBUG_REFCNT
1318 ieee80211_find_vap_node_locked_debug(struct ieee80211_node_table *nt,
1319 	const struct ieee80211vap *vap,
1320 	const uint8_t macaddr[IEEE80211_ADDR_LEN], const char *func, int line)
1321 #else
1322 ieee80211_find_vap_node_locked(struct ieee80211_node_table *nt,
1323 	const struct ieee80211vap *vap,
1324 	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1325 #endif
1326 {
1327 	struct ieee80211_node *ni;
1328 	int hash;
1329 
1330 	IEEE80211_NODE_LOCK_ASSERT(nt);
1331 
1332 	hash = IEEE80211_NODE_HASH(nt->nt_ic, macaddr);
1333 	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1334 		if (ni->ni_vap == vap &&
1335 		    IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
1336 			ieee80211_ref_node(ni);	/* mark referenced */
1337 #ifdef IEEE80211_DEBUG_REFCNT
1338 			IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_NODE,
1339 			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1340 			    func, line,
1341 			    ni, ether_sprintf(ni->ni_macaddr),
1342 			    ieee80211_node_refcnt(ni));
1343 #endif
1344 			return ni;
1345 		}
1346 	}
1347 	return NULL;
1348 }
1349 
1350 struct ieee80211_node *
1351 #ifdef IEEE80211_DEBUG_REFCNT
1352 ieee80211_find_vap_node_debug(struct ieee80211_node_table *nt,
1353 	const struct ieee80211vap *vap,
1354 	const uint8_t macaddr[IEEE80211_ADDR_LEN], const char *func, int line)
1355 #else
1356 ieee80211_find_vap_node(struct ieee80211_node_table *nt,
1357 	const struct ieee80211vap *vap,
1358 	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1359 #endif
1360 {
1361 	struct ieee80211_node *ni;
1362 
1363 	IEEE80211_NODE_LOCK(nt);
1364 	ni = ieee80211_find_vap_node_locked(nt, vap, macaddr);
1365 	IEEE80211_NODE_UNLOCK(nt);
1366 	return ni;
1367 }
1368 
1369 /*
1370  * Fake up a node; this handles node discovery in adhoc mode.
1371  * Note that for the driver's benefit we we treat this like
1372  * an association so the driver has an opportunity to setup
1373  * it's private state.
1374  */
1375 struct ieee80211_node *
1376 ieee80211_fakeup_adhoc_node(struct ieee80211vap *vap,
1377 	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1378 {
1379 	struct ieee80211_node *ni;
1380 
1381 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1382 	    "%s: mac<%s>\n", __func__, ether_sprintf(macaddr));
1383 	ni = ieee80211_dup_bss(vap, macaddr);
1384 	if (ni != NULL) {
1385 		struct ieee80211com *ic = vap->iv_ic;
1386 
1387 		/* XXX no rate negotiation; just dup */
1388 		ni->ni_rates = vap->iv_bss->ni_rates;
1389 		if (ieee80211_iserp_rateset(&ni->ni_rates))
1390 			ni->ni_flags |= IEEE80211_NODE_ERP;
1391 		if (vap->iv_opmode == IEEE80211_M_AHDEMO) {
1392 			/*
1393 			 * In adhoc demo mode there are no management
1394 			 * frames to use to discover neighbor capabilities,
1395 			 * so blindly propagate the local configuration
1396 			 * so we can do interesting things (e.g. use
1397 			 * WME to disable ACK's).
1398 			 */
1399 			if (vap->iv_flags & IEEE80211_F_WME)
1400 				ni->ni_flags |= IEEE80211_NODE_QOS;
1401 #ifdef IEEE80211_SUPPORT_SUPERG
1402 			if (vap->iv_flags & IEEE80211_F_FF)
1403 				ni->ni_flags |= IEEE80211_NODE_FF;
1404 #endif
1405 		}
1406 		ieee80211_node_setuptxparms(ni);
1407 		if (vap->iv_caps & IEEE80211_C_RATECTL)
1408 			ieee80211_ratectl_node_init(ni);
1409 		if (ic->ic_newassoc != NULL)
1410 			ic->ic_newassoc(ni, 1);
1411 		/* XXX not right for 802.1x/WPA */
1412 		ieee80211_node_authorize(ni);
1413 	}
1414 	return ni;
1415 }
1416 
1417 void
1418 ieee80211_init_neighbor(struct ieee80211_node *ni,
1419 	const struct ieee80211_frame *wh,
1420 	const struct ieee80211_scanparams *sp)
1421 {
1422 	ni->ni_esslen = sp->ssid[1];
1423 	memcpy(ni->ni_essid, sp->ssid + 2, sp->ssid[1]);
1424 	IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
1425 	memcpy(ni->ni_tstamp.data, sp->tstamp, sizeof(ni->ni_tstamp));
1426 	ni->ni_intval = sp->bintval;
1427 	ni->ni_capinfo = sp->capinfo;
1428 	ni->ni_chan = ni->ni_ic->ic_curchan;
1429 	ni->ni_fhdwell = sp->fhdwell;
1430 	ni->ni_fhindex = sp->fhindex;
1431 	ni->ni_erp = sp->erp;
1432 	ni->ni_timoff = sp->timoff;
1433 #ifdef IEEE80211_SUPPORT_MESH
1434 	if (ni->ni_vap->iv_opmode == IEEE80211_M_MBSS)
1435 		ieee80211_mesh_init_neighbor(ni, wh, sp);
1436 #endif
1437 	if (ieee80211_ies_init(&ni->ni_ies, sp->ies, sp->ies_len)) {
1438 		ieee80211_ies_expand(&ni->ni_ies);
1439 		if (ni->ni_ies.wme_ie != NULL)
1440 			ni->ni_flags |= IEEE80211_NODE_QOS;
1441 		else
1442 			ni->ni_flags &= ~IEEE80211_NODE_QOS;
1443 #ifdef IEEE80211_SUPPORT_SUPERG
1444 		if (ni->ni_ies.ath_ie != NULL)
1445 			ieee80211_parse_ath(ni, ni->ni_ies.ath_ie);
1446 #endif
1447 	}
1448 
1449 	/* NB: must be after ni_chan is setup */
1450 	ieee80211_setup_rates(ni, sp->rates, sp->xrates,
1451 		IEEE80211_F_DOSORT | IEEE80211_F_DOFRATE |
1452 		IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
1453 }
1454 
1455 /*
1456  * Do node discovery in adhoc mode on receipt of a beacon
1457  * or probe response frame.  Note that for the driver's
1458  * benefit we we treat this like an association so the
1459  * driver has an opportunity to setup it's private state.
1460  */
1461 struct ieee80211_node *
1462 ieee80211_add_neighbor(struct ieee80211vap *vap,
1463 	const struct ieee80211_frame *wh,
1464 	const struct ieee80211_scanparams *sp)
1465 {
1466 	struct ieee80211_node *ni;
1467 
1468 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1469 	    "%s: mac<%s>\n", __func__, ether_sprintf(wh->i_addr2));
1470 	ni = ieee80211_dup_bss(vap, wh->i_addr2);/* XXX alloc_node? */
1471 	if (ni != NULL) {
1472 		struct ieee80211com *ic = vap->iv_ic;
1473 
1474 		ieee80211_init_neighbor(ni, wh, sp);
1475 		if (ieee80211_iserp_rateset(&ni->ni_rates))
1476 			ni->ni_flags |= IEEE80211_NODE_ERP;
1477 		ieee80211_node_setuptxparms(ni);
1478 		if (vap->iv_caps & IEEE80211_C_RATECTL)
1479 			ieee80211_ratectl_node_init(ni);
1480 		if (ic->ic_newassoc != NULL)
1481 			ic->ic_newassoc(ni, 1);
1482 		/* XXX not right for 802.1x/WPA */
1483 		ieee80211_node_authorize(ni);
1484 	}
1485 	return ni;
1486 }
1487 
1488 #define	IS_PROBEREQ(wh) \
1489 	((wh->i_fc[0] & (IEEE80211_FC0_TYPE_MASK|IEEE80211_FC0_SUBTYPE_MASK)) \
1490 	    == (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_REQ))
1491 #define	IS_BCAST_PROBEREQ(wh) \
1492 	(IS_PROBEREQ(wh) && IEEE80211_IS_MULTICAST( \
1493 	    ((const struct ieee80211_frame *)(wh))->i_addr3))
1494 
1495 static __inline struct ieee80211_node *
1496 _find_rxnode(struct ieee80211_node_table *nt,
1497     const struct ieee80211_frame_min *wh)
1498 {
1499 	if (IS_BCAST_PROBEREQ(wh))
1500 		return NULL;		/* spam bcast probe req to all vap's */
1501 	return ieee80211_find_node_locked(nt, wh->i_addr2);
1502 }
1503 
1504 /*
1505  * Locate the node for sender, track state, and then pass the
1506  * (referenced) node up to the 802.11 layer for its use.  Note
1507  * we can return NULL if the sender is not in the table.
1508  */
1509 struct ieee80211_node *
1510 #ifdef IEEE80211_DEBUG_REFCNT
1511 ieee80211_find_rxnode_debug(struct ieee80211com *ic,
1512 	const struct ieee80211_frame_min *wh, const char *func, int line)
1513 #else
1514 ieee80211_find_rxnode(struct ieee80211com *ic,
1515 	const struct ieee80211_frame_min *wh)
1516 #endif
1517 {
1518 	struct ieee80211_node_table *nt;
1519 	struct ieee80211_node *ni;
1520 
1521 	nt = &ic->ic_sta;
1522 	IEEE80211_NODE_LOCK(nt);
1523 	ni = _find_rxnode(nt, wh);
1524 	IEEE80211_NODE_UNLOCK(nt);
1525 
1526 	return ni;
1527 }
1528 
1529 /*
1530  * Like ieee80211_find_rxnode but use the supplied h/w
1531  * key index as a hint to locate the node in the key
1532  * mapping table.  If an entry is present at the key
1533  * index we return it; otherwise do a normal lookup and
1534  * update the mapping table if the station has a unicast
1535  * key assigned to it.
1536  */
1537 struct ieee80211_node *
1538 #ifdef IEEE80211_DEBUG_REFCNT
1539 ieee80211_find_rxnode_withkey_debug(struct ieee80211com *ic,
1540 	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix,
1541 	const char *func, int line)
1542 #else
1543 ieee80211_find_rxnode_withkey(struct ieee80211com *ic,
1544 	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix)
1545 #endif
1546 {
1547 	struct ieee80211_node_table *nt;
1548 	struct ieee80211_node *ni;
1549 
1550 	nt = &ic->ic_sta;
1551 	IEEE80211_NODE_LOCK(nt);
1552 	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax)
1553 		ni = nt->nt_keyixmap[keyix];
1554 	else
1555 		ni = NULL;
1556 	if (ni == NULL) {
1557 		ni = _find_rxnode(nt, wh);
1558 		if (ni != NULL && nt->nt_keyixmap != NULL) {
1559 			/*
1560 			 * If the station has a unicast key cache slot
1561 			 * assigned update the key->node mapping table.
1562 			 */
1563 			keyix = ni->ni_ucastkey.wk_rxkeyix;
1564 			/* XXX can keyixmap[keyix] != NULL? */
1565 			if (keyix < nt->nt_keyixmax &&
1566 			    nt->nt_keyixmap[keyix] == NULL) {
1567 				IEEE80211_DPRINTF(ni->ni_vap,
1568 				    IEEE80211_MSG_NODE,
1569 				    "%s: add key map entry %p<%s> refcnt %d\n",
1570 				    __func__, ni, ether_sprintf(ni->ni_macaddr),
1571 				    ieee80211_node_refcnt(ni)+1);
1572 				nt->nt_keyixmap[keyix] = ieee80211_ref_node(ni);
1573 			}
1574 		}
1575 	} else {
1576 		if (IS_BCAST_PROBEREQ(wh))
1577 			ni = NULL;	/* spam bcast probe req to all vap's */
1578 		else
1579 			ieee80211_ref_node(ni);
1580 	}
1581 	IEEE80211_NODE_UNLOCK(nt);
1582 
1583 	return ni;
1584 }
1585 #undef IS_BCAST_PROBEREQ
1586 #undef IS_PROBEREQ
1587 
1588 /*
1589  * Return a reference to the appropriate node for sending
1590  * a data frame.  This handles node discovery in adhoc networks.
1591  */
1592 struct ieee80211_node *
1593 #ifdef IEEE80211_DEBUG_REFCNT
1594 ieee80211_find_txnode_debug(struct ieee80211vap *vap,
1595 	const uint8_t macaddr[IEEE80211_ADDR_LEN],
1596 	const char *func, int line)
1597 #else
1598 ieee80211_find_txnode(struct ieee80211vap *vap,
1599 	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1600 #endif
1601 {
1602 	struct ieee80211_node_table *nt = &vap->iv_ic->ic_sta;
1603 	struct ieee80211_node *ni;
1604 
1605 	/*
1606 	 * The destination address should be in the node table
1607 	 * unless this is a multicast/broadcast frame.  We can
1608 	 * also optimize station mode operation, all frames go
1609 	 * to the bss node.
1610 	 */
1611 	/* XXX can't hold lock across dup_bss 'cuz of recursive locking */
1612 	IEEE80211_NODE_LOCK(nt);
1613 	if (vap->iv_opmode == IEEE80211_M_STA ||
1614 	    vap->iv_opmode == IEEE80211_M_WDS ||
1615 	    IEEE80211_IS_MULTICAST(macaddr))
1616 		ni = ieee80211_ref_node(vap->iv_bss);
1617 	else
1618 		ni = ieee80211_find_node_locked(nt, macaddr);
1619 	IEEE80211_NODE_UNLOCK(nt);
1620 
1621 	if (ni == NULL) {
1622 		if (vap->iv_opmode == IEEE80211_M_IBSS ||
1623 		    vap->iv_opmode == IEEE80211_M_AHDEMO) {
1624 			/*
1625 			 * In adhoc mode cons up a node for the destination.
1626 			 * Note that we need an additional reference for the
1627 			 * caller to be consistent with
1628 			 * ieee80211_find_node_locked.
1629 			 */
1630 			ni = ieee80211_fakeup_adhoc_node(vap, macaddr);
1631 			if (ni != NULL)
1632 				(void) ieee80211_ref_node(ni);
1633 		} else {
1634 			IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_OUTPUT, macaddr,
1635 			    "no node, discard frame (%s)", __func__);
1636 			vap->iv_stats.is_tx_nonode++;
1637 		}
1638 	}
1639 	return ni;
1640 }
1641 
1642 static void
1643 _ieee80211_free_node(struct ieee80211_node *ni)
1644 {
1645 	struct ieee80211_node_table *nt = ni->ni_table;
1646 
1647 	/*
1648 	 * NB: careful about referencing the vap as it may be
1649 	 * gone if the last reference was held by a driver.
1650 	 * We know the com will always be present so it's safe
1651 	 * to use ni_ic below to reclaim resources.
1652 	 */
1653 #if 0
1654 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1655 		"%s %p<%s> in %s table\n", __func__, ni,
1656 		ether_sprintf(ni->ni_macaddr),
1657 		nt != NULL ? nt->nt_name : "<gone>");
1658 #endif
1659 	if (ni->ni_associd != 0) {
1660 		struct ieee80211vap *vap = ni->ni_vap;
1661 		if (vap->iv_aid_bitmap != NULL)
1662 			IEEE80211_AID_CLR(vap, ni->ni_associd);
1663 	}
1664 	if (nt != NULL) {
1665 		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1666 		LIST_REMOVE(ni, ni_hash);
1667 	}
1668 	ni->ni_ic->ic_node_free(ni);
1669 }
1670 
1671 void
1672 #ifdef IEEE80211_DEBUG_REFCNT
1673 ieee80211_free_node_debug(struct ieee80211_node *ni, const char *func, int line)
1674 #else
1675 ieee80211_free_node(struct ieee80211_node *ni)
1676 #endif
1677 {
1678 	struct ieee80211_node_table *nt = ni->ni_table;
1679 
1680 #ifdef IEEE80211_DEBUG_REFCNT
1681 	IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_NODE,
1682 		"%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line, ni,
1683 		 ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)-1);
1684 #endif
1685 	if (nt != NULL) {
1686 		IEEE80211_NODE_LOCK(nt);
1687 		if (ieee80211_node_dectestref(ni)) {
1688 			/*
1689 			 * Last reference, reclaim state.
1690 			 */
1691 			_ieee80211_free_node(ni);
1692 		} else if (ieee80211_node_refcnt(ni) == 1 &&
1693 		    nt->nt_keyixmap != NULL) {
1694 			ieee80211_keyix keyix;
1695 			/*
1696 			 * Check for a last reference in the key mapping table.
1697 			 */
1698 			keyix = ni->ni_ucastkey.wk_rxkeyix;
1699 			if (keyix < nt->nt_keyixmax &&
1700 			    nt->nt_keyixmap[keyix] == ni) {
1701 				IEEE80211_DPRINTF(ni->ni_vap,
1702 				    IEEE80211_MSG_NODE,
1703 				    "%s: %p<%s> clear key map entry", __func__,
1704 				    ni, ether_sprintf(ni->ni_macaddr));
1705 				nt->nt_keyixmap[keyix] = NULL;
1706 				ieee80211_node_decref(ni); /* XXX needed? */
1707 				_ieee80211_free_node(ni);
1708 			}
1709 		}
1710 		IEEE80211_NODE_UNLOCK(nt);
1711 	} else {
1712 		if (ieee80211_node_dectestref(ni))
1713 			_ieee80211_free_node(ni);
1714 	}
1715 }
1716 
1717 /*
1718  * Reclaim a unicast key and clear any key cache state.
1719  */
1720 int
1721 ieee80211_node_delucastkey(struct ieee80211_node *ni)
1722 {
1723 	struct ieee80211com *ic = ni->ni_ic;
1724 	struct ieee80211_node_table *nt = &ic->ic_sta;
1725 	struct ieee80211_node *nikey;
1726 	ieee80211_keyix keyix;
1727 	int isowned, status;
1728 
1729 	/*
1730 	 * NB: We must beware of LOR here; deleting the key
1731 	 * can cause the crypto layer to block traffic updates
1732 	 * which can generate a LOR against the node table lock;
1733 	 * grab it here and stash the key index for our use below.
1734 	 *
1735 	 * Must also beware of recursion on the node table lock.
1736 	 * When called from node_cleanup we may already have
1737 	 * the node table lock held.  Unfortunately there's no
1738 	 * way to separate out this path so we must do this
1739 	 * conditionally.
1740 	 */
1741 	isowned = IEEE80211_NODE_IS_LOCKED(nt);
1742 	if (!isowned)
1743 		IEEE80211_NODE_LOCK(nt);
1744 	nikey = NULL;
1745 	status = 1;		/* NB: success */
1746 	if (ni->ni_ucastkey.wk_keyix != IEEE80211_KEYIX_NONE) {
1747 		keyix = ni->ni_ucastkey.wk_rxkeyix;
1748 		status = ieee80211_crypto_delkey(ni->ni_vap, &ni->ni_ucastkey);
1749 		if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax) {
1750 			nikey = nt->nt_keyixmap[keyix];
1751 			nt->nt_keyixmap[keyix] = NULL;
1752 		}
1753 	}
1754 	if (!isowned)
1755 		IEEE80211_NODE_UNLOCK(nt);
1756 
1757 	if (nikey != NULL) {
1758 		KASSERT(nikey == ni,
1759 			("key map out of sync, ni %p nikey %p", ni, nikey));
1760 		IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_NODE,
1761 			"%s: delete key map entry %p<%s> refcnt %d\n",
1762 			__func__, ni, ether_sprintf(ni->ni_macaddr),
1763 			ieee80211_node_refcnt(ni)-1);
1764 		ieee80211_free_node(ni);
1765 	}
1766 	return status;
1767 }
1768 
1769 /*
1770  * Reclaim a node.  If this is the last reference count then
1771  * do the normal free work.  Otherwise remove it from the node
1772  * table and mark it gone by clearing the back-reference.
1773  */
1774 static void
1775 node_reclaim(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1776 {
1777 	ieee80211_keyix keyix;
1778 
1779 	IEEE80211_NODE_LOCK_ASSERT(nt);
1780 
1781 	IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_NODE,
1782 		"%s: remove %p<%s> from %s table, refcnt %d\n",
1783 		__func__, ni, ether_sprintf(ni->ni_macaddr),
1784 		nt->nt_name, ieee80211_node_refcnt(ni)-1);
1785 	/*
1786 	 * Clear any entry in the unicast key mapping table.
1787 	 * We need to do it here so rx lookups don't find it
1788 	 * in the mapping table even if it's not in the hash
1789 	 * table.  We cannot depend on the mapping table entry
1790 	 * being cleared because the node may not be free'd.
1791 	 */
1792 	keyix = ni->ni_ucastkey.wk_rxkeyix;
1793 	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax &&
1794 	    nt->nt_keyixmap[keyix] == ni) {
1795 		IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_NODE,
1796 			"%s: %p<%s> clear key map entry %u\n",
1797 			__func__, ni, ether_sprintf(ni->ni_macaddr), keyix);
1798 		nt->nt_keyixmap[keyix] = NULL;
1799 		ieee80211_node_decref(ni);	/* NB: don't need free */
1800 	}
1801 	if (!ieee80211_node_dectestref(ni)) {
1802 		/*
1803 		 * Other references are present, just remove the
1804 		 * node from the table so it cannot be found.  When
1805 		 * the references are dropped storage will be
1806 		 * reclaimed.
1807 		 */
1808 		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1809 		LIST_REMOVE(ni, ni_hash);
1810 		ni->ni_table = NULL;		/* clear reference */
1811 	} else
1812 		_ieee80211_free_node(ni);
1813 }
1814 
1815 /*
1816  * Node table support.
1817  */
1818 
1819 static void
1820 ieee80211_node_table_init(struct ieee80211com *ic,
1821 	struct ieee80211_node_table *nt,
1822 	const char *name, int inact, int keyixmax)
1823 {
1824 	struct ifnet *ifp = ic->ic_ifp;
1825 
1826 	nt->nt_ic = ic;
1827 	IEEE80211_NODE_LOCK_INIT(nt, ifp->if_xname);
1828 	IEEE80211_NODE_ITERATE_LOCK_INIT(nt, ifp->if_xname);
1829 	TAILQ_INIT(&nt->nt_node);
1830 	nt->nt_name = name;
1831 	nt->nt_scangen = 1;
1832 	nt->nt_inact_init = inact;
1833 	nt->nt_keyixmax = keyixmax;
1834 	if (nt->nt_keyixmax > 0) {
1835 		nt->nt_keyixmap = (struct ieee80211_node **) malloc(
1836 			keyixmax * sizeof(struct ieee80211_node *),
1837 			M_80211_NODE, M_NOWAIT | M_ZERO);
1838 		if (nt->nt_keyixmap == NULL)
1839 			if_printf(ic->ic_ifp,
1840 			    "Cannot allocate key index map with %u entries\n",
1841 			    keyixmax);
1842 	} else
1843 		nt->nt_keyixmap = NULL;
1844 }
1845 
1846 static void
1847 ieee80211_node_table_reset(struct ieee80211_node_table *nt,
1848 	struct ieee80211vap *match)
1849 {
1850 	struct ieee80211_node *ni, *next;
1851 
1852 	IEEE80211_NODE_LOCK(nt);
1853 	TAILQ_FOREACH_SAFE(ni, &nt->nt_node, ni_list, next) {
1854 		if (match != NULL && ni->ni_vap != match)
1855 			continue;
1856 		/* XXX can this happen?  if so need's work */
1857 		if (ni->ni_associd != 0) {
1858 			struct ieee80211vap *vap = ni->ni_vap;
1859 
1860 			if (vap->iv_auth->ia_node_leave != NULL)
1861 				vap->iv_auth->ia_node_leave(ni);
1862 			if (vap->iv_aid_bitmap != NULL)
1863 				IEEE80211_AID_CLR(vap, ni->ni_associd);
1864 		}
1865 		ni->ni_wdsvap = NULL;		/* clear reference */
1866 		node_reclaim(nt, ni);
1867 	}
1868 	if (match != NULL && match->iv_opmode == IEEE80211_M_WDS) {
1869 		/*
1870 		 * Make a separate pass to clear references to this vap
1871 		 * held by DWDS entries.  They will not be matched above
1872 		 * because ni_vap will point to the ap vap but we still
1873 		 * need to clear ni_wdsvap when the WDS vap is destroyed
1874 		 * and/or reset.
1875 		 */
1876 		TAILQ_FOREACH_SAFE(ni, &nt->nt_node, ni_list, next)
1877 			if (ni->ni_wdsvap == match)
1878 				ni->ni_wdsvap = NULL;
1879 	}
1880 	IEEE80211_NODE_UNLOCK(nt);
1881 }
1882 
1883 static void
1884 ieee80211_node_table_cleanup(struct ieee80211_node_table *nt)
1885 {
1886 	ieee80211_node_table_reset(nt, NULL);
1887 	if (nt->nt_keyixmap != NULL) {
1888 #ifdef DIAGNOSTIC
1889 		/* XXX verify all entries are NULL */
1890 		int i;
1891 		for (i = 0; i < nt->nt_keyixmax; i++)
1892 			if (nt->nt_keyixmap[i] != NULL)
1893 				printf("%s: %s[%u] still active\n", __func__,
1894 					nt->nt_name, i);
1895 #endif
1896 		free(nt->nt_keyixmap, M_80211_NODE);
1897 		nt->nt_keyixmap = NULL;
1898 	}
1899 	IEEE80211_NODE_ITERATE_LOCK_DESTROY(nt);
1900 	IEEE80211_NODE_LOCK_DESTROY(nt);
1901 }
1902 
1903 /*
1904  * Timeout inactive stations and do related housekeeping.
1905  * Note that we cannot hold the node lock while sending a
1906  * frame as this would lead to a LOR.  Instead we use a
1907  * generation number to mark nodes that we've scanned and
1908  * drop the lock and restart a scan if we have to time out
1909  * a node.  Since we are single-threaded by virtue of
1910  * controlling the inactivity timer we can be sure this will
1911  * process each node only once.
1912  */
1913 static void
1914 ieee80211_timeout_stations(struct ieee80211com *ic)
1915 {
1916 	struct ieee80211_node_table *nt = &ic->ic_sta;
1917 	struct ieee80211vap *vap;
1918 	struct ieee80211_node *ni;
1919 	int gen = 0;
1920 
1921 	IEEE80211_NODE_ITERATE_LOCK(nt);
1922 	gen = ++nt->nt_scangen;
1923 restart:
1924 	IEEE80211_NODE_LOCK(nt);
1925 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1926 		if (ni->ni_scangen == gen)	/* previously handled */
1927 			continue;
1928 		ni->ni_scangen = gen;
1929 		/*
1930 		 * Ignore entries for which have yet to receive an
1931 		 * authentication frame.  These are transient and
1932 		 * will be reclaimed when the last reference to them
1933 		 * goes away (when frame xmits complete).
1934 		 */
1935 		vap = ni->ni_vap;
1936 		/*
1937 		 * Only process stations when in RUN state.  This
1938 		 * insures, for example, that we don't timeout an
1939 		 * inactive station during CAC.  Note that CSA state
1940 		 * is actually handled in ieee80211_node_timeout as
1941 		 * it applies to more than timeout processing.
1942 		 */
1943 		if (vap->iv_state != IEEE80211_S_RUN)
1944 			continue;
1945 		/* XXX can vap be NULL? */
1946 		if ((vap->iv_opmode == IEEE80211_M_HOSTAP ||
1947 		     vap->iv_opmode == IEEE80211_M_STA) &&
1948 		    (ni->ni_flags & IEEE80211_NODE_AREF) == 0)
1949 			continue;
1950 		/*
1951 		 * Free fragment if not needed anymore
1952 		 * (last fragment older than 1s).
1953 		 * XXX doesn't belong here, move to node_age
1954 		 */
1955 		if (ni->ni_rxfrag[0] != NULL &&
1956 		    ticks > ni->ni_rxfragstamp + hz) {
1957 			m_freem(ni->ni_rxfrag[0]);
1958 			ni->ni_rxfrag[0] = NULL;
1959 		}
1960 		if (ni->ni_inact > 0) {
1961 			ni->ni_inact--;
1962 			IEEE80211_NOTE(vap, IEEE80211_MSG_INACT, ni,
1963 			    "%s: inact %u inact_reload %u nrates %u",
1964 			    __func__, ni->ni_inact, ni->ni_inact_reload,
1965 			    ni->ni_rates.rs_nrates);
1966 		}
1967 		/*
1968 		 * Special case ourself; we may be idle for extended periods
1969 		 * of time and regardless reclaiming our state is wrong.
1970 		 * XXX run ic_node_age
1971 		 */
1972 		if (ni == vap->iv_bss)
1973 			continue;
1974 		if (ni->ni_associd != 0 ||
1975 		    (vap->iv_opmode == IEEE80211_M_IBSS ||
1976 		     vap->iv_opmode == IEEE80211_M_AHDEMO)) {
1977 			/*
1978 			 * Age/drain resources held by the station.
1979 			 */
1980 			ic->ic_node_age(ni);
1981 			/*
1982 			 * Probe the station before time it out.  We
1983 			 * send a null data frame which may not be
1984 			 * universally supported by drivers (need it
1985 			 * for ps-poll support so it should be...).
1986 			 *
1987 			 * XXX don't probe the station unless we've
1988 			 *     received a frame from them (and have
1989 			 *     some idea of the rates they are capable
1990 			 *     of); this will get fixed more properly
1991 			 *     soon with better handling of the rate set.
1992 			 */
1993 			if ((vap->iv_flags_ext & IEEE80211_FEXT_INACT) &&
1994 			    (0 < ni->ni_inact &&
1995 			     ni->ni_inact <= vap->iv_inact_probe) &&
1996 			    ni->ni_rates.rs_nrates != 0) {
1997 				IEEE80211_NOTE(vap,
1998 				    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE,
1999 				    ni, "%s",
2000 				    "probe station due to inactivity");
2001 				/*
2002 				 * Grab a reference before unlocking the table
2003 				 * so the node cannot be reclaimed before we
2004 				 * send the frame. ieee80211_send_nulldata
2005 				 * understands we've done this and reclaims the
2006 				 * ref for us as needed.
2007 				 */
2008 				ieee80211_ref_node(ni);
2009 				IEEE80211_NODE_UNLOCK(nt);
2010 				ieee80211_send_nulldata(ni);
2011 				/* XXX stat? */
2012 				goto restart;
2013 			}
2014 		}
2015 		if ((vap->iv_flags_ext & IEEE80211_FEXT_INACT) &&
2016 		    ni->ni_inact <= 0) {
2017 			IEEE80211_NOTE(vap,
2018 			    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE, ni,
2019 			    "station timed out due to inactivity "
2020 			    "(refcnt %u)", ieee80211_node_refcnt(ni));
2021 			/*
2022 			 * Send a deauthenticate frame and drop the station.
2023 			 * This is somewhat complicated due to reference counts
2024 			 * and locking.  At this point a station will typically
2025 			 * have a reference count of 1.  ieee80211_node_leave
2026 			 * will do a "free" of the node which will drop the
2027 			 * reference count.  But in the meantime a reference
2028 			 * wil be held by the deauth frame.  The actual reclaim
2029 			 * of the node will happen either after the tx is
2030 			 * completed or by ieee80211_node_leave.
2031 			 *
2032 			 * Separately we must drop the node lock before sending
2033 			 * in case the driver takes a lock, as this can result
2034 			 * in a LOR between the node lock and the driver lock.
2035 			 */
2036 			ieee80211_ref_node(ni);
2037 			IEEE80211_NODE_UNLOCK(nt);
2038 			if (ni->ni_associd != 0) {
2039 				IEEE80211_SEND_MGMT(ni,
2040 				    IEEE80211_FC0_SUBTYPE_DEAUTH,
2041 				    IEEE80211_REASON_AUTH_EXPIRE);
2042 			}
2043 			ieee80211_node_leave(ni);
2044 			ieee80211_free_node(ni);
2045 			vap->iv_stats.is_node_timeout++;
2046 			goto restart;
2047 		}
2048 	}
2049 	IEEE80211_NODE_UNLOCK(nt);
2050 
2051 	IEEE80211_NODE_ITERATE_UNLOCK(nt);
2052 }
2053 
2054 /*
2055  * Aggressively reclaim resources.  This should be used
2056  * only in a critical situation to reclaim mbuf resources.
2057  */
2058 void
2059 ieee80211_drain(struct ieee80211com *ic)
2060 {
2061 	struct ieee80211_node_table *nt = &ic->ic_sta;
2062 	struct ieee80211vap *vap;
2063 	struct ieee80211_node *ni;
2064 
2065 	IEEE80211_NODE_LOCK(nt);
2066 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
2067 		/*
2068 		 * Ignore entries for which have yet to receive an
2069 		 * authentication frame.  These are transient and
2070 		 * will be reclaimed when the last reference to them
2071 		 * goes away (when frame xmits complete).
2072 		 */
2073 		vap = ni->ni_vap;
2074 		/*
2075 		 * Only process stations when in RUN state.  This
2076 		 * insures, for example, that we don't timeout an
2077 		 * inactive station during CAC.  Note that CSA state
2078 		 * is actually handled in ieee80211_node_timeout as
2079 		 * it applies to more than timeout processing.
2080 		 */
2081 		if (vap->iv_state != IEEE80211_S_RUN)
2082 			continue;
2083 		/* XXX can vap be NULL? */
2084 		if ((vap->iv_opmode == IEEE80211_M_HOSTAP ||
2085 		     vap->iv_opmode == IEEE80211_M_STA) &&
2086 		    (ni->ni_flags & IEEE80211_NODE_AREF) == 0)
2087 			continue;
2088 		/*
2089 		 * Free fragments.
2090 		 * XXX doesn't belong here, move to node_drain
2091 		 */
2092 		if (ni->ni_rxfrag[0] != NULL) {
2093 			m_freem(ni->ni_rxfrag[0]);
2094 			ni->ni_rxfrag[0] = NULL;
2095 		}
2096 		/*
2097 		 * Drain resources held by the station.
2098 		 */
2099 		ic->ic_node_drain(ni);
2100 	}
2101 	IEEE80211_NODE_UNLOCK(nt);
2102 }
2103 
2104 /*
2105  * Per-ieee80211com inactivity timer callback.
2106  */
2107 void
2108 ieee80211_node_timeout(void *arg)
2109 {
2110 	struct ieee80211com *ic = arg;
2111 
2112 	/*
2113 	 * Defer timeout processing if a channel switch is pending.
2114 	 * We typically need to be mute so not doing things that
2115 	 * might generate frames is good to handle in one place.
2116 	 * Supressing the station timeout processing may extend the
2117 	 * lifetime of inactive stations (by not decrementing their
2118 	 * idle counters) but this should be ok unless the CSA is
2119 	 * active for an unusually long time.
2120 	 */
2121 	if ((ic->ic_flags & IEEE80211_F_CSAPENDING) == 0) {
2122 		ieee80211_scan_timeout(ic);
2123 		ieee80211_timeout_stations(ic);
2124 		ieee80211_ageq_age(&ic->ic_stageq, IEEE80211_INACT_WAIT);
2125 
2126 		IEEE80211_LOCK(ic);
2127 		ieee80211_erp_timeout(ic);
2128 		ieee80211_ht_timeout(ic);
2129 		IEEE80211_UNLOCK(ic);
2130 	}
2131 	callout_reset(&ic->ic_inact, IEEE80211_INACT_WAIT*hz,
2132 		ieee80211_node_timeout, ic);
2133 }
2134 
2135 void
2136 ieee80211_iterate_nodes(struct ieee80211_node_table *nt,
2137 	ieee80211_iter_func *f, void *arg)
2138 {
2139 	struct ieee80211_node *ni;
2140 	u_int gen;
2141 
2142 	IEEE80211_NODE_ITERATE_LOCK(nt);
2143 	gen = ++nt->nt_scangen;
2144 restart:
2145 	IEEE80211_NODE_LOCK(nt);
2146 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
2147 		if (ni->ni_scangen != gen) {
2148 			ni->ni_scangen = gen;
2149 			(void) ieee80211_ref_node(ni);
2150 			IEEE80211_NODE_UNLOCK(nt);
2151 			(*f)(arg, ni);
2152 			ieee80211_free_node(ni);
2153 			goto restart;
2154 		}
2155 	}
2156 	IEEE80211_NODE_UNLOCK(nt);
2157 
2158 	IEEE80211_NODE_ITERATE_UNLOCK(nt);
2159 }
2160 
2161 void
2162 ieee80211_dump_node(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
2163 {
2164 	printf("0x%p: mac %s refcnt %d\n", ni,
2165 		ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni));
2166 	printf("\tscangen %u authmode %u flags 0x%x\n",
2167 		ni->ni_scangen, ni->ni_authmode, ni->ni_flags);
2168 	printf("\tassocid 0x%x txpower %u vlan %u\n",
2169 		ni->ni_associd, ni->ni_txpower, ni->ni_vlan);
2170 	printf("\ttxseq %u rxseq %u fragno %u rxfragstamp %u\n",
2171 		ni->ni_txseqs[IEEE80211_NONQOS_TID],
2172 		ni->ni_rxseqs[IEEE80211_NONQOS_TID] >> IEEE80211_SEQ_SEQ_SHIFT,
2173 		ni->ni_rxseqs[IEEE80211_NONQOS_TID] & IEEE80211_SEQ_FRAG_MASK,
2174 		ni->ni_rxfragstamp);
2175 	printf("\trssi %d noise %d intval %u capinfo 0x%x\n",
2176 		node_getrssi(ni), ni->ni_noise,
2177 		ni->ni_intval, ni->ni_capinfo);
2178 	printf("\tbssid %s essid \"%.*s\" channel %u:0x%x\n",
2179 		ether_sprintf(ni->ni_bssid),
2180 		ni->ni_esslen, ni->ni_essid,
2181 		ni->ni_chan->ic_freq, ni->ni_chan->ic_flags);
2182 	printf("\tinact %u inact_reload %u txrate %u\n",
2183 		ni->ni_inact, ni->ni_inact_reload, ni->ni_txrate);
2184 	printf("\thtcap %x htparam %x htctlchan %u ht2ndchan %u\n",
2185 		ni->ni_htcap, ni->ni_htparam,
2186 		ni->ni_htctlchan, ni->ni_ht2ndchan);
2187 	printf("\thtopmode %x htstbc %x chw %u\n",
2188 		ni->ni_htopmode, ni->ni_htstbc, ni->ni_chw);
2189 }
2190 
2191 void
2192 ieee80211_dump_nodes(struct ieee80211_node_table *nt)
2193 {
2194 	ieee80211_iterate_nodes(nt,
2195 		(ieee80211_iter_func *) ieee80211_dump_node, nt);
2196 }
2197 
2198 static void
2199 ieee80211_notify_erp_locked(struct ieee80211com *ic)
2200 {
2201 	struct ieee80211vap *vap;
2202 
2203 	IEEE80211_LOCK_ASSERT(ic);
2204 
2205 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
2206 		if (vap->iv_opmode == IEEE80211_M_HOSTAP)
2207 			ieee80211_beacon_notify(vap, IEEE80211_BEACON_ERP);
2208 }
2209 
2210 void
2211 ieee80211_notify_erp(struct ieee80211com *ic)
2212 {
2213 	IEEE80211_LOCK(ic);
2214 	ieee80211_notify_erp_locked(ic);
2215 	IEEE80211_UNLOCK(ic);
2216 }
2217 
2218 /*
2219  * Handle a station joining an 11g network.
2220  */
2221 static void
2222 ieee80211_node_join_11g(struct ieee80211_node *ni)
2223 {
2224 	struct ieee80211com *ic = ni->ni_ic;
2225 
2226 	IEEE80211_LOCK_ASSERT(ic);
2227 
2228 	/*
2229 	 * Station isn't capable of short slot time.  Bump
2230 	 * the count of long slot time stations and disable
2231 	 * use of short slot time.  Note that the actual switch
2232 	 * over to long slot time use may not occur until the
2233 	 * next beacon transmission (per sec. 7.3.1.4 of 11g).
2234 	 */
2235 	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
2236 		ic->ic_longslotsta++;
2237 		IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ASSOC, ni,
2238 		    "station needs long slot time, count %d",
2239 		    ic->ic_longslotsta);
2240 		/* XXX vap's w/ conflicting needs won't work */
2241 		if (!IEEE80211_IS_CHAN_108G(ic->ic_bsschan)) {
2242 			/*
2243 			 * Don't force slot time when switched to turbo
2244 			 * mode as non-ERP stations won't be present; this
2245 			 * need only be done when on the normal G channel.
2246 			 */
2247 			ieee80211_set_shortslottime(ic, 0);
2248 		}
2249 	}
2250 	/*
2251 	 * If the new station is not an ERP station
2252 	 * then bump the counter and enable protection
2253 	 * if configured.
2254 	 */
2255 	if (!ieee80211_iserp_rateset(&ni->ni_rates)) {
2256 		ic->ic_nonerpsta++;
2257 		IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ASSOC, ni,
2258 		    "station is !ERP, %d non-ERP stations associated",
2259 		    ic->ic_nonerpsta);
2260 		/*
2261 		 * If station does not support short preamble
2262 		 * then we must enable use of Barker preamble.
2263 		 */
2264 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE) == 0) {
2265 			IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ASSOC, ni,
2266 			    "%s", "station needs long preamble");
2267 			ic->ic_flags |= IEEE80211_F_USEBARKER;
2268 			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
2269 		}
2270 		/*
2271 		 * If protection is configured and this is the first
2272 		 * indication we should use protection, enable it.
2273 		 */
2274 		if (ic->ic_protmode != IEEE80211_PROT_NONE &&
2275 		    ic->ic_nonerpsta == 1 &&
2276 		    (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) == 0) {
2277 			IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_ASSOC,
2278 			    "%s: enable use of protection\n", __func__);
2279 			ic->ic_flags |= IEEE80211_F_USEPROT;
2280 			ieee80211_notify_erp_locked(ic);
2281 		}
2282 	} else
2283 		ni->ni_flags |= IEEE80211_NODE_ERP;
2284 }
2285 
2286 void
2287 ieee80211_node_join(struct ieee80211_node *ni, int resp)
2288 {
2289 	struct ieee80211com *ic = ni->ni_ic;
2290 	struct ieee80211vap *vap = ni->ni_vap;
2291 	int newassoc;
2292 
2293 	if (ni->ni_associd == 0) {
2294 		uint16_t aid;
2295 
2296 		KASSERT(vap->iv_aid_bitmap != NULL, ("no aid bitmap"));
2297 		/*
2298 		 * It would be good to search the bitmap
2299 		 * more efficiently, but this will do for now.
2300 		 */
2301 		for (aid = 1; aid < vap->iv_max_aid; aid++) {
2302 			if (!IEEE80211_AID_ISSET(vap, aid))
2303 				break;
2304 		}
2305 		if (aid >= vap->iv_max_aid) {
2306 			IEEE80211_SEND_MGMT(ni, resp, IEEE80211_STATUS_TOOMANY);
2307 			ieee80211_node_leave(ni);
2308 			return;
2309 		}
2310 		ni->ni_associd = aid | 0xc000;
2311 		ni->ni_jointime = time_uptime;
2312 		IEEE80211_LOCK(ic);
2313 		IEEE80211_AID_SET(vap, ni->ni_associd);
2314 		vap->iv_sta_assoc++;
2315 		ic->ic_sta_assoc++;
2316 
2317 		if (IEEE80211_IS_CHAN_HT(ic->ic_bsschan))
2318 			ieee80211_ht_node_join(ni);
2319 		if (IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan) &&
2320 		    IEEE80211_IS_CHAN_FULL(ic->ic_bsschan))
2321 			ieee80211_node_join_11g(ni);
2322 		IEEE80211_UNLOCK(ic);
2323 
2324 		newassoc = 1;
2325 	} else
2326 		newassoc = 0;
2327 
2328 	IEEE80211_NOTE(vap, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG, ni,
2329 	    "station associated at aid %d: %s preamble, %s slot time%s%s%s%s%s%s%s%s",
2330 	    IEEE80211_NODE_AID(ni),
2331 	    ic->ic_flags & IEEE80211_F_SHPREAMBLE ? "short" : "long",
2332 	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long",
2333 	    ic->ic_flags & IEEE80211_F_USEPROT ? ", protection" : "",
2334 	    ni->ni_flags & IEEE80211_NODE_QOS ? ", QoS" : "",
2335 	    ni->ni_flags & IEEE80211_NODE_HT ?
2336 		(ni->ni_chw == 40 ? ", HT40" : ", HT20") : "",
2337 	    ni->ni_flags & IEEE80211_NODE_AMPDU ? " (+AMPDU)" : "",
2338 	    ni->ni_flags & IEEE80211_NODE_MIMO_RTS ? " (+SMPS-DYN)" :
2339 	        ni->ni_flags & IEEE80211_NODE_MIMO_PS ? " (+SMPS)" : "",
2340 	    ni->ni_flags & IEEE80211_NODE_RIFS ? " (+RIFS)" : "",
2341 	    IEEE80211_ATH_CAP(vap, ni, IEEE80211_NODE_FF) ?
2342 		", fast-frames" : "",
2343 	    IEEE80211_ATH_CAP(vap, ni, IEEE80211_NODE_TURBOP) ?
2344 		", turbo" : ""
2345 	);
2346 
2347 	ieee80211_node_setuptxparms(ni);
2348 	if (vap->iv_caps & IEEE80211_C_RATECTL)
2349 		ieee80211_ratectl_node_init(ni);
2350 	/* give driver a chance to setup state like ni_txrate */
2351 	if (ic->ic_newassoc != NULL)
2352 		ic->ic_newassoc(ni, newassoc);
2353 	IEEE80211_SEND_MGMT(ni, resp, IEEE80211_STATUS_SUCCESS);
2354 	/* tell the authenticator about new station */
2355 	if (vap->iv_auth->ia_node_join != NULL)
2356 		vap->iv_auth->ia_node_join(ni);
2357 	ieee80211_notify_node_join(ni,
2358 	    resp == IEEE80211_FC0_SUBTYPE_ASSOC_RESP);
2359 }
2360 
2361 static void
2362 disable_protection(struct ieee80211com *ic)
2363 {
2364 	KASSERT(ic->ic_nonerpsta == 0 &&
2365 	    (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) == 0,
2366 	   ("%d non ERP stations, flags 0x%x", ic->ic_nonerpsta,
2367 	   ic->ic_flags_ext));
2368 
2369 	ic->ic_flags &= ~IEEE80211_F_USEPROT;
2370 	/* XXX verify mode? */
2371 	if (ic->ic_caps & IEEE80211_C_SHPREAMBLE) {
2372 		ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
2373 		ic->ic_flags &= ~IEEE80211_F_USEBARKER;
2374 	}
2375 	ieee80211_notify_erp_locked(ic);
2376 }
2377 
2378 /*
2379  * Handle a station leaving an 11g network.
2380  */
2381 static void
2382 ieee80211_node_leave_11g(struct ieee80211_node *ni)
2383 {
2384 	struct ieee80211com *ic = ni->ni_ic;
2385 
2386 	IEEE80211_LOCK_ASSERT(ic);
2387 
2388 	KASSERT(IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan),
2389 	     ("not in 11g, bss %u:0x%x", ic->ic_bsschan->ic_freq,
2390 	      ic->ic_bsschan->ic_flags));
2391 
2392 	/*
2393 	 * If a long slot station do the slot time bookkeeping.
2394 	 */
2395 	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
2396 		KASSERT(ic->ic_longslotsta > 0,
2397 		    ("bogus long slot station count %d", ic->ic_longslotsta));
2398 		ic->ic_longslotsta--;
2399 		IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ASSOC, ni,
2400 		    "long slot time station leaves, count now %d",
2401 		    ic->ic_longslotsta);
2402 		if (ic->ic_longslotsta == 0) {
2403 			/*
2404 			 * Re-enable use of short slot time if supported
2405 			 * and not operating in IBSS mode (per spec).
2406 			 */
2407 			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
2408 			    ic->ic_opmode != IEEE80211_M_IBSS) {
2409 				IEEE80211_DPRINTF(ni->ni_vap,
2410 				    IEEE80211_MSG_ASSOC,
2411 				    "%s: re-enable use of short slot time\n",
2412 				    __func__);
2413 				ieee80211_set_shortslottime(ic, 1);
2414 			}
2415 		}
2416 	}
2417 	/*
2418 	 * If a non-ERP station do the protection-related bookkeeping.
2419 	 */
2420 	if ((ni->ni_flags & IEEE80211_NODE_ERP) == 0) {
2421 		KASSERT(ic->ic_nonerpsta > 0,
2422 		    ("bogus non-ERP station count %d", ic->ic_nonerpsta));
2423 		ic->ic_nonerpsta--;
2424 		IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ASSOC, ni,
2425 		    "non-ERP station leaves, count now %d%s", ic->ic_nonerpsta,
2426 		    (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) ?
2427 			" (non-ERP sta present)" : "");
2428 		if (ic->ic_nonerpsta == 0 &&
2429 		    (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) == 0) {
2430 			IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_ASSOC,
2431 				"%s: disable use of protection\n", __func__);
2432 			disable_protection(ic);
2433 		}
2434 	}
2435 }
2436 
2437 /*
2438  * Time out presence of an overlapping bss with non-ERP
2439  * stations.  When operating in hostap mode we listen for
2440  * beacons from other stations and if we identify a non-ERP
2441  * station is present we enable protection.  To identify
2442  * when all non-ERP stations are gone we time out this
2443  * condition.
2444  */
2445 static void
2446 ieee80211_erp_timeout(struct ieee80211com *ic)
2447 {
2448 
2449 	IEEE80211_LOCK_ASSERT(ic);
2450 
2451 	if ((ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) &&
2452 	    time_after(ticks, ic->ic_lastnonerp + IEEE80211_NONERP_PRESENT_AGE)) {
2453 #if 0
2454 		IEEE80211_NOTE(vap, IEEE80211_MSG_ASSOC, ni,
2455 		    "%s", "age out non-ERP sta present on channel");
2456 #endif
2457 		ic->ic_flags_ext &= ~IEEE80211_FEXT_NONERP_PR;
2458 		if (ic->ic_nonerpsta == 0)
2459 			disable_protection(ic);
2460 	}
2461 }
2462 
2463 /*
2464  * Handle bookkeeping for station deauthentication/disassociation
2465  * when operating as an ap.
2466  */
2467 void
2468 ieee80211_node_leave(struct ieee80211_node *ni)
2469 {
2470 	struct ieee80211com *ic = ni->ni_ic;
2471 	struct ieee80211vap *vap = ni->ni_vap;
2472 	struct ieee80211_node_table *nt = ni->ni_table;
2473 
2474 	IEEE80211_NOTE(vap, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG, ni,
2475 	    "station with aid %d leaves", IEEE80211_NODE_AID(ni));
2476 
2477 	KASSERT(vap->iv_opmode != IEEE80211_M_STA,
2478 		("unexpected operating mode %u", vap->iv_opmode));
2479 	/*
2480 	 * If node wasn't previously associated all
2481 	 * we need to do is reclaim the reference.
2482 	 */
2483 	/* XXX ibss mode bypasses 11g and notification */
2484 	if (ni->ni_associd == 0)
2485 		goto done;
2486 	/*
2487 	 * Tell the authenticator the station is leaving.
2488 	 * Note that we must do this before yanking the
2489 	 * association id as the authenticator uses the
2490 	 * associd to locate it's state block.
2491 	 */
2492 	if (vap->iv_auth->ia_node_leave != NULL)
2493 		vap->iv_auth->ia_node_leave(ni);
2494 
2495 	IEEE80211_LOCK(ic);
2496 	IEEE80211_AID_CLR(vap, ni->ni_associd);
2497 	ni->ni_associd = 0;
2498 	vap->iv_sta_assoc--;
2499 	ic->ic_sta_assoc--;
2500 
2501 	if (IEEE80211_IS_CHAN_HT(ic->ic_bsschan))
2502 		ieee80211_ht_node_leave(ni);
2503 	if (IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan) &&
2504 	    IEEE80211_IS_CHAN_FULL(ic->ic_bsschan))
2505 		ieee80211_node_leave_11g(ni);
2506 	IEEE80211_UNLOCK(ic);
2507 	/*
2508 	 * Cleanup station state.  In particular clear various
2509 	 * state that might otherwise be reused if the node
2510 	 * is reused before the reference count goes to zero
2511 	 * (and memory is reclaimed).
2512 	 */
2513 	ieee80211_sta_leave(ni);
2514 done:
2515 	/*
2516 	 * Remove the node from any table it's recorded in and
2517 	 * drop the caller's reference.  Removal from the table
2518 	 * is important to insure the node is not reprocessed
2519 	 * for inactivity.
2520 	 */
2521 	if (nt != NULL) {
2522 		IEEE80211_NODE_LOCK(nt);
2523 		node_reclaim(nt, ni);
2524 		IEEE80211_NODE_UNLOCK(nt);
2525 	} else
2526 		ieee80211_free_node(ni);
2527 }
2528 
2529 struct rssiinfo {
2530 	struct ieee80211vap *vap;
2531 	int	rssi_samples;
2532 	uint32_t rssi_total;
2533 };
2534 
2535 static void
2536 get_hostap_rssi(void *arg, struct ieee80211_node *ni)
2537 {
2538 	struct rssiinfo *info = arg;
2539 	struct ieee80211vap *vap = ni->ni_vap;
2540 	int8_t rssi;
2541 
2542 	if (info->vap != vap)
2543 		return;
2544 	/* only associated stations */
2545 	if (ni->ni_associd == 0)
2546 		return;
2547 	rssi = vap->iv_ic->ic_node_getrssi(ni);
2548 	if (rssi != 0) {
2549 		info->rssi_samples++;
2550 		info->rssi_total += rssi;
2551 	}
2552 }
2553 
2554 static void
2555 get_adhoc_rssi(void *arg, struct ieee80211_node *ni)
2556 {
2557 	struct rssiinfo *info = arg;
2558 	struct ieee80211vap *vap = ni->ni_vap;
2559 	int8_t rssi;
2560 
2561 	if (info->vap != vap)
2562 		return;
2563 	/* only neighbors */
2564 	/* XXX check bssid */
2565 	if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
2566 		return;
2567 	rssi = vap->iv_ic->ic_node_getrssi(ni);
2568 	if (rssi != 0) {
2569 		info->rssi_samples++;
2570 		info->rssi_total += rssi;
2571 	}
2572 }
2573 
2574 #ifdef IEEE80211_SUPPORT_MESH
2575 static void
2576 get_mesh_rssi(void *arg, struct ieee80211_node *ni)
2577 {
2578 	struct rssiinfo *info = arg;
2579 	struct ieee80211vap *vap = ni->ni_vap;
2580 	int8_t rssi;
2581 
2582 	if (info->vap != vap)
2583 		return;
2584 	/* only neighbors that peered successfully */
2585 	if (ni->ni_mlstate != IEEE80211_NODE_MESH_ESTABLISHED)
2586 		return;
2587 	rssi = vap->iv_ic->ic_node_getrssi(ni);
2588 	if (rssi != 0) {
2589 		info->rssi_samples++;
2590 		info->rssi_total += rssi;
2591 	}
2592 }
2593 #endif /* IEEE80211_SUPPORT_MESH */
2594 
2595 int8_t
2596 ieee80211_getrssi(struct ieee80211vap *vap)
2597 {
2598 #define	NZ(x)	((x) == 0 ? 1 : (x))
2599 	struct ieee80211com *ic = vap->iv_ic;
2600 	struct rssiinfo info;
2601 
2602 	info.rssi_total = 0;
2603 	info.rssi_samples = 0;
2604 	info.vap = vap;
2605 	switch (vap->iv_opmode) {
2606 	case IEEE80211_M_IBSS:		/* average of all ibss neighbors */
2607 	case IEEE80211_M_AHDEMO:	/* average of all neighbors */
2608 		ieee80211_iterate_nodes(&ic->ic_sta, get_adhoc_rssi, &info);
2609 		break;
2610 	case IEEE80211_M_HOSTAP:	/* average of all associated stations */
2611 		ieee80211_iterate_nodes(&ic->ic_sta, get_hostap_rssi, &info);
2612 		break;
2613 #ifdef IEEE80211_SUPPORT_MESH
2614 	case IEEE80211_M_MBSS:		/* average of all mesh neighbors */
2615 		ieee80211_iterate_nodes(&ic->ic_sta, get_mesh_rssi, &info);
2616 		break;
2617 #endif
2618 	case IEEE80211_M_MONITOR:	/* XXX */
2619 	case IEEE80211_M_STA:		/* use stats from associated ap */
2620 	default:
2621 		if (vap->iv_bss != NULL)
2622 			info.rssi_total = ic->ic_node_getrssi(vap->iv_bss);
2623 		info.rssi_samples = 1;
2624 		break;
2625 	}
2626 	return info.rssi_total / NZ(info.rssi_samples);
2627 #undef NZ
2628 }
2629 
2630 void
2631 ieee80211_getsignal(struct ieee80211vap *vap, int8_t *rssi, int8_t *noise)
2632 {
2633 
2634 	if (vap->iv_bss == NULL)		/* NB: shouldn't happen */
2635 		return;
2636 	vap->iv_ic->ic_node_getsignal(vap->iv_bss, rssi, noise);
2637 	/* for non-station mode return avg'd rssi accounting */
2638 	if (vap->iv_opmode != IEEE80211_M_STA)
2639 		*rssi = ieee80211_getrssi(vap);
2640 }
2641