Home | History | Annotate | Line # | Download | only in net80211
      1 /*	$NetBSD: ieee80211_node.c,v 1.84 2024/07/05 04:31:53 rin Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2001 Atsushi Onoe
      5  * Copyright (c) 2002-2005 Sam Leffler, Errno Consulting
      6  * All rights reserved.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  * 3. The name of the author may not be used to endorse or promote products
     17  *    derived from this software without specific prior written permission.
     18  *
     19  * Alternatively, this software may be distributed under the terms of the
     20  * GNU General Public License ("GPL") version 2 as published by the Free
     21  * Software Foundation.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 #ifdef __FreeBSD__
     37 __FBSDID("$FreeBSD: src/sys/net80211/ieee80211_node.c,v 1.65 2005/08/13 17:50:21 sam Exp $");
     38 #endif
     39 #ifdef __NetBSD__
     40 __KERNEL_RCSID(0, "$NetBSD: ieee80211_node.c,v 1.84 2024/07/05 04:31:53 rin Exp $");
     41 #endif
     42 
     43 #ifdef _KERNEL_OPT
     44 #include "opt_inet.h"
     45 #endif
     46 
     47 #include <sys/param.h>
     48 #include <sys/systm.h>
     49 #include <sys/mbuf.h>
     50 #include <sys/malloc.h>
     51 #include <sys/kernel.h>
     52 
     53 #include <sys/socket.h>
     54 #include <sys/sockio.h>
     55 #include <sys/endian.h>
     56 #include <sys/errno.h>
     57 #include <sys/proc.h>
     58 #include <sys/sysctl.h>
     59 
     60 #include <net/if.h>
     61 #include <net/if_media.h>
     62 #include <net/if_arp.h>
     63 #include <net/if_ether.h>
     64 #include <net/if_llc.h>
     65 
     66 #include <net80211/ieee80211_netbsd.h>
     67 #include <net80211/ieee80211_var.h>
     68 
     69 #include <net/bpf.h>
     70 
     71 #ifdef INET
     72 #include <netinet/in.h>
     73 #include <net/if_ether.h>
     74 #endif
     75 
     76 /*
     77  * Association id's are managed with a bit vector.
     78  */
     79 #define	IEEE80211_AID_SET(b, w) \
     80 	((w)[IEEE80211_AID(b) / 32] |= (1 << (IEEE80211_AID(b) % 32)))
     81 #define	IEEE80211_AID_CLR(b, w) \
     82 	((w)[IEEE80211_AID(b) / 32] &= ~(1 << (IEEE80211_AID(b) % 32)))
     83 #define	IEEE80211_AID_ISSET(b, w) \
     84 	((w)[IEEE80211_AID(b) / 32] & (1 << (IEEE80211_AID(b) % 32)))
     85 
     86 static struct ieee80211_node *node_alloc(struct ieee80211_node_table *);
     87 static void node_cleanup(struct ieee80211_node *);
     88 static void node_free(struct ieee80211_node *);
     89 static u_int8_t node_getrssi(const struct ieee80211_node *);
     90 
     91 static void ieee80211_setup_node(struct ieee80211_node_table *,
     92 		struct ieee80211_node *, const u_int8_t *);
     93 static void _ieee80211_free_node(struct ieee80211_node *);
     94 static void ieee80211_free_allnodes(struct ieee80211_node_table *);
     95 
     96 static void ieee80211_timeout_scan_candidates(struct ieee80211_node_table *);
     97 static void ieee80211_timeout_stations(struct ieee80211_node_table *);
     98 
     99 static void ieee80211_set_tim(struct ieee80211_node *, int set);
    100 
    101 static void ieee80211_node_table_init(struct ieee80211com *ic,
    102 	struct ieee80211_node_table *nt, const char *name,
    103 	int inact, int keyixmax,
    104 	void (*timeout)(struct ieee80211_node_table *));
    105 static void ieee80211_node_table_cleanup(struct ieee80211_node_table *nt);
    106 
    107 MALLOC_DEFINE(M_80211_NODE, "80211node", "802.11 node state");
    108 
    109 void
    110 ieee80211_node_attach(struct ieee80211com *ic)
    111 {
    112 
    113 	ic->ic_node_alloc = node_alloc;
    114 	ic->ic_node_free = node_free;
    115 	ic->ic_node_cleanup = node_cleanup;
    116 	ic->ic_node_getrssi = node_getrssi;
    117 
    118 	/* default station inactivity timer settings */
    119 	ic->ic_inact_init = IEEE80211_INACT_INIT;
    120 	ic->ic_inact_auth = IEEE80211_INACT_AUTH;
    121 	ic->ic_inact_run = IEEE80211_INACT_RUN;
    122 	ic->ic_inact_probe = IEEE80211_INACT_PROBE;
    123 
    124 	/* NB: driver should override */
    125 	ic->ic_max_aid = IEEE80211_AID_DEF;
    126 	ic->ic_set_tim = ieee80211_set_tim;
    127 }
    128 
    129 void
    130 ieee80211_node_lateattach(struct ieee80211com *ic)
    131 {
    132 	struct ieee80211_rsnparms *rsn;
    133 
    134 	if (ic->ic_max_aid > IEEE80211_AID_MAX)
    135 		ic->ic_max_aid = IEEE80211_AID_MAX;
    136 	ic->ic_aid_bitmap = malloc(howmany(ic->ic_max_aid, 32) *
    137 	    sizeof(u_int32_t), M_DEVBUF, M_WAITOK | M_ZERO);
    138 
    139 	/* XXX defer until using hostap/ibss mode */
    140 	ic->ic_tim_len = howmany(ic->ic_max_aid, 8) * sizeof(u_int8_t);
    141 	ic->ic_tim_bitmap = malloc(ic->ic_tim_len, M_DEVBUF, M_WAITOK | M_ZERO);
    142 
    143 	ieee80211_node_table_init(ic, &ic->ic_sta, "station",
    144 		IEEE80211_INACT_INIT, ic->ic_crypto.cs_max_keyix,
    145 		ieee80211_timeout_stations);
    146 	ieee80211_node_table_init(ic, &ic->ic_scan, "scan",
    147 		IEEE80211_INACT_SCAN, 0,
    148 		ieee80211_timeout_scan_candidates);
    149 
    150 	ieee80211_reset_bss(ic);
    151 	/*
    152 	 * Setup "global settings" in the bss node so that
    153 	 * each new station automatically inherits them.
    154 	 */
    155 	rsn = &ic->ic_bss->ni_rsn;
    156 	/* WEP, TKIP, and AES-CCM are always supported */
    157 	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_WEP;
    158 	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_TKIP;
    159 	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_AES_CCM;
    160 	if (ic->ic_caps & IEEE80211_C_AES)
    161 		rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_AES_OCB;
    162 	if (ic->ic_caps & IEEE80211_C_CKIP)
    163 		rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_CKIP;
    164 	/*
    165 	 * Default unicast cipher to WEP for 802.1x use.  If
    166 	 * WPA is enabled the management code will set these
    167 	 * values to reflect.
    168 	 */
    169 	rsn->rsn_ucastcipher = IEEE80211_CIPHER_WEP;
    170 	rsn->rsn_ucastkeylen = 104 / NBBY;
    171 	/*
    172 	 * WPA says the multicast cipher is the lowest unicast
    173 	 * cipher supported.  But we skip WEP which would
    174 	 * otherwise be used based on this criteria.
    175 	 */
    176 	rsn->rsn_mcastcipher = IEEE80211_CIPHER_TKIP;
    177 	rsn->rsn_mcastkeylen = 128 / NBBY;
    178 
    179 	/*
    180 	 * We support both WPA-PSK and 802.1x; the one used
    181 	 * is determined by the authentication mode and the
    182 	 * setting of the PSK state.
    183 	 */
    184 	rsn->rsn_keymgmtset = WPA_ASE_8021X_UNSPEC | WPA_ASE_8021X_PSK;
    185 	rsn->rsn_keymgmt = WPA_ASE_8021X_PSK;
    186 
    187 	ic->ic_auth = ieee80211_authenticator_get(ic->ic_bss->ni_authmode);
    188 }
    189 
    190 void
    191 ieee80211_node_detach(struct ieee80211com *ic)
    192 {
    193 
    194 	if (ic->ic_bss != NULL) {
    195 		ieee80211_free_node(ic->ic_bss);
    196 		ic->ic_bss = NULL;
    197 	}
    198 	ieee80211_node_table_cleanup(&ic->ic_scan);
    199 	ieee80211_node_table_cleanup(&ic->ic_sta);
    200 	if (ic->ic_aid_bitmap != NULL) {
    201 		free(ic->ic_aid_bitmap, M_DEVBUF);
    202 		ic->ic_aid_bitmap = NULL;
    203 	}
    204 	if (ic->ic_tim_bitmap != NULL) {
    205 		free(ic->ic_tim_bitmap, M_DEVBUF);
    206 		ic->ic_tim_bitmap = NULL;
    207 	}
    208 }
    209 
    210 /*
    211  * Port authorize/unauthorize interfaces for use by an authenticator.
    212  */
    213 
    214 void
    215 ieee80211_node_authorize(struct ieee80211_node *ni)
    216 {
    217 	struct ieee80211com *ic = ni->ni_ic;
    218 
    219 	ni->ni_flags |= IEEE80211_NODE_AUTH;
    220 	ni->ni_inact_reload = ic->ic_inact_run;
    221 }
    222 
    223 void
    224 ieee80211_node_unauthorize(struct ieee80211_node *ni)
    225 {
    226 	ni->ni_flags &= ~IEEE80211_NODE_AUTH;
    227 }
    228 
    229 /*
    230  * Set/change the channel.  The rate set is also updated as
    231  * to insure a consistent view by drivers.
    232  */
    233 static void
    234 ieee80211_set_chan(struct ieee80211com *ic,
    235 	struct ieee80211_node *ni, struct ieee80211_channel *chan)
    236 {
    237 	if (chan == IEEE80211_CHAN_ANYC)	/* XXX while scanning */
    238 		chan = ic->ic_curchan;
    239 	ni->ni_chan = chan;
    240 	ni->ni_rates = ic->ic_sup_rates[ieee80211_chan2mode(ic, chan)];
    241 }
    242 
    243 /*
    244  * AP scanning support.
    245  */
    246 
    247 #ifdef IEEE80211_DEBUG
    248 static void
    249 dump_chanlist(const u_char chans[])
    250 {
    251 	const char *sep;
    252 	int i;
    253 
    254 	sep = " ";
    255 	for (i = 0; i < IEEE80211_CHAN_MAX; i++)
    256 		if (isset(chans, i)) {
    257 			printf("%s%u", sep, i);
    258 			sep = ", ";
    259 		}
    260 }
    261 #endif /* IEEE80211_DEBUG */
    262 
    263 /*
    264  * Initialize the channel set to scan based on the
    265  * of available channels and the current PHY mode.
    266  */
    267 static void
    268 ieee80211_reset_scan(struct ieee80211com *ic)
    269 {
    270 
    271 	/* XXX ic_des_chan should be handled with ic_chan_active */
    272 	if (ic->ic_des_chan != IEEE80211_CHAN_ANYC) {
    273 		memset(ic->ic_chan_scan, 0, sizeof(ic->ic_chan_scan));
    274 		setbit(ic->ic_chan_scan,
    275 			ieee80211_chan2ieee(ic, ic->ic_des_chan));
    276 	} else
    277 		memcpy(ic->ic_chan_scan, ic->ic_chan_active,
    278 			sizeof(ic->ic_chan_active));
    279 #ifdef IEEE80211_DEBUG
    280 	if (ieee80211_msg_scan(ic)) {
    281 		printf("%s: scan set:", __func__);
    282 		dump_chanlist(ic->ic_chan_scan);
    283 		printf(" start chan %u\n",
    284 			ieee80211_chan2ieee(ic, ic->ic_curchan));
    285 	}
    286 #endif /* IEEE80211_DEBUG */
    287 }
    288 
    289 /*
    290  * Begin an active scan.
    291  */
    292 void
    293 ieee80211_begin_scan(struct ieee80211com *ic, int reset)
    294 {
    295 	ic->ic_scan.nt_scangen++;
    296 
    297 	/*
    298 	 * In all but hostap mode scanning starts off in
    299 	 * an active mode before switching to passive.
    300 	 */
    301 	if (ic->ic_opmode != IEEE80211_M_HOSTAP) {
    302 		ic->ic_flags |= IEEE80211_F_ASCAN;
    303 		ic->ic_stats.is_scan_active++;
    304 	} else
    305 		ic->ic_stats.is_scan_passive++;
    306 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
    307 		"begin %s scan in %s mode, scangen %u\n",
    308 		(ic->ic_flags & IEEE80211_F_ASCAN) ?  "active" : "passive",
    309 		ieee80211_phymode_name[ic->ic_curmode], ic->ic_scan.nt_scangen);
    310 
    311 	/*
    312 	 * Clear scan state and flush any previously seen AP's.
    313 	 */
    314 	ieee80211_reset_scan(ic);
    315 	if (reset)
    316 		ieee80211_free_allnodes(&ic->ic_scan);
    317 
    318 	ic->ic_flags |= IEEE80211_F_SCAN;
    319 
    320 	/* Scan the next channel. */
    321 	ieee80211_next_scan(ic);
    322 }
    323 
    324 /*
    325  * Switch to the next channel marked for scanning.
    326  */
    327 int
    328 ieee80211_next_scan(struct ieee80211com *ic)
    329 {
    330 	struct ieee80211_channel *chan;
    331 
    332 	/*
    333 	 * Insure any previous mgt frame timeouts don't fire.
    334 	 * This assumes the driver does the right thing in
    335 	 * flushing anything queued in the driver and below.
    336 	 */
    337 	ic->ic_mgt_timer = 0;
    338 	ic->ic_flags_ext &= ~IEEE80211_FEXT_PROBECHAN;
    339 
    340 	chan = ic->ic_curchan;
    341 	do {
    342 		if (++chan > &ic->ic_channels[IEEE80211_CHAN_MAX])
    343 			chan = &ic->ic_channels[0];
    344 		if (isset(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan))) {
    345 			clrbit(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan));
    346 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
    347 			    "%s: chan %d->%d\n", __func__,
    348 			    ieee80211_chan2ieee(ic, ic->ic_curchan),
    349 			    ieee80211_chan2ieee(ic, chan));
    350 			ic->ic_curchan = chan;
    351 			/*
    352 			 * XXX drivers should do this as needed,
    353 			 * XXX for now maintain compatibility
    354 			 */
    355 			ic->ic_bss->ni_rates =
    356 				ic->ic_sup_rates[ieee80211_chan2mode(ic, chan)];
    357 			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
    358 			return 1;
    359 		}
    360 	} while (chan != ic->ic_curchan);
    361 
    362 	ieee80211_end_scan(ic);
    363 	return 0;
    364 }
    365 
    366 /*
    367  * Probe the current channel, if allowed, while scanning.
    368  * If the channel is not marked passive-only then send
    369  * a probe request immediately.  Otherwise mark state and
    370  * listen for beacons on the channel; if we receive something
    371  * then we'll transmit a probe request.
    372  */
    373 void
    374 ieee80211_probe_curchan(struct ieee80211com *ic, int force)
    375 {
    376 	struct ifnet *ifp = ic->ic_ifp;
    377 
    378 	if ((ic->ic_curchan->ic_flags & IEEE80211_CHAN_PASSIVE) == 0 || force) {
    379 		/*
    380 		 * XXX send both broadcast+directed probe request
    381 		 */
    382 		ieee80211_send_probereq(ic->ic_bss,
    383 			ic->ic_myaddr, ifp->if_broadcastaddr,
    384 			ifp->if_broadcastaddr,
    385 			ic->ic_des_essid, ic->ic_des_esslen,
    386 			ic->ic_opt_ie, ic->ic_opt_ie_len);
    387 	} else
    388 		ic->ic_flags_ext |= IEEE80211_FEXT_PROBECHAN;
    389 }
    390 
    391 static __inline void
    392 copy_bss(struct ieee80211_node *nbss, const struct ieee80211_node *obss)
    393 {
    394 	/* propagate useful state */
    395 	nbss->ni_authmode = obss->ni_authmode;
    396 	nbss->ni_txpower = obss->ni_txpower;
    397 	nbss->ni_vlan = obss->ni_vlan;
    398 	nbss->ni_rsn = obss->ni_rsn;
    399 	/* XXX statistics? */
    400 }
    401 
    402 void
    403 ieee80211_create_ibss(struct ieee80211com* ic, struct ieee80211_channel *chan)
    404 {
    405 	struct ieee80211_node_table *nt;
    406 	struct ieee80211_node *ni;
    407 
    408 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
    409 		"%s: creating ibss\n", __func__);
    410 
    411 	/*
    412 	 * Create the station/neighbor table.  Note that for adhoc
    413 	 * mode we make the initial inactivity timer longer since
    414 	 * we create nodes only through discovery and they typically
    415 	 * are long-lived associations.
    416 	 */
    417 	nt = &ic->ic_sta;
    418 	IEEE80211_NODE_LOCK(nt);
    419 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
    420 		nt->nt_name = "station";
    421 		nt->nt_inact_init = ic->ic_inact_init;
    422 	} else {
    423 		nt->nt_name = "neighbor";
    424 		nt->nt_inact_init = ic->ic_inact_run;
    425 	}
    426 	IEEE80211_NODE_UNLOCK(nt);
    427 
    428 	ni = ieee80211_alloc_node(&ic->ic_sta, ic->ic_myaddr);
    429 	if (ni == NULL) {
    430 		/* XXX recovery? */
    431 		return;
    432 	}
    433 	IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_myaddr);
    434 	ni->ni_esslen = ic->ic_des_esslen;
    435 	memcpy(ni->ni_essid, ic->ic_des_essid, ni->ni_esslen);
    436 	copy_bss(ni, ic->ic_bss);
    437 	ni->ni_intval = ic->ic_bintval;
    438 	if (ic->ic_flags & IEEE80211_F_PRIVACY)
    439 		ni->ni_capinfo |= IEEE80211_CAPINFO_PRIVACY;
    440 	if (ic->ic_phytype == IEEE80211_T_FH) {
    441 		ni->ni_fhdwell = 200;	/* XXX */
    442 		ni->ni_fhindex = 1;
    443 	}
    444 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
    445 		ic->ic_flags |= IEEE80211_F_SIBSS;
    446 		ni->ni_capinfo |= IEEE80211_CAPINFO_IBSS;	/* XXX */
    447 		if (ic->ic_flags & IEEE80211_F_DESBSSID)
    448 			IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_des_bssid);
    449 		else
    450 			ni->ni_bssid[0] |= 0x02;	/* local bit for IBSS */
    451 	}
    452 
    453 	/*
    454 	 * Fix the channel and related attributes.
    455 	 */
    456 	ieee80211_set_chan(ic, ni, chan);
    457 	ic->ic_curchan = chan;
    458 	ic->ic_curmode = ieee80211_chan2mode(ic, chan);
    459 
    460 	/*
    461 	 * Do mode-specific rate setup.
    462 	 */
    463 	if (ic->ic_curmode == IEEE80211_MODE_11G) {
    464 		/*
    465 		 * Use a mixed 11b/11g rate set.
    466 		 */
    467 		ieee80211_set11gbasicrates(&ni->ni_rates, IEEE80211_MODE_11G);
    468 	} else if (ic->ic_curmode == IEEE80211_MODE_11B) {
    469 		/*
    470 		 * Force pure 11b rate set.
    471 		 */
    472 		ieee80211_set11gbasicrates(&ni->ni_rates, IEEE80211_MODE_11B);
    473 	}
    474 
    475 	(void)ieee80211_sta_join(ic, ieee80211_ref_node(ni));
    476 }
    477 
    478 void
    479 ieee80211_reset_bss(struct ieee80211com *ic)
    480 {
    481 	struct ieee80211_node *ni, *obss;
    482 
    483 	ieee80211_node_table_reset(&ic->ic_scan);
    484 	ieee80211_node_table_reset(&ic->ic_sta);
    485 
    486 	ni = ieee80211_alloc_node(&ic->ic_scan, ic->ic_myaddr);
    487 	IASSERT(ni != NULL, ("unable to setup initial BSS node"));
    488 	obss = ic->ic_bss;
    489 	ic->ic_bss = ieee80211_ref_node(ni);
    490 	if (obss != NULL) {
    491 		copy_bss(ni, obss);
    492 		ni->ni_intval = ic->ic_bintval;
    493 		ieee80211_free_node(obss);
    494 	}
    495 }
    496 
    497 /* XXX tunable */
    498 #define	STA_FAILS_MAX	2		/* assoc failures before ignored */
    499 
    500 static int
    501 ieee80211_match_bss(struct ieee80211com *ic, struct ieee80211_node *ni)
    502 {
    503 	u_int8_t rate;
    504 	int fail;
    505 
    506 	fail = 0;
    507 	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
    508 		fail |= 0x01;
    509 	if (ic->ic_des_chan != IEEE80211_CHAN_ANYC &&
    510 	    ni->ni_chan != ic->ic_des_chan)
    511 		fail |= 0x01;
    512 
    513 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
    514 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
    515 			fail |= 0x02;
    516 	} else {
    517 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
    518 			fail |= 0x02;
    519 	}
    520 
    521 	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
    522 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
    523 			fail |= 0x04;
    524 	} else {
    525 		/* XXX does this mean privacy is supported or required? */
    526 		if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
    527 			fail |= 0x04;
    528 	}
    529 
    530 	rate = ieee80211_fix_rate(ni, IEEE80211_R_DONEGO | IEEE80211_R_DOFRATE);
    531 	if (rate & IEEE80211_RATE_BASIC)
    532 		fail |= 0x08;
    533 
    534 	if (ic->ic_des_esslen != 0 &&
    535 	    (ni->ni_esslen != ic->ic_des_esslen ||
    536 	     memcmp(ni->ni_essid, ic->ic_des_essid, ic->ic_des_esslen) != 0))
    537 		fail |= 0x10;
    538 
    539 	if ((ic->ic_flags & IEEE80211_F_DESBSSID) &&
    540 	    !IEEE80211_ADDR_EQ(ic->ic_des_bssid, ni->ni_bssid))
    541 		fail |= 0x20;
    542 
    543 	if (ni->ni_fails >= STA_FAILS_MAX)
    544 		fail |= 0x40;
    545 
    546 	/* If no ESS/IBSS is desired, do not match any. */
    547 	if (ic->ic_des_esslen == 0)
    548 		fail |= 0x80;
    549 
    550 #ifdef IEEE80211_DEBUG
    551 	if (ieee80211_msg_scan(ic)) {
    552 		printf(" %c %s",
    553 		    fail & 0x40 ? '=' : fail & 0x80 ? '^' : fail ? '-' : '+',
    554 		    ether_sprintf(ni->ni_macaddr));
    555 		printf(" %s%c", ether_sprintf(ni->ni_bssid),
    556 		    fail & 0x20 ? '!' : ' ');
    557 		printf(" %3d%c", ieee80211_chan2ieee(ic, ni->ni_chan),
    558 			fail & 0x01 ? '!' : ' ');
    559 		printf(" %+4d", ni->ni_rssi);
    560 		printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
    561 		    fail & 0x08 ? '!' : ' ');
    562 		printf(" %4s%c",
    563 		    (ni->ni_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
    564 		    (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
    565 		    "????",
    566 		    fail & 0x02 ? '!' : ' ');
    567 		printf(" %3s%c ",
    568 		    (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) ?
    569 		    "wep" : "no",
    570 		    fail & 0x04 ? '!' : ' ');
    571 		ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
    572 		printf("%s\n", fail & 0x10 ? "!" : "");
    573 	}
    574 #endif
    575 
    576 	return fail;
    577 }
    578 
    579 static __inline u_int8_t
    580 maxrate(const struct ieee80211_node *ni)
    581 {
    582 	const struct ieee80211_rateset *rs = &ni->ni_rates;
    583 	/* NB: assumes rate set is sorted (happens on frame receive) */
    584 	return rs->rs_rates[rs->rs_nrates-1] & IEEE80211_RATE_VAL;
    585 }
    586 
    587 /*
    588  * Compare the capabilities of two nodes and decide which is
    589  * more desirable (return >0 if a is considered better).  Note
    590  * that we assume compatibility/usability has already been checked
    591  * so we don't need to (e.g. validate whether privacy is supported).
    592  * Used to select the best scan candidate for association in a BSS.
    593  */
    594 static int
    595 ieee80211_node_compare(struct ieee80211com *ic, const struct ieee80211_node *a,
    596     const struct ieee80211_node *b)
    597 {
    598 	u_int8_t maxa, maxb;
    599 	u_int8_t rssia, rssib;
    600 	int weight;
    601 
    602 	/* privacy support preferred */
    603 	if ((a->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) &&
    604 	    (b->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
    605 		return 1;
    606 	if ((a->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0 &&
    607 	    (b->ni_capinfo & IEEE80211_CAPINFO_PRIVACY))
    608 		return -1;
    609 
    610 	/* compare count of previous failures */
    611 	weight = b->ni_fails - a->ni_fails;
    612 	if (abs(weight) > 1)
    613 		return weight;
    614 
    615 	rssia = ic->ic_node_getrssi(a);
    616 	rssib = ic->ic_node_getrssi(b);
    617 	if (abs(rssib - rssia) < 5) {
    618 		/* best/max rate preferred if signal level close enough XXX */
    619 		maxa = maxrate(a);
    620 		maxb = maxrate(b);
    621 		if (maxa != maxb)
    622 			return maxa - maxb;
    623 		/* XXX use freq for channel preference */
    624 		/* for now just prefer 5 GHz band to all other bands */
    625 		if (IEEE80211_IS_CHAN_5GHZ(a->ni_chan) &&
    626 		   !IEEE80211_IS_CHAN_5GHZ(b->ni_chan))
    627 			return 1;
    628 		if (!IEEE80211_IS_CHAN_5GHZ(a->ni_chan) &&
    629 		     IEEE80211_IS_CHAN_5GHZ(b->ni_chan))
    630 			return -1;
    631 	}
    632 	/* all things being equal, use signal level */
    633 	return rssia - rssib;
    634 }
    635 
    636 /*
    637  * Mark an ongoing scan stopped.
    638  */
    639 void
    640 ieee80211_cancel_scan(struct ieee80211com *ic)
    641 {
    642 
    643 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN, "%s: end %s scan\n",
    644 		__func__,
    645 		(ic->ic_flags & IEEE80211_F_ASCAN) ?  "active" : "passive");
    646 
    647 	ic->ic_flags &= ~(IEEE80211_F_SCAN | IEEE80211_F_ASCAN);
    648 	ic->ic_flags_ext &= ~IEEE80211_FEXT_PROBECHAN;
    649 }
    650 
    651 /*
    652  * Complete a scan of potential channels.
    653  */
    654 void
    655 ieee80211_end_scan(struct ieee80211com *ic)
    656 {
    657 	struct ieee80211_node_table *nt = &ic->ic_scan;
    658 	struct ieee80211_node *ni, *selbs;
    659 
    660 	ieee80211_cancel_scan(ic);
    661 	ieee80211_notify_scan_done(ic);
    662 
    663 #ifndef IEEE80211_NO_HOSTAP
    664 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
    665 		u_int8_t maxrssi[IEEE80211_CHAN_MAX];	/* XXX off stack? */
    666 		int i, bestchan;
    667 		u_int8_t rssi;
    668 
    669 		/*
    670 		 * The passive scan to look for existing AP's completed,
    671 		 * select a channel to camp on.  Identify the channels
    672 		 * that already have one or more AP's and try to locate
    673 		 * an unoccupied one.  If that fails, pick a channel that
    674 		 * looks to be quietest.
    675 		 */
    676 		memset(maxrssi, 0, sizeof(maxrssi));
    677 		IEEE80211_NODE_LOCK(nt);
    678 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
    679 			rssi = ic->ic_node_getrssi(ni);
    680 			i = ieee80211_chan2ieee(ic, ni->ni_chan);
    681 			if (rssi > maxrssi[i])
    682 				maxrssi[i] = rssi;
    683 		}
    684 		IEEE80211_NODE_UNLOCK(nt);
    685 
    686 		/* XXX select channel more intelligently */
    687 		bestchan = -1;
    688 		for (i = 0; i < IEEE80211_CHAN_MAX; i++) {
    689 			if (isset(ic->ic_chan_active, i)) {
    690 				/*
    691 				 * If the channel is unoccupied the max rssi
    692 				 * should be zero; just take it.  Otherwise
    693 				 * track the channel with the lowest rssi and
    694 				 * use that when all channels appear occupied.
    695 				 */
    696 				if (maxrssi[i] == 0) {
    697 					bestchan = i;
    698 					break;
    699 				}
    700 				if (bestchan == -1 ||
    701 				    maxrssi[i] < maxrssi[bestchan])
    702 					bestchan = i;
    703 			}
    704 		}
    705 		if (bestchan != -1) {
    706 			ieee80211_create_ibss(ic, &ic->ic_channels[bestchan]);
    707 			return;
    708 		}
    709 		/* no suitable channel, should not happen */
    710 	}
    711 #endif /* !IEEE80211_NO_HOSTAP */
    712 
    713 	/*
    714 	 * When manually sequencing the state machine; scan just once
    715 	 * regardless of whether we have a candidate or not.  The
    716 	 * controlling application is expected to setup state and
    717 	 * initiate an association.
    718 	 */
    719 	if (ic->ic_roaming == IEEE80211_ROAMING_MANUAL)
    720 		return;
    721 
    722 	/*
    723 	 * Automatic sequencing; look for a candidate and
    724 	 * if found join the network.
    725 	 */
    726 	/* NB: unlocked read should be ok */
    727 	if (TAILQ_FIRST(&nt->nt_node) == NULL) {
    728 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
    729 			"%s: no scan candidate\n", __func__);
    730 
    731 notfound:
    732 		if (ic->ic_opmode == IEEE80211_M_IBSS &&
    733 		    (ic->ic_flags & IEEE80211_F_IBSSON) &&
    734 		    ic->ic_des_esslen != 0) {
    735 			ieee80211_create_ibss(ic, ic->ic_ibss_chan);
    736 			return;
    737 		}
    738 
    739 		/*
    740 		 * Decrement the failure counts so entries will be
    741 		 * reconsidered the next time around.  We really want
    742 		 * to do this only for sta's where we've previously
    743 		 * had some success.
    744 		 */
    745 		IEEE80211_NODE_LOCK(nt);
    746 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
    747 			if (ni->ni_fails)
    748 				ni->ni_fails--;
    749 		}
    750 		IEEE80211_NODE_UNLOCK(nt);
    751 
    752 		/*
    753 		 * Reset the list of channels to scan and start again.
    754 		 */
    755 		ieee80211_reset_scan(ic);
    756 		ic->ic_flags |= IEEE80211_F_SCAN;
    757 		ieee80211_next_scan(ic);
    758 		return;
    759 	}
    760 
    761 	selbs = NULL;
    762 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN, "\t%s\n",
    763 	    "macaddr          bssid         chan  rssi rate flag  wep  essid");
    764 
    765 	IEEE80211_NODE_LOCK(nt);
    766 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
    767 		if (ieee80211_match_bss(ic, ni) == 0) {
    768 			if (selbs == NULL)
    769 				selbs = ni;
    770 			else if (ieee80211_node_compare(ic, ni, selbs) > 0)
    771 				selbs = ni;
    772 		}
    773 	}
    774 	if (selbs != NULL)		/* NB: grab ref while dropping lock */
    775 		(void)ieee80211_ref_node(selbs);
    776 	IEEE80211_NODE_UNLOCK(nt);
    777 
    778 	if (selbs == NULL)
    779 		goto notfound;
    780 	if (!ieee80211_sta_join(ic, selbs)) {
    781 		ieee80211_free_node(selbs);
    782 		goto notfound;
    783 	}
    784 }
    785 
    786 /*
    787  * Handle 802.11 ad hoc network merge.  The
    788  * convention, set by the Wireless Ethernet Compatibility Alliance
    789  * (WECA), is that an 802.11 station will change its BSSID to match
    790  * the "oldest" 802.11 ad hoc network, on the same channel, that
    791  * has the station's desired SSID.  The "oldest" 802.11 network
    792  * sends beacons with the greatest TSF timestamp.
    793  *
    794  * The caller is assumed to validate TSF's before attempting a merge.
    795  *
    796  * Return !0 if the BSSID changed, 0 otherwise.
    797  */
    798 int
    799 ieee80211_ibss_merge(struct ieee80211_node *ni)
    800 {
    801 	struct ieee80211com *ic = ni->ni_ic;
    802 
    803 	if (ni == ic->ic_bss ||
    804 	    IEEE80211_ADDR_EQ(ni->ni_bssid, ic->ic_bss->ni_bssid)) {
    805 		/* unchanged, nothing to do */
    806 		return 0;
    807 	}
    808 	if (ieee80211_match_bss(ic, ni) != 0) {	/* capabilities mismatch */
    809 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
    810 		    "%s: merge failed, capabilities mismatch\n", __func__);
    811 		ic->ic_stats.is_ibss_capmismatch++;
    812 		return 0;
    813 	}
    814 	if (!ieee80211_sta_join(ic, ieee80211_ref_node(ni)))
    815 		return 0;
    816 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
    817 		"%s: new bssid %s: %s preamble, %s slot time%s\n", __func__,
    818 		ether_sprintf(ni->ni_bssid),
    819 		ic->ic_flags&IEEE80211_F_SHPREAMBLE ? "short" : "long",
    820 		ic->ic_flags&IEEE80211_F_SHSLOT ? "short" : "long",
    821 		ic->ic_flags&IEEE80211_F_USEPROT ? ", protection" : ""
    822 	);
    823 	ic->ic_flags &= ~IEEE80211_F_SIBSS;
    824 	return 1;
    825 }
    826 
    827 /*
    828  * Join the specified IBSS/BSS network.  The node is assumed to
    829  * be passed in with a held reference.
    830  */
    831 int
    832 ieee80211_sta_join(struct ieee80211com *ic, struct ieee80211_node *selbs)
    833 {
    834 	struct ieee80211_node *obss;
    835 
    836 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
    837 		struct ieee80211_node_table *nt;
    838 
    839 		/*
    840 		 * Delete unusable rates; we've already checked
    841 		 * that the negotiated rate set is acceptable.
    842 		 */
    843 		ieee80211_fix_rate(selbs, IEEE80211_R_DODEL);
    844 
    845 		/*
    846 		 * Fill in the neighbor table; it will already
    847 		 * exist if we are simply switching mastership.
    848 		 * XXX ic_sta always setup so this is unnecessary?
    849 		 */
    850 		nt = &ic->ic_sta;
    851 		IEEE80211_NODE_LOCK(nt);
    852 		nt->nt_name = "neighbor";
    853 		nt->nt_inact_init = ic->ic_inact_run;
    854 		IEEE80211_NODE_UNLOCK(nt);
    855 	}
    856 
    857 	/*
    858 	 * Committed to selbs, setup state.
    859 	 */
    860 	obss = ic->ic_bss;
    861 	ic->ic_bss = selbs;		/* NB: caller assumed to bump refcnt */
    862 	if (obss != NULL) {
    863 		copy_bss(selbs, obss);
    864 		ieee80211_free_node(obss);
    865 	}
    866 
    867 	/*
    868 	 * Set the erp state (mostly the slot time) to deal with
    869 	 * the auto-select case; this should be redundant if the
    870 	 * mode is locked.
    871 	 */
    872 	ic->ic_curmode = ieee80211_chan2mode(ic, selbs->ni_chan);
    873 	ic->ic_curchan = selbs->ni_chan;
    874 	ieee80211_reset_erp(ic);
    875 	ieee80211_wme_initparams(ic);
    876 
    877 	if (ic->ic_opmode == IEEE80211_M_STA)
    878 		ieee80211_new_state(ic, IEEE80211_S_AUTH, -1);
    879 	else
    880 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
    881 	return 1;
    882 }
    883 
    884 /*
    885  * Leave the specified IBSS/BSS network.  The node is assumed to
    886  * be passed in with a held reference.
    887  */
    888 void
    889 ieee80211_sta_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
    890 {
    891 	ic->ic_node_cleanup(ni);
    892 	ieee80211_notify_node_leave(ic, ni);
    893 }
    894 
    895 int
    896 ieee80211_get_rate(const struct ieee80211_node * const ni)
    897 {
    898 #define	RATE(_ix)	(ni->ni_rates.rs_rates[(_ix)] & IEEE80211_RATE_VAL)
    899 	int ix, rate;
    900 	struct ieee80211com *ic = ni->ni_ic;
    901 	const struct ieee80211_rateset *rs;
    902 
    903 	IASSERT(ni != NULL, ("ni != NULL"));
    904 	IASSERT(ieee80211_node_refcnt(ni) > 0,
    905 	    ("refcnt(ni) == %d", ieee80211_node_refcnt(ni)));
    906 	IASSERT(ic != NULL, ("ic != NULL"));
    907 
    908 	if (ic->ic_fixed_rate != IEEE80211_FIXED_RATE_NONE) {
    909 		rs = &ic->ic_sup_rates[ic->ic_curmode];
    910 		rate = rs->rs_rates[ic->ic_fixed_rate] & IEEE80211_RATE_VAL;
    911 		for (ix = ni->ni_rates.rs_nrates - 1;
    912 		     ix >= 0 && RATE(ix) != rate; ix--)
    913 			;
    914 		if (ix < 0) {
    915 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG,
    916 			    "%s: fixed rate %d (%d.%d Mb/s) not in rate set",
    917 			    __func__, ic->ic_fixed_rate, (rate * 5) / 10,
    918 			    (rate * 5) % 10);
    919 			goto no_rate;
    920 		}
    921 	} else if (ic->ic_state == IEEE80211_S_RUN) {
    922 		rate = ni->ni_rates.rs_rates[ni->ni_txrate];
    923 	} else {
    924 no_rate:
    925 		rs = &ni->ni_rates;
    926 		/* Choose node's lowest basic rate, or else its lowest rate. */
    927 		for (ix = 0; ix < rs->rs_nrates; ix++) {
    928 			if (rs->rs_rates[ix] & IEEE80211_RATE_BASIC)
    929 				return rs->rs_rates[ix] & IEEE80211_RATE_VAL;
    930 		}
    931 		return ni->ni_rates.rs_rates[0] & IEEE80211_RATE_VAL;
    932 	}
    933 
    934 	return rate & IEEE80211_RATE_VAL;
    935 }
    936 
    937 static struct ieee80211_node *
    938 node_alloc(struct ieee80211_node_table *nt)
    939 {
    940 	struct ieee80211_node *ni;
    941 
    942 	ni = malloc(sizeof(struct ieee80211_node),
    943 		M_80211_NODE, M_NOWAIT | M_ZERO);
    944 	return ni;
    945 }
    946 
    947 /*
    948  * Reclaim any resources in a node and reset any critical
    949  * state.  Typically nodes are free'd immediately after,
    950  * but in some cases the storage may be reused so we need
    951  * to insure consistent state (should probably fix that).
    952  */
    953 static void
    954 node_cleanup(struct ieee80211_node *ni)
    955 {
    956 #define	N(a)	(sizeof(a)/sizeof(a[0]))
    957 	struct ieee80211com *ic = ni->ni_ic;
    958 	int i, qlen;
    959 
    960 	/* NB: preserve ni_table */
    961 	if (ni->ni_flags & IEEE80211_NODE_PWR_MGT) {
    962 		ic->ic_ps_sta--;
    963 		ni->ni_flags &= ~IEEE80211_NODE_PWR_MGT;
    964 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
    965 		    "[%s] power save mode off, %u sta's in ps mode\n",
    966 		    ether_sprintf(ni->ni_macaddr), ic->ic_ps_sta);
    967 	}
    968 
    969 	/*
    970 	 * Clear AREF flag that marks the authorization refcnt bump
    971 	 * has happened.  This is probably not needed as the node
    972 	 * should always be removed from the table so not found but
    973 	 * do it just in case.
    974 	 */
    975 	ni->ni_flags &= ~IEEE80211_NODE_AREF;
    976 
    977 	/*
    978 	 * Drain power save queue and, if needed, clear TIM.
    979 	 */
    980 	IEEE80211_NODE_SAVEQ_DRAIN(ni, qlen);
    981 	if (qlen != 0 && ic->ic_set_tim != NULL)
    982 		ic->ic_set_tim(ni, 0);
    983 
    984 	ni->ni_associd = 0;
    985 	if (ni->ni_challenge != NULL) {
    986 		free(ni->ni_challenge, M_DEVBUF);
    987 		ni->ni_challenge = NULL;
    988 	}
    989 
    990 	/*
    991 	 * Preserve SSID, WPA, and WME ie's so the bss node is
    992 	 * reusable during a re-auth/re-assoc state transition.
    993 	 * If we remove these data they will not be recreated
    994 	 * because they come from a probe-response or beacon frame
    995 	 * which cannot be expected prior to the association-response.
    996 	 * This should not be an issue when operating in other modes
    997 	 * as stations leaving always go through a full state transition
    998 	 * which will rebuild this state.
    999 	 *
   1000 	 * XXX does this leave us open to inheriting old state?
   1001 	 */
   1002 	for (i = 0; i < N(ni->ni_rxfrag); i++) {
   1003 		m_freem(ni->ni_rxfrag[i]);
   1004 		ni->ni_rxfrag[i] = NULL;
   1005 	}
   1006 
   1007 	/*
   1008 	 * Must be careful here to remove any key map entry w/o a LOR.
   1009 	 */
   1010 	ieee80211_node_delucastkey(ni);
   1011 #undef N
   1012 }
   1013 
   1014 static void
   1015 node_free(struct ieee80211_node *ni)
   1016 {
   1017 	struct ieee80211com *ic = ni->ni_ic;
   1018 
   1019 	ic->ic_node_cleanup(ni);
   1020 	if (ni->ni_wpa_ie != NULL)
   1021 		free(ni->ni_wpa_ie, M_DEVBUF);
   1022 	if (ni->ni_wme_ie != NULL)
   1023 		free(ni->ni_wme_ie, M_DEVBUF);
   1024 	IEEE80211_NODE_SAVEQ_DESTROY(ni);
   1025 	free(ni, M_80211_NODE);
   1026 }
   1027 
   1028 static u_int8_t
   1029 node_getrssi(const struct ieee80211_node *ni)
   1030 {
   1031 	return ni->ni_rssi;
   1032 }
   1033 
   1034 static void
   1035 ieee80211_setup_node(struct ieee80211_node_table *nt,
   1036 	struct ieee80211_node *ni, const u_int8_t *macaddr)
   1037 {
   1038 	struct ieee80211com *ic = nt->nt_ic;
   1039 	int hash;
   1040 
   1041 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   1042 		"%s %p<%s> in %s table\n", __func__, ni,
   1043 		ether_sprintf(macaddr), nt->nt_name);
   1044 
   1045 	IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
   1046 	hash = IEEE80211_NODE_HASH(macaddr);
   1047 	ieee80211_node_initref(ni);		/* mark referenced */
   1048 	ni->ni_chan = IEEE80211_CHAN_ANYC;
   1049 	ni->ni_authmode = IEEE80211_AUTH_OPEN;
   1050 	ni->ni_txpower = ic->ic_txpowlimit;	/* max power */
   1051 	ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey, IEEE80211_KEYIX_NONE);
   1052 	ni->ni_inact_reload = nt->nt_inact_init;
   1053 	ni->ni_inact = ni->ni_inact_reload;
   1054 	IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
   1055 
   1056 	IEEE80211_NODE_LOCK(nt);
   1057 	TAILQ_INSERT_TAIL(&nt->nt_node, ni, ni_list);
   1058 	LIST_INSERT_HEAD(&nt->nt_hash[hash], ni, ni_hash);
   1059 	ni->ni_table = nt;
   1060 	ni->ni_ic = ic;
   1061 	IEEE80211_NODE_UNLOCK(nt);
   1062 }
   1063 
   1064 struct ieee80211_node *
   1065 ieee80211_alloc_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
   1066 {
   1067 	struct ieee80211com *ic = nt->nt_ic;
   1068 	struct ieee80211_node *ni;
   1069 
   1070 	ni = ic->ic_node_alloc(nt);
   1071 	if (ni != NULL)
   1072 		ieee80211_setup_node(nt, ni, macaddr);
   1073 	else
   1074 		ic->ic_stats.is_rx_nodealloc++;
   1075 	return ni;
   1076 }
   1077 
   1078 /*
   1079  * Craft a temporary node suitable for sending a management frame
   1080  * to the specified station.  We craft only as much state as we
   1081  * need to do the work since the node will be immediately reclaimed
   1082  * once the send completes.
   1083  */
   1084 struct ieee80211_node *
   1085 ieee80211_tmp_node(struct ieee80211com *ic, const u_int8_t *macaddr)
   1086 {
   1087 	struct ieee80211_node *ni;
   1088 
   1089 	ni = ic->ic_node_alloc(&ic->ic_sta);
   1090 	if (ni != NULL) {
   1091 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   1092 			"%s %p<%s>\n", __func__, ni, ether_sprintf(macaddr));
   1093 
   1094 		IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
   1095 		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
   1096 		ieee80211_node_initref(ni);		/* mark referenced */
   1097 		ni->ni_txpower = ic->ic_bss->ni_txpower;
   1098 		/* NB: required by ieee80211_fix_rate */
   1099 		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
   1100 		ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey,
   1101 			IEEE80211_KEYIX_NONE);
   1102 		/* XXX optimize away */
   1103 		IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
   1104 
   1105 		ni->ni_table = NULL;		/* NB: pedantic */
   1106 		ni->ni_ic = ic;
   1107 	} else {
   1108 		/* XXX msg */
   1109 		ic->ic_stats.is_rx_nodealloc++;
   1110 	}
   1111 	return ni;
   1112 }
   1113 
   1114 struct ieee80211_node *
   1115 ieee80211_dup_bss(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
   1116 {
   1117 	struct ieee80211com *ic = nt->nt_ic;
   1118 	struct ieee80211_node *ni;
   1119 
   1120 	ni = ic->ic_node_alloc(nt);
   1121 	if (ni != NULL) {
   1122 		ieee80211_setup_node(nt, ni, macaddr);
   1123 		/*
   1124 		 * Inherit from ic_bss.
   1125 		 */
   1126 		ni->ni_authmode = ic->ic_bss->ni_authmode;
   1127 		ni->ni_txpower = ic->ic_bss->ni_txpower;
   1128 		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
   1129 		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
   1130 		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
   1131 		ni->ni_rsn = ic->ic_bss->ni_rsn;
   1132 	} else {
   1133 		ic->ic_stats.is_rx_nodealloc++;
   1134 	}
   1135 	return ni;
   1136 }
   1137 
   1138 static struct ieee80211_node *
   1139 #ifdef IEEE80211_DEBUG_REFCNT
   1140 _ieee80211_find_node_debug(struct ieee80211_node_table *nt,
   1141 	const u_int8_t *macaddr, const char *func, int line)
   1142 #else
   1143 _ieee80211_find_node(struct ieee80211_node_table *nt,
   1144 	const u_int8_t *macaddr)
   1145 #endif
   1146 {
   1147 	struct ieee80211_node *ni;
   1148 	int hash;
   1149 
   1150 	IEEE80211_NODE_LOCK_ASSERT(nt);
   1151 
   1152 	hash = IEEE80211_NODE_HASH(macaddr);
   1153 	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
   1154 		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
   1155 			ieee80211_ref_node(ni);	/* mark referenced */
   1156 #ifdef IEEE80211_DEBUG_REFCNT
   1157 			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
   1158 			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
   1159 			    func, line,
   1160 			    ni, ether_sprintf(ni->ni_macaddr),
   1161 			    ieee80211_node_refcnt(ni));
   1162 #endif
   1163 			return ni;
   1164 		}
   1165 	}
   1166 	return NULL;
   1167 }
   1168 #ifdef IEEE80211_DEBUG_REFCNT
   1169 #define	_ieee80211_find_node(nt, mac) \
   1170 	_ieee80211_find_node_debug(nt, mac, func, line)
   1171 #endif
   1172 
   1173 struct ieee80211_node *
   1174 #ifdef IEEE80211_DEBUG_REFCNT
   1175 ieee80211_find_node_debug(struct ieee80211_node_table *nt,
   1176 	const u_int8_t *macaddr, const char *func, int line)
   1177 #else
   1178 ieee80211_find_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
   1179 #endif
   1180 {
   1181 	struct ieee80211_node *ni;
   1182 
   1183 	IEEE80211_NODE_LOCK(nt);
   1184 	ni = _ieee80211_find_node(nt, macaddr);
   1185 	IEEE80211_NODE_UNLOCK(nt);
   1186 	return ni;
   1187 }
   1188 
   1189 /*
   1190  * Fake up a node; this handles node discovery in adhoc mode.
   1191  * Note that for the driver's benefit we treat this like
   1192  * an association so the driver has an opportunity to setup
   1193  * its private state.
   1194  */
   1195 struct ieee80211_node *
   1196 ieee80211_fakeup_adhoc_node(struct ieee80211_node_table *nt,
   1197 	const u_int8_t macaddr[IEEE80211_ADDR_LEN])
   1198 {
   1199 	struct ieee80211com *ic = nt->nt_ic;
   1200 	struct ieee80211_node *ni;
   1201 
   1202 	ni = ieee80211_dup_bss(nt, macaddr);
   1203 	if (ni != NULL) {
   1204 		/* XXX no rate negotiation; just dup */
   1205 		ni->ni_rates = ic->ic_bss->ni_rates;
   1206 		if (ic->ic_newassoc != NULL)
   1207 			ic->ic_newassoc(ni, 1);
   1208 		/* XXX not right for 802.1x/WPA */
   1209 		ieee80211_node_authorize(ni);
   1210 	}
   1211 	return ni;
   1212 }
   1213 
   1214 #ifdef IEEE80211_DEBUG
   1215 static void
   1216 dump_probe_beacon(u_int8_t subtype, int isnew,
   1217 	const u_int8_t mac[IEEE80211_ADDR_LEN],
   1218 	const struct ieee80211_scanparams *sp)
   1219 {
   1220 
   1221 	printf("[%s] %s%s on chan %u (bss chan %u) ",
   1222 	    ether_sprintf(mac), isnew ? "new " : "",
   1223 	    ieee80211_mgt_subtype_name[subtype >> IEEE80211_FC0_SUBTYPE_SHIFT],
   1224 	    sp->sp_chan, sp->sp_bchan);
   1225 	ieee80211_print_essid(sp->sp_ssid + 2, sp->sp_ssid[1]);
   1226 	printf("\n");
   1227 
   1228 	if (isnew) {
   1229 		printf("[%s] caps 0x%x bintval %u erp 0x%x",
   1230 		    ether_sprintf(mac), sp->sp_capinfo, sp->sp_bintval,
   1231 		    sp->sp_erp);
   1232 		if (sp->sp_country != NULL) {
   1233 #ifdef __FreeBSD__
   1234 			printf(" country info %*D",
   1235 				sp->sp_country[1], sp->sp_country+2, " ");
   1236 #else
   1237 			int i;
   1238 			printf(" country info");
   1239 			for (i = 0; i < sp->sp_country[1]; i++)
   1240 				printf(" %02x", sp->sp_country[i+2]);
   1241 #endif
   1242 		}
   1243 		printf("\n");
   1244 	}
   1245 }
   1246 #endif /* IEEE80211_DEBUG */
   1247 
   1248 static void
   1249 saveie(u_int8_t **iep, const u_int8_t *ie)
   1250 {
   1251 
   1252 	if (ie == NULL)
   1253 		*iep = NULL;
   1254 	else
   1255 		ieee80211_saveie(iep, ie);
   1256 }
   1257 
   1258 /*
   1259  * Process a beacon or probe response frame.
   1260  */
   1261 void
   1262 ieee80211_add_scan(struct ieee80211com *ic,
   1263     const struct ieee80211_scanparams *sp, const struct ieee80211_frame *wh,
   1264     int subtype, int rssi, int rstamp)
   1265 {
   1266 #define	ISPROBE(_st)	((_st) == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
   1267 	struct ieee80211_node_table *nt = &ic->ic_scan;
   1268 	struct ieee80211_node *ni;
   1269 	int newnode = 0;
   1270 
   1271 	ni = ieee80211_find_node(nt, wh->i_addr2);
   1272 	if (ni == NULL) {
   1273 		/*
   1274 		 * Create a new entry.
   1275 		 */
   1276 		ni = ic->ic_node_alloc(nt);
   1277 		if (ni == NULL) {
   1278 			ic->ic_stats.is_rx_nodealloc++;
   1279 			return;
   1280 		}
   1281 		ieee80211_setup_node(nt, ni, wh->i_addr2);
   1282 
   1283 		/*
   1284 		 * XXX inherit from ic_bss.
   1285 		 */
   1286 		ni->ni_authmode = ic->ic_bss->ni_authmode;
   1287 		ni->ni_txpower = ic->ic_bss->ni_txpower;
   1288 		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
   1289 		ieee80211_set_chan(ic, ni, ic->ic_curchan);
   1290 		ni->ni_rsn = ic->ic_bss->ni_rsn;
   1291 		newnode = 1;
   1292 	}
   1293 
   1294 #ifdef IEEE80211_DEBUG
   1295 	if (ieee80211_msg_scan(ic) && (ic->ic_flags & IEEE80211_F_SCAN))
   1296 		dump_probe_beacon(subtype, newnode, wh->i_addr2, sp);
   1297 #endif
   1298 
   1299 	/* XXX ap beaconing multiple ssid w/ same bssid */
   1300 	if (sp->sp_ssid[1] != 0 && (ISPROBE(subtype) || ni->ni_esslen == 0)) {
   1301 		ni->ni_esslen = sp->sp_ssid[1];
   1302 		memset(ni->ni_essid, 0, sizeof(ni->ni_essid));
   1303 		memcpy(ni->ni_essid, sp->sp_ssid + 2, sp->sp_ssid[1]);
   1304 	}
   1305 
   1306 	ni->ni_scangen = ic->ic_scan.nt_scangen;
   1307 	IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
   1308 	ni->ni_rssi = rssi;
   1309 	ni->ni_rstamp = rstamp;
   1310 	memcpy(ni->ni_tstamp.data, sp->sp_tstamp, sizeof(ni->ni_tstamp));
   1311 	ni->ni_intval = sp->sp_bintval;
   1312 	ni->ni_capinfo = sp->sp_capinfo;
   1313 	ni->ni_chan = &ic->ic_channels[sp->sp_chan];
   1314 	ni->ni_fhdwell = sp->sp_fhdwell;
   1315 	ni->ni_fhindex = sp->sp_fhindex;
   1316 	ni->ni_erp = sp->sp_erp;
   1317 
   1318 	if (sp->sp_tim != NULL) {
   1319 		struct ieee80211_tim_ie *ie =
   1320 		    (struct ieee80211_tim_ie *)sp->sp_tim;
   1321 
   1322 		ni->ni_dtim_count = ie->tim_count;
   1323 		ni->ni_dtim_period = ie->tim_period;
   1324 	}
   1325 
   1326 	/*
   1327 	 * Record the byte offset from the mac header to
   1328 	 * the start of the TIM information element for
   1329 	 * use by hardware and/or to speedup software
   1330 	 * processing of beacon frames.
   1331 	 */
   1332 	ni->ni_timoff = sp->sp_timoff;
   1333 
   1334 	/*
   1335 	 * Record optional information elements that might be
   1336 	 * used by applications or drivers.
   1337 	 */
   1338 	saveie(&ni->ni_wme_ie, sp->sp_wme);
   1339 	saveie(&ni->ni_wpa_ie, sp->sp_wpa);
   1340 
   1341 	/* NB: must be after ni_chan is setup */
   1342 	ieee80211_setup_rates(ni, sp->sp_rates, sp->sp_xrates,
   1343 	    IEEE80211_R_DOSORT);
   1344 
   1345 	if (!newnode)
   1346 		ieee80211_free_node(ni);
   1347 #undef ISPROBE
   1348 }
   1349 
   1350 void
   1351 ieee80211_init_neighbor(struct ieee80211com *ic, struct ieee80211_node *ni,
   1352     const struct ieee80211_frame *wh, const struct ieee80211_scanparams *sp,
   1353     int isnew)
   1354 {
   1355 	ni->ni_esslen = sp->sp_ssid[1];
   1356 	memcpy(ni->ni_essid, sp->sp_ssid + 2, sp->sp_ssid[1]);
   1357 	IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
   1358 	memcpy(ni->ni_tstamp.data, sp->sp_tstamp, sizeof(ni->ni_tstamp));
   1359 	ni->ni_intval = sp->sp_bintval;
   1360 	ni->ni_capinfo = sp->sp_capinfo;
   1361 	ni->ni_chan = ic->ic_bss->ni_chan;
   1362 	ni->ni_fhdwell = sp->sp_fhdwell;
   1363 	ni->ni_fhindex = sp->sp_fhindex;
   1364 	ni->ni_erp = sp->sp_erp;
   1365 	ni->ni_timoff = sp->sp_timoff;
   1366 	if (sp->sp_wme != NULL)
   1367 		ieee80211_saveie(&ni->ni_wme_ie, sp->sp_wme);
   1368 	if (sp->sp_wpa != NULL)
   1369 		ieee80211_saveie(&ni->ni_wpa_ie, sp->sp_wpa);
   1370 
   1371 	/* NB: must be after ni_chan is setup */
   1372 	ieee80211_setup_rates(ni, sp->sp_rates, sp->sp_xrates,
   1373 	    IEEE80211_R_DODEL | IEEE80211_R_DONEGO | IEEE80211_R_DOSORT);
   1374 
   1375 	if (ic->ic_newassoc != NULL)
   1376 		ic->ic_newassoc(ni, isnew);
   1377 }
   1378 
   1379 /*
   1380  * Do node discovery in adhoc mode on receipt of a beacon
   1381  * or probe response frame.  Note that for the driver's
   1382  * benefit we treat this like an association so the
   1383  * driver has an opportunity to setup its private state.
   1384  */
   1385 struct ieee80211_node *
   1386 ieee80211_add_neighbor(struct ieee80211com *ic,
   1387 	const struct ieee80211_frame *wh,
   1388 	const struct ieee80211_scanparams *sp)
   1389 {
   1390 	struct ieee80211_node *ni;
   1391 
   1392 	ni = ieee80211_dup_bss(&ic->ic_sta, wh->i_addr2);/* XXX alloc_node? */
   1393 	if (ni != NULL) {
   1394 		ieee80211_init_neighbor(ic, ni, wh, sp, 1);
   1395 		/* XXX not right for 802.1x/WPA */
   1396 		ieee80211_node_authorize(ni);
   1397 	}
   1398 	return ni;
   1399 }
   1400 
   1401 #define	IS_CTL(wh) \
   1402 	((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_CTL)
   1403 #define	IS_PSPOLL(wh) \
   1404 	((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_PS_POLL)
   1405 /*
   1406  * Locate the node for sender, track state, and then pass the
   1407  * (referenced) node up to the 802.11 layer for its use.  We
   1408  * are required to pass some node so we fall back to ic_bss
   1409  * when this frame is from an unknown sender.  The 802.11 layer
   1410  * knows this means the sender wasn't in the node table and
   1411  * acts accordingly.
   1412  */
   1413 struct ieee80211_node *
   1414 #ifdef IEEE80211_DEBUG_REFCNT
   1415 ieee80211_find_rxnode_debug(struct ieee80211com *ic,
   1416 	const struct ieee80211_frame_min *wh, const char *func, int line)
   1417 #else
   1418 ieee80211_find_rxnode(struct ieee80211com *ic,
   1419 	const struct ieee80211_frame_min *wh)
   1420 #endif
   1421 {
   1422 	struct ieee80211_node_table *nt;
   1423 	struct ieee80211_node *ni;
   1424 
   1425 	/* XXX may want scanned nodes in the neighbor table for adhoc */
   1426 	if (ic->ic_opmode == IEEE80211_M_STA ||
   1427 	    ic->ic_opmode == IEEE80211_M_MONITOR ||
   1428 	    (ic->ic_flags & IEEE80211_F_SCAN))
   1429 		nt = &ic->ic_scan;
   1430 	else
   1431 		nt = &ic->ic_sta;
   1432 
   1433 	/* XXX check ic_bss first in station mode */
   1434 	/* XXX 4-address frames? */
   1435 	IEEE80211_NODE_LOCK(nt);
   1436 	if (IS_CTL(wh) && !IS_PSPOLL(wh) /*&& !IS_RTS(ah)*/)
   1437 		ni = _ieee80211_find_node(nt, wh->i_addr1);
   1438 	else
   1439 		ni = _ieee80211_find_node(nt, wh->i_addr2);
   1440 	if (ni == NULL)
   1441 		ni = ieee80211_ref_node(ic->ic_bss);
   1442 	IEEE80211_NODE_UNLOCK(nt);
   1443 
   1444 	return ni;
   1445 }
   1446 
   1447 /*
   1448  * Like ieee80211_find_rxnode but use the supplied h/w
   1449  * key index as a hint to locate the node in the key
   1450  * mapping table.  If an entry is present at the key
   1451  * index we return it; otherwise do a normal lookup and
   1452  * update the mapping table if the station has a unicast
   1453  * key assigned to it.
   1454  */
   1455 struct ieee80211_node *
   1456 #ifdef IEEE80211_DEBUG_REFCNT
   1457 ieee80211_find_rxnode_withkey_debug(struct ieee80211com *ic,
   1458 	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix,
   1459 	const char *func, int line)
   1460 #else
   1461 ieee80211_find_rxnode_withkey(struct ieee80211com *ic,
   1462 	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix)
   1463 #endif
   1464 {
   1465 	struct ieee80211_node_table *nt;
   1466 	struct ieee80211_node *ni;
   1467 
   1468 	if (ic->ic_opmode == IEEE80211_M_STA ||
   1469 	    ic->ic_opmode == IEEE80211_M_MONITOR ||
   1470 	    (ic->ic_flags & IEEE80211_F_SCAN)) {
   1471 		nt = &ic->ic_scan;
   1472 	} else {
   1473 		nt = &ic->ic_sta;
   1474 	}
   1475 
   1476 	IEEE80211_NODE_LOCK(nt);
   1477 	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax) {
   1478 		ni = nt->nt_keyixmap[keyix];
   1479 	} else {
   1480 		ni = NULL;
   1481 	}
   1482 	if (ni == NULL) {
   1483 		if (IS_CTL(wh) && !IS_PSPOLL(wh) /*&& !IS_RTS(ah)*/)
   1484 			ni = _ieee80211_find_node(nt, wh->i_addr1);
   1485 		else
   1486 			ni = _ieee80211_find_node(nt, wh->i_addr2);
   1487 		if (ni == NULL)
   1488 			ni = ieee80211_ref_node(ic->ic_bss);
   1489 		if (nt->nt_keyixmap != NULL) {
   1490 			/*
   1491 			 * If the station has a unicast key cache slot
   1492 			 * assigned update the key->node mapping table.
   1493 			 */
   1494 			keyix = ni->ni_ucastkey.wk_rxkeyix;
   1495 			/* XXX can keyixmap[keyix] != NULL? */
   1496 			if (keyix < nt->nt_keyixmax &&
   1497 			    nt->nt_keyixmap[keyix] == NULL) {
   1498 				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
   1499 				    "%s: add key map entry %p<%s> refcnt %d\n",
   1500 				    __func__, ni, ether_sprintf(ni->ni_macaddr),
   1501 				    ieee80211_node_refcnt(ni)+1);
   1502 				nt->nt_keyixmap[keyix] = ieee80211_ref_node(ni);
   1503 			}
   1504 		}
   1505 	} else {
   1506 		ieee80211_ref_node(ni);
   1507 	}
   1508 	IEEE80211_NODE_UNLOCK(nt);
   1509 
   1510 	return ni;
   1511 }
   1512 #undef IS_PSPOLL
   1513 #undef IS_CTL
   1514 
   1515 /*
   1516  * Return a reference to the appropriate node for sending
   1517  * a data frame.  This handles node discovery in adhoc networks.
   1518  */
   1519 struct ieee80211_node *
   1520 #ifdef IEEE80211_DEBUG_REFCNT
   1521 ieee80211_find_txnode_debug(struct ieee80211com *ic, const u_int8_t *macaddr,
   1522 	const char *func, int line)
   1523 #else
   1524 ieee80211_find_txnode(struct ieee80211com *ic, const u_int8_t *macaddr)
   1525 #endif
   1526 {
   1527 	struct ieee80211_node_table *nt = &ic->ic_sta;
   1528 	struct ieee80211_node *ni;
   1529 
   1530 	/*
   1531 	 * The destination address should be in the node table
   1532 	 * unless this is a multicast/broadcast frame.  We can
   1533 	 * also optimize station mode operation, all frames go
   1534 	 * to the bss node.
   1535 	 */
   1536 	/* XXX can't hold lock across dup_bss 'cuz of recursive locking */
   1537 	IEEE80211_NODE_LOCK(nt);
   1538 	if (ic->ic_opmode == IEEE80211_M_STA || IEEE80211_IS_MULTICAST(macaddr))
   1539 		ni = ieee80211_ref_node(ic->ic_bss);
   1540 	else
   1541 		ni = _ieee80211_find_node(nt, macaddr);
   1542 	IEEE80211_NODE_UNLOCK(nt);
   1543 
   1544 	if (ni == NULL) {
   1545 		if (ic->ic_opmode == IEEE80211_M_IBSS ||
   1546 		    ic->ic_opmode == IEEE80211_M_AHDEMO) {
   1547 			/*
   1548 			 * In adhoc mode cons up a node for the destination.
   1549 			 * Note that we need an additional reference for the
   1550 			 * caller to be consistent with _ieee80211_find_node.
   1551 			 */
   1552 			ni = ieee80211_fakeup_adhoc_node(nt, macaddr);
   1553 			if (ni != NULL)
   1554 				(void)ieee80211_ref_node(ni);
   1555 		} else {
   1556 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
   1557 				"[%s] no node, discard frame (%s)\n",
   1558 				ether_sprintf(macaddr), __func__);
   1559 			ic->ic_stats.is_tx_nonode++;
   1560 		}
   1561 	}
   1562 	return ni;
   1563 }
   1564 
   1565 /*
   1566  * Like find but search based on the channel too.
   1567  */
   1568 struct ieee80211_node *
   1569 #ifdef IEEE80211_DEBUG_REFCNT
   1570 ieee80211_find_node_with_channel_debug(struct ieee80211_node_table *nt,
   1571 	const u_int8_t *macaddr, struct ieee80211_channel *chan,
   1572 	const char *func, int line)
   1573 #else
   1574 ieee80211_find_node_with_channel(struct ieee80211_node_table *nt,
   1575 	const u_int8_t *macaddr, struct ieee80211_channel *chan)
   1576 #endif
   1577 {
   1578 	struct ieee80211_node *ni;
   1579 	int hash;
   1580 
   1581 	hash = IEEE80211_NODE_HASH(macaddr);
   1582 
   1583 	IEEE80211_NODE_LOCK(nt);
   1584 	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
   1585 		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
   1586 		    ni->ni_chan == chan) {
   1587 			ieee80211_ref_node(ni);		/* mark referenced */
   1588 #ifdef IEEE80211_DEBUG_REFCNT
   1589 			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
   1590 			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
   1591 			    func, line,
   1592 			    ni, ether_sprintf(ni->ni_macaddr),
   1593 			    ieee80211_node_refcnt(ni));
   1594 #else
   1595 			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
   1596 			    "%s %p<%s> refcnt %d\n", __func__,
   1597 			    ni, ether_sprintf(ni->ni_macaddr),
   1598 			    ieee80211_node_refcnt(ni));
   1599 #endif
   1600 			break;
   1601 		}
   1602 	}
   1603 	IEEE80211_NODE_UNLOCK(nt);
   1604 
   1605 	return ni;
   1606 }
   1607 
   1608 struct ieee80211_node *
   1609 ieee80211_refine_node_for_beacon(struct ieee80211com *ic,
   1610 	struct ieee80211_node *ni0, struct ieee80211_channel *chan,
   1611 	const u_int8_t *ssid)
   1612 {
   1613 	struct ieee80211_node_table *nt = ni0->ni_table;
   1614 	struct ieee80211_node *best, *ni;
   1615 	int best_score = 0, score;
   1616 
   1617 	if (nt == NULL)
   1618 		return ni0;
   1619 
   1620 	best = ni0;
   1621 	if (ssid[1] == 0 || best->ni_esslen == 0)
   1622 		best_score = 1;
   1623 	else if (ssid[1] == best->ni_esslen &&
   1624 		 memcmp(ssid + 2, best->ni_essid, ssid[1]) == 0)
   1625 		best_score = 2;
   1626 	else
   1627 		best_score = 0;
   1628 
   1629 	IEEE80211_NODE_LOCK(nt);
   1630 	for (ni = LIST_NEXT(ni0, ni_hash); ni != NULL;
   1631 	     ni = LIST_NEXT(ni, ni_hash)) {
   1632 		if (!IEEE80211_ADDR_EQ(ni->ni_macaddr, best->ni_macaddr) ||
   1633 		    ni->ni_ic != best->ni_ic || ni->ni_chan != chan)
   1634 			continue;
   1635 
   1636 		if (ssid[1] == 0 || ni->ni_esslen == 0)
   1637 			score = 1;
   1638 		else if (ssid[1] == ni->ni_esslen &&
   1639 			 memcmp(ssid + 2, ni->ni_essid, ssid[1]) == 0)
   1640 			score = 2;
   1641 		else
   1642 			continue;
   1643 
   1644 		if (score > best_score) {
   1645 			best = ni;
   1646 			best_score = score;
   1647 		}
   1648 	}
   1649 	IEEE80211_NODE_UNLOCK(nt);
   1650 
   1651 	return best;
   1652 }
   1653 
   1654 /*
   1655  * Like find but search based on the ssid too.
   1656  */
   1657 struct ieee80211_node *
   1658 #ifdef IEEE80211_DEBUG_REFCNT
   1659 ieee80211_find_node_with_ssid_debug(struct ieee80211_node_table *nt,
   1660 	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid,
   1661 	const char *func, int line)
   1662 #else
   1663 ieee80211_find_node_with_ssid(struct ieee80211_node_table *nt,
   1664 	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid)
   1665 #endif
   1666 {
   1667 #define	MATCH_SSID(ni, ssid, ssidlen) \
   1668 	(ni->ni_esslen == ssidlen && memcmp(ni->ni_essid, ssid, ssidlen) == 0)
   1669 	static const u_int8_t zeromac[IEEE80211_ADDR_LEN];
   1670 	struct ieee80211com *ic = nt->nt_ic;
   1671 	struct ieee80211_node *ni;
   1672 	int hash;
   1673 
   1674 	IEEE80211_NODE_LOCK(nt);
   1675 	__USE(ic);
   1676 
   1677 	/*
   1678 	 * A mac address that is all zero means match only the ssid;
   1679 	 * otherwise we must match both.
   1680 	 */
   1681 	if (IEEE80211_ADDR_EQ(macaddr, zeromac)) {
   1682 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
   1683 			if (MATCH_SSID(ni, ssid, ssidlen))
   1684 				break;
   1685 		}
   1686 	} else {
   1687 		hash = IEEE80211_NODE_HASH(macaddr);
   1688 		LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
   1689 			if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
   1690 			    MATCH_SSID(ni, ssid, ssidlen))
   1691 				break;
   1692 		}
   1693 	}
   1694 	if (ni != NULL) {
   1695 		ieee80211_ref_node(ni);	/* mark referenced */
   1696 #ifdef IEEE80211_DEBUG_REFCNT
   1697 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   1698 		    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
   1699 		    func, line,
   1700 		     ni, ether_sprintf(ni->ni_macaddr),
   1701 		     ieee80211_node_refcnt(ni));
   1702 #else
   1703 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   1704 		    "%s %p<%s> refcnt %d\n", __func__,
   1705 		     ni, ether_sprintf(ni->ni_macaddr),
   1706 		     ieee80211_node_refcnt(ni));
   1707 #endif
   1708 	}
   1709 
   1710 	IEEE80211_NODE_UNLOCK(nt);
   1711 
   1712 	return ni;
   1713 #undef MATCH_SSID
   1714 }
   1715 
   1716 static void
   1717 _ieee80211_free_node(struct ieee80211_node *ni)
   1718 {
   1719 	struct ieee80211com *ic = ni->ni_ic;
   1720 	struct ieee80211_node_table *nt = ni->ni_table;
   1721 
   1722 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   1723 		"%s %p<%s> in %s table\n", __func__, ni,
   1724 		ether_sprintf(ni->ni_macaddr),
   1725 		nt != NULL ? nt->nt_name : "<gone>");
   1726 
   1727 	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
   1728 	if (nt != NULL) {
   1729 		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
   1730 		LIST_REMOVE(ni, ni_hash);
   1731 	}
   1732 	ic->ic_node_free(ni);
   1733 }
   1734 
   1735 void
   1736 #ifdef IEEE80211_DEBUG_REFCNT
   1737 ieee80211_free_node_debug(struct ieee80211_node *ni, const char *func, int line)
   1738 #else
   1739 ieee80211_free_node(struct ieee80211_node *ni)
   1740 #endif
   1741 {
   1742 	struct ieee80211_node_table *nt = ni->ni_table;
   1743 
   1744 #ifdef IEEE80211_DEBUG_REFCNT
   1745 	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
   1746 		"%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line, ni,
   1747 		 ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)-1);
   1748 #endif
   1749 
   1750 	if (nt != NULL) {
   1751 		IEEE80211_NODE_LOCK(nt);
   1752 		if (ieee80211_node_dectestref(ni)) {
   1753 			/*
   1754 			 * Last reference, reclaim state.
   1755 			 */
   1756 			_ieee80211_free_node(ni);
   1757 		} else if (ieee80211_node_refcnt(ni) == 1 &&
   1758 		    nt->nt_keyixmap != NULL) {
   1759 			ieee80211_keyix keyix;
   1760 
   1761 			/*
   1762 			 * Check for a last reference in the key mapping table.
   1763 			 */
   1764 			keyix = ni->ni_ucastkey.wk_rxkeyix;
   1765 			if (keyix < nt->nt_keyixmax &&
   1766 			    nt->nt_keyixmap[keyix] == ni) {
   1767 				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
   1768 				    "%s: %p<%s> clear key map entry", __func__,
   1769 				    ni, ether_sprintf(ni->ni_macaddr));
   1770 				nt->nt_keyixmap[keyix] = NULL;
   1771 				ieee80211_node_decref(ni); /* XXX needed? */
   1772 				_ieee80211_free_node(ni);
   1773 			}
   1774 		}
   1775 		IEEE80211_NODE_UNLOCK(nt);
   1776 	} else {
   1777 		if (ieee80211_node_dectestref(ni))
   1778 			_ieee80211_free_node(ni);
   1779 	}
   1780 }
   1781 
   1782 /*
   1783  * Reclaim a unicast key and clear any key cache state.
   1784  */
   1785 int
   1786 ieee80211_node_delucastkey(struct ieee80211_node *ni)
   1787 {
   1788 	struct ieee80211com *ic = ni->ni_ic;
   1789 	struct ieee80211_node_table *nt = &ic->ic_sta;
   1790 	struct ieee80211_node *nikey;
   1791 	ieee80211_keyix keyix;
   1792 	int isowned, status;
   1793 
   1794 	/*
   1795 	 * NB: We must beware of LOR here; deleting the key
   1796 	 * can cause the crypto layer to block traffic updates
   1797 	 * which can generate a LOR against the node table lock;
   1798 	 * grab it here and stash the key index for our use below.
   1799 	 *
   1800 	 * Must also beware of recursion on the node table lock.
   1801 	 * When called from node_cleanup we may already have
   1802 	 * the node table lock held.  Unfortunately there's no
   1803 	 * way to separate out this path so we must do this
   1804 	 * conditionally.
   1805 	 */
   1806 	isowned = IEEE80211_NODE_IS_LOCKED(nt);
   1807 	if (!isowned)
   1808 		IEEE80211_NODE_LOCK(nt);
   1809 	keyix = ni->ni_ucastkey.wk_rxkeyix;
   1810 	status = ieee80211_crypto_delkey(ic, &ni->ni_ucastkey);
   1811 	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax) {
   1812 		nikey = nt->nt_keyixmap[keyix];
   1813 		nt->nt_keyixmap[keyix] = NULL;
   1814 	} else
   1815 		nikey = NULL;
   1816 	if (!isowned)
   1817 		IEEE80211_NODE_UNLOCK(&ic->ic_sta);
   1818 
   1819 	if (nikey != NULL) {
   1820 		IASSERT(nikey == ni,
   1821 			("key map out of sync, ni %p nikey %p", ni, nikey));
   1822 		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
   1823 			"%s: delete key map entry %p<%s> refcnt %d\n",
   1824 			__func__, ni, ether_sprintf(ni->ni_macaddr),
   1825 			ieee80211_node_refcnt(ni)-1);
   1826 		ieee80211_free_node(ni);
   1827 	}
   1828 	return status;
   1829 }
   1830 
   1831 /*
   1832  * Reclaim a node.  If this is the last reference count then
   1833  * do the normal free work.  Otherwise remove it from the node
   1834  * table and mark it gone by clearing the back-reference.
   1835  */
   1836 static void
   1837 node_reclaim(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
   1838 {
   1839 	ieee80211_keyix keyix;
   1840 
   1841 	IEEE80211_NODE_LOCK_ASSERT(nt);
   1842 
   1843 	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
   1844 		"%s: remove %p<%s> from %s table, refcnt %d\n",
   1845 		__func__, ni, ether_sprintf(ni->ni_macaddr),
   1846 		nt->nt_name, ieee80211_node_refcnt(ni)-1);
   1847 	/*
   1848 	 * Clear any entry in the unicast key mapping table.
   1849 	 * We need to do it here so rx lookups don't find it
   1850 	 * in the mapping table even if it's not in the hash
   1851 	 * table.  We cannot depend on the mapping table entry
   1852 	 * being cleared because the node may not be free'd.
   1853 	 */
   1854 	keyix = ni->ni_ucastkey.wk_rxkeyix;
   1855 	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax &&
   1856 	    nt->nt_keyixmap[keyix] == ni) {
   1857 		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
   1858 			"%s: %p<%s> clear key map entry\n",
   1859 			__func__, ni, ether_sprintf(ni->ni_macaddr));
   1860 		nt->nt_keyixmap[keyix] = NULL;
   1861 		ieee80211_node_decref(ni);	/* NB: don't need free */
   1862 	}
   1863 	if (!ieee80211_node_dectestref(ni)) {
   1864 		/*
   1865 		 * Other references are present, just remove the
   1866 		 * node from the table so it cannot be found.  When
   1867 		 * the references are dropped storage will be
   1868 		 * reclaimed.
   1869 		 */
   1870 		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
   1871 		LIST_REMOVE(ni, ni_hash);
   1872 		ni->ni_table = NULL;		/* clear reference */
   1873 	} else
   1874 		_ieee80211_free_node(ni);
   1875 }
   1876 
   1877 static void
   1878 ieee80211_free_allnodes_locked(struct ieee80211_node_table *nt)
   1879 {
   1880 	struct ieee80211com *ic = nt->nt_ic;
   1881 	struct ieee80211_node *ni;
   1882 
   1883 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   1884 		"%s: free all nodes in %s table\n", __func__, nt->nt_name);
   1885 
   1886 	while ((ni = TAILQ_FIRST(&nt->nt_node)) != NULL) {
   1887 		if (ni->ni_associd != 0) {
   1888 			if (ic->ic_auth->ia_node_leave != NULL)
   1889 				ic->ic_auth->ia_node_leave(ic, ni);
   1890 			IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
   1891 		}
   1892 		node_reclaim(nt, ni);
   1893 	}
   1894 	ieee80211_reset_erp(ic);
   1895 }
   1896 
   1897 static void
   1898 ieee80211_free_allnodes(struct ieee80211_node_table *nt)
   1899 {
   1900 
   1901 	IEEE80211_NODE_LOCK(nt);
   1902 	ieee80211_free_allnodes_locked(nt);
   1903 	IEEE80211_NODE_UNLOCK(nt);
   1904 }
   1905 
   1906 /*
   1907  * Timeout entries in the scan cache.
   1908  */
   1909 static void
   1910 ieee80211_timeout_scan_candidates(struct ieee80211_node_table *nt)
   1911 {
   1912 	struct ieee80211com *ic = nt->nt_ic;
   1913 	struct ieee80211_node *ni, *tni;
   1914 
   1915 	IEEE80211_NODE_LOCK(nt);
   1916 	ni = ic->ic_bss;
   1917 	/* XXX belongs elsewhere */
   1918 	if (ni->ni_rxfrag[0] != NULL && ticks > ni->ni_rxfragstamp + hz) {
   1919 		m_freem(ni->ni_rxfrag[0]);
   1920 		ni->ni_rxfrag[0] = NULL;
   1921 	}
   1922 	TAILQ_FOREACH_SAFE(ni, &nt->nt_node, ni_list, tni) {
   1923 		if (ni->ni_inact && --ni->ni_inact == 0) {
   1924 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   1925 			    "[%s] scan candidate purged from cache "
   1926 			    "(refcnt %u)\n", ether_sprintf(ni->ni_macaddr),
   1927 			    ieee80211_node_refcnt(ni));
   1928 			node_reclaim(nt, ni);
   1929 		}
   1930 	}
   1931 	IEEE80211_NODE_UNLOCK(nt);
   1932 
   1933 	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
   1934 }
   1935 
   1936 /*
   1937  * Timeout inactive stations and do related housekeeping.
   1938  * Note that we cannot hold the node lock while sending a
   1939  * frame as this would lead to a LOR.  Instead we use a
   1940  * generation number to mark nodes that we've scanned and
   1941  * drop the lock and restart a scan if we have to time out
   1942  * a node.  Since we are single-threaded by virtue of
   1943  * controlling the inactivity timer we can be sure this will
   1944  * process each node only once.
   1945  */
   1946 static void
   1947 ieee80211_timeout_stations(struct ieee80211_node_table *nt)
   1948 {
   1949 	struct ieee80211com *ic = nt->nt_ic;
   1950 	struct ieee80211_node *ni;
   1951 	u_int gen;
   1952 	int isadhoc;
   1953 
   1954 	isadhoc = (ic->ic_opmode == IEEE80211_M_IBSS ||
   1955 		   ic->ic_opmode == IEEE80211_M_AHDEMO);
   1956 	IEEE80211_SCAN_LOCK(nt);
   1957 	gen = ++nt->nt_scangen;
   1958 	IEEE80211_SCAN_UNLOCK(nt);
   1959 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   1960 		"%s: %s scangen %u\n", __func__, nt->nt_name, gen);
   1961 restart:
   1962 	IEEE80211_SCAN_LOCK(nt);
   1963 	if (gen != nt->nt_scangen) {
   1964 		printf("%s: scan aborted %u\n", __func__, gen);
   1965 		IEEE80211_SCAN_UNLOCK(nt);
   1966 		return;
   1967 	}
   1968 	IEEE80211_SCAN_UNLOCK(nt);
   1969 
   1970 	IEEE80211_NODE_LOCK(nt);
   1971 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
   1972 		if (ni->ni_scangen == gen)	/* previously handled */
   1973 			continue;
   1974 		ni->ni_scangen = gen;
   1975 		/*
   1976 		 * Ignore entries for which have yet to receive an
   1977 		 * authentication frame.  These are transient and
   1978 		 * will be reclaimed when the last reference to them
   1979 		 * goes away (when frame xmits complete).
   1980 		 */
   1981 		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
   1982 		    (ni->ni_flags & IEEE80211_NODE_AREF) == 0)
   1983 			continue;
   1984 		/*
   1985 		 * Free fragment if not needed anymore
   1986 		 * (last fragment older than 1s).
   1987 		 * XXX doesn't belong here
   1988 		 */
   1989 		if (ni->ni_rxfrag[0] != NULL &&
   1990 		    ticks > ni->ni_rxfragstamp + hz) {
   1991 			m_freem(ni->ni_rxfrag[0]);
   1992 			ni->ni_rxfrag[0] = NULL;
   1993 		}
   1994 		/*
   1995 		 * Special case ourself; we may be idle for extended periods
   1996 		 * of time and regardless reclaiming our state is wrong.
   1997 		 */
   1998 		if (ni == ic->ic_bss)
   1999 			continue;
   2000 		ni->ni_inact--;
   2001 		if (ni->ni_associd != 0 || isadhoc) {
   2002 			/*
   2003 			 * Age frames on the power save queue. The
   2004 			 * aging interval is 4 times the listen
   2005 			 * interval specified by the station.  This
   2006 			 * number is factored into the age calculations
   2007 			 * when the frame is placed on the queue.  We
   2008 			 * store ages as time differences we can check
   2009 			 * and/or adjust only the head of the list.
   2010 			 */
   2011 			if (IEEE80211_NODE_SAVEQ_QLEN(ni) != 0) {
   2012 				struct mbuf *m;
   2013 				int discard = 0;
   2014 
   2015 				IEEE80211_NODE_SAVEQ_LOCK(ni);
   2016 				while (IF_POLL(&ni->ni_savedq, m) != NULL &&
   2017 				     M_AGE_GET(m) < IEEE80211_INACT_WAIT) {
   2018 IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER, "[%s] discard frame, age %u\n", ether_sprintf(ni->ni_macaddr), M_AGE_GET(m));/*XXX*/
   2019 					_IEEE80211_NODE_SAVEQ_DEQUEUE_HEAD(ni, m);
   2020 					m_freem(m);
   2021 					discard++;
   2022 				}
   2023 				if (m != NULL)
   2024 					M_AGE_SUB(m, IEEE80211_INACT_WAIT);
   2025 				IEEE80211_NODE_SAVEQ_UNLOCK(ni);
   2026 
   2027 				if (discard != 0) {
   2028 					IEEE80211_DPRINTF(ic,
   2029 					    IEEE80211_MSG_POWER,
   2030 					    "[%s] discard %u frames for age\n",
   2031 					    ether_sprintf(ni->ni_macaddr),
   2032 					    discard);
   2033 					IEEE80211_NODE_STAT_ADD(ni,
   2034 						ps_discard, discard);
   2035 					if (IEEE80211_NODE_SAVEQ_QLEN(ni) == 0)
   2036 						ic->ic_set_tim(ni, 0);
   2037 				}
   2038 			}
   2039 			/*
   2040 			 * Probe the station before time it out.  We
   2041 			 * send a null data frame which may not be
   2042 			 * universally supported by drivers (need it
   2043 			 * for ps-poll support so it should be...).
   2044 			 */
   2045 			if (0 < ni->ni_inact &&
   2046 			    ni->ni_inact <= ic->ic_inact_probe) {
   2047 				IEEE80211_NOTE(ic,
   2048 				    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE,
   2049 				    ni, "%s",
   2050 				    "probe station due to inactivity");
   2051 				/*
   2052 				 * Grab a reference before unlocking the table
   2053 				 * so the node cannot be reclaimed before we
   2054 				 * send the frame. ieee80211_send_nulldata
   2055 				 * understands we've done this and reclaims the
   2056 				 * ref for us as needed.
   2057 				 */
   2058 				ieee80211_ref_node(ni);
   2059 				IEEE80211_NODE_UNLOCK(nt);
   2060 				ieee80211_send_nulldata(ni);
   2061 				/* XXX stat? */
   2062 				goto restart;
   2063 			}
   2064 		}
   2065 		if (ni->ni_inact <= 0) {
   2066 			IEEE80211_NOTE(ic,
   2067 			    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE, ni,
   2068 			    "station timed out due to inactivity "
   2069 			    "(refcnt %u)", ieee80211_node_refcnt(ni));
   2070 			/*
   2071 			 * Send a deauthenticate frame and drop the station.
   2072 			 * This is somewhat complicated due to reference counts
   2073 			 * and locking.  At this point a station will typically
   2074 			 * have a reference count of 1.  ieee80211_node_leave
   2075 			 * will do a "free" of the node which will drop the
   2076 			 * reference count.  But in the meantime a reference
   2077 			 * will be held by the deauth frame.  The actual reclaim
   2078 			 * of the node will happen either after the tx is
   2079 			 * completed or by ieee80211_node_leave.
   2080 			 *
   2081 			 * Separately we must drop the node lock before sending
   2082 			 * in case the driver takes a lock, as this will result
   2083 			 * in  LOR between the node lock and the driver lock.
   2084 			 */
   2085 			IEEE80211_NODE_UNLOCK(nt);
   2086 			if (ni->ni_associd != 0) {
   2087 				IEEE80211_SEND_MGMT(ic, ni,
   2088 				    IEEE80211_FC0_SUBTYPE_DEAUTH,
   2089 				    IEEE80211_REASON_AUTH_EXPIRE);
   2090 			}
   2091 			ieee80211_node_leave(ic, ni);
   2092 			ic->ic_stats.is_node_timeout++;
   2093 			goto restart;
   2094 		}
   2095 	}
   2096 	IEEE80211_NODE_UNLOCK(nt);
   2097 
   2098 	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
   2099 }
   2100 
   2101 void
   2102 ieee80211_iterate_nodes(struct ieee80211_node_table *nt, ieee80211_iter_func *f, void *arg)
   2103 {
   2104 	struct ieee80211_node *ni;
   2105 	u_int gen;
   2106 
   2107 	IEEE80211_SCAN_LOCK(nt);
   2108 	gen = ++nt->nt_scangen;
   2109 	IEEE80211_SCAN_UNLOCK(nt);
   2110 restart:
   2111 	IEEE80211_SCAN_LOCK(nt);
   2112 	if (gen != nt->nt_scangen) {
   2113 		printf("%s: scan aborted %u\n", __func__, gen);
   2114 		IEEE80211_SCAN_UNLOCK(nt);
   2115 		return;
   2116 	}
   2117 	IEEE80211_SCAN_UNLOCK(nt);
   2118 
   2119 	IEEE80211_NODE_LOCK(nt);
   2120 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
   2121 		if (ni->ni_scangen != gen) {
   2122 			ni->ni_scangen = gen;
   2123 			(void) ieee80211_ref_node(ni);
   2124 			IEEE80211_NODE_UNLOCK(nt);
   2125 			(*f)(arg, ni);
   2126 			ieee80211_free_node(ni);
   2127 			goto restart;
   2128 		}
   2129 	}
   2130 	IEEE80211_NODE_UNLOCK(nt);
   2131 }
   2132 
   2133 void
   2134 ieee80211_dump_node(struct ieee80211_node_table *nt,
   2135     struct ieee80211_node *ni)
   2136 {
   2137 	printf("%p: mac %s refcnt %d\n", ni,
   2138 		ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni));
   2139 	printf("\tscangen %u authmode %u flags 0x%x\n",
   2140 		ni->ni_scangen, ni->ni_authmode, ni->ni_flags);
   2141 	printf("\tassocid 0x%x txpower %u vlan %u\n",
   2142 		ni->ni_associd, ni->ni_txpower, ni->ni_vlan);
   2143 	printf("\ttxseq %u rxseq %u fragno %u rxfragstamp %u\n",
   2144 		ni->ni_txseqs[0],
   2145 		ni->ni_rxseqs[0] >> IEEE80211_SEQ_SEQ_SHIFT,
   2146 		ni->ni_rxseqs[0] & IEEE80211_SEQ_FRAG_MASK,
   2147 		ni->ni_rxfragstamp);
   2148 	printf("\trstamp %u rssi %u intval %u capinfo 0x%x\n",
   2149 		ni->ni_rstamp, ni->ni_rssi, ni->ni_intval, ni->ni_capinfo);
   2150 	printf("\tbssid %s essid \"%.*s\" channel %u:0x%x\n",
   2151 		ether_sprintf(ni->ni_bssid),
   2152 		ni->ni_esslen, ni->ni_essid,
   2153 		ni->ni_chan->ic_freq, ni->ni_chan->ic_flags);
   2154 	printf("\tfails %u inact %u txrate %u\n",
   2155 		ni->ni_fails, ni->ni_inact, ni->ni_txrate);
   2156 }
   2157 
   2158 void
   2159 ieee80211_dump_nodes(struct ieee80211_node_table *nt)
   2160 {
   2161 	ieee80211_iterate_nodes(nt,
   2162 		(ieee80211_iter_func *) ieee80211_dump_node, nt);
   2163 }
   2164 
   2165 /*
   2166  * Handle a station joining an 11g network.
   2167  */
   2168 static void
   2169 ieee80211_node_join_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
   2170 {
   2171 
   2172 	/*
   2173 	 * Station isn't capable of short slot time.  Bump
   2174 	 * the count of long slot time stations and disable
   2175 	 * use of short slot time.  Note that the actual switch
   2176 	 * over to long slot time use may not occur until the
   2177 	 * next beacon transmission (per sec. 7.3.1.4 of 11g).
   2178 	 */
   2179 	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
   2180 		ic->ic_longslotsta++;
   2181 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
   2182 		    "[%s] station needs long slot time, count %d\n",
   2183 		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
   2184 		/* XXX vap's w/ conflicting needs won't work */
   2185 		ieee80211_set_shortslottime(ic, 0);
   2186 	}
   2187 
   2188 	/*
   2189 	 * If the new station is not an ERP station
   2190 	 * then bump the counter and enable protection
   2191 	 * if configured.
   2192 	 */
   2193 	if (!ieee80211_iserp_rateset(ic, &ni->ni_rates)) {
   2194 		ic->ic_nonerpsta++;
   2195 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
   2196 		    "[%s] station is !ERP, %d non-ERP stations associated\n",
   2197 		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
   2198 		/*
   2199 		 * If protection is configured, enable it.
   2200 		 */
   2201 		if (ic->ic_protmode != IEEE80211_PROT_NONE) {
   2202 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
   2203 			    "%s: enable use of protection\n", __func__);
   2204 			ic->ic_flags |= IEEE80211_F_USEPROT;
   2205 		}
   2206 		/*
   2207 		 * If station does not support short preamble
   2208 		 * then we must enable use of Barker preamble.
   2209 		 */
   2210 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE) == 0) {
   2211 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
   2212 			    "[%s] station needs long preamble\n",
   2213 			    ether_sprintf(ni->ni_macaddr));
   2214 			ic->ic_flags |= IEEE80211_F_USEBARKER;
   2215 			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
   2216 		}
   2217 	} else {
   2218 		ni->ni_flags |= IEEE80211_NODE_ERP;
   2219 	}
   2220 }
   2221 
   2222 void
   2223 ieee80211_node_join(struct ieee80211com *ic, struct ieee80211_node *ni,
   2224     int resp)
   2225 {
   2226 	int newassoc;
   2227 
   2228 	if (ni->ni_associd == 0) {
   2229 		u_int16_t aid;
   2230 
   2231 		/*
   2232 		 * It would be good to search the bitmap
   2233 		 * more efficiently, but this will do for now.
   2234 		 */
   2235 		for (aid = 1; aid < ic->ic_max_aid; aid++) {
   2236 			if (!IEEE80211_AID_ISSET(aid,
   2237 			    ic->ic_aid_bitmap))
   2238 				break;
   2239 		}
   2240 		if (aid >= ic->ic_max_aid) {
   2241 			IEEE80211_SEND_MGMT(ic, ni, resp,
   2242 			    IEEE80211_REASON_ASSOC_TOOMANY);
   2243 			ieee80211_node_leave(ic, ni);
   2244 			return;
   2245 		}
   2246 		ni->ni_associd = aid | 0xc000;
   2247 		IEEE80211_AID_SET(ni->ni_associd, ic->ic_aid_bitmap);
   2248 		ic->ic_sta_assoc++;
   2249 		newassoc = 1;
   2250 		if (ic->ic_curmode == IEEE80211_MODE_11G)
   2251 			ieee80211_node_join_11g(ic, ni);
   2252 	} else
   2253 		newassoc = 0;
   2254 
   2255 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
   2256 	    "[%s] station %sassociated at aid %d: %s preamble, %s slot time%s%s\n",
   2257 	    ether_sprintf(ni->ni_macaddr), newassoc ? "" : "re",
   2258 	    IEEE80211_NODE_AID(ni),
   2259 	    ic->ic_flags & IEEE80211_F_SHPREAMBLE ? "short" : "long",
   2260 	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long",
   2261 	    ic->ic_flags & IEEE80211_F_USEPROT ? ", protection" : "",
   2262 	    ni->ni_flags & IEEE80211_NODE_QOS ? ", QoS" : ""
   2263 	);
   2264 
   2265 	/* give driver a chance to setup state like ni_txrate */
   2266 	if (ic->ic_newassoc != NULL)
   2267 		ic->ic_newassoc(ni, newassoc);
   2268 	ni->ni_inact_reload = ic->ic_inact_auth;
   2269 	ni->ni_inact = ni->ni_inact_reload;
   2270 	IEEE80211_SEND_MGMT(ic, ni, resp, IEEE80211_STATUS_SUCCESS);
   2271 	/* tell the authenticator about new station */
   2272 	if (ic->ic_auth->ia_node_join != NULL)
   2273 		ic->ic_auth->ia_node_join(ic, ni);
   2274 	ieee80211_notify_node_join(ic, ni, newassoc);
   2275 }
   2276 
   2277 /*
   2278  * Handle a station leaving an 11g network.
   2279  */
   2280 static void
   2281 ieee80211_node_leave_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
   2282 {
   2283 
   2284 	IASSERT(ic->ic_curmode == IEEE80211_MODE_11G,
   2285 	     ("not in 11g, bss %u:0x%x, curmode %u", ni->ni_chan->ic_freq,
   2286 	      ni->ni_chan->ic_flags, ic->ic_curmode));
   2287 
   2288 	/*
   2289 	 * If a long slot station do the slot time bookkeeping.
   2290 	 */
   2291 	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
   2292 		IASSERT(ic->ic_longslotsta > 0,
   2293 		    ("bogus long slot station count %d", ic->ic_longslotsta));
   2294 		ic->ic_longslotsta--;
   2295 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
   2296 		    "[%s] long slot time station leaves, count now %d\n",
   2297 		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
   2298 		if (ic->ic_longslotsta == 0) {
   2299 			/*
   2300 			 * Re-enable use of short slot time if supported
   2301 			 * and not operating in IBSS mode (per spec).
   2302 			 */
   2303 			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
   2304 			    ic->ic_opmode != IEEE80211_M_IBSS) {
   2305 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
   2306 				    "%s: re-enable use of short slot time\n",
   2307 				    __func__);
   2308 				ieee80211_set_shortslottime(ic, 1);
   2309 			}
   2310 		}
   2311 	}
   2312 
   2313 	/*
   2314 	 * If a non-ERP station do the protection-related bookkeeping.
   2315 	 */
   2316 	if ((ni->ni_flags & IEEE80211_NODE_ERP) == 0) {
   2317 		IASSERT(ic->ic_nonerpsta > 0,
   2318 		    ("bogus non-ERP station count %d", ic->ic_nonerpsta));
   2319 		ic->ic_nonerpsta--;
   2320 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
   2321 		    "[%s] non-ERP station leaves, count now %d\n",
   2322 		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
   2323 		if (ic->ic_nonerpsta == 0) {
   2324 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
   2325 				"%s: disable use of protection\n", __func__);
   2326 			ic->ic_flags &= ~IEEE80211_F_USEPROT;
   2327 			/* XXX verify mode? */
   2328 			if (ic->ic_caps & IEEE80211_C_SHPREAMBLE) {
   2329 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
   2330 				    "%s: re-enable use of short preamble\n",
   2331 				    __func__);
   2332 				ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
   2333 				ic->ic_flags &= ~IEEE80211_F_USEBARKER;
   2334 			}
   2335 		}
   2336 	}
   2337 }
   2338 
   2339 /*
   2340  * Handle bookkeeping for station deauthentication/disassociation
   2341  * when operating as an ap.
   2342  */
   2343 void
   2344 ieee80211_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
   2345 {
   2346 	struct ieee80211_node_table *nt = ni->ni_table;
   2347 
   2348 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
   2349 	    "[%s] station with aid %d leaves\n",
   2350 	    ether_sprintf(ni->ni_macaddr), IEEE80211_NODE_AID(ni));
   2351 	IASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
   2352 		ic->ic_opmode == IEEE80211_M_IBSS ||
   2353 		ic->ic_opmode == IEEE80211_M_AHDEMO,
   2354 		("unexpected operating mode %u", ic->ic_opmode));
   2355 
   2356 	/*
   2357 	 * If node wasn't previously associated all
   2358 	 * we need to do is reclaim the reference.
   2359 	 */
   2360 	/* XXX ibss mode bypasses 11g and notification */
   2361 	if (ni->ni_associd == 0)
   2362 		goto done;
   2363 
   2364 	/*
   2365 	 * Tell the authenticator the station is leaving.
   2366 	 * Note that we must do this before yanking the
   2367 	 * association id as the authenticator uses the
   2368 	 * associd to locate its state block.
   2369 	 */
   2370 	if (ic->ic_auth->ia_node_leave != NULL)
   2371 		ic->ic_auth->ia_node_leave(ic, ni);
   2372 	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
   2373 	ni->ni_associd = 0;
   2374 	ic->ic_sta_assoc--;
   2375 
   2376 	if (ic->ic_curmode == IEEE80211_MODE_11G)
   2377 		ieee80211_node_leave_11g(ic, ni);
   2378 
   2379 	/*
   2380 	 * Cleanup station state.  In particular clear various
   2381 	 * state that might otherwise be reused if the node
   2382 	 * is reused before the reference count goes to zero
   2383 	 * (and memory is reclaimed).
   2384 	 */
   2385 	ieee80211_sta_leave(ic, ni);
   2386 
   2387 done:
   2388 	/*
   2389 	 * Remove the node from any table it's recorded in and
   2390 	 * drop the caller's reference.  Removal from the table
   2391 	 * is important to insure the node is not reprocessed
   2392 	 * for inactivity.
   2393 	 */
   2394 	if (nt != NULL) {
   2395 		IEEE80211_NODE_LOCK(nt);
   2396 		node_reclaim(nt, ni);
   2397 		IEEE80211_NODE_UNLOCK(nt);
   2398 	} else
   2399 		ieee80211_free_node(ni);
   2400 }
   2401 
   2402 u_int8_t
   2403 ieee80211_getrssi(struct ieee80211com *ic)
   2404 {
   2405 #define	NZ(x)	((x) == 0 ? 1 : (x))
   2406 	struct ieee80211_node_table *nt = &ic->ic_sta;
   2407 	u_int32_t rssi_samples, rssi_total;
   2408 	struct ieee80211_node *ni;
   2409 
   2410 	rssi_total = 0;
   2411 	rssi_samples = 0;
   2412 	switch (ic->ic_opmode) {
   2413 	case IEEE80211_M_IBSS:		/* average of all ibss neighbors */
   2414 		/* XXX locking */
   2415 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
   2416 			if (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) {
   2417 				rssi_samples++;
   2418 				rssi_total += ic->ic_node_getrssi(ni);
   2419 			}
   2420 		break;
   2421 	case IEEE80211_M_AHDEMO:	/* average of all neighbors */
   2422 		/* XXX locking */
   2423 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
   2424 			rssi_samples++;
   2425 			rssi_total += ic->ic_node_getrssi(ni);
   2426 		}
   2427 		break;
   2428 	case IEEE80211_M_HOSTAP:	/* average of all associated stations */
   2429 #ifndef IEEE80211_NO_HOSTAP
   2430 		/* XXX locking */
   2431 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
   2432 			if (IEEE80211_AID(ni->ni_associd) != 0) {
   2433 				rssi_samples++;
   2434 				rssi_total += ic->ic_node_getrssi(ni);
   2435 			}
   2436 #endif /* !IEEE80211_NO_HOSTAP */
   2437 		break;
   2438 	case IEEE80211_M_MONITOR:	/* XXX */
   2439 	case IEEE80211_M_STA:		/* use stats from associated ap */
   2440 	default:
   2441 		if (ic->ic_bss != NULL)
   2442 			rssi_total = ic->ic_node_getrssi(ic->ic_bss);
   2443 		rssi_samples = 1;
   2444 		break;
   2445 	}
   2446 	return rssi_total / NZ(rssi_samples);
   2447 #undef NZ
   2448 }
   2449 
   2450 /*
   2451  * Indicate whether there are frames queued for a station in power-save mode.
   2452  */
   2453 static void
   2454 ieee80211_set_tim(struct ieee80211_node *ni, int set)
   2455 {
   2456 	struct ieee80211com *ic = ni->ni_ic;
   2457 	u_int16_t aid;
   2458 
   2459 	IASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
   2460 		ic->ic_opmode == IEEE80211_M_IBSS,
   2461 		("operating mode %u", ic->ic_opmode));
   2462 
   2463 	aid = IEEE80211_AID(ni->ni_associd);
   2464 	IASSERT(aid < ic->ic_max_aid,
   2465 		("bogus aid %u, max %u", aid, ic->ic_max_aid));
   2466 
   2467 	IEEE80211_BEACON_LOCK(ic);
   2468 	if (set != (isset(ic->ic_tim_bitmap, aid) != 0)) {
   2469 		if (set) {
   2470 			setbit(ic->ic_tim_bitmap, aid);
   2471 			ic->ic_ps_pending++;
   2472 		} else {
   2473 			clrbit(ic->ic_tim_bitmap, aid);
   2474 			ic->ic_ps_pending--;
   2475 		}
   2476 		ic->ic_flags |= IEEE80211_F_TIMUPDATE;
   2477 	}
   2478 	IEEE80211_BEACON_UNLOCK(ic);
   2479 }
   2480 
   2481 /*
   2482  * Node table support.
   2483  */
   2484 
   2485 static void
   2486 ieee80211_node_table_init(struct ieee80211com *ic,
   2487 	struct ieee80211_node_table *nt,
   2488 	const char *name, int inact, int keyixmax,
   2489 	void (*timeout)(struct ieee80211_node_table *))
   2490 {
   2491 
   2492 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   2493 		"%s %s table, inact %u\n", __func__, name, inact);
   2494 
   2495 	nt->nt_ic = ic;
   2496 	/* XXX need unit */
   2497 	IEEE80211_NODE_LOCK_INIT(nt, ic->ic_ifp->if_xname);
   2498 	IEEE80211_SCAN_LOCK_INIT(nt, ic->ic_ifp->if_xname);
   2499 	TAILQ_INIT(&nt->nt_node);
   2500 	nt->nt_name = name;
   2501 	nt->nt_scangen = 1;
   2502 	nt->nt_inact_init = inact;
   2503 	nt->nt_timeout = timeout;
   2504 	nt->nt_keyixmax = keyixmax;
   2505 	if (nt->nt_keyixmax > 0) {
   2506 		nt->nt_keyixmap = malloc(keyixmax *
   2507 		    sizeof(struct ieee80211_node *), M_80211_NODE,
   2508 		    M_WAITOK | M_ZERO);
   2509 	} else
   2510 		nt->nt_keyixmap = NULL;
   2511 }
   2512 
   2513 void
   2514 ieee80211_node_table_reset(struct ieee80211_node_table *nt)
   2515 {
   2516 
   2517 	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
   2518 		"%s %s table\n", __func__, nt->nt_name);
   2519 
   2520 	IEEE80211_NODE_LOCK(nt);
   2521 	nt->nt_inact_timer = 0;
   2522 	ieee80211_free_allnodes_locked(nt);
   2523 	IEEE80211_NODE_UNLOCK(nt);
   2524 }
   2525 
   2526 static void
   2527 ieee80211_node_table_cleanup(struct ieee80211_node_table *nt)
   2528 {
   2529 
   2530 	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
   2531 		"%s %s table\n", __func__, nt->nt_name);
   2532 
   2533 	IEEE80211_NODE_LOCK(nt);
   2534 	ieee80211_free_allnodes_locked(nt);
   2535 	IEEE80211_NODE_UNLOCK(nt);
   2536 	if (nt->nt_keyixmap != NULL) {
   2537 		/* XXX verify all entries are NULL */
   2538 		int i;
   2539 		for (i = 0; i < nt->nt_keyixmax; i++)
   2540 			if (nt->nt_keyixmap[i] != NULL)
   2541 				printf("%s: %s[%u] still active\n", __func__,
   2542 					nt->nt_name, i);
   2543 		free(nt->nt_keyixmap, M_80211_NODE);
   2544 		nt->nt_keyixmap = NULL;
   2545 	}
   2546 	IEEE80211_SCAN_LOCK_DESTROY(nt);
   2547 	IEEE80211_NODE_LOCK_DESTROY(nt);
   2548 }
   2549