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