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