ieee80211_node.c revision 153351
1139823Simp/*-
21541Srgrimes * Copyright (c) 2001 Atsushi Onoe
31541Srgrimes * Copyright (c) 2002-2005 Sam Leffler, Errno Consulting
41541Srgrimes * All rights reserved.
51541Srgrimes *
61541Srgrimes * Redistribution and use in source and binary forms, with or without
71541Srgrimes * modification, are permitted provided that the following conditions
81541Srgrimes * are met:
91541Srgrimes * 1. Redistributions of source code must retain the above copyright
101541Srgrimes *    notice, this list of conditions and the following disclaimer.
111541Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
121541Srgrimes *    notice, this list of conditions and the following disclaimer in the
131541Srgrimes *    documentation and/or other materials provided with the distribution.
141541Srgrimes * 3. The name of the author may not be used to endorse or promote products
151541Srgrimes *    derived from this software without specific prior written permission.
161541Srgrimes *
171541Srgrimes * Alternatively, this software may be distributed under the terms of the
181541Srgrimes * GNU General Public License ("GPL") version 2 as published by the Free
191541Srgrimes * Software Foundation.
201541Srgrimes *
211541Srgrimes * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
221541Srgrimes * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
231541Srgrimes * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
241541Srgrimes * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
251541Srgrimes * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
261541Srgrimes * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
271541Srgrimes * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
281541Srgrimes * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
291541Srgrimes * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
3050477Speter * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
311541Srgrimes */
321541Srgrimes
332169Spaul#include <sys/cdefs.h>
34121498Sume__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_node.c 153351 2005-12-12 18:42:20Z sam $");
352169Spaul
3695336Smike#include <sys/param.h>
3793514Smike#include <sys/systm.h>
3895336Smike#include <sys/mbuf.h>
3993514Smike#include <sys/malloc.h>
4095336Smike#include <sys/kernel.h>
4195336Smike
4295336Smike#include <sys/socket.h>
4395336Smike
4495336Smike#include <net/if.h>
4595336Smike#include <net/if_media.h>
4695336Smike#include <net/ethernet.h>
4795336Smike
4895336Smike#include <net80211/ieee80211_var.h>
4995336Smike
5095336Smike#include <net/bpf.h>
5195336Smike
5295336Smike/*
5395336Smike * Association id's are managed with a bit vector.
5495336Smike */
5595336Smike#define	IEEE80211_AID_SET(b, w) \
5695336Smike	((w)[IEEE80211_AID(b) / 32] |= (1 << (IEEE80211_AID(b) % 32)))
5795336Smike#define	IEEE80211_AID_CLR(b, w) \
5895336Smike	((w)[IEEE80211_AID(b) / 32] &= ~(1 << (IEEE80211_AID(b) % 32)))
5995336Smike#define	IEEE80211_AID_ISSET(b, w) \
6095336Smike	((w)[IEEE80211_AID(b) / 32] & (1 << (IEEE80211_AID(b) % 32)))
6195336Smike
6295336Smikestatic struct ieee80211_node *node_alloc(struct ieee80211_node_table *);
6395336Smikestatic void node_cleanup(struct ieee80211_node *);
6495336Smikestatic void node_free(struct ieee80211_node *);
6595336Smikestatic u_int8_t node_getrssi(const struct ieee80211_node *);
6695336Smike
6795336Smikestatic void ieee80211_setup_node(struct ieee80211_node_table *,
6895336Smike		struct ieee80211_node *, const u_int8_t *);
6995336Smikestatic void _ieee80211_free_node(struct ieee80211_node *);
7095336Smikestatic void ieee80211_free_allnodes(struct ieee80211_node_table *);
7195336Smike
7295336Smikestatic void ieee80211_timeout_scan_candidates(struct ieee80211_node_table *);
7395336Smikestatic void ieee80211_timeout_stations(struct ieee80211_node_table *);
74102227Smike
75102227Smikestatic void ieee80211_set_tim(struct ieee80211_node *, int set);
76102227Smike
7795336Smikestatic void ieee80211_node_table_init(struct ieee80211com *ic,
7895336Smike	struct ieee80211_node_table *nt, const char *name,
7995336Smike	int inact, int keyixmax,
8095336Smike	void (*timeout)(struct ieee80211_node_table *));
8195336Smikestatic void ieee80211_node_table_cleanup(struct ieee80211_node_table *nt);
8295336Smike
8395336SmikeMALLOC_DEFINE(M_80211_NODE, "80211node", "802.11 node state");
8495336Smike
8595336Smikevoid
8695336Smikeieee80211_node_attach(struct ieee80211com *ic)
87170613Sbms{
88170613Sbms
89170613Sbms	ic->ic_node_alloc = node_alloc;
90170613Sbms	ic->ic_node_free = node_free;
91170613Sbms	ic->ic_node_cleanup = node_cleanup;
92196967Sphk	ic->ic_node_getrssi = node_getrssi;
93170613Sbms
9495336Smike	/* default station inactivity timer setings */
9595336Smike	ic->ic_inact_init = IEEE80211_INACT_INIT;
9695336Smike	ic->ic_inact_auth = IEEE80211_INACT_AUTH;
9795336Smike	ic->ic_inact_run = IEEE80211_INACT_RUN;
9895336Smike	ic->ic_inact_probe = IEEE80211_INACT_PROBE;
9995336Smike
10095336Smike	/* NB: driver should override */
10195336Smike	ic->ic_max_aid = IEEE80211_AID_DEF;
10295336Smike	ic->ic_set_tim = ieee80211_set_tim;
103189829Sdas}
10495336Smike
10595336Smikevoid
10695336Smikeieee80211_node_lateattach(struct ieee80211com *ic)
10795336Smike{
10895336Smike	struct ieee80211_rsnparms *rsn;
10995336Smike
11095336Smike	if (ic->ic_max_aid > IEEE80211_AID_MAX)
11195336Smike		ic->ic_max_aid = IEEE80211_AID_MAX;
11295336Smike	MALLOC(ic->ic_aid_bitmap, u_int32_t *,
11395336Smike		howmany(ic->ic_max_aid, 32) * sizeof(u_int32_t),
11495336Smike		M_DEVBUF, M_NOWAIT | M_ZERO);
11595336Smike	if (ic->ic_aid_bitmap == NULL) {
11695336Smike		/* XXX no way to recover */
11795336Smike		printf("%s: no memory for AID bitmap!\n", __func__);
11895336Smike		ic->ic_max_aid = 0;
11995336Smike	}
12095336Smike
12195336Smike	/* XXX defer until using hostap/ibss mode */
12295336Smike	ic->ic_tim_len = howmany(ic->ic_max_aid, 8) * sizeof(u_int8_t);
123189829Sdas	MALLOC(ic->ic_tim_bitmap, u_int8_t *, ic->ic_tim_len,
12495336Smike		M_DEVBUF, M_NOWAIT | M_ZERO);
12595336Smike	if (ic->ic_tim_bitmap == NULL) {
126250000Scperciva		/* XXX no way to recover */
12795336Smike		printf("%s: no memory for TIM bitmap!\n", __func__);
12895336Smike	}
12995336Smike
13095336Smike	ieee80211_node_table_init(ic, &ic->ic_sta, "station",
13195336Smike		IEEE80211_INACT_INIT, ic->ic_crypto.cs_max_keyix,
1321541Srgrimes		ieee80211_timeout_stations);
1331541Srgrimes	ieee80211_node_table_init(ic, &ic->ic_scan, "scan",
1341541Srgrimes		IEEE80211_INACT_SCAN, 0,
1351541Srgrimes		ieee80211_timeout_scan_candidates);
1361541Srgrimes
1371541Srgrimes	ieee80211_reset_bss(ic);
13833804Sjulian	/*
1391541Srgrimes	 * Setup "global settings" in the bss node so that
14052904Sshin	 * each new station automatically inherits them.
1411541Srgrimes	 */
1421541Srgrimes	rsn = &ic->ic_bss->ni_rsn;
143133874Srwatson	/* WEP, TKIP, and AES-CCM are always supported */
144133874Srwatson	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_WEP;
14533804Sjulian	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_TKIP;
1461541Srgrimes	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_AES_CCM;
14733804Sjulian	if (ic->ic_caps & IEEE80211_C_AES)
14833804Sjulian		rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_AES_OCB;
14933804Sjulian	if (ic->ic_caps & IEEE80211_C_CKIP)
1501541Srgrimes		rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_CKIP;
15133804Sjulian	/*
15233804Sjulian	 * Default unicast cipher to WEP for 802.1x use.  If
15333804Sjulian	 * WPA is enabled the management code will set these
15433804Sjulian	 * values to reflect.
15533804Sjulian	 */
15633804Sjulian	rsn->rsn_ucastcipher = IEEE80211_CIPHER_WEP;
15733804Sjulian	rsn->rsn_ucastkeylen = 104 / NBBY;
15833804Sjulian	/*
1591541Srgrimes	 * WPA says the multicast cipher is the lowest unicast
16033804Sjulian	 * cipher supported.  But we skip WEP which would
16133804Sjulian	 * otherwise be used based on this criteria.
16233804Sjulian	 */
16333804Sjulian	rsn->rsn_mcastcipher = IEEE80211_CIPHER_TKIP;
16433804Sjulian	rsn->rsn_mcastkeylen = 128 / NBBY;
16533804Sjulian
166133874Srwatson	/*
16733804Sjulian	 * We support both WPA-PSK and 802.1x; the one used
16833804Sjulian	 * is determined by the authentication mode and the
16933804Sjulian	 * setting of the PSK state.
17033804Sjulian	 */
17133804Sjulian	rsn->rsn_keymgmtset = WPA_ASE_8021X_UNSPEC | WPA_ASE_8021X_PSK;
17233804Sjulian	rsn->rsn_keymgmt = WPA_ASE_8021X_PSK;
17333804Sjulian
17433804Sjulian	ic->ic_auth = ieee80211_authenticator_get(ic->ic_bss->ni_authmode);
17533804Sjulian}
17633804Sjulian
17733804Sjulianvoid
17833804Sjulianieee80211_node_detach(struct ieee80211com *ic)
17952904Sshin{
18052904Sshin
18133804Sjulian	if (ic->ic_bss != NULL) {
182133874Srwatson		ieee80211_free_node(ic->ic_bss);
18333804Sjulian		ic->ic_bss = NULL;
18433804Sjulian	}
18533804Sjulian	ieee80211_node_table_cleanup(&ic->ic_scan);
18652904Sshin	ieee80211_node_table_cleanup(&ic->ic_sta);
18752904Sshin	if (ic->ic_aid_bitmap != NULL) {
18833804Sjulian		FREE(ic->ic_aid_bitmap, M_DEVBUF);
18933804Sjulian		ic->ic_aid_bitmap = NULL;
19033804Sjulian	}
191133874Srwatson	if (ic->ic_tim_bitmap != NULL) {
192133874Srwatson		FREE(ic->ic_tim_bitmap, M_DEVBUF);
193133874Srwatson		ic->ic_tim_bitmap = NULL;
19452904Sshin	}
19552904Sshin}
19652904Sshin
19733804Sjulian/*
19833804Sjulian * Port authorize/unauthorize interfaces for use by an authenticator.
19933804Sjulian */
20033804Sjulian
20133804Sjulianvoid
20233804Sjulianieee80211_node_authorize(struct ieee80211_node *ni)
20333804Sjulian{
20433804Sjulian	struct ieee80211com *ic = ni->ni_ic;
20533804Sjulian
20633804Sjulian	ni->ni_flags |= IEEE80211_NODE_AUTH;
20733804Sjulian	ni->ni_inact_reload = ic->ic_inact_run;
20833804Sjulian}
20933804Sjulian
21033804Sjulianvoid
21133804Sjulianieee80211_node_unauthorize(struct ieee80211_node *ni)
21233804Sjulian{
21333804Sjulian	ni->ni_flags &= ~IEEE80211_NODE_AUTH;
21433804Sjulian}
21533804Sjulian
2161541Srgrimes/*
21733804Sjulian * Set/change the channel.  The rate set is also updated as
21833804Sjulian * to insure a consistent view by drivers.
21933804Sjulian */
22033804Sjulianstatic void
22133804Sjulianieee80211_set_chan(struct ieee80211com *ic,
22233804Sjulian	struct ieee80211_node *ni, struct ieee80211_channel *chan)
22333814Sjulian{
22433804Sjulian	if (chan == IEEE80211_CHAN_ANYC)	/* XXX while scanning */
22533804Sjulian		chan = ic->ic_curchan;
22633804Sjulian	ni->ni_chan = chan;
22733804Sjulian	ni->ni_rates = ic->ic_sup_rates[ieee80211_chan2mode(ic, chan)];
22833804Sjulian}
22933804Sjulian
23033804Sjulian/*
23133804Sjulian * AP scanning support.
23233804Sjulian */
23333804Sjulian
2341541Srgrimes#ifdef IEEE80211_DEBUG
23533804Sjulianstatic void
23633804Sjuliandump_chanlist(const u_char chans[])
23752904Sshin{
238153553Sdelphij	const char *sep;
239206022Sdelphij	int i;
240265946Skevlo
241265946Skevlo	sep = " ";
242265946Skevlo	for (i = 0; i < IEEE80211_CHAN_MAX; i++)
24346420Sluigi		if (isset(chans, i)) {
24452904Sshin			printf("%s%u", sep, i);
245142215Sglebius			sep = ", ";
24646420Sluigi		}
247236157Semaste}
248130609Smlaier#endif /* IEEE80211_DEBUG */
249265946Skevlo
250265946Skevlo/*
25133804Sjulian * Initialize the channel set to scan based on the
252106152Sfenner * of available channels and the current PHY mode.
253106152Sfenner */
2541541Srgrimesstatic void
2551541Srgrimesieee80211_reset_scan(struct ieee80211com *ic)
25652904Sshin{
25752904Sshin
2581541Srgrimes	/* XXX ic_des_chan should be handled with ic_chan_active */
259106152Sfenner	if (ic->ic_des_chan != IEEE80211_CHAN_ANYC) {
260106152Sfenner		memset(ic->ic_chan_scan, 0, sizeof(ic->ic_chan_scan));
261211501Sanchie		setbit(ic->ic_chan_scan,
262106152Sfenner			ieee80211_chan2ieee(ic, ic->ic_des_chan));
2631541Srgrimes	} else
264136712Sandre		memcpy(ic->ic_chan_scan, ic->ic_chan_active,
265136712Sandre			sizeof(ic->ic_chan_active));
266136712Sandre#ifdef IEEE80211_DEBUG
267136712Sandre	if (ieee80211_msg_scan(ic)) {
268136712Sandre		printf("%s: scan set:", __func__);
269136712Sandre		dump_chanlist(ic->ic_chan_scan);
2701541Srgrimes		printf(" start chan %u\n",
27114195Speter			ieee80211_chan2ieee(ic, ic->ic_curchan));
27214195Speter	}
27314195Speter#endif /* IEEE80211_DEBUG */
27494291Ssilby}
27594291Ssilby
27614195Speter/*
27714195Speter * Begin an active scan.
27814195Speter */
27914195Spetervoid
28014195Speterieee80211_begin_scan(struct ieee80211com *ic, int reset)
28114195Speter{
28214195Speter
28314195Speter	ic->ic_scan.nt_scangen++;
284176805Srpaulo	/*
28514195Speter	 * In all but hostap mode scanning starts off in
28614195Speter	 * an active mode before switching to passive.
28714195Speter	 */
28814195Speter	if (ic->ic_opmode != IEEE80211_M_HOSTAP) {
28914195Speter		ic->ic_flags |= IEEE80211_F_ASCAN;
29014195Speter		ic->ic_stats.is_scan_active++;
29114195Speter	} else
29217541Speter		ic->ic_stats.is_scan_passive++;
29314195Speter	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
29414195Speter		"begin %s scan in %s mode, scangen %u\n",
295108533Sschweikh		(ic->ic_flags & IEEE80211_F_ASCAN) ?  "active" : "passive",
29614195Speter		ieee80211_phymode_name[ic->ic_curmode], ic->ic_scan.nt_scangen);
29714195Speter	/*
29814195Speter	 * Clear scan state and flush any previously seen AP's.
29914195Speter	 */
30014195Speter	ieee80211_reset_scan(ic);
30135304Sphk	if (reset)
30235304Sphk		ieee80211_free_allnodes(&ic->ic_scan);
30335304Sphk
30435304Sphk	ic->ic_flags |= IEEE80211_F_SCAN;
30535304Sphk
30635304Sphk	/* Scan the next channel. */
30735304Sphk	ieee80211_next_scan(ic);
30835304Sphk}
30935304Sphk
31035304Sphk/*
31135304Sphk * Switch to the next channel marked for scanning.
31214195Speter */
31314195Speterint
31414195Speterieee80211_next_scan(struct ieee80211com *ic)
3151541Srgrimes{
31614195Speter	struct ieee80211_channel *chan;
3171541Srgrimes
3181541Srgrimes	/*
3191541Srgrimes	 * Insure any previous mgt frame timeouts don't fire.
3201541Srgrimes	 * This assumes the driver does the right thing in
321176805Srpaulo	 * flushing anything queued in the driver and below.
32213491Speter	 */
323176805Srpaulo	ic->ic_mgt_timer = 0;
324176805Srpaulo
325176805Srpaulo	chan = ic->ic_curchan;
326176805Srpaulo	do {
327176805Srpaulo		if (++chan > &ic->ic_channels[IEEE80211_CHAN_MAX])
328176805Srpaulo			chan = &ic->ic_channels[0];
32935304Sphk		if (isset(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan))) {
33035304Sphk			clrbit(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan));
33113491Speter			IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
33213491Speter			    "%s: chan %d->%d\n", __func__,
33317541Speter			    ieee80211_chan2ieee(ic, ic->ic_curchan),
33417541Speter			    ieee80211_chan2ieee(ic, chan));
33517541Speter			ic->ic_curchan = chan;
33617541Speter			/*
33717541Speter			 * XXX drivers should do this as needed,
338133874Srwatson			 * XXX for now maintain compatibility
33917541Speter			 */
34087158Smike			ic->ic_bss->ni_rates =
34187158Smike				ic->ic_sup_rates[ieee80211_chan2mode(ic, chan)];
34217541Speter			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
3431541Srgrimes			return 1;
3441541Srgrimes		}
3451541Srgrimes	} while (chan != ic->ic_curchan);
3461541Srgrimes	ieee80211_end_scan(ic);
34735919Sjb	return 0;
3481541Srgrimes}
3491541Srgrimes
3501541Srgrimesstatic __inline void
3511541Srgrimescopy_bss(struct ieee80211_node *nbss, const struct ieee80211_node *obss)
3521541Srgrimes{
35335919Sjb	/* propagate useful state */
3541541Srgrimes	nbss->ni_authmode = obss->ni_authmode;
3551541Srgrimes	nbss->ni_txpower = obss->ni_txpower;
3561541Srgrimes	nbss->ni_vlan = obss->ni_vlan;
3571541Srgrimes	nbss->ni_rsn = obss->ni_rsn;
3581541Srgrimes	/* XXX statistics? */
35935919Sjb}
3601541Srgrimes
3611541Srgrimesvoid
3621541Srgrimesieee80211_create_ibss(struct ieee80211com* ic, struct ieee80211_channel *chan)
3631541Srgrimes{
36435919Sjb	struct ieee80211_node_table *nt;
3651541Srgrimes	struct ieee80211_node *ni;
3661541Srgrimes
3671541Srgrimes	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
3681541Srgrimes		"%s: creating ibss\n", __func__);
3691541Srgrimes
37035919Sjb	/*
37135919Sjb	 * Create the station/neighbor table.  Note that for adhoc
3721541Srgrimes	 * mode we make the initial inactivity timer longer since
373166368Sbms	 * we create nodes only through discovery and they typically
374178280Sgnn	 * are long-lived associations.
375178280Sgnn	 */
376166368Sbms	nt = &ic->ic_sta;
377166368Sbms	IEEE80211_NODE_LOCK(nt);
378166368Sbms	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
379166368Sbms		nt->nt_name = "station";
380166368Sbms		nt->nt_inact_init = ic->ic_inact_init;
381166368Sbms	} else {
382166368Sbms		nt->nt_name = "neighbor";
383166368Sbms		nt->nt_inact_init = ic->ic_inact_run;
384166368Sbms	}
38535919Sjb	IEEE80211_NODE_UNLOCK(nt);
38655205Speter
3871541Srgrimes	ni = ieee80211_alloc_node(&ic->ic_sta, ic->ic_myaddr);
3881541Srgrimes	if (ni == NULL) {
3891541Srgrimes		/* XXX recovery? */
39035919Sjb		return;
39135919Sjb	}
39235919Sjb	IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_myaddr);
393167072Sbms	ni->ni_esslen = ic->ic_des_esslen;
394142215Sglebius	memcpy(ni->ni_essid, ic->ic_des_essid, ni->ni_esslen);
395130609Smlaier	copy_bss(ni, ic->ic_bss);
396114259Smdodd	ni->ni_intval = ic->ic_bintval;
39735919Sjb	if (ic->ic_flags & IEEE80211_F_PRIVACY)
3981541Srgrimes		ni->ni_capinfo |= IEEE80211_CAPINFO_PRIVACY;
3991541Srgrimes	if (ic->ic_phytype == IEEE80211_T_FH) {
4001541Srgrimes		ni->ni_fhdwell = 200;	/* XXX */
401226402Sglebius		ni->ni_fhindex = 1;
402226402Sglebius	}
4031541Srgrimes	if (ic->ic_opmode == IEEE80211_M_IBSS) {
4041541Srgrimes		ic->ic_flags |= IEEE80211_F_SIBSS;
4051541Srgrimes		ni->ni_capinfo |= IEEE80211_CAPINFO_IBSS;	/* XXX */
4061541Srgrimes		if (ic->ic_flags & IEEE80211_F_DESBSSID)
4071541Srgrimes			IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_des_bssid);
4081541Srgrimes		else
4091541Srgrimes			ni->ni_bssid[0] |= 0x02;	/* local bit for IBSS */
4101541Srgrimes	}
4111541Srgrimes	/*
4121541Srgrimes	 * Fix the channel and related attributes.
4131541Srgrimes	 */
414105651Siedowse	ieee80211_set_chan(ic, ni, chan);
4151541Srgrimes	ic->ic_curchan = chan;
416170613Sbms	ic->ic_curmode = ieee80211_chan2mode(ic, chan);
417170613Sbms	/*
4181541Srgrimes	 * Do mode-specific rate setup.
4191541Srgrimes	 */
4201541Srgrimes	if (ic->ic_curmode == IEEE80211_MODE_11G) {
4211541Srgrimes		/*
422133874Srwatson		 * Use a mixed 11b/11g rate set.
423133874Srwatson		 */
424133874Srwatson		ieee80211_set11gbasicrates(&ni->ni_rates, IEEE80211_MODE_11G);
425133874Srwatson	} else if (ic->ic_curmode == IEEE80211_MODE_11B) {
426133874Srwatson		/*
427133874Srwatson		 * Force pure 11b rate set.
42819622Sfenner		 */
42952904Sshin		ieee80211_set11gbasicrates(&ni->ni_rates, IEEE80211_MODE_11B);
43052904Sshin	}
43152904Sshin
4321541Srgrimes	(void) ieee80211_sta_join(ic, ieee80211_ref_node(ni));
433119178Sbms}
434193217Spjd
435119178Sbmsvoid
436200023Sluigiieee80211_reset_bss(struct ieee80211com *ic)
437200023Sluigi{
438200023Sluigi	struct ieee80211_node *ni, *obss;
439200023Sluigi
440200023Sluigi	ieee80211_node_table_reset(&ic->ic_scan);
441130281Sru	ieee80211_node_table_reset(&ic->ic_sta);
442130281Sru
443130281Sru	ni = ieee80211_alloc_node(&ic->ic_scan, ic->ic_myaddr);
444130281Sru	KASSERT(ni != NULL, ("unable to setup inital BSS node"));
445130281Sru	obss = ic->ic_bss;
446130281Sru	ic->ic_bss = ieee80211_ref_node(ni);
447200023Sluigi	if (obss != NULL) {
448200023Sluigi		copy_bss(ni, obss);
449200023Sluigi		ni->ni_intval = ic->ic_bintval;
450133874Srwatson		ieee80211_free_node(obss);
451133874Srwatson	}
452133874Srwatson}
453133874Srwatson
454133874Srwatson/* XXX tunable */
45552904Sshin#define	STA_FAILS_MAX	2		/* assoc failures before ignored */
45617758Ssos
457165648Spisostatic int
458165648Spisoieee80211_match_bss(struct ieee80211com *ic, struct ieee80211_node *ni)
459165648Spiso{
460165648Spiso        u_int8_t rate;
461165648Spiso        int fail;
46241793Sluigi
46341793Sluigi	fail = 0;
46441793Sluigi	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
46541793Sluigi		fail |= 0x01;
46641793Sluigi	if (ic->ic_des_chan != IEEE80211_CHAN_ANYC &&
467114258Smdodd	    ni->ni_chan != ic->ic_des_chan)
468149371Sandre		fail |= 0x01;
469150594Sandre	if (ic->ic_opmode == IEEE80211_M_IBSS) {
470236959Stuexen		if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
471114258Smdodd			fail |= 0x02;
472170613Sbms	} else {
473170613Sbms		if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
474170613Sbms			fail |= 0x02;
475170613Sbms	}
476170613Sbms	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
477170613Sbms		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
478170613Sbms			fail |= 0x04;
479170613Sbms	} else {
480170613Sbms		/* XXX does this mean privacy is supported or required? */
481170613Sbms		if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
482170613Sbms			fail |= 0x04;
483170613Sbms	}
484170613Sbms	rate = ieee80211_fix_rate(ni, IEEE80211_F_DONEGO | IEEE80211_F_DOFRATE);
485170613Sbms	if (rate & IEEE80211_RATE_BASIC)
486170613Sbms		fail |= 0x08;
487170613Sbms	if (ic->ic_des_esslen != 0 &&
488170613Sbms	    (ni->ni_esslen != ic->ic_des_esslen ||
4891541Srgrimes	     memcmp(ni->ni_essid, ic->ic_des_essid, ic->ic_des_esslen) != 0))
4901541Srgrimes		fail |= 0x10;
4911541Srgrimes	if ((ic->ic_flags & IEEE80211_F_DESBSSID) &&
4921541Srgrimes	    !IEEE80211_ADDR_EQ(ic->ic_des_bssid, ni->ni_bssid))
4931541Srgrimes		fail |= 0x20;
4941541Srgrimes	if (ni->ni_fails >= STA_FAILS_MAX)
4951541Srgrimes		fail |= 0x40;
496158563Sbms#ifdef IEEE80211_DEBUG
497158563Sbms	if (ieee80211_msg_scan(ic)) {
498158563Sbms		printf(" %c %s",
499158563Sbms		    fail & 0x40 ? '=' : fail & 0x80 ? '^' : fail ? '-' : '+',
500158563Sbms		    ether_sprintf(ni->ni_macaddr));
501158563Sbms		printf(" %s%c", ether_sprintf(ni->ni_bssid),
502189346Sbms		    fail & 0x20 ? '!' : ' ');
503158563Sbms		printf(" %3d%c", ieee80211_chan2ieee(ic, ni->ni_chan),
504158563Sbms			fail & 0x01 ? '!' : ' ');
505189346Sbms		printf(" %+4d", ni->ni_rssi);
506189346Sbms		printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
507189346Sbms		    fail & 0x08 ? '!' : ' ');
508189346Sbms		printf(" %4s%c",
509189346Sbms		    (ni->ni_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
510189592Sbms		    (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
511189346Sbms		    "????",
512189346Sbms		    fail & 0x02 ? '!' : ' ');
5131541Srgrimes		printf(" %3s%c ",
5141541Srgrimes		    (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) ?
5151541Srgrimes		    "wep" : "no",
5161541Srgrimes		    fail & 0x04 ? '!' : ' ');
5171541Srgrimes		ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
5181541Srgrimes		printf("%s\n", fail & 0x10 ? "!" : "");
5191541Srgrimes	}
5201541Srgrimes#endif
521170613Sbms	return fail;
522170613Sbms}
523170613Sbms
524170613Sbmsstatic __inline u_int8_t
525170613Sbmsmaxrate(const struct ieee80211_node *ni)
526170613Sbms{
527170613Sbms	const struct ieee80211_rateset *rs = &ni->ni_rates;
528170613Sbms	/* NB: assumes rate set is sorted (happens on frame receive) */
529170613Sbms	return rs->rs_rates[rs->rs_nrates-1] & IEEE80211_RATE_VAL;
530170613Sbms}
531170613Sbms
532170613Sbms/*
533170613Sbms * Compare the capabilities of two nodes and decide which is
534170613Sbms * more desirable (return >0 if a is considered better).  Note
535170613Sbms * that we assume compatibility/usability has already been checked
536170613Sbms * so we don't need to (e.g. validate whether privacy is supported).
537170613Sbms * Used to select the best scan candidate for association in a BSS.
538170613Sbms */
539170613Sbmsstatic int
540170613Sbmsieee80211_node_compare(struct ieee80211com *ic,
541170613Sbms		       const struct ieee80211_node *a,
542170613Sbms		       const struct ieee80211_node *b)
543170613Sbms{
544170613Sbms	u_int8_t maxa, maxb;
545170613Sbms	u_int8_t rssia, rssib;
546170613Sbms	int weight;
547170613Sbms
548170613Sbms	/* privacy support preferred */
549170613Sbms	if ((a->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) &&
550170613Sbms	    (b->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
551170613Sbms		return 1;
552170613Sbms	if ((a->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0 &&
553170613Sbms	    (b->ni_capinfo & IEEE80211_CAPINFO_PRIVACY))
554170613Sbms		return -1;
555170613Sbms
556170613Sbms	/* compare count of previous failures */
557170613Sbms	weight = b->ni_fails - a->ni_fails;
558170613Sbms	if (abs(weight) > 1)
559170613Sbms		return weight;
560170613Sbms
561170613Sbms	rssia = ic->ic_node_getrssi(a);
562170613Sbms	rssib = ic->ic_node_getrssi(b);
563170613Sbms	if (abs(rssib - rssia) < 5) {
564170613Sbms		/* best/max rate preferred if signal level close enough XXX */
565170613Sbms		maxa = maxrate(a);
566170613Sbms		maxb = maxrate(b);
567170613Sbms		if (maxa != maxb)
568170613Sbms			return maxa - maxb;
569170613Sbms		/* XXX use freq for channel preference */
570170613Sbms		/* for now just prefer 5Ghz band to all other bands */
571170613Sbms		if (IEEE80211_IS_CHAN_5GHZ(a->ni_chan) &&
572170613Sbms		   !IEEE80211_IS_CHAN_5GHZ(b->ni_chan))
573170613Sbms			return 1;
574170613Sbms		if (!IEEE80211_IS_CHAN_5GHZ(a->ni_chan) &&
575170613Sbms		     IEEE80211_IS_CHAN_5GHZ(b->ni_chan))
576170613Sbms			return -1;
577170613Sbms	}
578170613Sbms	/* all things being equal, use signal level */
579170613Sbms	return rssia - rssib;
580170613Sbms}
581170613Sbms
582170613Sbms/*
583170613Sbms * Mark an ongoing scan stopped.
584170613Sbms */
585170613Sbmsvoid
586170613Sbmsieee80211_cancel_scan(struct ieee80211com *ic)
587170613Sbms{
588170613Sbms
589170613Sbms	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN, "%s: end %s scan\n",
590170613Sbms		__func__,
591170613Sbms		(ic->ic_flags & IEEE80211_F_ASCAN) ?  "active" : "passive");
592170613Sbms
593189346Sbms	ic->ic_flags &= ~(IEEE80211_F_SCAN | IEEE80211_F_ASCAN);
594170613Sbms}
595170613Sbms
596170613Sbms/*
597170613Sbms * Complete a scan of potential channels.
59814195Speter */
59914195Spetervoid
60014195Speterieee80211_end_scan(struct ieee80211com *ic)
60114195Speter{
60214195Speter	struct ieee80211_node_table *nt = &ic->ic_scan;
60314195Speter	struct ieee80211_node *ni, *selbs;
60414195Speter
60514195Speter	ieee80211_cancel_scan(ic);
6061541Srgrimes	ieee80211_notify_scan_done(ic);
6071541Srgrimes
6081541Srgrimes	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
6091541Srgrimes		u_int8_t maxrssi[IEEE80211_CHAN_MAX];	/* XXX off stack? */
6101541Srgrimes		int i, bestchan;
61162587Sitojun		u_int8_t rssi;
6121541Srgrimes
6131541Srgrimes		/*
6141541Srgrimes		 * The passive scan to look for existing AP's completed,
6151541Srgrimes		 * select a channel to camp on.  Identify the channels
6161541Srgrimes		 * that already have one or more AP's and try to locate
6171541Srgrimes		 * an unoccupied one.  If that fails, pick a channel that
6181541Srgrimes		 * looks to be quietest.
6191541Srgrimes		 */
6201541Srgrimes		memset(maxrssi, 0, sizeof(maxrssi));
6211541Srgrimes		IEEE80211_NODE_LOCK(nt);
6221541Srgrimes		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
6231541Srgrimes			rssi = ic->ic_node_getrssi(ni);
6241541Srgrimes			i = ieee80211_chan2ieee(ic, ni->ni_chan);
6251541Srgrimes			if (rssi > maxrssi[i])
6261541Srgrimes				maxrssi[i] = rssi;
6271541Srgrimes		}
6281541Srgrimes		IEEE80211_NODE_UNLOCK(nt);
6291541Srgrimes		/* XXX select channel more intelligently */
6301541Srgrimes		bestchan = -1;
6311541Srgrimes		for (i = 0; i < IEEE80211_CHAN_MAX; i++)
6321541Srgrimes			if (isset(ic->ic_chan_active, i)) {
6331541Srgrimes				/*
6341541Srgrimes				 * If the channel is unoccupied the max rssi
6351541Srgrimes				 * should be zero; just take it.  Otherwise
6361541Srgrimes				 * track the channel with the lowest rssi and
63762587Sitojun				 * use that when all channels appear occupied.
63862587Sitojun				 */
63962587Sitojun				if (maxrssi[i] == 0) {
64062587Sitojun					bestchan = i;
64162587Sitojun					break;
64262587Sitojun				}
64362587Sitojun				if (bestchan == -1 ||
64462587Sitojun				    maxrssi[i] < maxrssi[bestchan])
64562587Sitojun					bestchan = i;
64662587Sitojun			}
64762587Sitojun		if (bestchan != -1) {
64862587Sitojun			ieee80211_create_ibss(ic, &ic->ic_channels[bestchan]);
64962587Sitojun			return;
65062587Sitojun		}
65162587Sitojun		/* no suitable channel, should not happen */
65262587Sitojun	}
65362587Sitojun
65462587Sitojun	/*
65562587Sitojun	 * When manually sequencing the state machine; scan just once
65662587Sitojun	 * regardless of whether we have a candidate or not.  The
65762587Sitojun	 * controlling application is expected to setup state and
65862587Sitojun	 * initiate an association.
65962587Sitojun	 */
66062587Sitojun	if (ic->ic_roaming == IEEE80211_ROAMING_MANUAL)
66162587Sitojun		return;
66262587Sitojun	/*
66362587Sitojun	 * Automatic sequencing; look for a candidate and
66462587Sitojun	 * if found join the network.
66562587Sitojun	 */
666118622Shsu	/* NB: unlocked read should be ok */
667118622Shsu	if (TAILQ_FIRST(&nt->nt_node) == NULL) {
668118622Shsu		IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
669118622Shsu			"%s: no scan candidate\n", __func__);
670118622Shsu  notfound:
671118622Shsu		if (ic->ic_opmode == IEEE80211_M_IBSS &&
672118622Shsu		    (ic->ic_flags & IEEE80211_F_IBSSON) &&
673118622Shsu		    ic->ic_des_esslen != 0) {
674118622Shsu			ieee80211_create_ibss(ic, ic->ic_ibss_chan);
675118622Shsu			return;
676118622Shsu		}
677118622Shsu		/*
678118622Shsu		 * Decrement the failure counts so entries will be
679118622Shsu		 * reconsidered the next time around.  We really want
680118622Shsu		 * to do this only for sta's where we've previously
681118622Shsu		 had some success.
6821541Srgrimes		 */
6831541Srgrimes		IEEE80211_NODE_LOCK(nt);
6841541Srgrimes		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
6851541Srgrimes			if (ni->ni_fails)
6861541Srgrimes				ni->ni_fails--;
6871541Srgrimes		IEEE80211_NODE_UNLOCK(nt);
6881541Srgrimes		/*
6891541Srgrimes		 * Reset the list of channels to scan and start again.
6901541Srgrimes		 */
6911541Srgrimes		ieee80211_reset_scan(ic);
6921541Srgrimes		ic->ic_flags |= IEEE80211_F_SCAN;
693133874Srwatson		ieee80211_next_scan(ic);
694133874Srwatson		return;
695133874Srwatson	}
6967091Swollman	selbs = NULL;
6979575Speter	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN, "\t%s\n",
698133874Srwatson	    "macaddr          bssid         chan  rssi rate flag  wep  essid");
69952904Sshin	IEEE80211_NODE_LOCK(nt);
70029838Swollman	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
70133440Sguido		if (ieee80211_match_bss(ic, ni) == 0) {
70252904Sshin			if (selbs == NULL)
70355009Sshin				selbs = ni;
70452904Sshin			else if (ieee80211_node_compare(ic, ni, selbs) > 0)
70552904Sshin				selbs = ni;
7061541Srgrimes		}
70795336Smike	}
70895336Smike	if (selbs != NULL)		/* NB: grab ref while dropping lock */
70978243Speter		(void) ieee80211_ref_node(selbs);
71095336Smike	IEEE80211_NODE_UNLOCK(nt);
71178243Speter	if (selbs == NULL)
71278243Speter		goto notfound;
71392723Salfred	if (!ieee80211_sta_join(ic, selbs)) {
71492723Salfred		ieee80211_free_node(selbs);
71592723Salfred		goto notfound;
716133486Sandre	}
717199208Sattilio}
718133874Srwatson
71992723Salfred/*
720213103Sattilio * Handle 802.11 ad hoc network merge.  The
721213103Sattilio * convention, set by the Wireless Ethernet Compatibility Alliance
722150296Srwatson * (WECA), is that an 802.11 station will change its BSSID to match
7232169Spaul * the "oldest" 802.11 ad hoc network, on the same channel, that
724133874Srwatson * has the station's desired SSID.  The "oldest" 802.11 network
725133874Srwatson * sends beacons with the greatest TSF timestamp.
726189346Sbms *
727102925Ssobomax * The caller is assumed to validate TSF's before attempting a merge.
728133874Srwatson *
729133874Srwatson * Return !0 if the BSSID changed, 0 otherwise.
730133874Srwatson */
73195336Smikeint
73290868Smikeieee80211_ibss_merge(struct ieee80211_node *ni)
73395336Smike{
73495336Smike	struct ieee80211com *ic = ni->ni_ic;
73595336Smike
73695336Smike	if (ni == ic->ic_bss ||
73795336Smike	    IEEE80211_ADDR_EQ(ni->ni_bssid, ic->ic_bss->ni_bssid)) {
73891959Smike		/* unchanged, nothing to do */
73991959Smike		return 0;
74095336Smike	}
741	if (ieee80211_match_bss(ic, ni) != 0) {	/* capabilities mismatch */
742		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
743		    "%s: merge failed, capabilities mismatch\n", __func__);
744		ic->ic_stats.is_ibss_capmismatch++;
745		return 0;
746	}
747	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
748		"%s: new bssid %s: %s preamble, %s slot time%s\n", __func__,
749		ether_sprintf(ni->ni_bssid),
750		ic->ic_flags&IEEE80211_F_SHPREAMBLE ? "short" : "long",
751		ic->ic_flags&IEEE80211_F_SHSLOT ? "short" : "long",
752		ic->ic_flags&IEEE80211_F_USEPROT ? ", protection" : ""
753	);
754	return ieee80211_sta_join(ic, ieee80211_ref_node(ni));
755}
756
757/*
758 * Join the specified IBSS/BSS network.  The node is assumed to
759 * be passed in with a held reference.
760 */
761int
762ieee80211_sta_join(struct ieee80211com *ic, struct ieee80211_node *selbs)
763{
764	struct ieee80211_node *obss;
765
766	if (ic->ic_opmode == IEEE80211_M_IBSS) {
767		struct ieee80211_node_table *nt;
768		/*
769		 * Delete unusable rates; we've already checked
770		 * that the negotiated rate set is acceptable.
771		 */
772		ieee80211_fix_rate(selbs, IEEE80211_F_DODEL);
773		/*
774		 * Fillin the neighbor table; it will already
775		 * exist if we are simply switching mastership.
776		 * XXX ic_sta always setup so this is unnecessary?
777		 */
778		nt = &ic->ic_sta;
779		IEEE80211_NODE_LOCK(nt);
780		nt->nt_name = "neighbor";
781		nt->nt_inact_init = ic->ic_inact_run;
782		IEEE80211_NODE_UNLOCK(nt);
783	}
784
785	/*
786	 * Committed to selbs, setup state.
787	 */
788	obss = ic->ic_bss;
789	ic->ic_bss = selbs;		/* NB: caller assumed to bump refcnt */
790	if (obss != NULL)
791		ieee80211_free_node(obss);
792	/*
793	 * Set the erp state (mostly the slot time) to deal with
794	 * the auto-select case; this should be redundant if the
795	 * mode is locked.
796	 */
797	ic->ic_curmode = ieee80211_chan2mode(ic, selbs->ni_chan);
798	ic->ic_curchan = selbs->ni_chan;
799	ieee80211_reset_erp(ic);
800	ieee80211_wme_initparams(ic);
801
802	if (ic->ic_opmode == IEEE80211_M_STA)
803		ieee80211_new_state(ic, IEEE80211_S_AUTH, -1);
804	else
805		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
806	return 1;
807}
808
809/*
810 * Leave the specified IBSS/BSS network.  The node is assumed to
811 * be passed in with a held reference.
812 */
813void
814ieee80211_sta_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
815{
816	ic->ic_node_cleanup(ni);
817	ieee80211_notify_node_leave(ic, ni);
818}
819
820static struct ieee80211_node *
821node_alloc(struct ieee80211_node_table *nt)
822{
823	struct ieee80211_node *ni;
824
825	MALLOC(ni, struct ieee80211_node *, sizeof(struct ieee80211_node),
826		M_80211_NODE, M_NOWAIT | M_ZERO);
827	return ni;
828}
829
830/*
831 * Reclaim any resources in a node and reset any critical
832 * state.  Typically nodes are free'd immediately after,
833 * but in some cases the storage may be reused so we need
834 * to insure consistent state (should probably fix that).
835 */
836static void
837node_cleanup(struct ieee80211_node *ni)
838{
839#define	N(a)	(sizeof(a)/sizeof(a[0]))
840	struct ieee80211com *ic = ni->ni_ic;
841	int i, qlen;
842
843	/* NB: preserve ni_table */
844	if (ni->ni_flags & IEEE80211_NODE_PWR_MGT) {
845		ic->ic_ps_sta--;
846		ni->ni_flags &= ~IEEE80211_NODE_PWR_MGT;
847		IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
848		    "[%s] power save mode off, %u sta's in ps mode\n",
849		    ether_sprintf(ni->ni_macaddr), ic->ic_ps_sta);
850	}
851	/*
852	 * Clear AREF flag that marks the authorization refcnt bump
853	 * has happened.  This is probably not needed as the node
854	 * should always be removed from the table so not found but
855	 * do it just in case.
856	 */
857	ni->ni_flags &= ~IEEE80211_NODE_AREF;
858
859	/*
860	 * Drain power save queue and, if needed, clear TIM.
861	 */
862	IEEE80211_NODE_SAVEQ_DRAIN(ni, qlen);
863	if (qlen != 0 && ic->ic_set_tim != NULL)
864		ic->ic_set_tim(ni, 0);
865
866	ni->ni_associd = 0;
867	if (ni->ni_challenge != NULL) {
868		FREE(ni->ni_challenge, M_DEVBUF);
869		ni->ni_challenge = NULL;
870	}
871	/*
872	 * Preserve SSID, WPA, and WME ie's so the bss node is
873	 * reusable during a re-auth/re-assoc state transition.
874	 * If we remove these data they will not be recreated
875	 * because they come from a probe-response or beacon frame
876	 * which cannot be expected prior to the association-response.
877	 * This should not be an issue when operating in other modes
878	 * as stations leaving always go through a full state transition
879	 * which will rebuild this state.
880	 *
881	 * XXX does this leave us open to inheriting old state?
882	 */
883	for (i = 0; i < N(ni->ni_rxfrag); i++)
884		if (ni->ni_rxfrag[i] != NULL) {
885			m_freem(ni->ni_rxfrag[i]);
886			ni->ni_rxfrag[i] = NULL;
887		}
888	/*
889	 * Must be careful here to remove any key map entry w/o a LOR.
890	 */
891	ieee80211_node_delucastkey(ni);
892#undef N
893}
894
895static void
896node_free(struct ieee80211_node *ni)
897{
898	struct ieee80211com *ic = ni->ni_ic;
899
900	ic->ic_node_cleanup(ni);
901	if (ni->ni_wpa_ie != NULL)
902		FREE(ni->ni_wpa_ie, M_DEVBUF);
903	if (ni->ni_wme_ie != NULL)
904		FREE(ni->ni_wme_ie, M_DEVBUF);
905	IEEE80211_NODE_SAVEQ_DESTROY(ni);
906	FREE(ni, M_80211_NODE);
907}
908
909static u_int8_t
910node_getrssi(const struct ieee80211_node *ni)
911{
912	return ni->ni_rssi;
913}
914
915static void
916ieee80211_setup_node(struct ieee80211_node_table *nt,
917	struct ieee80211_node *ni, const u_int8_t *macaddr)
918{
919	struct ieee80211com *ic = nt->nt_ic;
920	int hash;
921
922	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
923		"%s %p<%s> in %s table\n", __func__, ni,
924		ether_sprintf(macaddr), nt->nt_name);
925
926	IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
927	hash = IEEE80211_NODE_HASH(macaddr);
928	ieee80211_node_initref(ni);		/* mark referenced */
929	ni->ni_chan = IEEE80211_CHAN_ANYC;
930	ni->ni_authmode = IEEE80211_AUTH_OPEN;
931	ni->ni_txpower = ic->ic_txpowlimit;	/* max power */
932	ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey, IEEE80211_KEYIX_NONE);
933	ni->ni_inact_reload = nt->nt_inact_init;
934	ni->ni_inact = ni->ni_inact_reload;
935	IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
936
937	IEEE80211_NODE_LOCK(nt);
938	TAILQ_INSERT_TAIL(&nt->nt_node, ni, ni_list);
939	LIST_INSERT_HEAD(&nt->nt_hash[hash], ni, ni_hash);
940	ni->ni_table = nt;
941	ni->ni_ic = ic;
942	IEEE80211_NODE_UNLOCK(nt);
943}
944
945struct ieee80211_node *
946ieee80211_alloc_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
947{
948	struct ieee80211com *ic = nt->nt_ic;
949	struct ieee80211_node *ni;
950
951	ni = ic->ic_node_alloc(nt);
952	if (ni != NULL)
953		ieee80211_setup_node(nt, ni, macaddr);
954	else
955		ic->ic_stats.is_rx_nodealloc++;
956	return ni;
957}
958
959/*
960 * Craft a temporary node suitable for sending a management frame
961 * to the specified station.  We craft only as much state as we
962 * need to do the work since the node will be immediately reclaimed
963 * once the send completes.
964 */
965struct ieee80211_node *
966ieee80211_tmp_node(struct ieee80211com *ic, const u_int8_t *macaddr)
967{
968	struct ieee80211_node *ni;
969
970	ni = ic->ic_node_alloc(&ic->ic_sta);
971	if (ni != NULL) {
972		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
973			"%s %p<%s>\n", __func__, ni, ether_sprintf(macaddr));
974
975		IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
976		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
977		ieee80211_node_initref(ni);		/* mark referenced */
978		ni->ni_txpower = ic->ic_bss->ni_txpower;
979		/* NB: required by ieee80211_fix_rate */
980		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
981		ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey,
982			IEEE80211_KEYIX_NONE);
983		/* XXX optimize away */
984		IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
985
986		ni->ni_table = NULL;		/* NB: pedantic */
987		ni->ni_ic = ic;
988	} else {
989		/* XXX msg */
990		ic->ic_stats.is_rx_nodealloc++;
991	}
992	return ni;
993}
994
995struct ieee80211_node *
996ieee80211_dup_bss(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
997{
998	struct ieee80211com *ic = nt->nt_ic;
999	struct ieee80211_node *ni;
1000
1001	ni = ic->ic_node_alloc(nt);
1002	if (ni != NULL) {
1003		ieee80211_setup_node(nt, ni, macaddr);
1004		/*
1005		 * Inherit from ic_bss.
1006		 */
1007		ni->ni_authmode = ic->ic_bss->ni_authmode;
1008		ni->ni_txpower = ic->ic_bss->ni_txpower;
1009		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
1010		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
1011		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
1012		ni->ni_rsn = ic->ic_bss->ni_rsn;
1013	} else
1014		ic->ic_stats.is_rx_nodealloc++;
1015	return ni;
1016}
1017
1018static struct ieee80211_node *
1019#ifdef IEEE80211_DEBUG_REFCNT
1020_ieee80211_find_node_debug(struct ieee80211_node_table *nt,
1021	const u_int8_t *macaddr, const char *func, int line)
1022#else
1023_ieee80211_find_node(struct ieee80211_node_table *nt,
1024	const u_int8_t *macaddr)
1025#endif
1026{
1027	struct ieee80211_node *ni;
1028	int hash;
1029
1030	IEEE80211_NODE_LOCK_ASSERT(nt);
1031
1032	hash = IEEE80211_NODE_HASH(macaddr);
1033	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1034		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
1035			ieee80211_ref_node(ni);	/* mark referenced */
1036#ifdef IEEE80211_DEBUG_REFCNT
1037			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1038			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1039			    func, line,
1040			    ni, ether_sprintf(ni->ni_macaddr),
1041			    ieee80211_node_refcnt(ni));
1042#endif
1043			return ni;
1044		}
1045	}
1046	return NULL;
1047}
1048#ifdef IEEE80211_DEBUG_REFCNT
1049#define	_ieee80211_find_node(nt, mac) \
1050	_ieee80211_find_node_debug(nt, mac, func, line)
1051#endif
1052
1053struct ieee80211_node *
1054#ifdef IEEE80211_DEBUG_REFCNT
1055ieee80211_find_node_debug(struct ieee80211_node_table *nt,
1056	const u_int8_t *macaddr, const char *func, int line)
1057#else
1058ieee80211_find_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
1059#endif
1060{
1061	struct ieee80211_node *ni;
1062
1063	IEEE80211_NODE_LOCK(nt);
1064	ni = _ieee80211_find_node(nt, macaddr);
1065	IEEE80211_NODE_UNLOCK(nt);
1066	return ni;
1067}
1068
1069/*
1070 * Fake up a node; this handles node discovery in adhoc mode.
1071 * Note that for the driver's benefit we we treat this like
1072 * an association so the driver has an opportunity to setup
1073 * it's private state.
1074 */
1075struct ieee80211_node *
1076ieee80211_fakeup_adhoc_node(struct ieee80211_node_table *nt,
1077	const u_int8_t macaddr[IEEE80211_ADDR_LEN])
1078{
1079	struct ieee80211com *ic = nt->nt_ic;
1080	struct ieee80211_node *ni;
1081
1082	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1083	    "%s: mac<%s>\n", __func__, ether_sprintf(macaddr));
1084	ni = ieee80211_dup_bss(nt, macaddr);
1085	if (ni != NULL) {
1086		/* XXX no rate negotiation; just dup */
1087		ni->ni_rates = ic->ic_bss->ni_rates;
1088		if (ic->ic_newassoc != NULL)
1089			ic->ic_newassoc(ni, 1);
1090		/* XXX not right for 802.1x/WPA */
1091		ieee80211_node_authorize(ni);
1092	}
1093	return ni;
1094}
1095
1096#ifdef IEEE80211_DEBUG
1097static void
1098dump_probe_beacon(u_int8_t subtype, int isnew,
1099	const u_int8_t mac[IEEE80211_ADDR_LEN],
1100	const struct ieee80211_scanparams *sp)
1101{
1102
1103	printf("[%s] %s%s on chan %u (bss chan %u) ",
1104	    ether_sprintf(mac), isnew ? "new " : "",
1105	    ieee80211_mgt_subtype_name[subtype >> IEEE80211_FC0_SUBTYPE_SHIFT],
1106	    sp->chan, sp->bchan);
1107	ieee80211_print_essid(sp->ssid + 2, sp->ssid[1]);
1108	printf("\n");
1109
1110	if (isnew) {
1111		printf("[%s] caps 0x%x bintval %u erp 0x%x",
1112			ether_sprintf(mac), sp->capinfo, sp->bintval, sp->erp);
1113		if (sp->country != NULL) {
1114#ifdef __FreeBSD__
1115			printf(" country info %*D",
1116				sp->country[1], sp->country+2, " ");
1117#else
1118			int i;
1119			printf(" country info");
1120			for (i = 0; i < sp->country[1]; i++)
1121				printf(" %02x", sp->country[i+2]);
1122#endif
1123		}
1124		printf("\n");
1125	}
1126}
1127#endif /* IEEE80211_DEBUG */
1128
1129static void
1130saveie(u_int8_t **iep, const u_int8_t *ie)
1131{
1132
1133	if (ie == NULL)
1134		*iep = NULL;
1135	else
1136		ieee80211_saveie(iep, ie);
1137}
1138
1139/*
1140 * Process a beacon or probe response frame.
1141 */
1142void
1143ieee80211_add_scan(struct ieee80211com *ic,
1144	const struct ieee80211_scanparams *sp,
1145	const struct ieee80211_frame *wh,
1146	int subtype, int rssi, int rstamp)
1147{
1148#define	ISPROBE(_st)	((_st) == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1149	struct ieee80211_node_table *nt = &ic->ic_scan;
1150	struct ieee80211_node *ni;
1151	int newnode = 0;
1152
1153	ni = ieee80211_find_node(nt, wh->i_addr2);
1154	if (ni == NULL) {
1155		/*
1156		 * Create a new entry.
1157		 */
1158		ni = ic->ic_node_alloc(nt);
1159		if (ni == NULL) {
1160			ic->ic_stats.is_rx_nodealloc++;
1161			return;
1162		}
1163		ieee80211_setup_node(nt, ni, wh->i_addr2);
1164		/*
1165		 * XXX inherit from ic_bss.
1166		 */
1167		ni->ni_authmode = ic->ic_bss->ni_authmode;
1168		ni->ni_txpower = ic->ic_bss->ni_txpower;
1169		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
1170		ieee80211_set_chan(ic, ni, ic->ic_curchan);
1171		ni->ni_rsn = ic->ic_bss->ni_rsn;
1172		newnode = 1;
1173	}
1174#ifdef IEEE80211_DEBUG
1175	if (ieee80211_msg_scan(ic) && (ic->ic_flags & IEEE80211_F_SCAN))
1176		dump_probe_beacon(subtype, newnode, wh->i_addr2, sp);
1177#endif
1178	/* XXX ap beaconing multiple ssid w/ same bssid */
1179	if (sp->ssid[1] != 0 &&
1180	    (ISPROBE(subtype) || ni->ni_esslen == 0)) {
1181		ni->ni_esslen = sp->ssid[1];
1182		memset(ni->ni_essid, 0, sizeof(ni->ni_essid));
1183		memcpy(ni->ni_essid, sp->ssid + 2, sp->ssid[1]);
1184	}
1185	ni->ni_scangen = ic->ic_scan.nt_scangen;
1186	IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
1187	ni->ni_rssi = rssi;
1188	ni->ni_rstamp = rstamp;
1189	memcpy(ni->ni_tstamp.data, sp->tstamp, sizeof(ni->ni_tstamp));
1190	ni->ni_intval = sp->bintval;
1191	ni->ni_capinfo = sp->capinfo;
1192	ni->ni_chan = &ic->ic_channels[sp->chan];
1193	ni->ni_fhdwell = sp->fhdwell;
1194	ni->ni_fhindex = sp->fhindex;
1195	ni->ni_erp = sp->erp;
1196	if (sp->tim != NULL) {
1197		struct ieee80211_tim_ie *ie =
1198		    (struct ieee80211_tim_ie *) sp->tim;
1199
1200		ni->ni_dtim_count = ie->tim_count;
1201		ni->ni_dtim_period = ie->tim_period;
1202	}
1203	/*
1204	 * Record the byte offset from the mac header to
1205	 * the start of the TIM information element for
1206	 * use by hardware and/or to speedup software
1207	 * processing of beacon frames.
1208	 */
1209	ni->ni_timoff = sp->timoff;
1210	/*
1211	 * Record optional information elements that might be
1212	 * used by applications or drivers.
1213	 */
1214	saveie(&ni->ni_wme_ie, sp->wme);
1215	saveie(&ni->ni_wpa_ie, sp->wpa);
1216
1217	/* NB: must be after ni_chan is setup */
1218	ieee80211_setup_rates(ni, sp->rates, sp->xrates, IEEE80211_F_DOSORT);
1219
1220	if (!newnode)
1221		ieee80211_free_node(ni);
1222#undef ISPROBE
1223}
1224
1225void
1226ieee80211_init_neighbor(struct ieee80211_node *ni,
1227	const struct ieee80211_frame *wh,
1228	const struct ieee80211_scanparams *sp)
1229{
1230
1231	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1232	    "%s: %p<%s>\n", __func__, ni, ether_sprintf(ni->ni_macaddr));
1233	ni->ni_esslen = sp->ssid[1];
1234	memcpy(ni->ni_essid, sp->ssid + 2, sp->ssid[1]);
1235	IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
1236	memcpy(ni->ni_tstamp.data, sp->tstamp, sizeof(ni->ni_tstamp));
1237	ni->ni_intval = sp->bintval;
1238	ni->ni_capinfo = sp->capinfo;
1239	ni->ni_chan = ni->ni_ic->ic_curchan;
1240	ni->ni_fhdwell = sp->fhdwell;
1241	ni->ni_fhindex = sp->fhindex;
1242	ni->ni_erp = sp->erp;
1243	ni->ni_timoff = sp->timoff;
1244	if (sp->wme != NULL)
1245		ieee80211_saveie(&ni->ni_wme_ie, sp->wme);
1246	if (sp->wpa != NULL)
1247		ieee80211_saveie(&ni->ni_wpa_ie, sp->wpa);
1248
1249	/* NB: must be after ni_chan is setup */
1250	ieee80211_setup_rates(ni, sp->rates, sp->xrates, IEEE80211_F_DOSORT);
1251}
1252
1253/*
1254 * Do node discovery in adhoc mode on receipt of a beacon
1255 * or probe response frame.  Note that for the driver's
1256 * benefit we we treat this like an association so the
1257 * driver has an opportunity to setup it's private state.
1258 */
1259struct ieee80211_node *
1260ieee80211_add_neighbor(struct ieee80211com *ic,
1261	const struct ieee80211_frame *wh,
1262	const struct ieee80211_scanparams *sp)
1263{
1264	struct ieee80211_node *ni;
1265
1266	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1267	    "%s: mac<%s>\n", __func__, ether_sprintf(wh->i_addr2));
1268	ni = ieee80211_dup_bss(&ic->ic_sta, wh->i_addr2);/* XXX alloc_node? */
1269	if (ni != NULL) {
1270		ieee80211_init_neighbor(ni, wh, sp);
1271		if (ic->ic_newassoc != NULL)
1272			ic->ic_newassoc(ni, 1);
1273		/* XXX not right for 802.1x/WPA */
1274		ieee80211_node_authorize(ni);
1275	}
1276	return ni;
1277}
1278
1279#define	IS_CTL(wh) \
1280	((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_CTL)
1281#define	IS_PSPOLL(wh) \
1282	((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_PS_POLL)
1283/*
1284 * Locate the node for sender, track state, and then pass the
1285 * (referenced) node up to the 802.11 layer for its use.  We
1286 * are required to pass some node so we fall back to ic_bss
1287 * when this frame is from an unknown sender.  The 802.11 layer
1288 * knows this means the sender wasn't in the node table and
1289 * acts accordingly.
1290 */
1291struct ieee80211_node *
1292#ifdef IEEE80211_DEBUG_REFCNT
1293ieee80211_find_rxnode_debug(struct ieee80211com *ic,
1294	const struct ieee80211_frame_min *wh, const char *func, int line)
1295#else
1296ieee80211_find_rxnode(struct ieee80211com *ic,
1297	const struct ieee80211_frame_min *wh)
1298#endif
1299{
1300	struct ieee80211_node_table *nt;
1301	struct ieee80211_node *ni;
1302
1303	/* XXX may want scanned nodes in the neighbor table for adhoc */
1304	if (ic->ic_opmode == IEEE80211_M_STA ||
1305	    ic->ic_opmode == IEEE80211_M_MONITOR ||
1306	    (ic->ic_flags & IEEE80211_F_SCAN))
1307		nt = &ic->ic_scan;
1308	else
1309		nt = &ic->ic_sta;
1310	/* XXX check ic_bss first in station mode */
1311	/* XXX 4-address frames? */
1312	IEEE80211_NODE_LOCK(nt);
1313	if (IS_CTL(wh) && !IS_PSPOLL(wh) /*&& !IS_RTS(ah)*/)
1314		ni = _ieee80211_find_node(nt, wh->i_addr1);
1315	else
1316		ni = _ieee80211_find_node(nt, wh->i_addr2);
1317	if (ni == NULL)
1318		ni = ieee80211_ref_node(ic->ic_bss);
1319	IEEE80211_NODE_UNLOCK(nt);
1320
1321	return ni;
1322}
1323
1324/*
1325 * Like ieee80211_find_rxnode but use the supplied h/w
1326 * key index as a hint to locate the node in the key
1327 * mapping table.  If an entry is present at the key
1328 * index we return it; otherwise do a normal lookup and
1329 * update the mapping table if the station has a unicast
1330 * key assigned to it.
1331 */
1332struct ieee80211_node *
1333#ifdef IEEE80211_DEBUG_REFCNT
1334ieee80211_find_rxnode_withkey_debug(struct ieee80211com *ic,
1335	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix,
1336	const char *func, int line)
1337#else
1338ieee80211_find_rxnode_withkey(struct ieee80211com *ic,
1339	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix)
1340#endif
1341{
1342	struct ieee80211_node_table *nt;
1343	struct ieee80211_node *ni;
1344
1345	if (ic->ic_opmode == IEEE80211_M_STA ||
1346	    ic->ic_opmode == IEEE80211_M_MONITOR ||
1347	    (ic->ic_flags & IEEE80211_F_SCAN))
1348		nt = &ic->ic_scan;
1349	else
1350		nt = &ic->ic_sta;
1351	IEEE80211_NODE_LOCK(nt);
1352	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax)
1353		ni = nt->nt_keyixmap[keyix];
1354	else
1355		ni = NULL;
1356	if (ni == NULL) {
1357		if (IS_CTL(wh) && !IS_PSPOLL(wh) /*&& !IS_RTS(ah)*/)
1358			ni = _ieee80211_find_node(nt, wh->i_addr1);
1359		else
1360			ni = _ieee80211_find_node(nt, wh->i_addr2);
1361		if (ni == NULL)
1362			ni = ieee80211_ref_node(ic->ic_bss);
1363		if (nt->nt_keyixmap != NULL) {
1364			/*
1365			 * If the station has a unicast key cache slot
1366			 * assigned update the key->node mapping table.
1367			 */
1368			keyix = ni->ni_ucastkey.wk_rxkeyix;
1369			/* XXX can keyixmap[keyix] != NULL? */
1370			if (keyix < nt->nt_keyixmax &&
1371			    nt->nt_keyixmap[keyix] == NULL) {
1372				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1373				    "%s: add key map entry %p<%s> refcnt %d\n",
1374				    __func__, ni, ether_sprintf(ni->ni_macaddr),
1375				    ieee80211_node_refcnt(ni)+1);
1376				nt->nt_keyixmap[keyix] = ieee80211_ref_node(ni);
1377			}
1378		}
1379	} else {
1380		ieee80211_ref_node(ni);
1381	}
1382	IEEE80211_NODE_UNLOCK(nt);
1383
1384	return ni;
1385}
1386#undef IS_PSPOLL
1387#undef IS_CTL
1388
1389/*
1390 * Return a reference to the appropriate node for sending
1391 * a data frame.  This handles node discovery in adhoc networks.
1392 */
1393struct ieee80211_node *
1394#ifdef IEEE80211_DEBUG_REFCNT
1395ieee80211_find_txnode_debug(struct ieee80211com *ic, const u_int8_t *macaddr,
1396	const char *func, int line)
1397#else
1398ieee80211_find_txnode(struct ieee80211com *ic, const u_int8_t *macaddr)
1399#endif
1400{
1401	struct ieee80211_node_table *nt = &ic->ic_sta;
1402	struct ieee80211_node *ni;
1403
1404	/*
1405	 * The destination address should be in the node table
1406	 * unless this is a multicast/broadcast frame.  We can
1407	 * also optimize station mode operation, all frames go
1408	 * to the bss node.
1409	 */
1410	/* XXX can't hold lock across dup_bss 'cuz of recursive locking */
1411	IEEE80211_NODE_LOCK(nt);
1412	if (ic->ic_opmode == IEEE80211_M_STA || IEEE80211_IS_MULTICAST(macaddr))
1413		ni = ieee80211_ref_node(ic->ic_bss);
1414	else
1415		ni = _ieee80211_find_node(nt, macaddr);
1416	IEEE80211_NODE_UNLOCK(nt);
1417
1418	if (ni == NULL) {
1419		if (ic->ic_opmode == IEEE80211_M_IBSS ||
1420		    ic->ic_opmode == IEEE80211_M_AHDEMO) {
1421			/*
1422			 * In adhoc mode cons up a node for the destination.
1423			 * Note that we need an additional reference for the
1424			 * caller to be consistent with _ieee80211_find_node.
1425			 */
1426			ni = ieee80211_fakeup_adhoc_node(nt, macaddr);
1427			if (ni != NULL)
1428				(void) ieee80211_ref_node(ni);
1429		} else {
1430			IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
1431				"[%s] no node, discard frame (%s)\n",
1432				ether_sprintf(macaddr), __func__);
1433			ic->ic_stats.is_tx_nonode++;
1434		}
1435	}
1436	return ni;
1437}
1438
1439/*
1440 * Like find but search based on the channel too.
1441 */
1442struct ieee80211_node *
1443#ifdef IEEE80211_DEBUG_REFCNT
1444ieee80211_find_node_with_channel_debug(struct ieee80211_node_table *nt,
1445	const u_int8_t *macaddr, struct ieee80211_channel *chan,
1446	const char *func, int line)
1447#else
1448ieee80211_find_node_with_channel(struct ieee80211_node_table *nt,
1449	const u_int8_t *macaddr, struct ieee80211_channel *chan)
1450#endif
1451{
1452	struct ieee80211_node *ni;
1453	int hash;
1454
1455	hash = IEEE80211_NODE_HASH(macaddr);
1456	IEEE80211_NODE_LOCK(nt);
1457	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1458		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1459		    ni->ni_chan == chan) {
1460			ieee80211_ref_node(ni);		/* mark referenced */
1461			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1462#ifdef IEEE80211_DEBUG_REFCNT
1463			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1464			    func, line,
1465#else
1466			    "%s %p<%s> refcnt %d\n", __func__,
1467#endif
1468			    ni, ether_sprintf(ni->ni_macaddr),
1469			    ieee80211_node_refcnt(ni));
1470			break;
1471		}
1472	}
1473	IEEE80211_NODE_UNLOCK(nt);
1474	return ni;
1475}
1476
1477/*
1478 * Like find but search based on the ssid too.
1479 */
1480struct ieee80211_node *
1481#ifdef IEEE80211_DEBUG_REFCNT
1482ieee80211_find_node_with_ssid_debug(struct ieee80211_node_table *nt,
1483	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid,
1484	const char *func, int line)
1485#else
1486ieee80211_find_node_with_ssid(struct ieee80211_node_table *nt,
1487	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid)
1488#endif
1489{
1490#define	MATCH_SSID(ni, ssid, ssidlen) \
1491	(ni->ni_esslen == ssidlen && memcmp(ni->ni_essid, ssid, ssidlen) == 0)
1492	static const u_int8_t zeromac[IEEE80211_ADDR_LEN];
1493	struct ieee80211com *ic = nt->nt_ic;
1494	struct ieee80211_node *ni;
1495	int hash;
1496
1497	IEEE80211_NODE_LOCK(nt);
1498	/*
1499	 * A mac address that is all zero means match only the ssid;
1500	 * otherwise we must match both.
1501	 */
1502	if (IEEE80211_ADDR_EQ(macaddr, zeromac)) {
1503		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1504			if (MATCH_SSID(ni, ssid, ssidlen))
1505				break;
1506		}
1507	} else {
1508		hash = IEEE80211_NODE_HASH(macaddr);
1509		LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1510			if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1511			    MATCH_SSID(ni, ssid, ssidlen))
1512				break;
1513		}
1514	}
1515	if (ni != NULL) {
1516		ieee80211_ref_node(ni);	/* mark referenced */
1517		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1518#ifdef IEEE80211_DEBUG_REFCNT
1519		    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1520		    func, line,
1521#else
1522		    "%s %p<%s> refcnt %d\n", __func__,
1523#endif
1524		     ni, ether_sprintf(ni->ni_macaddr),
1525		     ieee80211_node_refcnt(ni));
1526	}
1527	IEEE80211_NODE_UNLOCK(nt);
1528	return ni;
1529#undef MATCH_SSID
1530}
1531
1532static void
1533_ieee80211_free_node(struct ieee80211_node *ni)
1534{
1535	struct ieee80211com *ic = ni->ni_ic;
1536	struct ieee80211_node_table *nt = ni->ni_table;
1537
1538	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1539		"%s %p<%s> in %s table\n", __func__, ni,
1540		ether_sprintf(ni->ni_macaddr),
1541		nt != NULL ? nt->nt_name : "<gone>");
1542
1543	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1544	if (nt != NULL) {
1545		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1546		LIST_REMOVE(ni, ni_hash);
1547	}
1548	ic->ic_node_free(ni);
1549}
1550
1551void
1552#ifdef IEEE80211_DEBUG_REFCNT
1553ieee80211_free_node_debug(struct ieee80211_node *ni, const char *func, int line)
1554#else
1555ieee80211_free_node(struct ieee80211_node *ni)
1556#endif
1557{
1558	struct ieee80211_node_table *nt = ni->ni_table;
1559
1560#ifdef IEEE80211_DEBUG_REFCNT
1561	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1562		"%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line, ni,
1563		 ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)-1);
1564#endif
1565	if (nt != NULL) {
1566		IEEE80211_NODE_LOCK(nt);
1567		if (ieee80211_node_dectestref(ni)) {
1568			/*
1569			 * Last reference, reclaim state.
1570			 */
1571			_ieee80211_free_node(ni);
1572		} else if (ieee80211_node_refcnt(ni) == 1 &&
1573		    nt->nt_keyixmap != NULL) {
1574			ieee80211_keyix keyix;
1575			/*
1576			 * Check for a last reference in the key mapping table.
1577			 */
1578			keyix = ni->ni_ucastkey.wk_rxkeyix;
1579			if (keyix < nt->nt_keyixmax &&
1580			    nt->nt_keyixmap[keyix] == ni) {
1581				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1582				    "%s: %p<%s> clear key map entry", __func__,
1583				    ni, ether_sprintf(ni->ni_macaddr));
1584				nt->nt_keyixmap[keyix] = NULL;
1585				ieee80211_node_decref(ni); /* XXX needed? */
1586				_ieee80211_free_node(ni);
1587			}
1588		}
1589		IEEE80211_NODE_UNLOCK(nt);
1590	} else {
1591		if (ieee80211_node_dectestref(ni))
1592			_ieee80211_free_node(ni);
1593	}
1594}
1595
1596/*
1597 * Reclaim a unicast key and clear any key cache state.
1598 */
1599int
1600ieee80211_node_delucastkey(struct ieee80211_node *ni)
1601{
1602	struct ieee80211com *ic = ni->ni_ic;
1603	struct ieee80211_node_table *nt = &ic->ic_sta;
1604	struct ieee80211_node *nikey;
1605	ieee80211_keyix keyix;
1606	int isowned, status;
1607
1608	/*
1609	 * NB: We must beware of LOR here; deleting the key
1610	 * can cause the crypto layer to block traffic updates
1611	 * which can generate a LOR against the node table lock;
1612	 * grab it here and stash the key index for our use below.
1613	 *
1614	 * Must also beware of recursion on the node table lock.
1615	 * When called from node_cleanup we may already have
1616	 * the node table lock held.  Unfortunately there's no
1617	 * way to separate out this path so we must do this
1618	 * conditionally.
1619	 */
1620	isowned = IEEE80211_NODE_IS_LOCKED(nt);
1621	if (!isowned)
1622		IEEE80211_NODE_LOCK(nt);
1623	keyix = ni->ni_ucastkey.wk_rxkeyix;
1624	status = ieee80211_crypto_delkey(ic, &ni->ni_ucastkey);
1625	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax) {
1626		nikey = nt->nt_keyixmap[keyix];
1627		nt->nt_keyixmap[keyix] = NULL;;
1628	} else
1629		nikey = NULL;
1630	if (!isowned)
1631		IEEE80211_NODE_UNLOCK(&ic->ic_sta);
1632
1633	if (nikey != NULL) {
1634		KASSERT(nikey == ni,
1635			("key map out of sync, ni %p nikey %p", ni, nikey));
1636		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1637			"%s: delete key map entry %p<%s> refcnt %d\n",
1638			__func__, ni, ether_sprintf(ni->ni_macaddr),
1639			ieee80211_node_refcnt(ni)-1);
1640		ieee80211_free_node(ni);
1641	}
1642	return status;
1643}
1644
1645/*
1646 * Reclaim a node.  If this is the last reference count then
1647 * do the normal free work.  Otherwise remove it from the node
1648 * table and mark it gone by clearing the back-reference.
1649 */
1650static void
1651node_reclaim(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1652{
1653	ieee80211_keyix keyix;
1654
1655	IEEE80211_NODE_LOCK_ASSERT(nt);
1656
1657	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1658		"%s: remove %p<%s> from %s table, refcnt %d\n",
1659		__func__, ni, ether_sprintf(ni->ni_macaddr),
1660		nt->nt_name, ieee80211_node_refcnt(ni)-1);
1661	/*
1662	 * Clear any entry in the unicast key mapping table.
1663	 * We need to do it here so rx lookups don't find it
1664	 * in the mapping table even if it's not in the hash
1665	 * table.  We cannot depend on the mapping table entry
1666	 * being cleared because the node may not be free'd.
1667	 */
1668	keyix = ni->ni_ucastkey.wk_rxkeyix;
1669	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax &&
1670	    nt->nt_keyixmap[keyix] == ni) {
1671		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1672			"%s: %p<%s> clear key map entry\n",
1673			__func__, ni, ether_sprintf(ni->ni_macaddr));
1674		nt->nt_keyixmap[keyix] = NULL;
1675		ieee80211_node_decref(ni);	/* NB: don't need free */
1676	}
1677	if (!ieee80211_node_dectestref(ni)) {
1678		/*
1679		 * Other references are present, just remove the
1680		 * node from the table so it cannot be found.  When
1681		 * the references are dropped storage will be
1682		 * reclaimed.
1683		 */
1684		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1685		LIST_REMOVE(ni, ni_hash);
1686		ni->ni_table = NULL;		/* clear reference */
1687	} else
1688		_ieee80211_free_node(ni);
1689}
1690
1691static void
1692ieee80211_free_allnodes_locked(struct ieee80211_node_table *nt)
1693{
1694	struct ieee80211com *ic = nt->nt_ic;
1695	struct ieee80211_node *ni;
1696
1697	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1698		"%s: free all nodes in %s table\n", __func__, nt->nt_name);
1699
1700	while ((ni = TAILQ_FIRST(&nt->nt_node)) != NULL) {
1701		if (ni->ni_associd != 0) {
1702			if (ic->ic_auth->ia_node_leave != NULL)
1703				ic->ic_auth->ia_node_leave(ic, ni);
1704			IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1705		}
1706		node_reclaim(nt, ni);
1707	}
1708	ieee80211_reset_erp(ic);
1709}
1710
1711static void
1712ieee80211_free_allnodes(struct ieee80211_node_table *nt)
1713{
1714
1715	IEEE80211_NODE_LOCK(nt);
1716	ieee80211_free_allnodes_locked(nt);
1717	IEEE80211_NODE_UNLOCK(nt);
1718}
1719
1720/*
1721 * Timeout entries in the scan cache.
1722 */
1723static void
1724ieee80211_timeout_scan_candidates(struct ieee80211_node_table *nt)
1725{
1726	struct ieee80211com *ic = nt->nt_ic;
1727	struct ieee80211_node *ni, *tni;
1728
1729	IEEE80211_NODE_LOCK(nt);
1730	ni = ic->ic_bss;
1731	/* XXX belongs elsewhere */
1732	if (ni->ni_rxfrag[0] != NULL && ticks > ni->ni_rxfragstamp + hz) {
1733		m_freem(ni->ni_rxfrag[0]);
1734		ni->ni_rxfrag[0] = NULL;
1735	}
1736	TAILQ_FOREACH_SAFE(ni, &nt->nt_node, ni_list, tni) {
1737		if (ni->ni_inact && --ni->ni_inact == 0) {
1738			IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1739			    "[%s] scan candidate purged from cache "
1740			    "(refcnt %u)\n", ether_sprintf(ni->ni_macaddr),
1741			    ieee80211_node_refcnt(ni));
1742			node_reclaim(nt, ni);
1743		}
1744	}
1745	IEEE80211_NODE_UNLOCK(nt);
1746
1747	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
1748}
1749
1750/*
1751 * Timeout inactive stations and do related housekeeping.
1752 * Note that we cannot hold the node lock while sending a
1753 * frame as this would lead to a LOR.  Instead we use a
1754 * generation number to mark nodes that we've scanned and
1755 * drop the lock and restart a scan if we have to time out
1756 * a node.  Since we are single-threaded by virtue of
1757 * controlling the inactivity timer we can be sure this will
1758 * process each node only once.
1759 */
1760static void
1761ieee80211_timeout_stations(struct ieee80211_node_table *nt)
1762{
1763	struct ieee80211com *ic = nt->nt_ic;
1764	struct ieee80211_node *ni;
1765	u_int gen;
1766	int isadhoc;
1767
1768	isadhoc = (ic->ic_opmode == IEEE80211_M_IBSS ||
1769		   ic->ic_opmode == IEEE80211_M_AHDEMO);
1770	IEEE80211_SCAN_LOCK(nt);
1771	gen = nt->nt_scangen++;
1772	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1773		"%s: %s scangen %u\n", __func__, nt->nt_name, gen);
1774restart:
1775	IEEE80211_NODE_LOCK(nt);
1776	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1777		if (ni->ni_scangen == gen)	/* previously handled */
1778			continue;
1779		ni->ni_scangen = gen;
1780		/*
1781		 * Ignore entries for which have yet to receive an
1782		 * authentication frame.  These are transient and
1783		 * will be reclaimed when the last reference to them
1784		 * goes away (when frame xmits complete).
1785		 */
1786		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
1787		    (ni->ni_flags & IEEE80211_NODE_AREF) == 0)
1788			continue;
1789		/*
1790		 * Free fragment if not needed anymore
1791		 * (last fragment older than 1s).
1792		 * XXX doesn't belong here
1793		 */
1794		if (ni->ni_rxfrag[0] != NULL &&
1795		    ticks > ni->ni_rxfragstamp + hz) {
1796			m_freem(ni->ni_rxfrag[0]);
1797			ni->ni_rxfrag[0] = NULL;
1798		}
1799		/*
1800		 * Special case ourself; we may be idle for extended periods
1801		 * of time and regardless reclaiming our state is wrong.
1802		 */
1803		if (ni == ic->ic_bss)
1804			continue;
1805		ni->ni_inact--;
1806		if (ni->ni_associd != 0 || isadhoc) {
1807			/*
1808			 * Age frames on the power save queue. The
1809			 * aging interval is 4 times the listen
1810			 * interval specified by the station.  This
1811			 * number is factored into the age calculations
1812			 * when the frame is placed on the queue.  We
1813			 * store ages as time differences we can check
1814			 * and/or adjust only the head of the list.
1815			 */
1816			if (IEEE80211_NODE_SAVEQ_QLEN(ni) != 0) {
1817				struct mbuf *m;
1818				int discard = 0;
1819
1820				IEEE80211_NODE_SAVEQ_LOCK(ni);
1821				while (IF_POLL(&ni->ni_savedq, m) != NULL &&
1822				     M_AGE_GET(m) < IEEE80211_INACT_WAIT) {
1823IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER, "[%s] discard frame, age %u\n", ether_sprintf(ni->ni_macaddr), M_AGE_GET(m));/*XXX*/
1824					_IEEE80211_NODE_SAVEQ_DEQUEUE_HEAD(ni, m);
1825					m_freem(m);
1826					discard++;
1827				}
1828				if (m != NULL)
1829					M_AGE_SUB(m, IEEE80211_INACT_WAIT);
1830				IEEE80211_NODE_SAVEQ_UNLOCK(ni);
1831
1832				if (discard != 0) {
1833					IEEE80211_DPRINTF(ic,
1834					    IEEE80211_MSG_POWER,
1835					    "[%s] discard %u frames for age\n",
1836					    ether_sprintf(ni->ni_macaddr),
1837					    discard);
1838					IEEE80211_NODE_STAT_ADD(ni,
1839						ps_discard, discard);
1840					if (IEEE80211_NODE_SAVEQ_QLEN(ni) == 0)
1841						ic->ic_set_tim(ni, 0);
1842				}
1843			}
1844			/*
1845			 * Probe the station before time it out.  We
1846			 * send a null data frame which may not be
1847			 * universally supported by drivers (need it
1848			 * for ps-poll support so it should be...).
1849			 */
1850			if (0 < ni->ni_inact &&
1851			    ni->ni_inact <= ic->ic_inact_probe) {
1852				IEEE80211_NOTE(ic,
1853				    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE,
1854				    ni, "%s",
1855				    "probe station due to inactivity");
1856				/*
1857				 * Grab a reference before unlocking the table
1858				 * so the node cannot be reclaimed before we
1859				 * send the frame. ieee80211_send_nulldata
1860				 * understands we've done this and reclaims the
1861				 * ref for us as needed.
1862				 */
1863				ieee80211_ref_node(ni);
1864				IEEE80211_NODE_UNLOCK(nt);
1865				ieee80211_send_nulldata(ni);
1866				/* XXX stat? */
1867				goto restart;
1868			}
1869		}
1870		if (ni->ni_inact <= 0) {
1871			IEEE80211_NOTE(ic,
1872			    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE, ni,
1873			    "station timed out due to inactivity "
1874			    "(refcnt %u)", ieee80211_node_refcnt(ni));
1875			/*
1876			 * Send a deauthenticate frame and drop the station.
1877			 * This is somewhat complicated due to reference counts
1878			 * and locking.  At this point a station will typically
1879			 * have a reference count of 1.  ieee80211_node_leave
1880			 * will do a "free" of the node which will drop the
1881			 * reference count.  But in the meantime a reference
1882			 * wil be held by the deauth frame.  The actual reclaim
1883			 * of the node will happen either after the tx is
1884			 * completed or by ieee80211_node_leave.
1885			 *
1886			 * Separately we must drop the node lock before sending
1887			 * in case the driver takes a lock, as this will result
1888			 * in  LOR between the node lock and the driver lock.
1889			 */
1890			IEEE80211_NODE_UNLOCK(nt);
1891			if (ni->ni_associd != 0) {
1892				IEEE80211_SEND_MGMT(ic, ni,
1893				    IEEE80211_FC0_SUBTYPE_DEAUTH,
1894				    IEEE80211_REASON_AUTH_EXPIRE);
1895			}
1896			ieee80211_node_leave(ic, ni);
1897			ic->ic_stats.is_node_timeout++;
1898			goto restart;
1899		}
1900	}
1901	IEEE80211_NODE_UNLOCK(nt);
1902
1903	IEEE80211_SCAN_UNLOCK(nt);
1904
1905	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
1906}
1907
1908void
1909ieee80211_iterate_nodes(struct ieee80211_node_table *nt, ieee80211_iter_func *f, void *arg)
1910{
1911	struct ieee80211_node *ni;
1912	u_int gen;
1913
1914	IEEE80211_SCAN_LOCK(nt);
1915	gen = nt->nt_scangen++;
1916restart:
1917	IEEE80211_NODE_LOCK(nt);
1918	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1919		if (ni->ni_scangen != gen) {
1920			ni->ni_scangen = gen;
1921			(void) ieee80211_ref_node(ni);
1922			IEEE80211_NODE_UNLOCK(nt);
1923			(*f)(arg, ni);
1924			ieee80211_free_node(ni);
1925			goto restart;
1926		}
1927	}
1928	IEEE80211_NODE_UNLOCK(nt);
1929
1930	IEEE80211_SCAN_UNLOCK(nt);
1931}
1932
1933void
1934ieee80211_dump_node(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1935{
1936	printf("0x%p: mac %s refcnt %d\n", ni,
1937		ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni));
1938	printf("\tscangen %u authmode %u flags 0x%x\n",
1939		ni->ni_scangen, ni->ni_authmode, ni->ni_flags);
1940	printf("\tassocid 0x%x txpower %u vlan %u\n",
1941		ni->ni_associd, ni->ni_txpower, ni->ni_vlan);
1942	printf("\ttxseq %u rxseq %u fragno %u rxfragstamp %u\n",
1943		ni->ni_txseqs[0],
1944		ni->ni_rxseqs[0] >> IEEE80211_SEQ_SEQ_SHIFT,
1945		ni->ni_rxseqs[0] & IEEE80211_SEQ_FRAG_MASK,
1946		ni->ni_rxfragstamp);
1947	printf("\trstamp %u rssi %u intval %u capinfo 0x%x\n",
1948		ni->ni_rstamp, ni->ni_rssi, ni->ni_intval, ni->ni_capinfo);
1949	printf("\tbssid %s essid \"%.*s\" channel %u:0x%x\n",
1950		ether_sprintf(ni->ni_bssid),
1951		ni->ni_esslen, ni->ni_essid,
1952		ni->ni_chan->ic_freq, ni->ni_chan->ic_flags);
1953	printf("\tfails %u inact %u txrate %u\n",
1954		ni->ni_fails, ni->ni_inact, ni->ni_txrate);
1955}
1956
1957void
1958ieee80211_dump_nodes(struct ieee80211_node_table *nt)
1959{
1960	ieee80211_iterate_nodes(nt,
1961		(ieee80211_iter_func *) ieee80211_dump_node, nt);
1962}
1963
1964/*
1965 * Handle a station joining an 11g network.
1966 */
1967static void
1968ieee80211_node_join_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
1969{
1970
1971	/*
1972	 * Station isn't capable of short slot time.  Bump
1973	 * the count of long slot time stations and disable
1974	 * use of short slot time.  Note that the actual switch
1975	 * over to long slot time use may not occur until the
1976	 * next beacon transmission (per sec. 7.3.1.4 of 11g).
1977	 */
1978	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
1979		ic->ic_longslotsta++;
1980		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1981		    "[%s] station needs long slot time, count %d\n",
1982		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
1983		/* XXX vap's w/ conflicting needs won't work */
1984		ieee80211_set_shortslottime(ic, 0);
1985	}
1986	/*
1987	 * If the new station is not an ERP station
1988	 * then bump the counter and enable protection
1989	 * if configured.
1990	 */
1991	if (!ieee80211_iserp_rateset(ic, &ni->ni_rates)) {
1992		ic->ic_nonerpsta++;
1993		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1994		    "[%s] station is !ERP, %d non-ERP stations associated\n",
1995		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
1996		/*
1997		 * If protection is configured, enable it.
1998		 */
1999		if (ic->ic_protmode != IEEE80211_PROT_NONE) {
2000			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2001			    "%s: enable use of protection\n", __func__);
2002			ic->ic_flags |= IEEE80211_F_USEPROT;
2003		}
2004		/*
2005		 * If station does not support short preamble
2006		 * then we must enable use of Barker preamble.
2007		 */
2008		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE) == 0) {
2009			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2010			    "[%s] station needs long preamble\n",
2011			    ether_sprintf(ni->ni_macaddr));
2012			ic->ic_flags |= IEEE80211_F_USEBARKER;
2013			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
2014		}
2015	} else
2016		ni->ni_flags |= IEEE80211_NODE_ERP;
2017}
2018
2019void
2020ieee80211_node_join(struct ieee80211com *ic, struct ieee80211_node *ni, int resp)
2021{
2022	int newassoc;
2023
2024	if (ni->ni_associd == 0) {
2025		u_int16_t aid;
2026
2027		/*
2028		 * It would be good to search the bitmap
2029		 * more efficiently, but this will do for now.
2030		 */
2031		for (aid = 1; aid < ic->ic_max_aid; aid++) {
2032			if (!IEEE80211_AID_ISSET(aid,
2033			    ic->ic_aid_bitmap))
2034				break;
2035		}
2036		if (aid >= ic->ic_max_aid) {
2037			IEEE80211_SEND_MGMT(ic, ni, resp,
2038			    IEEE80211_REASON_ASSOC_TOOMANY);
2039			ieee80211_node_leave(ic, ni);
2040			return;
2041		}
2042		ni->ni_associd = aid | 0xc000;
2043		IEEE80211_AID_SET(ni->ni_associd, ic->ic_aid_bitmap);
2044		ic->ic_sta_assoc++;
2045		newassoc = 1;
2046		if (ic->ic_curmode == IEEE80211_MODE_11G)
2047			ieee80211_node_join_11g(ic, ni);
2048	} else
2049		newassoc = 0;
2050
2051	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
2052	    "[%s] station %sassociated at aid %d: %s preamble, %s slot time%s%s\n",
2053	    ether_sprintf(ni->ni_macaddr), newassoc ? "" : "re",
2054	    IEEE80211_NODE_AID(ni),
2055	    ic->ic_flags & IEEE80211_F_SHPREAMBLE ? "short" : "long",
2056	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long",
2057	    ic->ic_flags & IEEE80211_F_USEPROT ? ", protection" : "",
2058	    ni->ni_flags & IEEE80211_NODE_QOS ? ", QoS" : ""
2059	);
2060
2061	/* give driver a chance to setup state like ni_txrate */
2062	if (ic->ic_newassoc != NULL)
2063		ic->ic_newassoc(ni, newassoc);
2064	ni->ni_inact_reload = ic->ic_inact_auth;
2065	ni->ni_inact = ni->ni_inact_reload;
2066	IEEE80211_SEND_MGMT(ic, ni, resp, IEEE80211_STATUS_SUCCESS);
2067	/* tell the authenticator about new station */
2068	if (ic->ic_auth->ia_node_join != NULL)
2069		ic->ic_auth->ia_node_join(ic, ni);
2070	ieee80211_notify_node_join(ic, ni, newassoc);
2071}
2072
2073/*
2074 * Handle a station leaving an 11g network.
2075 */
2076static void
2077ieee80211_node_leave_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
2078{
2079
2080	KASSERT(ic->ic_curmode == IEEE80211_MODE_11G,
2081	     ("not in 11g, bss %u:0x%x, curmode %u", ni->ni_chan->ic_freq,
2082	      ni->ni_chan->ic_flags, ic->ic_curmode));
2083
2084	/*
2085	 * If a long slot station do the slot time bookkeeping.
2086	 */
2087	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
2088		KASSERT(ic->ic_longslotsta > 0,
2089		    ("bogus long slot station count %d", ic->ic_longslotsta));
2090		ic->ic_longslotsta--;
2091		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2092		    "[%s] long slot time station leaves, count now %d\n",
2093		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
2094		if (ic->ic_longslotsta == 0) {
2095			/*
2096			 * Re-enable use of short slot time if supported
2097			 * and not operating in IBSS mode (per spec).
2098			 */
2099			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
2100			    ic->ic_opmode != IEEE80211_M_IBSS) {
2101				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2102				    "%s: re-enable use of short slot time\n",
2103				    __func__);
2104				ieee80211_set_shortslottime(ic, 1);
2105			}
2106		}
2107	}
2108	/*
2109	 * If a non-ERP station do the protection-related bookkeeping.
2110	 */
2111	if ((ni->ni_flags & IEEE80211_NODE_ERP) == 0) {
2112		KASSERT(ic->ic_nonerpsta > 0,
2113		    ("bogus non-ERP station count %d", ic->ic_nonerpsta));
2114		ic->ic_nonerpsta--;
2115		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2116		    "[%s] non-ERP station leaves, count now %d\n",
2117		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
2118		if (ic->ic_nonerpsta == 0) {
2119			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2120				"%s: disable use of protection\n", __func__);
2121			ic->ic_flags &= ~IEEE80211_F_USEPROT;
2122			/* XXX verify mode? */
2123			if (ic->ic_caps & IEEE80211_C_SHPREAMBLE) {
2124				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2125				    "%s: re-enable use of short preamble\n",
2126				    __func__);
2127				ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
2128				ic->ic_flags &= ~IEEE80211_F_USEBARKER;
2129			}
2130		}
2131	}
2132}
2133
2134/*
2135 * Handle bookkeeping for station deauthentication/disassociation
2136 * when operating as an ap.
2137 */
2138void
2139ieee80211_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
2140{
2141	struct ieee80211_node_table *nt = ni->ni_table;
2142
2143	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
2144	    "[%s] station with aid %d leaves\n",
2145	    ether_sprintf(ni->ni_macaddr), IEEE80211_NODE_AID(ni));
2146
2147	KASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
2148		ic->ic_opmode == IEEE80211_M_IBSS ||
2149		ic->ic_opmode == IEEE80211_M_AHDEMO,
2150		("unexpected operating mode %u", ic->ic_opmode));
2151	/*
2152	 * If node wasn't previously associated all
2153	 * we need to do is reclaim the reference.
2154	 */
2155	/* XXX ibss mode bypasses 11g and notification */
2156	if (ni->ni_associd == 0)
2157		goto done;
2158	/*
2159	 * Tell the authenticator the station is leaving.
2160	 * Note that we must do this before yanking the
2161	 * association id as the authenticator uses the
2162	 * associd to locate it's state block.
2163	 */
2164	if (ic->ic_auth->ia_node_leave != NULL)
2165		ic->ic_auth->ia_node_leave(ic, ni);
2166	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
2167	ni->ni_associd = 0;
2168	ic->ic_sta_assoc--;
2169
2170	if (ic->ic_curmode == IEEE80211_MODE_11G)
2171		ieee80211_node_leave_11g(ic, ni);
2172	/*
2173	 * Cleanup station state.  In particular clear various
2174	 * state that might otherwise be reused if the node
2175	 * is reused before the reference count goes to zero
2176	 * (and memory is reclaimed).
2177	 */
2178	ieee80211_sta_leave(ic, ni);
2179done:
2180	/*
2181	 * Remove the node from any table it's recorded in and
2182	 * drop the caller's reference.  Removal from the table
2183	 * is important to insure the node is not reprocessed
2184	 * for inactivity.
2185	 */
2186	if (nt != NULL) {
2187		IEEE80211_NODE_LOCK(nt);
2188		node_reclaim(nt, ni);
2189		IEEE80211_NODE_UNLOCK(nt);
2190	} else
2191		ieee80211_free_node(ni);
2192}
2193
2194u_int8_t
2195ieee80211_getrssi(struct ieee80211com *ic)
2196{
2197#define	NZ(x)	((x) == 0 ? 1 : (x))
2198	struct ieee80211_node_table *nt = &ic->ic_sta;
2199	u_int32_t rssi_samples, rssi_total;
2200	struct ieee80211_node *ni;
2201
2202	rssi_total = 0;
2203	rssi_samples = 0;
2204	switch (ic->ic_opmode) {
2205	case IEEE80211_M_IBSS:		/* average of all ibss neighbors */
2206		/* XXX locking */
2207		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
2208			if (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) {
2209				rssi_samples++;
2210				rssi_total += ic->ic_node_getrssi(ni);
2211			}
2212		break;
2213	case IEEE80211_M_AHDEMO:	/* average of all neighbors */
2214		/* XXX locking */
2215		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
2216			rssi_samples++;
2217			rssi_total += ic->ic_node_getrssi(ni);
2218		}
2219		break;
2220	case IEEE80211_M_HOSTAP:	/* average of all associated stations */
2221		/* XXX locking */
2222		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
2223			if (IEEE80211_AID(ni->ni_associd) != 0) {
2224				rssi_samples++;
2225				rssi_total += ic->ic_node_getrssi(ni);
2226			}
2227		break;
2228	case IEEE80211_M_MONITOR:	/* XXX */
2229	case IEEE80211_M_STA:		/* use stats from associated ap */
2230	default:
2231		if (ic->ic_bss != NULL)
2232			rssi_total = ic->ic_node_getrssi(ic->ic_bss);
2233		rssi_samples = 1;
2234		break;
2235	}
2236	return rssi_total / NZ(rssi_samples);
2237#undef NZ
2238}
2239
2240/*
2241 * Indicate whether there are frames queued for a station in power-save mode.
2242 */
2243static void
2244ieee80211_set_tim(struct ieee80211_node *ni, int set)
2245{
2246	struct ieee80211com *ic = ni->ni_ic;
2247	u_int16_t aid;
2248
2249	KASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
2250		ic->ic_opmode == IEEE80211_M_IBSS,
2251		("operating mode %u", ic->ic_opmode));
2252
2253	aid = IEEE80211_AID(ni->ni_associd);
2254	KASSERT(aid < ic->ic_max_aid,
2255		("bogus aid %u, max %u", aid, ic->ic_max_aid));
2256
2257	IEEE80211_BEACON_LOCK(ic);
2258	if (set != (isset(ic->ic_tim_bitmap, aid) != 0)) {
2259		if (set) {
2260			setbit(ic->ic_tim_bitmap, aid);
2261			ic->ic_ps_pending++;
2262		} else {
2263			clrbit(ic->ic_tim_bitmap, aid);
2264			ic->ic_ps_pending--;
2265		}
2266		ic->ic_flags |= IEEE80211_F_TIMUPDATE;
2267	}
2268	IEEE80211_BEACON_UNLOCK(ic);
2269}
2270
2271/*
2272 * Node table support.
2273 */
2274
2275static void
2276ieee80211_node_table_init(struct ieee80211com *ic,
2277	struct ieee80211_node_table *nt,
2278	const char *name, int inact, int keyixmax,
2279	void (*timeout)(struct ieee80211_node_table *))
2280{
2281
2282	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
2283		"%s %s table, inact %u\n", __func__, name, inact);
2284
2285	nt->nt_ic = ic;
2286	/* XXX need unit */
2287	IEEE80211_NODE_LOCK_INIT(nt, ic->ic_ifp->if_xname);
2288	IEEE80211_SCAN_LOCK_INIT(nt, ic->ic_ifp->if_xname);
2289	TAILQ_INIT(&nt->nt_node);
2290	nt->nt_name = name;
2291	nt->nt_scangen = 1;
2292	nt->nt_inact_init = inact;
2293	nt->nt_timeout = timeout;
2294	nt->nt_keyixmax = keyixmax;
2295	if (nt->nt_keyixmax > 0) {
2296		MALLOC(nt->nt_keyixmap, struct ieee80211_node **,
2297			keyixmax * sizeof(struct ieee80211_node *),
2298			M_80211_NODE, M_NOWAIT | M_ZERO);
2299		if (nt->nt_keyixmap == NULL)
2300			if_printf(ic->ic_ifp,
2301			    "Cannot allocate key index map with %u entries\n",
2302			    keyixmax);
2303	} else
2304		nt->nt_keyixmap = NULL;
2305}
2306
2307void
2308ieee80211_node_table_reset(struct ieee80211_node_table *nt)
2309{
2310
2311	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
2312		"%s %s table\n", __func__, nt->nt_name);
2313
2314	IEEE80211_NODE_LOCK(nt);
2315	nt->nt_inact_timer = 0;
2316	ieee80211_free_allnodes_locked(nt);
2317	IEEE80211_NODE_UNLOCK(nt);
2318}
2319
2320static void
2321ieee80211_node_table_cleanup(struct ieee80211_node_table *nt)
2322{
2323
2324	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
2325		"%s %s table\n", __func__, nt->nt_name);
2326
2327	IEEE80211_NODE_LOCK(nt);
2328	ieee80211_free_allnodes_locked(nt);
2329	if (nt->nt_keyixmap != NULL) {
2330		/* XXX verify all entries are NULL */
2331		int i;
2332		for (i = 0; i < nt->nt_keyixmax; i++)
2333			if (nt->nt_keyixmap[i] != NULL)
2334				printf("%s: %s[%u] still active\n", __func__,
2335					nt->nt_name, i);
2336		FREE(nt->nt_keyixmap, M_80211_NODE);
2337		nt->nt_keyixmap = NULL;
2338	}
2339	IEEE80211_SCAN_LOCK_DESTROY(nt);
2340	IEEE80211_NODE_LOCK_DESTROY(nt);
2341}
2342