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