Home | History | Annotate | Line # | Download | only in net80211
ieee80211_node.c revision 1.76
      1 /*	$NetBSD: ieee80211_node.c,v 1.76 2019/11/10 21:16:38 chs 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.76 2019/11/10 21:16:38 chs 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 setings */
    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 curent 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 inital 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 #ifdef IEEE80211_DEBUG
    547 	if (ieee80211_msg_scan(ic)) {
    548 		printf(" %c %s",
    549 		    fail & 0x40 ? '=' : fail & 0x80 ? '^' : fail ? '-' : '+',
    550 		    ether_sprintf(ni->ni_macaddr));
    551 		printf(" %s%c", ether_sprintf(ni->ni_bssid),
    552 		    fail & 0x20 ? '!' : ' ');
    553 		printf(" %3d%c", ieee80211_chan2ieee(ic, ni->ni_chan),
    554 			fail & 0x01 ? '!' : ' ');
    555 		printf(" %+4d", ni->ni_rssi);
    556 		printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
    557 		    fail & 0x08 ? '!' : ' ');
    558 		printf(" %4s%c",
    559 		    (ni->ni_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
    560 		    (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
    561 		    "????",
    562 		    fail & 0x02 ? '!' : ' ');
    563 		printf(" %3s%c ",
    564 		    (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) ?
    565 		    "wep" : "no",
    566 		    fail & 0x04 ? '!' : ' ');
    567 		ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
    568 		printf("%s\n", fail & 0x10 ? "!" : "");
    569 	}
    570 #endif
    571 
    572 	return fail;
    573 }
    574 
    575 static __inline u_int8_t
    576 maxrate(const struct ieee80211_node *ni)
    577 {
    578 	const struct ieee80211_rateset *rs = &ni->ni_rates;
    579 	/* NB: assumes rate set is sorted (happens on frame receive) */
    580 	return rs->rs_rates[rs->rs_nrates-1] & IEEE80211_RATE_VAL;
    581 }
    582 
    583 /*
    584  * Compare the capabilities of two nodes and decide which is
    585  * more desirable (return >0 if a is considered better).  Note
    586  * that we assume compatibility/usability has already been checked
    587  * so we don't need to (e.g. validate whether privacy is supported).
    588  * Used to select the best scan candidate for association in a BSS.
    589  */
    590 static int
    591 ieee80211_node_compare(struct ieee80211com *ic, const struct ieee80211_node *a,
    592     const struct ieee80211_node *b)
    593 {
    594 	u_int8_t maxa, maxb;
    595 	u_int8_t rssia, rssib;
    596 	int weight;
    597 
    598 	/* privacy support preferred */
    599 	if ((a->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) &&
    600 	    (b->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
    601 		return 1;
    602 	if ((a->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0 &&
    603 	    (b->ni_capinfo & IEEE80211_CAPINFO_PRIVACY))
    604 		return -1;
    605 
    606 	/* compare count of previous failures */
    607 	weight = b->ni_fails - a->ni_fails;
    608 	if (abs(weight) > 1)
    609 		return weight;
    610 
    611 	rssia = ic->ic_node_getrssi(a);
    612 	rssib = ic->ic_node_getrssi(b);
    613 	if (abs(rssib - rssia) < 5) {
    614 		/* best/max rate preferred if signal level close enough XXX */
    615 		maxa = maxrate(a);
    616 		maxb = maxrate(b);
    617 		if (maxa != maxb)
    618 			return maxa - maxb;
    619 		/* XXX use freq for channel preference */
    620 		/* for now just prefer 5 GHz band to all other bands */
    621 		if (IEEE80211_IS_CHAN_5GHZ(a->ni_chan) &&
    622 		   !IEEE80211_IS_CHAN_5GHZ(b->ni_chan))
    623 			return 1;
    624 		if (!IEEE80211_IS_CHAN_5GHZ(a->ni_chan) &&
    625 		     IEEE80211_IS_CHAN_5GHZ(b->ni_chan))
    626 			return -1;
    627 	}
    628 	/* all things being equal, use signal level */
    629 	return rssia - rssib;
    630 }
    631 
    632 /*
    633  * Mark an ongoing scan stopped.
    634  */
    635 void
    636 ieee80211_cancel_scan(struct ieee80211com *ic)
    637 {
    638 
    639 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN, "%s: end %s scan\n",
    640 		__func__,
    641 		(ic->ic_flags & IEEE80211_F_ASCAN) ?  "active" : "passive");
    642 
    643 	ic->ic_flags &= ~(IEEE80211_F_SCAN | IEEE80211_F_ASCAN);
    644 	ic->ic_flags_ext &= ~IEEE80211_FEXT_PROBECHAN;
    645 }
    646 
    647 /*
    648  * Complete a scan of potential channels.
    649  */
    650 void
    651 ieee80211_end_scan(struct ieee80211com *ic)
    652 {
    653 	struct ieee80211_node_table *nt = &ic->ic_scan;
    654 	struct ieee80211_node *ni, *selbs;
    655 
    656 	ieee80211_cancel_scan(ic);
    657 	ieee80211_notify_scan_done(ic);
    658 
    659 #ifndef IEEE80211_NO_HOSTAP
    660 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
    661 		u_int8_t maxrssi[IEEE80211_CHAN_MAX];	/* XXX off stack? */
    662 		int i, bestchan;
    663 		u_int8_t rssi;
    664 
    665 		/*
    666 		 * The passive scan to look for existing AP's completed,
    667 		 * select a channel to camp on.  Identify the channels
    668 		 * that already have one or more AP's and try to locate
    669 		 * an unoccupied one.  If that fails, pick a channel that
    670 		 * looks to be quietest.
    671 		 */
    672 		memset(maxrssi, 0, sizeof(maxrssi));
    673 		IEEE80211_NODE_LOCK(nt);
    674 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
    675 			rssi = ic->ic_node_getrssi(ni);
    676 			i = ieee80211_chan2ieee(ic, ni->ni_chan);
    677 			if (rssi > maxrssi[i])
    678 				maxrssi[i] = rssi;
    679 		}
    680 		IEEE80211_NODE_UNLOCK(nt);
    681 
    682 		/* XXX select channel more intelligently */
    683 		bestchan = -1;
    684 		for (i = 0; i < IEEE80211_CHAN_MAX; i++) {
    685 			if (isset(ic->ic_chan_active, i)) {
    686 				/*
    687 				 * If the channel is unoccupied the max rssi
    688 				 * should be zero; just take it.  Otherwise
    689 				 * track the channel with the lowest rssi and
    690 				 * use that when all channels appear occupied.
    691 				 */
    692 				if (maxrssi[i] == 0) {
    693 					bestchan = i;
    694 					break;
    695 				}
    696 				if (bestchan == -1 ||
    697 				    maxrssi[i] < maxrssi[bestchan])
    698 					bestchan = i;
    699 			}
    700 		}
    701 		if (bestchan != -1) {
    702 			ieee80211_create_ibss(ic, &ic->ic_channels[bestchan]);
    703 			return;
    704 		}
    705 		/* no suitable channel, should not happen */
    706 	}
    707 #endif /* !IEEE80211_NO_HOSTAP */
    708 
    709 	/*
    710 	 * When manually sequencing the state machine; scan just once
    711 	 * regardless of whether we have a candidate or not.  The
    712 	 * controlling application is expected to setup state and
    713 	 * initiate an association.
    714 	 */
    715 	if (ic->ic_roaming == IEEE80211_ROAMING_MANUAL)
    716 		return;
    717 
    718 	/*
    719 	 * Automatic sequencing; look for a candidate and
    720 	 * if found join the network.
    721 	 */
    722 	/* NB: unlocked read should be ok */
    723 	if (TAILQ_FIRST(&nt->nt_node) == NULL) {
    724 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
    725 			"%s: no scan candidate\n", __func__);
    726 
    727 notfound:
    728 		if (ic->ic_opmode == IEEE80211_M_IBSS &&
    729 		    (ic->ic_flags & IEEE80211_F_IBSSON) &&
    730 		    ic->ic_des_esslen != 0) {
    731 			ieee80211_create_ibss(ic, ic->ic_ibss_chan);
    732 			return;
    733 		}
    734 
    735 		/*
    736 		 * Decrement the failure counts so entries will be
    737 		 * reconsidered the next time around.  We really want
    738 		 * to do this only for sta's where we've previously
    739 		 * had some success.
    740 		 */
    741 		IEEE80211_NODE_LOCK(nt);
    742 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
    743 			if (ni->ni_fails)
    744 				ni->ni_fails--;
    745 		}
    746 		IEEE80211_NODE_UNLOCK(nt);
    747 
    748 		/*
    749 		 * Reset the list of channels to scan and start again.
    750 		 */
    751 		ieee80211_reset_scan(ic);
    752 		ic->ic_flags |= IEEE80211_F_SCAN;
    753 		ieee80211_next_scan(ic);
    754 		return;
    755 	}
    756 
    757 	selbs = NULL;
    758 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN, "\t%s\n",
    759 	    "macaddr          bssid         chan  rssi rate flag  wep  essid");
    760 
    761 	IEEE80211_NODE_LOCK(nt);
    762 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
    763 		if (ieee80211_match_bss(ic, ni) == 0) {
    764 			if (selbs == NULL)
    765 				selbs = ni;
    766 			else if (ieee80211_node_compare(ic, ni, selbs) > 0)
    767 				selbs = ni;
    768 		}
    769 	}
    770 	if (selbs != NULL)		/* NB: grab ref while dropping lock */
    771 		(void)ieee80211_ref_node(selbs);
    772 	IEEE80211_NODE_UNLOCK(nt);
    773 
    774 	if (selbs == NULL)
    775 		goto notfound;
    776 	if (!ieee80211_sta_join(ic, selbs)) {
    777 		ieee80211_free_node(selbs);
    778 		goto notfound;
    779 	}
    780 }
    781 
    782 /*
    783  * Handle 802.11 ad hoc network merge.  The
    784  * convention, set by the Wireless Ethernet Compatibility Alliance
    785  * (WECA), is that an 802.11 station will change its BSSID to match
    786  * the "oldest" 802.11 ad hoc network, on the same channel, that
    787  * has the station's desired SSID.  The "oldest" 802.11 network
    788  * sends beacons with the greatest TSF timestamp.
    789  *
    790  * The caller is assumed to validate TSF's before attempting a merge.
    791  *
    792  * Return !0 if the BSSID changed, 0 otherwise.
    793  */
    794 int
    795 ieee80211_ibss_merge(struct ieee80211_node *ni)
    796 {
    797 	struct ieee80211com *ic = ni->ni_ic;
    798 
    799 	if (ni == ic->ic_bss ||
    800 	    IEEE80211_ADDR_EQ(ni->ni_bssid, ic->ic_bss->ni_bssid)) {
    801 		/* unchanged, nothing to do */
    802 		return 0;
    803 	}
    804 	if (ieee80211_match_bss(ic, ni) != 0) {	/* capabilities mismatch */
    805 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
    806 		    "%s: merge failed, capabilities mismatch\n", __func__);
    807 		ic->ic_stats.is_ibss_capmismatch++;
    808 		return 0;
    809 	}
    810 	if (!ieee80211_sta_join(ic, ieee80211_ref_node(ni)))
    811 		return 0;
    812 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
    813 		"%s: new bssid %s: %s preamble, %s slot time%s\n", __func__,
    814 		ether_sprintf(ni->ni_bssid),
    815 		ic->ic_flags&IEEE80211_F_SHPREAMBLE ? "short" : "long",
    816 		ic->ic_flags&IEEE80211_F_SHSLOT ? "short" : "long",
    817 		ic->ic_flags&IEEE80211_F_USEPROT ? ", protection" : ""
    818 	);
    819 	ic->ic_flags &= ~IEEE80211_F_SIBSS;
    820 	return 1;
    821 }
    822 
    823 /*
    824  * Join the specified IBSS/BSS network.  The node is assumed to
    825  * be passed in with a held reference.
    826  */
    827 int
    828 ieee80211_sta_join(struct ieee80211com *ic, struct ieee80211_node *selbs)
    829 {
    830 	struct ieee80211_node *obss;
    831 
    832 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
    833 		struct ieee80211_node_table *nt;
    834 
    835 		/*
    836 		 * Delete unusable rates; we've already checked
    837 		 * that the negotiated rate set is acceptable.
    838 		 */
    839 		ieee80211_fix_rate(selbs, IEEE80211_R_DODEL);
    840 
    841 		/*
    842 		 * Fill in the neighbor table; it will already
    843 		 * exist if we are simply switching mastership.
    844 		 * XXX ic_sta always setup so this is unnecessary?
    845 		 */
    846 		nt = &ic->ic_sta;
    847 		IEEE80211_NODE_LOCK(nt);
    848 		nt->nt_name = "neighbor";
    849 		nt->nt_inact_init = ic->ic_inact_run;
    850 		IEEE80211_NODE_UNLOCK(nt);
    851 	}
    852 
    853 	/*
    854 	 * Committed to selbs, setup state.
    855 	 */
    856 	obss = ic->ic_bss;
    857 	ic->ic_bss = selbs;		/* NB: caller assumed to bump refcnt */
    858 	if (obss != NULL) {
    859 		copy_bss(selbs, obss);
    860 		ieee80211_free_node(obss);
    861 	}
    862 
    863 	/*
    864 	 * Set the erp state (mostly the slot time) to deal with
    865 	 * the auto-select case; this should be redundant if the
    866 	 * mode is locked.
    867 	 */
    868 	ic->ic_curmode = ieee80211_chan2mode(ic, selbs->ni_chan);
    869 	ic->ic_curchan = selbs->ni_chan;
    870 	ieee80211_reset_erp(ic);
    871 	ieee80211_wme_initparams(ic);
    872 
    873 	if (ic->ic_opmode == IEEE80211_M_STA)
    874 		ieee80211_new_state(ic, IEEE80211_S_AUTH, -1);
    875 	else
    876 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
    877 	return 1;
    878 }
    879 
    880 /*
    881  * Leave the specified IBSS/BSS network.  The node is assumed to
    882  * be passed in with a held reference.
    883  */
    884 void
    885 ieee80211_sta_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
    886 {
    887 	ic->ic_node_cleanup(ni);
    888 	ieee80211_notify_node_leave(ic, ni);
    889 }
    890 
    891 int
    892 ieee80211_get_rate(const struct ieee80211_node * const ni)
    893 {
    894 #define	RATE(_ix)	(ni->ni_rates.rs_rates[(_ix)] & IEEE80211_RATE_VAL)
    895 	int ix, rate;
    896 	struct ieee80211com *ic = ni->ni_ic;
    897 	const struct ieee80211_rateset *rs;
    898 
    899 	IASSERT(ni != NULL, ("ni != NULL"));
    900 	IASSERT(ieee80211_node_refcnt(ni) > 0,
    901 	    ("refcnt(ni) == %d", ieee80211_node_refcnt(ni)));
    902 	IASSERT(ic != NULL, ("ic != NULL"));
    903 
    904 	if (ic->ic_fixed_rate != IEEE80211_FIXED_RATE_NONE) {
    905 		rs = &ic->ic_sup_rates[ic->ic_curmode];
    906 		rate = rs->rs_rates[ic->ic_fixed_rate] & IEEE80211_RATE_VAL;
    907 		for (ix = ni->ni_rates.rs_nrates - 1;
    908 		     ix >= 0 && RATE(ix) != rate; ix--)
    909 			;
    910 		if (ix < 0) {
    911 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG,
    912 			    "%s: fixed rate %d (%d.%d Mb/s) not in rate set",
    913 			    __func__, ic->ic_fixed_rate, (rate * 5) / 10,
    914 			    (rate * 5) % 10);
    915 			goto no_rate;
    916 		}
    917 	} else if (ic->ic_state == IEEE80211_S_RUN) {
    918 		rate = ni->ni_rates.rs_rates[ni->ni_txrate];
    919 	} else {
    920 no_rate:
    921 		rs = &ni->ni_rates;
    922 		/* Choose node's lowest basic rate, or else its lowest rate. */
    923 		for (ix = 0; ix < rs->rs_nrates; ix++) {
    924 			if (rs->rs_rates[ix] & IEEE80211_RATE_BASIC)
    925 				return rs->rs_rates[ix] & IEEE80211_RATE_VAL;
    926 		}
    927 		return ni->ni_rates.rs_rates[0] & IEEE80211_RATE_VAL;
    928 	}
    929 
    930 	return rate & IEEE80211_RATE_VAL;
    931 }
    932 
    933 static struct ieee80211_node *
    934 node_alloc(struct ieee80211_node_table *nt)
    935 {
    936 	struct ieee80211_node *ni;
    937 
    938 	ni = malloc(sizeof(struct ieee80211_node),
    939 		M_80211_NODE, M_NOWAIT | M_ZERO);
    940 	return ni;
    941 }
    942 
    943 /*
    944  * Reclaim any resources in a node and reset any critical
    945  * state.  Typically nodes are free'd immediately after,
    946  * but in some cases the storage may be reused so we need
    947  * to insure consistent state (should probably fix that).
    948  */
    949 static void
    950 node_cleanup(struct ieee80211_node *ni)
    951 {
    952 #define	N(a)	(sizeof(a)/sizeof(a[0]))
    953 	struct ieee80211com *ic = ni->ni_ic;
    954 	int i, qlen;
    955 
    956 	/* NB: preserve ni_table */
    957 	if (ni->ni_flags & IEEE80211_NODE_PWR_MGT) {
    958 		ic->ic_ps_sta--;
    959 		ni->ni_flags &= ~IEEE80211_NODE_PWR_MGT;
    960 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
    961 		    "[%s] power save mode off, %u sta's in ps mode\n",
    962 		    ether_sprintf(ni->ni_macaddr), ic->ic_ps_sta);
    963 	}
    964 
    965 	/*
    966 	 * Clear AREF flag that marks the authorization refcnt bump
    967 	 * has happened.  This is probably not needed as the node
    968 	 * should always be removed from the table so not found but
    969 	 * do it just in case.
    970 	 */
    971 	ni->ni_flags &= ~IEEE80211_NODE_AREF;
    972 
    973 	/*
    974 	 * Drain power save queue and, if needed, clear TIM.
    975 	 */
    976 	IEEE80211_NODE_SAVEQ_DRAIN(ni, qlen);
    977 	if (qlen != 0 && ic->ic_set_tim != NULL)
    978 		ic->ic_set_tim(ni, 0);
    979 
    980 	ni->ni_associd = 0;
    981 	if (ni->ni_challenge != NULL) {
    982 		free(ni->ni_challenge, M_DEVBUF);
    983 		ni->ni_challenge = NULL;
    984 	}
    985 
    986 	/*
    987 	 * Preserve SSID, WPA, and WME ie's so the bss node is
    988 	 * reusable during a re-auth/re-assoc state transition.
    989 	 * If we remove these data they will not be recreated
    990 	 * because they come from a probe-response or beacon frame
    991 	 * which cannot be expected prior to the association-response.
    992 	 * This should not be an issue when operating in other modes
    993 	 * as stations leaving always go through a full state transition
    994 	 * which will rebuild this state.
    995 	 *
    996 	 * XXX does this leave us open to inheriting old state?
    997 	 */
    998 	for (i = 0; i < N(ni->ni_rxfrag); i++) {
    999 		if (ni->ni_rxfrag[i] != NULL) {
   1000 			m_freem(ni->ni_rxfrag[i]);
   1001 			ni->ni_rxfrag[i] = NULL;
   1002 		}
   1003 	}
   1004 
   1005 	/*
   1006 	 * Must be careful here to remove any key map entry w/o a LOR.
   1007 	 */
   1008 	ieee80211_node_delucastkey(ni);
   1009 #undef N
   1010 }
   1011 
   1012 static void
   1013 node_free(struct ieee80211_node *ni)
   1014 {
   1015 	struct ieee80211com *ic = ni->ni_ic;
   1016 
   1017 	ic->ic_node_cleanup(ni);
   1018 	if (ni->ni_wpa_ie != NULL)
   1019 		free(ni->ni_wpa_ie, M_DEVBUF);
   1020 	if (ni->ni_wme_ie != NULL)
   1021 		free(ni->ni_wme_ie, M_DEVBUF);
   1022 	IEEE80211_NODE_SAVEQ_DESTROY(ni);
   1023 	free(ni, M_80211_NODE);
   1024 }
   1025 
   1026 static u_int8_t
   1027 node_getrssi(const struct ieee80211_node *ni)
   1028 {
   1029 	return ni->ni_rssi;
   1030 }
   1031 
   1032 static void
   1033 ieee80211_setup_node(struct ieee80211_node_table *nt,
   1034 	struct ieee80211_node *ni, const u_int8_t *macaddr)
   1035 {
   1036 	struct ieee80211com *ic = nt->nt_ic;
   1037 	int hash;
   1038 
   1039 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   1040 		"%s %p<%s> in %s table\n", __func__, ni,
   1041 		ether_sprintf(macaddr), nt->nt_name);
   1042 
   1043 	IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
   1044 	hash = IEEE80211_NODE_HASH(macaddr);
   1045 	ieee80211_node_initref(ni);		/* mark referenced */
   1046 	ni->ni_chan = IEEE80211_CHAN_ANYC;
   1047 	ni->ni_authmode = IEEE80211_AUTH_OPEN;
   1048 	ni->ni_txpower = ic->ic_txpowlimit;	/* max power */
   1049 	ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey, IEEE80211_KEYIX_NONE);
   1050 	ni->ni_inact_reload = nt->nt_inact_init;
   1051 	ni->ni_inact = ni->ni_inact_reload;
   1052 	IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
   1053 
   1054 	IEEE80211_NODE_LOCK(nt);
   1055 	TAILQ_INSERT_TAIL(&nt->nt_node, ni, ni_list);
   1056 	LIST_INSERT_HEAD(&nt->nt_hash[hash], ni, ni_hash);
   1057 	ni->ni_table = nt;
   1058 	ni->ni_ic = ic;
   1059 	IEEE80211_NODE_UNLOCK(nt);
   1060 }
   1061 
   1062 struct ieee80211_node *
   1063 ieee80211_alloc_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
   1064 {
   1065 	struct ieee80211com *ic = nt->nt_ic;
   1066 	struct ieee80211_node *ni;
   1067 
   1068 	ni = ic->ic_node_alloc(nt);
   1069 	if (ni != NULL)
   1070 		ieee80211_setup_node(nt, ni, macaddr);
   1071 	else
   1072 		ic->ic_stats.is_rx_nodealloc++;
   1073 	return ni;
   1074 }
   1075 
   1076 /*
   1077  * Craft a temporary node suitable for sending a management frame
   1078  * to the specified station.  We craft only as much state as we
   1079  * need to do the work since the node will be immediately reclaimed
   1080  * once the send completes.
   1081  */
   1082 struct ieee80211_node *
   1083 ieee80211_tmp_node(struct ieee80211com *ic, const u_int8_t *macaddr)
   1084 {
   1085 	struct ieee80211_node *ni;
   1086 
   1087 	ni = ic->ic_node_alloc(&ic->ic_sta);
   1088 	if (ni != NULL) {
   1089 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   1090 			"%s %p<%s>\n", __func__, ni, ether_sprintf(macaddr));
   1091 
   1092 		IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
   1093 		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
   1094 		ieee80211_node_initref(ni);		/* mark referenced */
   1095 		ni->ni_txpower = ic->ic_bss->ni_txpower;
   1096 		/* NB: required by ieee80211_fix_rate */
   1097 		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
   1098 		ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey,
   1099 			IEEE80211_KEYIX_NONE);
   1100 		/* XXX optimize away */
   1101 		IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
   1102 
   1103 		ni->ni_table = NULL;		/* NB: pedantic */
   1104 		ni->ni_ic = ic;
   1105 	} else {
   1106 		/* XXX msg */
   1107 		ic->ic_stats.is_rx_nodealloc++;
   1108 	}
   1109 	return ni;
   1110 }
   1111 
   1112 struct ieee80211_node *
   1113 ieee80211_dup_bss(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
   1114 {
   1115 	struct ieee80211com *ic = nt->nt_ic;
   1116 	struct ieee80211_node *ni;
   1117 
   1118 	ni = ic->ic_node_alloc(nt);
   1119 	if (ni != NULL) {
   1120 		ieee80211_setup_node(nt, ni, macaddr);
   1121 		/*
   1122 		 * Inherit from ic_bss.
   1123 		 */
   1124 		ni->ni_authmode = ic->ic_bss->ni_authmode;
   1125 		ni->ni_txpower = ic->ic_bss->ni_txpower;
   1126 		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
   1127 		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
   1128 		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
   1129 		ni->ni_rsn = ic->ic_bss->ni_rsn;
   1130 	} else {
   1131 		ic->ic_stats.is_rx_nodealloc++;
   1132 	}
   1133 	return ni;
   1134 }
   1135 
   1136 static struct ieee80211_node *
   1137 #ifdef IEEE80211_DEBUG_REFCNT
   1138 _ieee80211_find_node_debug(struct ieee80211_node_table *nt,
   1139 	const u_int8_t *macaddr, const char *func, int line)
   1140 #else
   1141 _ieee80211_find_node(struct ieee80211_node_table *nt,
   1142 	const u_int8_t *macaddr)
   1143 #endif
   1144 {
   1145 	struct ieee80211_node *ni;
   1146 	int hash;
   1147 
   1148 	IEEE80211_NODE_LOCK_ASSERT(nt);
   1149 
   1150 	hash = IEEE80211_NODE_HASH(macaddr);
   1151 	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
   1152 		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
   1153 			ieee80211_ref_node(ni);	/* mark referenced */
   1154 #ifdef IEEE80211_DEBUG_REFCNT
   1155 			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
   1156 			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
   1157 			    func, line,
   1158 			    ni, ether_sprintf(ni->ni_macaddr),
   1159 			    ieee80211_node_refcnt(ni));
   1160 #endif
   1161 			return ni;
   1162 		}
   1163 	}
   1164 	return NULL;
   1165 }
   1166 #ifdef IEEE80211_DEBUG_REFCNT
   1167 #define	_ieee80211_find_node(nt, mac) \
   1168 	_ieee80211_find_node_debug(nt, mac, func, line)
   1169 #endif
   1170 
   1171 struct ieee80211_node *
   1172 #ifdef IEEE80211_DEBUG_REFCNT
   1173 ieee80211_find_node_debug(struct ieee80211_node_table *nt,
   1174 	const u_int8_t *macaddr, const char *func, int line)
   1175 #else
   1176 ieee80211_find_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
   1177 #endif
   1178 {
   1179 	struct ieee80211_node *ni;
   1180 
   1181 	IEEE80211_NODE_LOCK(nt);
   1182 	ni = _ieee80211_find_node(nt, macaddr);
   1183 	IEEE80211_NODE_UNLOCK(nt);
   1184 	return ni;
   1185 }
   1186 
   1187 /*
   1188  * Fake up a node; this handles node discovery in adhoc mode.
   1189  * Note that for the driver's benefit we treat this like
   1190  * an association so the driver has an opportunity to setup
   1191  * its private state.
   1192  */
   1193 struct ieee80211_node *
   1194 ieee80211_fakeup_adhoc_node(struct ieee80211_node_table *nt,
   1195 	const u_int8_t macaddr[IEEE80211_ADDR_LEN])
   1196 {
   1197 	struct ieee80211com *ic = nt->nt_ic;
   1198 	struct ieee80211_node *ni;
   1199 
   1200 	ni = ieee80211_dup_bss(nt, macaddr);
   1201 	if (ni != NULL) {
   1202 		/* XXX no rate negotiation; just dup */
   1203 		ni->ni_rates = ic->ic_bss->ni_rates;
   1204 		if (ic->ic_newassoc != NULL)
   1205 			ic->ic_newassoc(ni, 1);
   1206 		/* XXX not right for 802.1x/WPA */
   1207 		ieee80211_node_authorize(ni);
   1208 	}
   1209 	return ni;
   1210 }
   1211 
   1212 #ifdef IEEE80211_DEBUG
   1213 static void
   1214 dump_probe_beacon(u_int8_t subtype, int isnew,
   1215 	const u_int8_t mac[IEEE80211_ADDR_LEN],
   1216 	const struct ieee80211_scanparams *sp)
   1217 {
   1218 
   1219 	printf("[%s] %s%s on chan %u (bss chan %u) ",
   1220 	    ether_sprintf(mac), isnew ? "new " : "",
   1221 	    ieee80211_mgt_subtype_name[subtype >> IEEE80211_FC0_SUBTYPE_SHIFT],
   1222 	    sp->sp_chan, sp->sp_bchan);
   1223 	ieee80211_print_essid(sp->sp_ssid + 2, sp->sp_ssid[1]);
   1224 	printf("\n");
   1225 
   1226 	if (isnew) {
   1227 		printf("[%s] caps 0x%x bintval %u erp 0x%x",
   1228 		    ether_sprintf(mac), sp->sp_capinfo, sp->sp_bintval,
   1229 		    sp->sp_erp);
   1230 		if (sp->sp_country != NULL) {
   1231 #ifdef __FreeBSD__
   1232 			printf(" country info %*D",
   1233 				sp->sp_country[1], sp->sp_country+2, " ");
   1234 #else
   1235 			int i;
   1236 			printf(" country info");
   1237 			for (i = 0; i < sp->sp_country[1]; i++)
   1238 				printf(" %02x", sp->sp_country[i+2]);
   1239 #endif
   1240 		}
   1241 		printf("\n");
   1242 	}
   1243 }
   1244 #endif /* IEEE80211_DEBUG */
   1245 
   1246 static void
   1247 saveie(u_int8_t **iep, const u_int8_t *ie)
   1248 {
   1249 
   1250 	if (ie == NULL)
   1251 		*iep = NULL;
   1252 	else
   1253 		ieee80211_saveie(iep, ie);
   1254 }
   1255 
   1256 /*
   1257  * Process a beacon or probe response frame.
   1258  */
   1259 void
   1260 ieee80211_add_scan(struct ieee80211com *ic,
   1261     const struct ieee80211_scanparams *sp, const struct ieee80211_frame *wh,
   1262     int subtype, int rssi, int rstamp)
   1263 {
   1264 #define	ISPROBE(_st)	((_st) == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
   1265 	struct ieee80211_node_table *nt = &ic->ic_scan;
   1266 	struct ieee80211_node *ni;
   1267 	int newnode = 0;
   1268 
   1269 	ni = ieee80211_find_node(nt, wh->i_addr2);
   1270 	if (ni == NULL) {
   1271 		/*
   1272 		 * Create a new entry.
   1273 		 */
   1274 		ni = ic->ic_node_alloc(nt);
   1275 		if (ni == NULL) {
   1276 			ic->ic_stats.is_rx_nodealloc++;
   1277 			return;
   1278 		}
   1279 		ieee80211_setup_node(nt, ni, wh->i_addr2);
   1280 
   1281 		/*
   1282 		 * XXX inherit from ic_bss.
   1283 		 */
   1284 		ni->ni_authmode = ic->ic_bss->ni_authmode;
   1285 		ni->ni_txpower = ic->ic_bss->ni_txpower;
   1286 		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
   1287 		ieee80211_set_chan(ic, ni, ic->ic_curchan);
   1288 		ni->ni_rsn = ic->ic_bss->ni_rsn;
   1289 		newnode = 1;
   1290 	}
   1291 
   1292 #ifdef IEEE80211_DEBUG
   1293 	if (ieee80211_msg_scan(ic) && (ic->ic_flags & IEEE80211_F_SCAN))
   1294 		dump_probe_beacon(subtype, newnode, wh->i_addr2, sp);
   1295 #endif
   1296 
   1297 	/* XXX ap beaconing multiple ssid w/ same bssid */
   1298 	if (sp->sp_ssid[1] != 0 && (ISPROBE(subtype) || ni->ni_esslen == 0)) {
   1299 		ni->ni_esslen = sp->sp_ssid[1];
   1300 		memset(ni->ni_essid, 0, sizeof(ni->ni_essid));
   1301 		memcpy(ni->ni_essid, sp->sp_ssid + 2, sp->sp_ssid[1]);
   1302 	}
   1303 
   1304 	ni->ni_scangen = ic->ic_scan.nt_scangen;
   1305 	IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
   1306 	ni->ni_rssi = rssi;
   1307 	ni->ni_rstamp = rstamp;
   1308 	memcpy(ni->ni_tstamp.data, sp->sp_tstamp, sizeof(ni->ni_tstamp));
   1309 	ni->ni_intval = sp->sp_bintval;
   1310 	ni->ni_capinfo = sp->sp_capinfo;
   1311 	ni->ni_chan = &ic->ic_channels[sp->sp_chan];
   1312 	ni->ni_fhdwell = sp->sp_fhdwell;
   1313 	ni->ni_fhindex = sp->sp_fhindex;
   1314 	ni->ni_erp = sp->sp_erp;
   1315 
   1316 	if (sp->sp_tim != NULL) {
   1317 		struct ieee80211_tim_ie *ie =
   1318 		    (struct ieee80211_tim_ie *)sp->sp_tim;
   1319 
   1320 		ni->ni_dtim_count = ie->tim_count;
   1321 		ni->ni_dtim_period = ie->tim_period;
   1322 	}
   1323 
   1324 	/*
   1325 	 * Record the byte offset from the mac header to
   1326 	 * the start of the TIM information element for
   1327 	 * use by hardware and/or to speedup software
   1328 	 * processing of beacon frames.
   1329 	 */
   1330 	ni->ni_timoff = sp->sp_timoff;
   1331 
   1332 	/*
   1333 	 * Record optional information elements that might be
   1334 	 * used by applications or drivers.
   1335 	 */
   1336 	saveie(&ni->ni_wme_ie, sp->sp_wme);
   1337 	saveie(&ni->ni_wpa_ie, sp->sp_wpa);
   1338 
   1339 	/* NB: must be after ni_chan is setup */
   1340 	ieee80211_setup_rates(ni, sp->sp_rates, sp->sp_xrates,
   1341 	    IEEE80211_R_DOSORT);
   1342 
   1343 	if (!newnode)
   1344 		ieee80211_free_node(ni);
   1345 #undef ISPROBE
   1346 }
   1347 
   1348 void
   1349 ieee80211_init_neighbor(struct ieee80211com *ic, struct ieee80211_node *ni,
   1350     const struct ieee80211_frame *wh, const struct ieee80211_scanparams *sp,
   1351     int isnew)
   1352 {
   1353 	ni->ni_esslen = sp->sp_ssid[1];
   1354 	memcpy(ni->ni_essid, sp->sp_ssid + 2, sp->sp_ssid[1]);
   1355 	IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
   1356 	memcpy(ni->ni_tstamp.data, sp->sp_tstamp, sizeof(ni->ni_tstamp));
   1357 	ni->ni_intval = sp->sp_bintval;
   1358 	ni->ni_capinfo = sp->sp_capinfo;
   1359 	ni->ni_chan = ic->ic_bss->ni_chan;
   1360 	ni->ni_fhdwell = sp->sp_fhdwell;
   1361 	ni->ni_fhindex = sp->sp_fhindex;
   1362 	ni->ni_erp = sp->sp_erp;
   1363 	ni->ni_timoff = sp->sp_timoff;
   1364 	if (sp->sp_wme != NULL)
   1365 		ieee80211_saveie(&ni->ni_wme_ie, sp->sp_wme);
   1366 	if (sp->sp_wpa != NULL)
   1367 		ieee80211_saveie(&ni->ni_wpa_ie, sp->sp_wpa);
   1368 
   1369 	/* NB: must be after ni_chan is setup */
   1370 	ieee80211_setup_rates(ni, sp->sp_rates, sp->sp_xrates,
   1371 	    IEEE80211_R_DODEL | IEEE80211_R_DONEGO | IEEE80211_R_DOSORT);
   1372 
   1373 	if (ic->ic_newassoc != NULL)
   1374 		ic->ic_newassoc(ni, isnew);
   1375 }
   1376 
   1377 /*
   1378  * Do node discovery in adhoc mode on receipt of a beacon
   1379  * or probe response frame.  Note that for the driver's
   1380  * benefit we we treat this like an association so the
   1381  * driver has an opportunity to setup its private state.
   1382  */
   1383 struct ieee80211_node *
   1384 ieee80211_add_neighbor(struct ieee80211com *ic,
   1385 	const struct ieee80211_frame *wh,
   1386 	const struct ieee80211_scanparams *sp)
   1387 {
   1388 	struct ieee80211_node *ni;
   1389 
   1390 	ni = ieee80211_dup_bss(&ic->ic_sta, wh->i_addr2);/* XXX alloc_node? */
   1391 	if (ni != NULL) {
   1392 		ieee80211_init_neighbor(ic, ni, wh, sp, 1);
   1393 		/* XXX not right for 802.1x/WPA */
   1394 		ieee80211_node_authorize(ni);
   1395 	}
   1396 	return ni;
   1397 }
   1398 
   1399 #define	IS_CTL(wh) \
   1400 	((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_CTL)
   1401 #define	IS_PSPOLL(wh) \
   1402 	((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_PS_POLL)
   1403 /*
   1404  * Locate the node for sender, track state, and then pass the
   1405  * (referenced) node up to the 802.11 layer for its use.  We
   1406  * are required to pass some node so we fall back to ic_bss
   1407  * when this frame is from an unknown sender.  The 802.11 layer
   1408  * knows this means the sender wasn't in the node table and
   1409  * acts accordingly.
   1410  */
   1411 struct ieee80211_node *
   1412 #ifdef IEEE80211_DEBUG_REFCNT
   1413 ieee80211_find_rxnode_debug(struct ieee80211com *ic,
   1414 	const struct ieee80211_frame_min *wh, const char *func, int line)
   1415 #else
   1416 ieee80211_find_rxnode(struct ieee80211com *ic,
   1417 	const struct ieee80211_frame_min *wh)
   1418 #endif
   1419 {
   1420 	struct ieee80211_node_table *nt;
   1421 	struct ieee80211_node *ni;
   1422 
   1423 	/* XXX may want scanned nodes in the neighbor table for adhoc */
   1424 	if (ic->ic_opmode == IEEE80211_M_STA ||
   1425 	    ic->ic_opmode == IEEE80211_M_MONITOR ||
   1426 	    (ic->ic_flags & IEEE80211_F_SCAN))
   1427 		nt = &ic->ic_scan;
   1428 	else
   1429 		nt = &ic->ic_sta;
   1430 
   1431 	/* XXX check ic_bss first in station mode */
   1432 	/* XXX 4-address frames? */
   1433 	IEEE80211_NODE_LOCK(nt);
   1434 	if (IS_CTL(wh) && !IS_PSPOLL(wh) /*&& !IS_RTS(ah)*/)
   1435 		ni = _ieee80211_find_node(nt, wh->i_addr1);
   1436 	else
   1437 		ni = _ieee80211_find_node(nt, wh->i_addr2);
   1438 	if (ni == NULL)
   1439 		ni = ieee80211_ref_node(ic->ic_bss);
   1440 	IEEE80211_NODE_UNLOCK(nt);
   1441 
   1442 	return ni;
   1443 }
   1444 
   1445 /*
   1446  * Like ieee80211_find_rxnode but use the supplied h/w
   1447  * key index as a hint to locate the node in the key
   1448  * mapping table.  If an entry is present at the key
   1449  * index we return it; otherwise do a normal lookup and
   1450  * update the mapping table if the station has a unicast
   1451  * key assigned to it.
   1452  */
   1453 struct ieee80211_node *
   1454 #ifdef IEEE80211_DEBUG_REFCNT
   1455 ieee80211_find_rxnode_withkey_debug(struct ieee80211com *ic,
   1456 	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix,
   1457 	const char *func, int line)
   1458 #else
   1459 ieee80211_find_rxnode_withkey(struct ieee80211com *ic,
   1460 	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix)
   1461 #endif
   1462 {
   1463 	struct ieee80211_node_table *nt;
   1464 	struct ieee80211_node *ni;
   1465 
   1466 	if (ic->ic_opmode == IEEE80211_M_STA ||
   1467 	    ic->ic_opmode == IEEE80211_M_MONITOR ||
   1468 	    (ic->ic_flags & IEEE80211_F_SCAN)) {
   1469 		nt = &ic->ic_scan;
   1470 	} else {
   1471 		nt = &ic->ic_sta;
   1472 	}
   1473 
   1474 	IEEE80211_NODE_LOCK(nt);
   1475 	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax) {
   1476 		ni = nt->nt_keyixmap[keyix];
   1477 	} else {
   1478 		ni = NULL;
   1479 	}
   1480 	if (ni == NULL) {
   1481 		if (IS_CTL(wh) && !IS_PSPOLL(wh) /*&& !IS_RTS(ah)*/)
   1482 			ni = _ieee80211_find_node(nt, wh->i_addr1);
   1483 		else
   1484 			ni = _ieee80211_find_node(nt, wh->i_addr2);
   1485 		if (ni == NULL)
   1486 			ni = ieee80211_ref_node(ic->ic_bss);
   1487 		if (nt->nt_keyixmap != NULL) {
   1488 			/*
   1489 			 * If the station has a unicast key cache slot
   1490 			 * assigned update the key->node mapping table.
   1491 			 */
   1492 			keyix = ni->ni_ucastkey.wk_rxkeyix;
   1493 			/* XXX can keyixmap[keyix] != NULL? */
   1494 			if (keyix < nt->nt_keyixmax &&
   1495 			    nt->nt_keyixmap[keyix] == NULL) {
   1496 				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
   1497 				    "%s: add key map entry %p<%s> refcnt %d\n",
   1498 				    __func__, ni, ether_sprintf(ni->ni_macaddr),
   1499 				    ieee80211_node_refcnt(ni)+1);
   1500 				nt->nt_keyixmap[keyix] = ieee80211_ref_node(ni);
   1501 			}
   1502 		}
   1503 	} else {
   1504 		ieee80211_ref_node(ni);
   1505 	}
   1506 	IEEE80211_NODE_UNLOCK(nt);
   1507 
   1508 	return ni;
   1509 }
   1510 #undef IS_PSPOLL
   1511 #undef IS_CTL
   1512 
   1513 /*
   1514  * Return a reference to the appropriate node for sending
   1515  * a data frame.  This handles node discovery in adhoc networks.
   1516  */
   1517 struct ieee80211_node *
   1518 #ifdef IEEE80211_DEBUG_REFCNT
   1519 ieee80211_find_txnode_debug(struct ieee80211com *ic, const u_int8_t *macaddr,
   1520 	const char *func, int line)
   1521 #else
   1522 ieee80211_find_txnode(struct ieee80211com *ic, const u_int8_t *macaddr)
   1523 #endif
   1524 {
   1525 	struct ieee80211_node_table *nt = &ic->ic_sta;
   1526 	struct ieee80211_node *ni;
   1527 
   1528 	/*
   1529 	 * The destination address should be in the node table
   1530 	 * unless this is a multicast/broadcast frame.  We can
   1531 	 * also optimize station mode operation, all frames go
   1532 	 * to the bss node.
   1533 	 */
   1534 	/* XXX can't hold lock across dup_bss 'cuz of recursive locking */
   1535 	IEEE80211_NODE_LOCK(nt);
   1536 	if (ic->ic_opmode == IEEE80211_M_STA || IEEE80211_IS_MULTICAST(macaddr))
   1537 		ni = ieee80211_ref_node(ic->ic_bss);
   1538 	else
   1539 		ni = _ieee80211_find_node(nt, macaddr);
   1540 	IEEE80211_NODE_UNLOCK(nt);
   1541 
   1542 	if (ni == NULL) {
   1543 		if (ic->ic_opmode == IEEE80211_M_IBSS ||
   1544 		    ic->ic_opmode == IEEE80211_M_AHDEMO) {
   1545 			/*
   1546 			 * In adhoc mode cons up a node for the destination.
   1547 			 * Note that we need an additional reference for the
   1548 			 * caller to be consistent with _ieee80211_find_node.
   1549 			 */
   1550 			ni = ieee80211_fakeup_adhoc_node(nt, macaddr);
   1551 			if (ni != NULL)
   1552 				(void)ieee80211_ref_node(ni);
   1553 		} else {
   1554 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
   1555 				"[%s] no node, discard frame (%s)\n",
   1556 				ether_sprintf(macaddr), __func__);
   1557 			ic->ic_stats.is_tx_nonode++;
   1558 		}
   1559 	}
   1560 	return ni;
   1561 }
   1562 
   1563 /*
   1564  * Like find but search based on the channel too.
   1565  */
   1566 struct ieee80211_node *
   1567 #ifdef IEEE80211_DEBUG_REFCNT
   1568 ieee80211_find_node_with_channel_debug(struct ieee80211_node_table *nt,
   1569 	const u_int8_t *macaddr, struct ieee80211_channel *chan,
   1570 	const char *func, int line)
   1571 #else
   1572 ieee80211_find_node_with_channel(struct ieee80211_node_table *nt,
   1573 	const u_int8_t *macaddr, struct ieee80211_channel *chan)
   1574 #endif
   1575 {
   1576 	struct ieee80211_node *ni;
   1577 	int hash;
   1578 
   1579 	hash = IEEE80211_NODE_HASH(macaddr);
   1580 
   1581 	IEEE80211_NODE_LOCK(nt);
   1582 	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
   1583 		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
   1584 		    ni->ni_chan == chan) {
   1585 			ieee80211_ref_node(ni);		/* mark referenced */
   1586 #ifdef IEEE80211_DEBUG_REFCNT
   1587 			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
   1588 			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
   1589 			    func, line,
   1590 			    ni, ether_sprintf(ni->ni_macaddr),
   1591 			    ieee80211_node_refcnt(ni));
   1592 #else
   1593 			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
   1594 			    "%s %p<%s> refcnt %d\n", __func__,
   1595 			    ni, ether_sprintf(ni->ni_macaddr),
   1596 			    ieee80211_node_refcnt(ni));
   1597 #endif
   1598 			break;
   1599 		}
   1600 	}
   1601 	IEEE80211_NODE_UNLOCK(nt);
   1602 
   1603 	return ni;
   1604 }
   1605 
   1606 struct ieee80211_node *
   1607 ieee80211_refine_node_for_beacon(struct ieee80211com *ic,
   1608 	struct ieee80211_node *ni0, struct ieee80211_channel *chan,
   1609 	const u_int8_t *ssid)
   1610 {
   1611 	struct ieee80211_node_table *nt = ni0->ni_table;
   1612 	struct ieee80211_node *best, *ni;
   1613 	int best_score = 0, score;
   1614 
   1615 	if (nt == NULL)
   1616 		return ni0;
   1617 
   1618 	best = ni0;
   1619 	if (ssid[1] == 0 || best->ni_esslen == 0)
   1620 		best_score = 1;
   1621 	else if (ssid[1] == best->ni_esslen &&
   1622 		 memcmp(ssid + 2, best->ni_essid, ssid[1]) == 0)
   1623 		best_score = 2;
   1624 	else
   1625 		best_score = 0;
   1626 
   1627 	IEEE80211_NODE_LOCK(nt);
   1628 	for (ni = LIST_NEXT(ni0, ni_hash); ni != NULL;
   1629 	     ni = LIST_NEXT(ni, ni_hash)) {
   1630 		if (!IEEE80211_ADDR_EQ(ni->ni_macaddr, best->ni_macaddr) ||
   1631 		    ni->ni_ic != best->ni_ic || ni->ni_chan != chan)
   1632 			continue;
   1633 
   1634 		if (ssid[1] == 0 || ni->ni_esslen == 0)
   1635 			score = 1;
   1636 		else if (ssid[1] == ni->ni_esslen &&
   1637 			 memcmp(ssid + 2, ni->ni_essid, ssid[1]) == 0)
   1638 			score = 2;
   1639 		else
   1640 			continue;
   1641 
   1642 		if (score > best_score) {
   1643 			best = ni;
   1644 			best_score = score;
   1645 		}
   1646 	}
   1647 	IEEE80211_NODE_UNLOCK(nt);
   1648 
   1649 	return best;
   1650 }
   1651 
   1652 /*
   1653  * Like find but search based on the ssid too.
   1654  */
   1655 struct ieee80211_node *
   1656 #ifdef IEEE80211_DEBUG_REFCNT
   1657 ieee80211_find_node_with_ssid_debug(struct ieee80211_node_table *nt,
   1658 	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid,
   1659 	const char *func, int line)
   1660 #else
   1661 ieee80211_find_node_with_ssid(struct ieee80211_node_table *nt,
   1662 	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid)
   1663 #endif
   1664 {
   1665 #define	MATCH_SSID(ni, ssid, ssidlen) \
   1666 	(ni->ni_esslen == ssidlen && memcmp(ni->ni_essid, ssid, ssidlen) == 0)
   1667 	static const u_int8_t zeromac[IEEE80211_ADDR_LEN];
   1668 	struct ieee80211com *ic = nt->nt_ic;
   1669 	struct ieee80211_node *ni;
   1670 	int hash;
   1671 
   1672 	IEEE80211_NODE_LOCK(nt);
   1673 	__USE(ic);
   1674 
   1675 	/*
   1676 	 * A mac address that is all zero means match only the ssid;
   1677 	 * otherwise we must match both.
   1678 	 */
   1679 	if (IEEE80211_ADDR_EQ(macaddr, zeromac)) {
   1680 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
   1681 			if (MATCH_SSID(ni, ssid, ssidlen))
   1682 				break;
   1683 		}
   1684 	} else {
   1685 		hash = IEEE80211_NODE_HASH(macaddr);
   1686 		LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
   1687 			if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
   1688 			    MATCH_SSID(ni, ssid, ssidlen))
   1689 				break;
   1690 		}
   1691 	}
   1692 	if (ni != NULL) {
   1693 		ieee80211_ref_node(ni);	/* mark referenced */
   1694 #ifdef IEEE80211_DEBUG_REFCNT
   1695 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   1696 		    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
   1697 		    func, line,
   1698 		     ni, ether_sprintf(ni->ni_macaddr),
   1699 		     ieee80211_node_refcnt(ni));
   1700 #else
   1701 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   1702 		    "%s %p<%s> refcnt %d\n", __func__,
   1703 		     ni, ether_sprintf(ni->ni_macaddr),
   1704 		     ieee80211_node_refcnt(ni));
   1705 #endif
   1706 	}
   1707 
   1708 	IEEE80211_NODE_UNLOCK(nt);
   1709 
   1710 	return ni;
   1711 #undef MATCH_SSID
   1712 }
   1713 
   1714 static void
   1715 _ieee80211_free_node(struct ieee80211_node *ni)
   1716 {
   1717 	struct ieee80211com *ic = ni->ni_ic;
   1718 	struct ieee80211_node_table *nt = ni->ni_table;
   1719 
   1720 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   1721 		"%s %p<%s> in %s table\n", __func__, ni,
   1722 		ether_sprintf(ni->ni_macaddr),
   1723 		nt != NULL ? nt->nt_name : "<gone>");
   1724 
   1725 	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
   1726 	if (nt != NULL) {
   1727 		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
   1728 		LIST_REMOVE(ni, ni_hash);
   1729 	}
   1730 	ic->ic_node_free(ni);
   1731 }
   1732 
   1733 void
   1734 #ifdef IEEE80211_DEBUG_REFCNT
   1735 ieee80211_free_node_debug(struct ieee80211_node *ni, const char *func, int line)
   1736 #else
   1737 ieee80211_free_node(struct ieee80211_node *ni)
   1738 #endif
   1739 {
   1740 	struct ieee80211_node_table *nt = ni->ni_table;
   1741 
   1742 #ifdef IEEE80211_DEBUG_REFCNT
   1743 	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
   1744 		"%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line, ni,
   1745 		 ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)-1);
   1746 #endif
   1747 
   1748 	if (nt != NULL) {
   1749 		IEEE80211_NODE_LOCK(nt);
   1750 		if (ieee80211_node_dectestref(ni)) {
   1751 			/*
   1752 			 * Last reference, reclaim state.
   1753 			 */
   1754 			_ieee80211_free_node(ni);
   1755 		} else if (ieee80211_node_refcnt(ni) == 1 &&
   1756 		    nt->nt_keyixmap != NULL) {
   1757 			ieee80211_keyix keyix;
   1758 
   1759 			/*
   1760 			 * Check for a last reference in the key mapping table.
   1761 			 */
   1762 			keyix = ni->ni_ucastkey.wk_rxkeyix;
   1763 			if (keyix < nt->nt_keyixmax &&
   1764 			    nt->nt_keyixmap[keyix] == ni) {
   1765 				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
   1766 				    "%s: %p<%s> clear key map entry", __func__,
   1767 				    ni, ether_sprintf(ni->ni_macaddr));
   1768 				nt->nt_keyixmap[keyix] = NULL;
   1769 				ieee80211_node_decref(ni); /* XXX needed? */
   1770 				_ieee80211_free_node(ni);
   1771 			}
   1772 		}
   1773 		IEEE80211_NODE_UNLOCK(nt);
   1774 	} else {
   1775 		if (ieee80211_node_dectestref(ni))
   1776 			_ieee80211_free_node(ni);
   1777 	}
   1778 }
   1779 
   1780 /*
   1781  * Reclaim a unicast key and clear any key cache state.
   1782  */
   1783 int
   1784 ieee80211_node_delucastkey(struct ieee80211_node *ni)
   1785 {
   1786 	struct ieee80211com *ic = ni->ni_ic;
   1787 	struct ieee80211_node_table *nt = &ic->ic_sta;
   1788 	struct ieee80211_node *nikey;
   1789 	ieee80211_keyix keyix;
   1790 	int isowned, status;
   1791 
   1792 	/*
   1793 	 * NB: We must beware of LOR here; deleting the key
   1794 	 * can cause the crypto layer to block traffic updates
   1795 	 * which can generate a LOR against the node table lock;
   1796 	 * grab it here and stash the key index for our use below.
   1797 	 *
   1798 	 * Must also beware of recursion on the node table lock.
   1799 	 * When called from node_cleanup we may already have
   1800 	 * the node table lock held.  Unfortunately there's no
   1801 	 * way to separate out this path so we must do this
   1802 	 * conditionally.
   1803 	 */
   1804 	isowned = IEEE80211_NODE_IS_LOCKED(nt);
   1805 	if (!isowned)
   1806 		IEEE80211_NODE_LOCK(nt);
   1807 	keyix = ni->ni_ucastkey.wk_rxkeyix;
   1808 	status = ieee80211_crypto_delkey(ic, &ni->ni_ucastkey);
   1809 	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax) {
   1810 		nikey = nt->nt_keyixmap[keyix];
   1811 		nt->nt_keyixmap[keyix] = NULL;
   1812 	} else
   1813 		nikey = NULL;
   1814 	if (!isowned)
   1815 		IEEE80211_NODE_UNLOCK(&ic->ic_sta);
   1816 
   1817 	if (nikey != NULL) {
   1818 		IASSERT(nikey == ni,
   1819 			("key map out of sync, ni %p nikey %p", ni, nikey));
   1820 		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
   1821 			"%s: delete key map entry %p<%s> refcnt %d\n",
   1822 			__func__, ni, ether_sprintf(ni->ni_macaddr),
   1823 			ieee80211_node_refcnt(ni)-1);
   1824 		ieee80211_free_node(ni);
   1825 	}
   1826 	return status;
   1827 }
   1828 
   1829 /*
   1830  * Reclaim a node.  If this is the last reference count then
   1831  * do the normal free work.  Otherwise remove it from the node
   1832  * table and mark it gone by clearing the back-reference.
   1833  */
   1834 static void
   1835 node_reclaim(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
   1836 {
   1837 	ieee80211_keyix keyix;
   1838 
   1839 	IEEE80211_NODE_LOCK_ASSERT(nt);
   1840 
   1841 	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
   1842 		"%s: remove %p<%s> from %s table, refcnt %d\n",
   1843 		__func__, ni, ether_sprintf(ni->ni_macaddr),
   1844 		nt->nt_name, ieee80211_node_refcnt(ni)-1);
   1845 	/*
   1846 	 * Clear any entry in the unicast key mapping table.
   1847 	 * We need to do it here so rx lookups don't find it
   1848 	 * in the mapping table even if it's not in the hash
   1849 	 * table.  We cannot depend on the mapping table entry
   1850 	 * being cleared because the node may not be free'd.
   1851 	 */
   1852 	keyix = ni->ni_ucastkey.wk_rxkeyix;
   1853 	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax &&
   1854 	    nt->nt_keyixmap[keyix] == ni) {
   1855 		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
   1856 			"%s: %p<%s> clear key map entry\n",
   1857 			__func__, ni, ether_sprintf(ni->ni_macaddr));
   1858 		nt->nt_keyixmap[keyix] = NULL;
   1859 		ieee80211_node_decref(ni);	/* NB: don't need free */
   1860 	}
   1861 	if (!ieee80211_node_dectestref(ni)) {
   1862 		/*
   1863 		 * Other references are present, just remove the
   1864 		 * node from the table so it cannot be found.  When
   1865 		 * the references are dropped storage will be
   1866 		 * reclaimed.
   1867 		 */
   1868 		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
   1869 		LIST_REMOVE(ni, ni_hash);
   1870 		ni->ni_table = NULL;		/* clear reference */
   1871 	} else
   1872 		_ieee80211_free_node(ni);
   1873 }
   1874 
   1875 static void
   1876 ieee80211_free_allnodes_locked(struct ieee80211_node_table *nt)
   1877 {
   1878 	struct ieee80211com *ic = nt->nt_ic;
   1879 	struct ieee80211_node *ni;
   1880 
   1881 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   1882 		"%s: free all nodes in %s table\n", __func__, nt->nt_name);
   1883 
   1884 	while ((ni = TAILQ_FIRST(&nt->nt_node)) != NULL) {
   1885 		if (ni->ni_associd != 0) {
   1886 			if (ic->ic_auth->ia_node_leave != NULL)
   1887 				ic->ic_auth->ia_node_leave(ic, ni);
   1888 			IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
   1889 		}
   1890 		node_reclaim(nt, ni);
   1891 	}
   1892 	ieee80211_reset_erp(ic);
   1893 }
   1894 
   1895 static void
   1896 ieee80211_free_allnodes(struct ieee80211_node_table *nt)
   1897 {
   1898 
   1899 	IEEE80211_NODE_LOCK(nt);
   1900 	ieee80211_free_allnodes_locked(nt);
   1901 	IEEE80211_NODE_UNLOCK(nt);
   1902 }
   1903 
   1904 /*
   1905  * Timeout entries in the scan cache.
   1906  */
   1907 static void
   1908 ieee80211_timeout_scan_candidates(struct ieee80211_node_table *nt)
   1909 {
   1910 	struct ieee80211com *ic = nt->nt_ic;
   1911 	struct ieee80211_node *ni, *tni;
   1912 
   1913 	IEEE80211_NODE_LOCK(nt);
   1914 	ni = ic->ic_bss;
   1915 	/* XXX belongs elsewhere */
   1916 	if (ni->ni_rxfrag[0] != NULL && ticks > ni->ni_rxfragstamp + hz) {
   1917 		m_freem(ni->ni_rxfrag[0]);
   1918 		ni->ni_rxfrag[0] = NULL;
   1919 	}
   1920 	TAILQ_FOREACH_SAFE(ni, &nt->nt_node, ni_list, tni) {
   1921 		if (ni->ni_inact && --ni->ni_inact == 0) {
   1922 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   1923 			    "[%s] scan candidate purged from cache "
   1924 			    "(refcnt %u)\n", ether_sprintf(ni->ni_macaddr),
   1925 			    ieee80211_node_refcnt(ni));
   1926 			node_reclaim(nt, ni);
   1927 		}
   1928 	}
   1929 	IEEE80211_NODE_UNLOCK(nt);
   1930 
   1931 	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
   1932 }
   1933 
   1934 /*
   1935  * Timeout inactive stations and do related housekeeping.
   1936  * Note that we cannot hold the node lock while sending a
   1937  * frame as this would lead to a LOR.  Instead we use a
   1938  * generation number to mark nodes that we've scanned and
   1939  * drop the lock and restart a scan if we have to time out
   1940  * a node.  Since we are single-threaded by virtue of
   1941  * controlling the inactivity timer we can be sure this will
   1942  * process each node only once.
   1943  */
   1944 static void
   1945 ieee80211_timeout_stations(struct ieee80211_node_table *nt)
   1946 {
   1947 	struct ieee80211com *ic = nt->nt_ic;
   1948 	struct ieee80211_node *ni;
   1949 	u_int gen;
   1950 	int isadhoc;
   1951 
   1952 	isadhoc = (ic->ic_opmode == IEEE80211_M_IBSS ||
   1953 		   ic->ic_opmode == IEEE80211_M_AHDEMO);
   1954 	IEEE80211_SCAN_LOCK(nt);
   1955 	gen = ++nt->nt_scangen;
   1956 	IEEE80211_SCAN_UNLOCK(nt);
   1957 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   1958 		"%s: %s scangen %u\n", __func__, nt->nt_name, gen);
   1959 restart:
   1960 	IEEE80211_SCAN_LOCK(nt);
   1961 	if (gen != nt->nt_scangen) {
   1962 		printf("%s: scan aborted %u\n", __func__, gen);
   1963 		IEEE80211_SCAN_UNLOCK(nt);
   1964 		return;
   1965 	}
   1966 	IEEE80211_SCAN_UNLOCK(nt);
   1967 
   1968 	IEEE80211_NODE_LOCK(nt);
   1969 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
   1970 		if (ni->ni_scangen == gen)	/* previously handled */
   1971 			continue;
   1972 		ni->ni_scangen = gen;
   1973 		/*
   1974 		 * Ignore entries for which have yet to receive an
   1975 		 * authentication frame.  These are transient and
   1976 		 * will be reclaimed when the last reference to them
   1977 		 * goes away (when frame xmits complete).
   1978 		 */
   1979 		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
   1980 		    (ni->ni_flags & IEEE80211_NODE_AREF) == 0)
   1981 			continue;
   1982 		/*
   1983 		 * Free fragment if not needed anymore
   1984 		 * (last fragment older than 1s).
   1985 		 * XXX doesn't belong here
   1986 		 */
   1987 		if (ni->ni_rxfrag[0] != NULL &&
   1988 		    ticks > ni->ni_rxfragstamp + hz) {
   1989 			m_freem(ni->ni_rxfrag[0]);
   1990 			ni->ni_rxfrag[0] = NULL;
   1991 		}
   1992 		/*
   1993 		 * Special case ourself; we may be idle for extended periods
   1994 		 * of time and regardless reclaiming our state is wrong.
   1995 		 */
   1996 		if (ni == ic->ic_bss)
   1997 			continue;
   1998 		ni->ni_inact--;
   1999 		if (ni->ni_associd != 0 || isadhoc) {
   2000 			/*
   2001 			 * Age frames on the power save queue. The
   2002 			 * aging interval is 4 times the listen
   2003 			 * interval specified by the station.  This
   2004 			 * number is factored into the age calculations
   2005 			 * when the frame is placed on the queue.  We
   2006 			 * store ages as time differences we can check
   2007 			 * and/or adjust only the head of the list.
   2008 			 */
   2009 			if (IEEE80211_NODE_SAVEQ_QLEN(ni) != 0) {
   2010 				struct mbuf *m;
   2011 				int discard = 0;
   2012 
   2013 				IEEE80211_NODE_SAVEQ_LOCK(ni);
   2014 				while (IF_POLL(&ni->ni_savedq, m) != NULL &&
   2015 				     M_AGE_GET(m) < IEEE80211_INACT_WAIT) {
   2016 IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER, "[%s] discard frame, age %u\n", ether_sprintf(ni->ni_macaddr), M_AGE_GET(m));/*XXX*/
   2017 					_IEEE80211_NODE_SAVEQ_DEQUEUE_HEAD(ni, m);
   2018 					m_freem(m);
   2019 					discard++;
   2020 				}
   2021 				if (m != NULL)
   2022 					M_AGE_SUB(m, IEEE80211_INACT_WAIT);
   2023 				IEEE80211_NODE_SAVEQ_UNLOCK(ni);
   2024 
   2025 				if (discard != 0) {
   2026 					IEEE80211_DPRINTF(ic,
   2027 					    IEEE80211_MSG_POWER,
   2028 					    "[%s] discard %u frames for age\n",
   2029 					    ether_sprintf(ni->ni_macaddr),
   2030 					    discard);
   2031 					IEEE80211_NODE_STAT_ADD(ni,
   2032 						ps_discard, discard);
   2033 					if (IEEE80211_NODE_SAVEQ_QLEN(ni) == 0)
   2034 						ic->ic_set_tim(ni, 0);
   2035 				}
   2036 			}
   2037 			/*
   2038 			 * Probe the station before time it out.  We
   2039 			 * send a null data frame which may not be
   2040 			 * universally supported by drivers (need it
   2041 			 * for ps-poll support so it should be...).
   2042 			 */
   2043 			if (0 < ni->ni_inact &&
   2044 			    ni->ni_inact <= ic->ic_inact_probe) {
   2045 				IEEE80211_NOTE(ic,
   2046 				    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE,
   2047 				    ni, "%s",
   2048 				    "probe station due to inactivity");
   2049 				/*
   2050 				 * Grab a reference before unlocking the table
   2051 				 * so the node cannot be reclaimed before we
   2052 				 * send the frame. ieee80211_send_nulldata
   2053 				 * understands we've done this and reclaims the
   2054 				 * ref for us as needed.
   2055 				 */
   2056 				ieee80211_ref_node(ni);
   2057 				IEEE80211_NODE_UNLOCK(nt);
   2058 				ieee80211_send_nulldata(ni);
   2059 				/* XXX stat? */
   2060 				goto restart;
   2061 			}
   2062 		}
   2063 		if (ni->ni_inact <= 0) {
   2064 			IEEE80211_NOTE(ic,
   2065 			    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE, ni,
   2066 			    "station timed out due to inactivity "
   2067 			    "(refcnt %u)", ieee80211_node_refcnt(ni));
   2068 			/*
   2069 			 * Send a deauthenticate frame and drop the station.
   2070 			 * This is somewhat complicated due to reference counts
   2071 			 * and locking.  At this point a station will typically
   2072 			 * have a reference count of 1.  ieee80211_node_leave
   2073 			 * will do a "free" of the node which will drop the
   2074 			 * reference count.  But in the meantime a reference
   2075 			 * will be held by the deauth frame.  The actual reclaim
   2076 			 * of the node will happen either after the tx is
   2077 			 * completed or by ieee80211_node_leave.
   2078 			 *
   2079 			 * Separately we must drop the node lock before sending
   2080 			 * in case the driver takes a lock, as this will result
   2081 			 * in  LOR between the node lock and the driver lock.
   2082 			 */
   2083 			IEEE80211_NODE_UNLOCK(nt);
   2084 			if (ni->ni_associd != 0) {
   2085 				IEEE80211_SEND_MGMT(ic, ni,
   2086 				    IEEE80211_FC0_SUBTYPE_DEAUTH,
   2087 				    IEEE80211_REASON_AUTH_EXPIRE);
   2088 			}
   2089 			ieee80211_node_leave(ic, ni);
   2090 			ic->ic_stats.is_node_timeout++;
   2091 			goto restart;
   2092 		}
   2093 	}
   2094 	IEEE80211_NODE_UNLOCK(nt);
   2095 
   2096 	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
   2097 }
   2098 
   2099 void
   2100 ieee80211_iterate_nodes(struct ieee80211_node_table *nt, ieee80211_iter_func *f, void *arg)
   2101 {
   2102 	struct ieee80211_node *ni;
   2103 	u_int gen;
   2104 
   2105 	IEEE80211_SCAN_LOCK(nt);
   2106 	gen = ++nt->nt_scangen;
   2107 	IEEE80211_SCAN_UNLOCK(nt);
   2108 restart:
   2109 	IEEE80211_SCAN_LOCK(nt);
   2110 	if (gen != nt->nt_scangen) {
   2111 		printf("%s: scan aborted %u\n", __func__, gen);
   2112 		IEEE80211_SCAN_UNLOCK(nt);
   2113 		return;
   2114 	}
   2115 	IEEE80211_SCAN_UNLOCK(nt);
   2116 
   2117 	IEEE80211_NODE_LOCK(nt);
   2118 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
   2119 		if (ni->ni_scangen != gen) {
   2120 			ni->ni_scangen = gen;
   2121 			(void) ieee80211_ref_node(ni);
   2122 			IEEE80211_NODE_UNLOCK(nt);
   2123 			(*f)(arg, ni);
   2124 			ieee80211_free_node(ni);
   2125 			goto restart;
   2126 		}
   2127 	}
   2128 	IEEE80211_NODE_UNLOCK(nt);
   2129 }
   2130 
   2131 void
   2132 ieee80211_dump_node(struct ieee80211_node_table *nt,
   2133     struct ieee80211_node *ni)
   2134 {
   2135 	printf("0x%p: mac %s refcnt %d\n", ni,
   2136 		ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni));
   2137 	printf("\tscangen %u authmode %u flags 0x%x\n",
   2138 		ni->ni_scangen, ni->ni_authmode, ni->ni_flags);
   2139 	printf("\tassocid 0x%x txpower %u vlan %u\n",
   2140 		ni->ni_associd, ni->ni_txpower, ni->ni_vlan);
   2141 	printf("\ttxseq %u rxseq %u fragno %u rxfragstamp %u\n",
   2142 		ni->ni_txseqs[0],
   2143 		ni->ni_rxseqs[0] >> IEEE80211_SEQ_SEQ_SHIFT,
   2144 		ni->ni_rxseqs[0] & IEEE80211_SEQ_FRAG_MASK,
   2145 		ni->ni_rxfragstamp);
   2146 	printf("\trstamp %u rssi %u intval %u capinfo 0x%x\n",
   2147 		ni->ni_rstamp, ni->ni_rssi, ni->ni_intval, ni->ni_capinfo);
   2148 	printf("\tbssid %s essid \"%.*s\" channel %u:0x%x\n",
   2149 		ether_sprintf(ni->ni_bssid),
   2150 		ni->ni_esslen, ni->ni_essid,
   2151 		ni->ni_chan->ic_freq, ni->ni_chan->ic_flags);
   2152 	printf("\tfails %u inact %u txrate %u\n",
   2153 		ni->ni_fails, ni->ni_inact, ni->ni_txrate);
   2154 }
   2155 
   2156 void
   2157 ieee80211_dump_nodes(struct ieee80211_node_table *nt)
   2158 {
   2159 	ieee80211_iterate_nodes(nt,
   2160 		(ieee80211_iter_func *) ieee80211_dump_node, nt);
   2161 }
   2162 
   2163 /*
   2164  * Handle a station joining an 11g network.
   2165  */
   2166 static void
   2167 ieee80211_node_join_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
   2168 {
   2169 
   2170 	/*
   2171 	 * Station isn't capable of short slot time.  Bump
   2172 	 * the count of long slot time stations and disable
   2173 	 * use of short slot time.  Note that the actual switch
   2174 	 * over to long slot time use may not occur until the
   2175 	 * next beacon transmission (per sec. 7.3.1.4 of 11g).
   2176 	 */
   2177 	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
   2178 		ic->ic_longslotsta++;
   2179 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
   2180 		    "[%s] station needs long slot time, count %d\n",
   2181 		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
   2182 		/* XXX vap's w/ conflicting needs won't work */
   2183 		ieee80211_set_shortslottime(ic, 0);
   2184 	}
   2185 
   2186 	/*
   2187 	 * If the new station is not an ERP station
   2188 	 * then bump the counter and enable protection
   2189 	 * if configured.
   2190 	 */
   2191 	if (!ieee80211_iserp_rateset(ic, &ni->ni_rates)) {
   2192 		ic->ic_nonerpsta++;
   2193 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
   2194 		    "[%s] station is !ERP, %d non-ERP stations associated\n",
   2195 		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
   2196 		/*
   2197 		 * If protection is configured, enable it.
   2198 		 */
   2199 		if (ic->ic_protmode != IEEE80211_PROT_NONE) {
   2200 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
   2201 			    "%s: enable use of protection\n", __func__);
   2202 			ic->ic_flags |= IEEE80211_F_USEPROT;
   2203 		}
   2204 		/*
   2205 		 * If station does not support short preamble
   2206 		 * then we must enable use of Barker preamble.
   2207 		 */
   2208 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE) == 0) {
   2209 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
   2210 			    "[%s] station needs long preamble\n",
   2211 			    ether_sprintf(ni->ni_macaddr));
   2212 			ic->ic_flags |= IEEE80211_F_USEBARKER;
   2213 			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
   2214 		}
   2215 	} else {
   2216 		ni->ni_flags |= IEEE80211_NODE_ERP;
   2217 	}
   2218 }
   2219 
   2220 void
   2221 ieee80211_node_join(struct ieee80211com *ic, struct ieee80211_node *ni,
   2222     int resp)
   2223 {
   2224 	int newassoc;
   2225 
   2226 	if (ni->ni_associd == 0) {
   2227 		u_int16_t aid;
   2228 
   2229 		/*
   2230 		 * It would be good to search the bitmap
   2231 		 * more efficiently, but this will do for now.
   2232 		 */
   2233 		for (aid = 1; aid < ic->ic_max_aid; aid++) {
   2234 			if (!IEEE80211_AID_ISSET(aid,
   2235 			    ic->ic_aid_bitmap))
   2236 				break;
   2237 		}
   2238 		if (aid >= ic->ic_max_aid) {
   2239 			IEEE80211_SEND_MGMT(ic, ni, resp,
   2240 			    IEEE80211_REASON_ASSOC_TOOMANY);
   2241 			ieee80211_node_leave(ic, ni);
   2242 			return;
   2243 		}
   2244 		ni->ni_associd = aid | 0xc000;
   2245 		IEEE80211_AID_SET(ni->ni_associd, ic->ic_aid_bitmap);
   2246 		ic->ic_sta_assoc++;
   2247 		newassoc = 1;
   2248 		if (ic->ic_curmode == IEEE80211_MODE_11G)
   2249 			ieee80211_node_join_11g(ic, ni);
   2250 	} else
   2251 		newassoc = 0;
   2252 
   2253 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
   2254 	    "[%s] station %sassociated at aid %d: %s preamble, %s slot time%s%s\n",
   2255 	    ether_sprintf(ni->ni_macaddr), newassoc ? "" : "re",
   2256 	    IEEE80211_NODE_AID(ni),
   2257 	    ic->ic_flags & IEEE80211_F_SHPREAMBLE ? "short" : "long",
   2258 	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long",
   2259 	    ic->ic_flags & IEEE80211_F_USEPROT ? ", protection" : "",
   2260 	    ni->ni_flags & IEEE80211_NODE_QOS ? ", QoS" : ""
   2261 	);
   2262 
   2263 	/* give driver a chance to setup state like ni_txrate */
   2264 	if (ic->ic_newassoc != NULL)
   2265 		ic->ic_newassoc(ni, newassoc);
   2266 	ni->ni_inact_reload = ic->ic_inact_auth;
   2267 	ni->ni_inact = ni->ni_inact_reload;
   2268 	IEEE80211_SEND_MGMT(ic, ni, resp, IEEE80211_STATUS_SUCCESS);
   2269 	/* tell the authenticator about new station */
   2270 	if (ic->ic_auth->ia_node_join != NULL)
   2271 		ic->ic_auth->ia_node_join(ic, ni);
   2272 	ieee80211_notify_node_join(ic, ni, newassoc);
   2273 }
   2274 
   2275 /*
   2276  * Handle a station leaving an 11g network.
   2277  */
   2278 static void
   2279 ieee80211_node_leave_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
   2280 {
   2281 
   2282 	IASSERT(ic->ic_curmode == IEEE80211_MODE_11G,
   2283 	     ("not in 11g, bss %u:0x%x, curmode %u", ni->ni_chan->ic_freq,
   2284 	      ni->ni_chan->ic_flags, ic->ic_curmode));
   2285 
   2286 	/*
   2287 	 * If a long slot station do the slot time bookkeeping.
   2288 	 */
   2289 	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
   2290 		IASSERT(ic->ic_longslotsta > 0,
   2291 		    ("bogus long slot station count %d", ic->ic_longslotsta));
   2292 		ic->ic_longslotsta--;
   2293 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
   2294 		    "[%s] long slot time station leaves, count now %d\n",
   2295 		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
   2296 		if (ic->ic_longslotsta == 0) {
   2297 			/*
   2298 			 * Re-enable use of short slot time if supported
   2299 			 * and not operating in IBSS mode (per spec).
   2300 			 */
   2301 			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
   2302 			    ic->ic_opmode != IEEE80211_M_IBSS) {
   2303 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
   2304 				    "%s: re-enable use of short slot time\n",
   2305 				    __func__);
   2306 				ieee80211_set_shortslottime(ic, 1);
   2307 			}
   2308 		}
   2309 	}
   2310 
   2311 	/*
   2312 	 * If a non-ERP station do the protection-related bookkeeping.
   2313 	 */
   2314 	if ((ni->ni_flags & IEEE80211_NODE_ERP) == 0) {
   2315 		IASSERT(ic->ic_nonerpsta > 0,
   2316 		    ("bogus non-ERP station count %d", ic->ic_nonerpsta));
   2317 		ic->ic_nonerpsta--;
   2318 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
   2319 		    "[%s] non-ERP station leaves, count now %d\n",
   2320 		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
   2321 		if (ic->ic_nonerpsta == 0) {
   2322 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
   2323 				"%s: disable use of protection\n", __func__);
   2324 			ic->ic_flags &= ~IEEE80211_F_USEPROT;
   2325 			/* XXX verify mode? */
   2326 			if (ic->ic_caps & IEEE80211_C_SHPREAMBLE) {
   2327 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
   2328 				    "%s: re-enable use of short preamble\n",
   2329 				    __func__);
   2330 				ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
   2331 				ic->ic_flags &= ~IEEE80211_F_USEBARKER;
   2332 			}
   2333 		}
   2334 	}
   2335 }
   2336 
   2337 /*
   2338  * Handle bookkeeping for station deauthentication/disassociation
   2339  * when operating as an ap.
   2340  */
   2341 void
   2342 ieee80211_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
   2343 {
   2344 	struct ieee80211_node_table *nt = ni->ni_table;
   2345 
   2346 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
   2347 	    "[%s] station with aid %d leaves\n",
   2348 	    ether_sprintf(ni->ni_macaddr), IEEE80211_NODE_AID(ni));
   2349 	IASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
   2350 		ic->ic_opmode == IEEE80211_M_IBSS ||
   2351 		ic->ic_opmode == IEEE80211_M_AHDEMO,
   2352 		("unexpected operating mode %u", ic->ic_opmode));
   2353 
   2354 	/*
   2355 	 * If node wasn't previously associated all
   2356 	 * we need to do is reclaim the reference.
   2357 	 */
   2358 	/* XXX ibss mode bypasses 11g and notification */
   2359 	if (ni->ni_associd == 0)
   2360 		goto done;
   2361 
   2362 	/*
   2363 	 * Tell the authenticator the station is leaving.
   2364 	 * Note that we must do this before yanking the
   2365 	 * association id as the authenticator uses the
   2366 	 * associd to locate its state block.
   2367 	 */
   2368 	if (ic->ic_auth->ia_node_leave != NULL)
   2369 		ic->ic_auth->ia_node_leave(ic, ni);
   2370 	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
   2371 	ni->ni_associd = 0;
   2372 	ic->ic_sta_assoc--;
   2373 
   2374 	if (ic->ic_curmode == IEEE80211_MODE_11G)
   2375 		ieee80211_node_leave_11g(ic, ni);
   2376 
   2377 	/*
   2378 	 * Cleanup station state.  In particular clear various
   2379 	 * state that might otherwise be reused if the node
   2380 	 * is reused before the reference count goes to zero
   2381 	 * (and memory is reclaimed).
   2382 	 */
   2383 	ieee80211_sta_leave(ic, ni);
   2384 
   2385 done:
   2386 	/*
   2387 	 * Remove the node from any table it's recorded in and
   2388 	 * drop the caller's reference.  Removal from the table
   2389 	 * is important to insure the node is not reprocessed
   2390 	 * for inactivity.
   2391 	 */
   2392 	if (nt != NULL) {
   2393 		IEEE80211_NODE_LOCK(nt);
   2394 		node_reclaim(nt, ni);
   2395 		IEEE80211_NODE_UNLOCK(nt);
   2396 	} else
   2397 		ieee80211_free_node(ni);
   2398 }
   2399 
   2400 u_int8_t
   2401 ieee80211_getrssi(struct ieee80211com *ic)
   2402 {
   2403 #define	NZ(x)	((x) == 0 ? 1 : (x))
   2404 	struct ieee80211_node_table *nt = &ic->ic_sta;
   2405 	u_int32_t rssi_samples, rssi_total;
   2406 	struct ieee80211_node *ni;
   2407 
   2408 	rssi_total = 0;
   2409 	rssi_samples = 0;
   2410 	switch (ic->ic_opmode) {
   2411 	case IEEE80211_M_IBSS:		/* average of all ibss neighbors */
   2412 		/* XXX locking */
   2413 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
   2414 			if (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) {
   2415 				rssi_samples++;
   2416 				rssi_total += ic->ic_node_getrssi(ni);
   2417 			}
   2418 		break;
   2419 	case IEEE80211_M_AHDEMO:	/* average of all neighbors */
   2420 		/* XXX locking */
   2421 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
   2422 			rssi_samples++;
   2423 			rssi_total += ic->ic_node_getrssi(ni);
   2424 		}
   2425 		break;
   2426 	case IEEE80211_M_HOSTAP:	/* average of all associated stations */
   2427 #ifndef IEEE80211_NO_HOSTAP
   2428 		/* XXX locking */
   2429 		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
   2430 			if (IEEE80211_AID(ni->ni_associd) != 0) {
   2431 				rssi_samples++;
   2432 				rssi_total += ic->ic_node_getrssi(ni);
   2433 			}
   2434 #endif /* !IEEE80211_NO_HOSTAP */
   2435 		break;
   2436 	case IEEE80211_M_MONITOR:	/* XXX */
   2437 	case IEEE80211_M_STA:		/* use stats from associated ap */
   2438 	default:
   2439 		if (ic->ic_bss != NULL)
   2440 			rssi_total = ic->ic_node_getrssi(ic->ic_bss);
   2441 		rssi_samples = 1;
   2442 		break;
   2443 	}
   2444 	return rssi_total / NZ(rssi_samples);
   2445 #undef NZ
   2446 }
   2447 
   2448 /*
   2449  * Indicate whether there are frames queued for a station in power-save mode.
   2450  */
   2451 static void
   2452 ieee80211_set_tim(struct ieee80211_node *ni, int set)
   2453 {
   2454 	struct ieee80211com *ic = ni->ni_ic;
   2455 	u_int16_t aid;
   2456 
   2457 	IASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
   2458 		ic->ic_opmode == IEEE80211_M_IBSS,
   2459 		("operating mode %u", ic->ic_opmode));
   2460 
   2461 	aid = IEEE80211_AID(ni->ni_associd);
   2462 	IASSERT(aid < ic->ic_max_aid,
   2463 		("bogus aid %u, max %u", aid, ic->ic_max_aid));
   2464 
   2465 	IEEE80211_BEACON_LOCK(ic);
   2466 	if (set != (isset(ic->ic_tim_bitmap, aid) != 0)) {
   2467 		if (set) {
   2468 			setbit(ic->ic_tim_bitmap, aid);
   2469 			ic->ic_ps_pending++;
   2470 		} else {
   2471 			clrbit(ic->ic_tim_bitmap, aid);
   2472 			ic->ic_ps_pending--;
   2473 		}
   2474 		ic->ic_flags |= IEEE80211_F_TIMUPDATE;
   2475 	}
   2476 	IEEE80211_BEACON_UNLOCK(ic);
   2477 }
   2478 
   2479 /*
   2480  * Node table support.
   2481  */
   2482 
   2483 static void
   2484 ieee80211_node_table_init(struct ieee80211com *ic,
   2485 	struct ieee80211_node_table *nt,
   2486 	const char *name, int inact, int keyixmax,
   2487 	void (*timeout)(struct ieee80211_node_table *))
   2488 {
   2489 
   2490 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   2491 		"%s %s table, inact %u\n", __func__, name, inact);
   2492 
   2493 	nt->nt_ic = ic;
   2494 	/* XXX need unit */
   2495 	IEEE80211_NODE_LOCK_INIT(nt, ic->ic_ifp->if_xname);
   2496 	IEEE80211_SCAN_LOCK_INIT(nt, ic->ic_ifp->if_xname);
   2497 	TAILQ_INIT(&nt->nt_node);
   2498 	nt->nt_name = name;
   2499 	nt->nt_scangen = 1;
   2500 	nt->nt_inact_init = inact;
   2501 	nt->nt_timeout = timeout;
   2502 	nt->nt_keyixmax = keyixmax;
   2503 	if (nt->nt_keyixmax > 0) {
   2504 		nt->nt_keyixmap = malloc(keyixmax *
   2505 		    sizeof(struct ieee80211_node *), M_80211_NODE,
   2506 		    M_WAITOK | M_ZERO);
   2507 	} else
   2508 		nt->nt_keyixmap = NULL;
   2509 }
   2510 
   2511 void
   2512 ieee80211_node_table_reset(struct ieee80211_node_table *nt)
   2513 {
   2514 
   2515 	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
   2516 		"%s %s table\n", __func__, nt->nt_name);
   2517 
   2518 	IEEE80211_NODE_LOCK(nt);
   2519 	nt->nt_inact_timer = 0;
   2520 	ieee80211_free_allnodes_locked(nt);
   2521 	IEEE80211_NODE_UNLOCK(nt);
   2522 }
   2523 
   2524 static void
   2525 ieee80211_node_table_cleanup(struct ieee80211_node_table *nt)
   2526 {
   2527 
   2528 	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
   2529 		"%s %s table\n", __func__, nt->nt_name);
   2530 
   2531 	IEEE80211_NODE_LOCK(nt);
   2532 	ieee80211_free_allnodes_locked(nt);
   2533 	IEEE80211_NODE_UNLOCK(nt);
   2534 	if (nt->nt_keyixmap != NULL) {
   2535 		/* XXX verify all entries are NULL */
   2536 		int i;
   2537 		for (i = 0; i < nt->nt_keyixmax; i++)
   2538 			if (nt->nt_keyixmap[i] != NULL)
   2539 				printf("%s: %s[%u] still active\n", __func__,
   2540 					nt->nt_name, i);
   2541 		free(nt->nt_keyixmap, M_80211_NODE);
   2542 		nt->nt_keyixmap = NULL;
   2543 	}
   2544 	IEEE80211_SCAN_LOCK_DESTROY(nt);
   2545 	IEEE80211_NODE_LOCK_DESTROY(nt);
   2546 }
   2547