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