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