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