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