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