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