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