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