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