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