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