1 /*-
2  * Copyright (c) 2001 Atsushi Onoe
3  * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  *
26  * $FreeBSD: head/sys/net80211/ieee80211_node.c 206358 2010-04-07 15:29:13Z rpaulo $
27  */
28 
29 #include "opt_wlan.h"
30 
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/mbuf.h>
34 #include <sys/malloc.h>
35 #include <sys/kernel.h>
36 
37 #include <sys/socket.h>
38 
39 #include <net/if.h>
40 #include <net/if_media.h>
41 #include <net/ethernet.h>
42 #include <net/route.h>
43 
44 #include <netproto/802_11/ieee80211_var.h>
45 #include <netproto/802_11/ieee80211_input.h>
46 #ifdef IEEE80211_SUPPORT_SUPERG
47 #include <netproto/802_11/ieee80211_superg.h>
48 #endif
49 #ifdef IEEE80211_SUPPORT_TDMA
50 #include <netproto/802_11/ieee80211_tdma.h>
51 #endif
52 #include <netproto/802_11/ieee80211_wds.h>
53 #include <netproto/802_11/ieee80211_mesh.h>
54 #include <netproto/802_11/ieee80211_ratectl.h>
55 
56 #include <net/bpf.h>
57 
58 /*
59  * IEEE80211_NODE_HASHSIZE must be a power of 2.
60  */
61 CTASSERT((IEEE80211_NODE_HASHSIZE & (IEEE80211_NODE_HASHSIZE-1)) == 0);
62 
63 /*
64  * Association id's are managed with a bit vector.
65  */
66 #define	IEEE80211_AID_SET(_vap, b) \
67 	((_vap)->iv_aid_bitmap[IEEE80211_AID(b) / 32] |= \
68 		(1 << (IEEE80211_AID(b) % 32)))
69 #define	IEEE80211_AID_CLR(_vap, b) \
70 	((_vap)->iv_aid_bitmap[IEEE80211_AID(b) / 32] &= \
71 		~(1 << (IEEE80211_AID(b) % 32)))
72 #define	IEEE80211_AID_ISSET(_vap, b) \
73 	((_vap)->iv_aid_bitmap[IEEE80211_AID(b) / 32] & (1 << (IEEE80211_AID(b) % 32)))
74 
75 #ifdef IEEE80211_DEBUG_REFCNT
76 #define REFCNT_LOC "%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line
77 #else
78 #define REFCNT_LOC "%s %p<%s> refcnt %d\n", __func__
79 #endif
80 
81 static int ieee80211_sta_join1(struct ieee80211_node *);
82 
83 static struct ieee80211_node *node_alloc(struct ieee80211vap *,
84 	const uint8_t [IEEE80211_ADDR_LEN]);
85 static void node_cleanup(struct ieee80211_node *);
86 static void node_free(struct ieee80211_node *);
87 static void node_age(struct ieee80211_node *);
88 static int8_t node_getrssi(const struct ieee80211_node *);
89 static void node_getsignal(const struct ieee80211_node *, int8_t *, int8_t *);
90 static void node_getmimoinfo(const struct ieee80211_node *,
91 	struct ieee80211_mimo_info *);
92 static void ieee80211_node_timeout_callout(void *arg);
93 
94 static void _ieee80211_free_node(struct ieee80211_node *);
95 
96 static void ieee80211_node_table_init(struct ieee80211com *ic,
97 	struct ieee80211_node_table *nt, const char *name,
98 	int inact, int keymaxix);
99 static void ieee80211_node_table_reset(struct ieee80211_node_table *,
100 	struct ieee80211vap *);
101 static void ieee80211_node_table_cleanup(struct ieee80211_node_table *nt);
102 static void ieee80211_erp_timeout(struct ieee80211com *);
103 
104 MALLOC_DEFINE(M_80211_NODE, "80211node", "802.11 node state");
105 MALLOC_DEFINE(M_80211_NODE_IE, "80211nodeie", "802.11 node ie");
106 
107 void
108 ieee80211_node_attach(struct ieee80211com *ic)
109 {
110 	/* XXX really want maxlen enforced per-sta */
111 	ieee80211_ageq_init(&ic->ic_stageq, ic->ic_max_keyix * 8,
112 	    "802.11 staging q");
113 	ieee80211_node_table_init(ic, &ic->ic_sta, "station",
114 		IEEE80211_INACT_INIT, ic->ic_max_keyix);
115 	callout_init_mp(&ic->ic_inact);
116 	callout_reset(&ic->ic_inact, IEEE80211_INACT_WAIT*hz,
117 		      ieee80211_node_timeout_callout, ic);
118 
119 	ic->ic_node_alloc = node_alloc;
120 	ic->ic_node_free = node_free;
121 	ic->ic_node_cleanup = node_cleanup;
122 	ic->ic_node_age = node_age;
123 	ic->ic_node_drain = node_age;		/* NB: same as age */
124 	ic->ic_node_getrssi = node_getrssi;
125 	ic->ic_node_getsignal = node_getsignal;
126 	ic->ic_node_getmimoinfo = node_getmimoinfo;
127 
128 	/*
129 	 * Set flags to be propagated to all vap's;
130 	 * these define default behaviour/configuration.
131 	 */
132 	ic->ic_flags_ext |= IEEE80211_FEXT_INACT; /* inactivity processing */
133 }
134 
135 void
136 ieee80211_node_detach(struct ieee80211com *ic)
137 {
138 
139 	callout_stop(&ic->ic_inact);
140 	ieee80211_node_table_cleanup(&ic->ic_sta);
141 	ieee80211_ageq_cleanup(&ic->ic_stageq);
142 }
143 
144 void
145 ieee80211_node_vattach(struct ieee80211vap *vap)
146 {
147 	/* NB: driver can override */
148 	vap->iv_max_aid = IEEE80211_AID_DEF;
149 
150 	/* default station inactivity timer setings */
151 	vap->iv_inact_init = IEEE80211_INACT_INIT;
152 	vap->iv_inact_auth = IEEE80211_INACT_AUTH;
153 	vap->iv_inact_run = IEEE80211_INACT_RUN;
154 	vap->iv_inact_probe = IEEE80211_INACT_PROBE;
155 
156 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_INACT,
157 	    "%s: init %u auth %u run %u probe %u\n", __func__,
158 	    vap->iv_inact_init, vap->iv_inact_auth,
159 	    vap->iv_inact_run, vap->iv_inact_probe);
160 }
161 
162 void
163 ieee80211_node_latevattach(struct ieee80211vap *vap)
164 {
165 	if (vap->iv_opmode == IEEE80211_M_HOSTAP) {
166 		/* XXX should we allow max aid to be zero? */
167 		if (vap->iv_max_aid < IEEE80211_AID_MIN) {
168 			vap->iv_max_aid = IEEE80211_AID_MIN;
169 			if_printf(vap->iv_ifp,
170 			    "WARNING: max aid too small, changed to %d\n",
171 			    vap->iv_max_aid);
172 		}
173 		vap->iv_aid_bitmap = (uint32_t *) kmalloc(
174 			howmany(vap->iv_max_aid, 32) * sizeof(uint32_t),
175 			M_80211_NODE, M_INTWAIT | M_ZERO);
176 		if (vap->iv_aid_bitmap == NULL) {
177 			/* XXX no way to recover */
178 			kprintf("%s: no memory for AID bitmap, max aid %d!\n",
179 			    __func__, vap->iv_max_aid);
180 			vap->iv_max_aid = 0;
181 		}
182 	}
183 
184 	ieee80211_reset_bss(vap);
185 
186 	vap->iv_auth = ieee80211_authenticator_get(vap->iv_bss->ni_authmode);
187 }
188 
189 void
190 ieee80211_node_vdetach(struct ieee80211vap *vap)
191 {
192 	struct ieee80211com *ic = vap->iv_ic;
193 
194 	ieee80211_node_table_reset(&ic->ic_sta, vap);
195 	if (vap->iv_bss != NULL) {
196 		ieee80211_free_node(vap->iv_bss);
197 		vap->iv_bss = NULL;
198 	}
199 	if (vap->iv_aid_bitmap != NULL) {
200 		kfree(vap->iv_aid_bitmap, M_80211_NODE);
201 		vap->iv_aid_bitmap = NULL;
202 	}
203 }
204 
205 /*
206  * Port authorize/unauthorize interfaces for use by an authenticator.
207  */
208 
209 void
210 ieee80211_node_authorize(struct ieee80211_node *ni)
211 {
212 	struct ieee80211vap *vap = ni->ni_vap;
213 
214 	ni->ni_flags |= IEEE80211_NODE_AUTH;
215 	ni->ni_inact_reload = vap->iv_inact_run;
216 	ni->ni_inact = ni->ni_inact_reload;
217 
218 	IEEE80211_NOTE(vap, IEEE80211_MSG_INACT, ni,
219 	    "%s: inact_reload %u", __func__, ni->ni_inact_reload);
220 }
221 
222 void
223 ieee80211_node_unauthorize(struct ieee80211_node *ni)
224 {
225 	struct ieee80211vap *vap = ni->ni_vap;
226 
227 	ni->ni_flags &= ~IEEE80211_NODE_AUTH;
228 	ni->ni_inact_reload = vap->iv_inact_auth;
229 	if (ni->ni_inact > ni->ni_inact_reload)
230 		ni->ni_inact = ni->ni_inact_reload;
231 
232 	IEEE80211_NOTE(vap, IEEE80211_MSG_INACT, ni,
233 	    "%s: inact_reload %u inact %u", __func__,
234 	    ni->ni_inact_reload, ni->ni_inact);
235 }
236 
237 /*
238  * Fix tx parameters for a node according to ``association state''.
239  */
240 void
241 ieee80211_node_setuptxparms(struct ieee80211_node *ni)
242 {
243 	struct ieee80211vap *vap = ni->ni_vap;
244 	enum ieee80211_phymode mode;
245 
246 	if (ni->ni_flags & IEEE80211_NODE_HT) {
247 		if (IEEE80211_IS_CHAN_5GHZ(ni->ni_chan))
248 			mode = IEEE80211_MODE_11NA;
249 		else
250 			mode = IEEE80211_MODE_11NG;
251 	} else {				/* legacy rate handling */
252 		if (IEEE80211_IS_CHAN_ST(ni->ni_chan))
253 			mode = IEEE80211_MODE_STURBO_A;
254 		else if (IEEE80211_IS_CHAN_HALF(ni->ni_chan))
255 			mode = IEEE80211_MODE_HALF;
256 		else if (IEEE80211_IS_CHAN_QUARTER(ni->ni_chan))
257 			mode = IEEE80211_MODE_QUARTER;
258 		/* NB: 108A should be handled as 11a */
259 		else if (IEEE80211_IS_CHAN_A(ni->ni_chan))
260 			mode = IEEE80211_MODE_11A;
261 		else if (IEEE80211_IS_CHAN_108G(ni->ni_chan) ||
262 		    (ni->ni_flags & IEEE80211_NODE_ERP))
263 			mode = IEEE80211_MODE_11G;
264 		else
265 			mode = IEEE80211_MODE_11B;
266 	}
267 	ni->ni_txparms = &vap->iv_txparms[mode];
268 }
269 
270 /*
271  * Set/change the channel.  The rate set is also updated as
272  * to insure a consistent view by drivers.
273  * XXX should be private but hostap needs it to deal with CSA
274  */
275 void
276 ieee80211_node_set_chan(struct ieee80211_node *ni,
277 	struct ieee80211_channel *chan)
278 {
279 	struct ieee80211com *ic = ni->ni_ic;
280 	struct ieee80211vap *vap = ni->ni_vap;
281 	enum ieee80211_phymode mode;
282 
283 	KASSERT(chan != IEEE80211_CHAN_ANYC, ("no channel"));
284 
285 	ni->ni_chan = chan;
286 	mode = ieee80211_chan2mode(chan);
287 	if (IEEE80211_IS_CHAN_HT(chan)) {
288 		/*
289 		 * XXX Gotta be careful here; the rate set returned by
290 		 * ieee80211_get_suprates is actually any HT rate
291 		 * set so blindly copying it will be bad.  We must
292 		 * install the legacy rate est in ni_rates and the
293 		 * HT rate set in ni_htrates.
294 		 */
295 		ni->ni_htrates = *ieee80211_get_suphtrates(ic, chan);
296 		/*
297 		 * Setup bss tx parameters based on operating mode.  We
298 		 * use legacy rates when operating in a mixed HT+non-HT bss
299 		 * and non-ERP rates in 11g for mixed ERP+non-ERP bss.
300 		 */
301 		if (mode == IEEE80211_MODE_11NA &&
302 		    (vap->iv_flags_ht & IEEE80211_FHT_PUREN) == 0)
303 			mode = IEEE80211_MODE_11A;
304 		else if (mode == IEEE80211_MODE_11NG &&
305 		    (vap->iv_flags_ht & IEEE80211_FHT_PUREN) == 0)
306 			mode = IEEE80211_MODE_11G;
307 		if (mode == IEEE80211_MODE_11G &&
308 		    (vap->iv_flags & IEEE80211_F_PUREG) == 0)
309 			mode = IEEE80211_MODE_11B;
310 	}
311 	ni->ni_txparms = &vap->iv_txparms[mode];
312 	ni->ni_rates = *ieee80211_get_suprates(ic, chan);
313 }
314 
315 static __inline void
316 copy_bss(struct ieee80211_node *nbss, const struct ieee80211_node *obss)
317 {
318 	/* propagate useful state */
319 	nbss->ni_authmode = obss->ni_authmode;
320 	nbss->ni_txpower = obss->ni_txpower;
321 	nbss->ni_vlan = obss->ni_vlan;
322 	/* XXX statistics? */
323 	/* XXX legacy WDS bssid? */
324 }
325 
326 void
327 ieee80211_create_ibss(struct ieee80211vap* vap, struct ieee80211_channel *chan)
328 {
329 	struct ieee80211com *ic = vap->iv_ic;
330 	struct ieee80211_node *ni;
331 
332 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
333 		"%s: creating %s on channel %u\n", __func__,
334 		ieee80211_opmode_name[vap->iv_opmode],
335 		ieee80211_chan2ieee(ic, chan));
336 
337 	ni = ieee80211_alloc_node(&ic->ic_sta, vap, vap->iv_myaddr);
338 	if (ni == NULL) {
339 		/* XXX recovery? */
340 		return;
341 	}
342 	IEEE80211_ADDR_COPY(ni->ni_bssid, vap->iv_myaddr);
343 	ni->ni_esslen = vap->iv_des_ssid[0].len;
344 	memcpy(ni->ni_essid, vap->iv_des_ssid[0].ssid, ni->ni_esslen);
345 	if (vap->iv_bss != NULL)
346 		copy_bss(ni, vap->iv_bss);
347 	ni->ni_intval = ic->ic_bintval;
348 	if (vap->iv_flags & IEEE80211_F_PRIVACY)
349 		ni->ni_capinfo |= IEEE80211_CAPINFO_PRIVACY;
350 	if (ic->ic_phytype == IEEE80211_T_FH) {
351 		ni->ni_fhdwell = 200;	/* XXX */
352 		ni->ni_fhindex = 1;
353 	}
354 	if (vap->iv_opmode == IEEE80211_M_IBSS) {
355 		vap->iv_flags |= IEEE80211_F_SIBSS;
356 		ni->ni_capinfo |= IEEE80211_CAPINFO_IBSS;	/* XXX */
357 		if (vap->iv_flags & IEEE80211_F_DESBSSID)
358 			IEEE80211_ADDR_COPY(ni->ni_bssid, vap->iv_des_bssid);
359 		else {
360 			get_random_bytes(ni->ni_bssid, IEEE80211_ADDR_LEN);
361 			/* clear group bit, add local bit */
362 			ni->ni_bssid[0] = (ni->ni_bssid[0] &~ 0x01) | 0x02;
363 		}
364 	} else if (vap->iv_opmode == IEEE80211_M_AHDEMO) {
365 		if (vap->iv_flags & IEEE80211_F_DESBSSID)
366 			IEEE80211_ADDR_COPY(ni->ni_bssid, vap->iv_des_bssid);
367 		else
368 #ifdef IEEE80211_SUPPORT_TDMA
369 		if ((vap->iv_caps & IEEE80211_C_TDMA) == 0)
370 #endif
371 			memset(ni->ni_bssid, 0, IEEE80211_ADDR_LEN);
372 #ifdef IEEE80211_SUPPORT_MESH
373 	} else if (vap->iv_opmode == IEEE80211_M_MBSS) {
374 		ni->ni_meshidlen = vap->iv_mesh->ms_idlen;
375 		memcpy(ni->ni_meshid, vap->iv_mesh->ms_id, ni->ni_meshidlen);
376 #endif
377 	}
378 	/*
379 	 * Fix the channel and related attributes.
380 	 */
381 	/* clear DFS CAC state on previous channel */
382 	if (ic->ic_bsschan != IEEE80211_CHAN_ANYC &&
383 	    ic->ic_bsschan->ic_freq != chan->ic_freq &&
384 	    IEEE80211_IS_CHAN_CACDONE(ic->ic_bsschan))
385 		ieee80211_dfs_cac_clear(ic, ic->ic_bsschan);
386 	ic->ic_bsschan = chan;
387 	ieee80211_node_set_chan(ni, chan);
388 	ic->ic_curmode = ieee80211_chan2mode(chan);
389 	/*
390 	 * Do mode-specific setup.
391 	 */
392 	if (IEEE80211_IS_CHAN_FULL(chan)) {
393 		if (IEEE80211_IS_CHAN_ANYG(chan)) {
394 			/*
395 			 * Use a mixed 11b/11g basic rate set.
396 			 */
397 			ieee80211_setbasicrates(&ni->ni_rates,
398 			    IEEE80211_MODE_11G);
399 			if (vap->iv_flags & IEEE80211_F_PUREG) {
400 				/*
401 				 * Also mark OFDM rates basic so 11b
402 				 * stations do not join (WiFi compliance).
403 				 */
404 				ieee80211_addbasicrates(&ni->ni_rates,
405 				    IEEE80211_MODE_11A);
406 			}
407 		} else if (IEEE80211_IS_CHAN_B(chan)) {
408 			/*
409 			 * Force pure 11b rate set.
410 			 */
411 			ieee80211_setbasicrates(&ni->ni_rates,
412 				IEEE80211_MODE_11B);
413 		}
414 	}
415 
416 	(void) ieee80211_sta_join1(ieee80211_ref_node(ni));
417 }
418 
419 /*
420  * Reset bss state on transition to the INIT state.
421  * Clear any stations from the table (they have been
422  * deauth'd) and reset the bss node (clears key, rate
423  * etc. state).
424  */
425 void
426 ieee80211_reset_bss(struct ieee80211vap *vap)
427 {
428 	struct ieee80211com *ic = vap->iv_ic;
429 	struct ieee80211_node *ni, *obss;
430 
431 	ieee80211_node_table_reset(&ic->ic_sta, vap);
432 	/* XXX multi-bss: wrong */
433 	ieee80211_reset_erp(ic);
434 
435 	ni = ieee80211_alloc_node(&ic->ic_sta, vap, vap->iv_myaddr);
436 	KASSERT(ni != NULL, ("unable to setup initial BSS node"));
437 	obss = vap->iv_bss;
438 	vap->iv_bss = ieee80211_ref_node(ni);
439 	if (obss != NULL) {
440 		copy_bss(ni, obss);
441 		ni->ni_intval = ic->ic_bintval;
442 		ieee80211_free_node(obss);
443 	} else
444 		IEEE80211_ADDR_COPY(ni->ni_bssid, vap->iv_myaddr);
445 }
446 
447 static int
448 match_ssid(const struct ieee80211_node *ni,
449 	int nssid, const struct ieee80211_scan_ssid ssids[])
450 {
451 	int i;
452 
453 	for (i = 0; i < nssid; i++) {
454 		if (ni->ni_esslen == ssids[i].len &&
455 		     memcmp(ni->ni_essid, ssids[i].ssid, ni->ni_esslen) == 0)
456 			return 1;
457 	}
458 	return 0;
459 }
460 
461 /*
462  * Test a node for suitability/compatibility.
463  */
464 static int
465 check_bss(struct ieee80211vap *vap, struct ieee80211_node *ni)
466 {
467 	struct ieee80211com *ic = ni->ni_ic;
468         uint8_t rate;
469 
470 	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
471 		return 0;
472 	if (vap->iv_opmode == IEEE80211_M_IBSS) {
473 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
474 			return 0;
475 	} else {
476 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
477 			return 0;
478 	}
479 	if (vap->iv_flags & IEEE80211_F_PRIVACY) {
480 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
481 			return 0;
482 	} else {
483 		/* XXX does this mean privacy is supported or required? */
484 		if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
485 			return 0;
486 	}
487 	rate = ieee80211_fix_rate(ni, &ni->ni_rates,
488 	    IEEE80211_F_JOIN | IEEE80211_F_DONEGO | IEEE80211_F_DOFRATE);
489 	if (rate & IEEE80211_RATE_BASIC)
490 		return 0;
491 	if (vap->iv_des_nssid != 0 &&
492 	    !match_ssid(ni, vap->iv_des_nssid, vap->iv_des_ssid))
493 		return 0;
494 	if ((vap->iv_flags & IEEE80211_F_DESBSSID) &&
495 	    !IEEE80211_ADDR_EQ(vap->iv_des_bssid, ni->ni_bssid))
496 		return 0;
497 	return 1;
498 }
499 
500 #ifdef IEEE80211_DEBUG
501 /*
502  * Display node suitability/compatibility.
503  */
504 static void
505 check_bss_debug(struct ieee80211vap *vap, struct ieee80211_node *ni)
506 {
507 	struct ieee80211com *ic = ni->ni_ic;
508         uint8_t rate;
509         int fail;
510 	char ethstr[ETHER_ADDRSTRLEN + 1];
511 
512 	fail = 0;
513 	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
514 		fail |= 0x01;
515 	if (vap->iv_opmode == IEEE80211_M_IBSS) {
516 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
517 			fail |= 0x02;
518 	} else {
519 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
520 			fail |= 0x02;
521 	}
522 	if (vap->iv_flags & IEEE80211_F_PRIVACY) {
523 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
524 			fail |= 0x04;
525 	} else {
526 		/* XXX does this mean privacy is supported or required? */
527 		if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
528 			fail |= 0x04;
529 	}
530 	rate = ieee80211_fix_rate(ni, &ni->ni_rates,
531 	     IEEE80211_F_JOIN | IEEE80211_F_DONEGO | IEEE80211_F_DOFRATE);
532 	if (rate & IEEE80211_RATE_BASIC)
533 		fail |= 0x08;
534 	if (vap->iv_des_nssid != 0 &&
535 	    !match_ssid(ni, vap->iv_des_nssid, vap->iv_des_ssid))
536 		fail |= 0x10;
537 	if ((vap->iv_flags & IEEE80211_F_DESBSSID) &&
538 	    !IEEE80211_ADDR_EQ(vap->iv_des_bssid, ni->ni_bssid))
539 		fail |= 0x20;
540 
541 	kprintf(" %c %s", fail ? '-' : '+', kether_ntoa(ni->ni_macaddr, ethstr));
542 	kprintf(" %s%c", kether_ntoa(ni->ni_bssid, ethstr), fail & 0x20 ? '!' : ' ');
543 	kprintf(" %3d%c",
544 	    ieee80211_chan2ieee(ic, ni->ni_chan), fail & 0x01 ? '!' : ' ');
545 	kprintf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
546 	    fail & 0x08 ? '!' : ' ');
547 	kprintf(" %4s%c",
548 	    (ni->ni_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
549 	    (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
550 	    "????",
551 	    fail & 0x02 ? '!' : ' ');
552 	kprintf(" %3s%c ",
553 	    (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) ?  "wep" : "no",
554 	    fail & 0x04 ? '!' : ' ');
555 	ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
556 	kprintf("%s\n", fail & 0x10 ? "!" : "");
557 }
558 #endif /* IEEE80211_DEBUG */
559 
560 /*
561  * Handle 802.11 ad hoc network merge.  The
562  * convention, set by the Wireless Ethernet Compatibility Alliance
563  * (WECA), is that an 802.11 station will change its BSSID to match
564  * the "oldest" 802.11 ad hoc network, on the same channel, that
565  * has the station's desired SSID.  The "oldest" 802.11 network
566  * sends beacons with the greatest TSF timestamp.
567  *
568  * The caller is assumed to validate TSF's before attempting a merge.
569  *
570  * Return !0 if the BSSID changed, 0 otherwise.
571  */
572 int
573 ieee80211_ibss_merge(struct ieee80211_node *ni)
574 {
575 	struct ieee80211vap *vap = ni->ni_vap;
576 #ifdef IEEE80211_DEBUG
577 	struct ieee80211com *ic = ni->ni_ic;
578 	char ethstr[ETHER_ADDRSTRLEN + 1];
579 #endif
580 
581 	if (ni == vap->iv_bss ||
582 	    IEEE80211_ADDR_EQ(ni->ni_bssid, vap->iv_bss->ni_bssid)) {
583 		/* unchanged, nothing to do */
584 		return 0;
585 	}
586 	if (!check_bss(vap, ni)) {
587 		/* capabilities mismatch */
588 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_ASSOC,
589 		    "%s: merge failed, capabilities mismatch\n", __func__);
590 #ifdef IEEE80211_DEBUG
591 		if (ieee80211_msg_assoc(vap))
592 			check_bss_debug(vap, ni);
593 #endif
594 		vap->iv_stats.is_ibss_capmismatch++;
595 		return 0;
596 	}
597 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_ASSOC,
598 		"%s: new bssid %s: %s preamble, %s slot time%s\n", __func__,
599 		kether_ntoa(ni->ni_bssid, ethstr),
600 		ic->ic_flags&IEEE80211_F_SHPREAMBLE ? "short" : "long",
601 		ic->ic_flags&IEEE80211_F_SHSLOT ? "short" : "long",
602 		ic->ic_flags&IEEE80211_F_USEPROT ? ", protection" : ""
603 	);
604 	return ieee80211_sta_join1(ieee80211_ref_node(ni));
605 }
606 
607 /*
608  * Calculate HT channel promotion flags for all vaps.
609  * This assumes ni_chan have been setup for each vap.
610  */
611 static int
612 gethtadjustflags(struct ieee80211com *ic)
613 {
614 	struct ieee80211vap *vap;
615 	int flags;
616 
617 	flags = 0;
618 	/* XXX locking */
619 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
620 		if (vap->iv_state < IEEE80211_S_RUN)
621 			continue;
622 		switch (vap->iv_opmode) {
623 		case IEEE80211_M_WDS:
624 		case IEEE80211_M_STA:
625 		case IEEE80211_M_AHDEMO:
626 		case IEEE80211_M_HOSTAP:
627 		case IEEE80211_M_IBSS:
628 		case IEEE80211_M_MBSS:
629 			flags |= ieee80211_htchanflags(vap->iv_bss->ni_chan);
630 			break;
631 		default:
632 			break;
633 		}
634 	}
635 	return flags;
636 }
637 
638 /*
639  * Check if the current channel needs to change based on whether
640  * any vap's are using HT20/HT40.  This is used to sync the state
641  * of ic_curchan after a channel width change on a running vap.
642  */
643 void
644 ieee80211_sync_curchan(struct ieee80211com *ic)
645 {
646 	struct ieee80211_channel *c;
647 
648 	c = ieee80211_ht_adjust_channel(ic, ic->ic_curchan, gethtadjustflags(ic));
649 	if (c != ic->ic_curchan) {
650 		ic->ic_curchan = c;
651 		ic->ic_curmode = ieee80211_chan2mode(ic->ic_curchan);
652 		ic->ic_rt = ieee80211_get_ratetable(ic->ic_curchan);
653 		ic->ic_set_channel(ic);
654 		ieee80211_radiotap_chan_change(ic);
655 	}
656 }
657 
658 /*
659  * Setup the current channel.  The request channel may be
660  * promoted if other vap's are operating with HT20/HT40.
661  */
662 void
663 ieee80211_setupcurchan(struct ieee80211com *ic, struct ieee80211_channel *c)
664 {
665 	if (ic->ic_htcaps & IEEE80211_HTC_HT) {
666 		int flags = gethtadjustflags(ic);
667 		/*
668 		 * Check for channel promotion required to support the
669 		 * set of running vap's.  This assumes we are called
670 		 * after ni_chan is setup for each vap.
671 		 */
672 		/* NB: this assumes IEEE80211_FHT_USEHT40 > IEEE80211_FHT_HT */
673 		if (flags > ieee80211_htchanflags(c))
674 			c = ieee80211_ht_adjust_channel(ic, c, flags);
675 	}
676 	ic->ic_bsschan = ic->ic_curchan = c;
677 	ic->ic_curmode = ieee80211_chan2mode(ic->ic_curchan);
678 	ic->ic_rt = ieee80211_get_ratetable(ic->ic_curchan);
679 }
680 
681 /*
682  * Change the current channel.  The channel change is guaranteed to have
683  * happened before the next state change.
684  */
685 void
686 ieee80211_setcurchan(struct ieee80211com *ic, struct ieee80211_channel *c)
687 {
688 	ieee80211_setupcurchan(ic, c);
689 	ieee80211_runtask(ic, &ic->ic_chan_task);
690 }
691 
692 /*
693  * Join the specified IBSS/BSS network.  The node is assumed to
694  * be passed in with a held reference.
695  */
696 static int
697 ieee80211_sta_join1(struct ieee80211_node *selbs)
698 {
699 	struct ieee80211vap *vap = selbs->ni_vap;
700 	struct ieee80211com *ic = selbs->ni_ic;
701 	struct ieee80211_node *obss;
702 	int canreassoc;
703 
704 	/*
705 	 * Committed to selbs, setup state.
706 	 */
707 	obss = vap->iv_bss;
708 	/*
709 	 * Check if old+new node have the same address in which
710 	 * case we can reassociate when operating in sta mode.
711 	 */
712 	canreassoc = (obss != NULL &&
713 		vap->iv_state == IEEE80211_S_RUN &&
714 		IEEE80211_ADDR_EQ(obss->ni_macaddr, selbs->ni_macaddr));
715 	vap->iv_bss = selbs;		/* NB: caller assumed to bump refcnt */
716 	if (obss != NULL) {
717 		copy_bss(selbs, obss);
718 		ieee80211_node_decref(obss);	/* iv_bss reference */
719 		ieee80211_free_node(obss);	/* station table reference */
720 		obss = NULL;		/* NB: guard against later use */
721 	}
722 
723 	/*
724 	 * Delete unusable rates; we've already checked
725 	 * that the negotiated rate set is acceptable.
726 	 */
727 	ieee80211_fix_rate(vap->iv_bss, &vap->iv_bss->ni_rates,
728 		IEEE80211_F_DODEL | IEEE80211_F_JOIN);
729 
730 	ieee80211_setcurchan(ic, selbs->ni_chan);
731 	/*
732 	 * Set the erp state (mostly the slot time) to deal with
733 	 * the auto-select case; this should be redundant if the
734 	 * mode is locked.
735 	 */
736 	ieee80211_reset_erp(ic);
737 	ieee80211_wme_initparams(vap);
738 
739 	if (vap->iv_opmode == IEEE80211_M_STA) {
740 		if (canreassoc) {
741 			/* Reassociate */
742 			ieee80211_new_state(vap, IEEE80211_S_ASSOC, 1);
743 		} else {
744 			/*
745 			 * Act as if we received a DEAUTH frame in case we
746 			 * are invoked from the RUN state.  This will cause
747 			 * us to try to re-authenticate if we are operating
748 			 * as a station.
749 			 */
750 			ieee80211_new_state(vap, IEEE80211_S_AUTH,
751 				IEEE80211_FC0_SUBTYPE_DEAUTH);
752 		}
753 	} else
754 		ieee80211_new_state(vap, IEEE80211_S_RUN, -1);
755 	return 1;
756 }
757 
758 int
759 ieee80211_sta_join(struct ieee80211vap *vap, struct ieee80211_channel *chan,
760 	const struct ieee80211_scan_entry *se)
761 {
762 	struct ieee80211com *ic = vap->iv_ic;
763 	struct ieee80211_node *ni;
764 
765 	ni = ieee80211_alloc_node(&ic->ic_sta, vap, se->se_macaddr);
766 	if (ni == NULL) {
767 		/* XXX msg */
768 		return 0;
769 	}
770 	/*
771 	 * Expand scan state into node's format.
772 	 * XXX may not need all this stuff
773 	 */
774 	IEEE80211_ADDR_COPY(ni->ni_bssid, se->se_bssid);
775 	ni->ni_esslen = se->se_ssid[1];
776 	memcpy(ni->ni_essid, se->se_ssid+2, ni->ni_esslen);
777 	ni->ni_tstamp.tsf = se->se_tstamp.tsf;
778 	ni->ni_intval = se->se_intval;
779 	ni->ni_capinfo = se->se_capinfo;
780 	ni->ni_chan = chan;
781 	ni->ni_timoff = se->se_timoff;
782 	ni->ni_fhdwell = se->se_fhdwell;
783 	ni->ni_fhindex = se->se_fhindex;
784 	ni->ni_erp = se->se_erp;
785 	IEEE80211_RSSI_LPF(ni->ni_avgrssi, se->se_rssi);
786 	ni->ni_noise = se->se_noise;
787 	if (vap->iv_opmode == IEEE80211_M_STA) {
788 		/* NB: only infrastructure mode requires an associd */
789 		ni->ni_flags |= IEEE80211_NODE_ASSOCID;
790 	}
791 
792 	if (ieee80211_ies_init(&ni->ni_ies, se->se_ies.data, se->se_ies.len)) {
793 		ieee80211_ies_expand(&ni->ni_ies);
794 #ifdef IEEE80211_SUPPORT_SUPERG
795 		if (ni->ni_ies.ath_ie != NULL)
796 			ieee80211_parse_ath(ni, ni->ni_ies.ath_ie);
797 #endif
798 		if (ni->ni_ies.htcap_ie != NULL)
799 			ieee80211_parse_htcap(ni, ni->ni_ies.htcap_ie);
800 		if (ni->ni_ies.htinfo_ie != NULL)
801 			ieee80211_parse_htinfo(ni, ni->ni_ies.htinfo_ie);
802 #ifdef IEEE80211_SUPPORT_MESH
803 		if (ni->ni_ies.meshid_ie != NULL)
804 			ieee80211_parse_meshid(ni, ni->ni_ies.meshid_ie);
805 #endif
806 #ifdef IEEE80211_SUPPORT_TDMA
807 		if (ni->ni_ies.tdma_ie != NULL)
808 			ieee80211_parse_tdma(ni, ni->ni_ies.tdma_ie);
809 #endif
810 	}
811 
812 	vap->iv_dtim_period = se->se_dtimperiod;
813 	vap->iv_dtim_count = 0;
814 
815 	/* NB: must be after ni_chan is setup */
816 	ieee80211_setup_rates(ni, se->se_rates, se->se_xrates,
817 		IEEE80211_F_DOSORT);
818 	if (ieee80211_iserp_rateset(&ni->ni_rates))
819 		ni->ni_flags |= IEEE80211_NODE_ERP;
820 	ieee80211_node_setuptxparms(ni);
821 
822 	return ieee80211_sta_join1(ieee80211_ref_node(ni));
823 }
824 
825 /*
826  * Leave the specified IBSS/BSS network.  The node is assumed to
827  * be passed in with a held reference.
828  */
829 void
830 ieee80211_sta_leave(struct ieee80211_node *ni)
831 {
832 	struct ieee80211com *ic = ni->ni_ic;
833 
834 	ic->ic_node_cleanup(ni);
835 	ieee80211_notify_node_leave(ni);
836 }
837 
838 /*
839  * Send a deauthenticate frame and drop the station.
840  */
841 void
842 ieee80211_node_deauth(struct ieee80211_node *ni, int reason)
843 {
844 	/* NB: bump the refcnt to be sure temporay nodes are not reclaimed */
845 	ieee80211_ref_node(ni);
846 	if (ni->ni_associd != 0)
847 		IEEE80211_SEND_MGMT(ni, IEEE80211_FC0_SUBTYPE_DEAUTH, reason);
848 	ieee80211_node_leave(ni);
849 	ieee80211_free_node(ni);
850 }
851 
852 static struct ieee80211_node *
853 node_alloc(struct ieee80211vap *vap, const uint8_t macaddr[IEEE80211_ADDR_LEN])
854 {
855 	struct ieee80211_node *ni;
856 
857 	ni = (struct ieee80211_node *) kmalloc(sizeof(struct ieee80211_node),
858 		M_80211_NODE, M_INTWAIT | M_ZERO);
859 	return ni;
860 }
861 
862 /*
863  * Initialize an ie blob with the specified data.  If previous
864  * data exists re-use the data block.  As a side effect we clear
865  * all references to specific ie's; the caller is required to
866  * recalculate them.
867  */
868 int
869 ieee80211_ies_init(struct ieee80211_ies *ies, const uint8_t *data, int len)
870 {
871 	/* NB: assumes data+len are the last fields */
872 	memset(ies, 0, offsetof(struct ieee80211_ies, data));
873 	if (ies->data != NULL && ies->len != len) {
874 		/* data size changed */
875 		kfree(ies->data, M_80211_NODE_IE);
876 		ies->data = NULL;
877 	}
878 	if (ies->data == NULL) {
879 		ies->data = (uint8_t *) kmalloc(len, M_80211_NODE_IE, M_INTWAIT);
880 		if (ies->data == NULL) {
881 			ies->len = 0;
882 			/* NB: pointers have already been zero'd above */
883 			return 0;
884 		}
885 	}
886 	memcpy(ies->data, data, len);
887 	ies->len = len;
888 	return 1;
889 }
890 
891 /*
892  * Reclaim storage for an ie blob.
893  */
894 void
895 ieee80211_ies_cleanup(struct ieee80211_ies *ies)
896 {
897 	if (ies->data != NULL)
898 		kfree(ies->data, M_80211_NODE_IE);
899 }
900 
901 /*
902  * Expand an ie blob data contents and to fillin individual
903  * ie pointers.  The data blob is assumed to be well-formed;
904  * we don't do any validity checking of ie lengths.
905  */
906 void
907 ieee80211_ies_expand(struct ieee80211_ies *ies)
908 {
909 	uint8_t *ie;
910 	int ielen;
911 
912 	ie = ies->data;
913 	ielen = ies->len;
914 	while (ielen > 0) {
915 		switch (ie[0]) {
916 		case IEEE80211_ELEMID_VENDOR:
917 			if (iswpaoui(ie))
918 				ies->wpa_ie = ie;
919 			else if (iswmeoui(ie))
920 				ies->wme_ie = ie;
921 #ifdef IEEE80211_SUPPORT_SUPERG
922 			else if (isatherosoui(ie))
923 				ies->ath_ie = ie;
924 #endif
925 #ifdef IEEE80211_SUPPORT_TDMA
926 			else if (istdmaoui(ie))
927 				ies->tdma_ie = ie;
928 #endif
929 			break;
930 		case IEEE80211_ELEMID_RSN:
931 			ies->rsn_ie = ie;
932 			break;
933 		case IEEE80211_ELEMID_HTCAP:
934 			ies->htcap_ie = ie;
935 			break;
936 #ifdef IEEE80211_SUPPORT_MESH
937 		case IEEE80211_ELEMID_MESHID:
938 			ies->meshid_ie = ie;
939 			break;
940 #endif
941 		}
942 		ielen -= 2 + ie[1];
943 		ie += 2 + ie[1];
944 	}
945 }
946 
947 /*
948  * Reclaim any resources in a node and reset any critical
949  * state.  Typically nodes are free'd immediately after,
950  * but in some cases the storage may be reused so we need
951  * to insure consistent state (should probably fix that).
952  */
953 static void
954 node_cleanup(struct ieee80211_node *ni)
955 {
956 	struct ieee80211vap *vap = ni->ni_vap;
957 	struct ieee80211com *ic = ni->ni_ic;
958 	int i;
959 
960 	/* NB: preserve ni_table */
961 	if (ni->ni_flags & IEEE80211_NODE_PWR_MGT) {
962 		if (vap->iv_opmode != IEEE80211_M_STA)
963 			vap->iv_ps_sta--;
964 		ni->ni_flags &= ~IEEE80211_NODE_PWR_MGT;
965 		IEEE80211_NOTE(vap, IEEE80211_MSG_POWER, ni,
966 		    "power save mode off, %u sta's in ps mode", vap->iv_ps_sta);
967 	}
968 	/*
969 	 * Cleanup any HT-related state.
970 	 */
971 	if (ni->ni_flags & IEEE80211_NODE_HT)
972 		ieee80211_ht_node_cleanup(ni);
973 #ifdef IEEE80211_SUPPORT_SUPERG
974 	else if (ni->ni_ath_flags & IEEE80211_NODE_ATH)
975 		ieee80211_ff_node_cleanup(ni);
976 #endif
977 #ifdef IEEE80211_SUPPORT_MESH
978 	/*
979 	 * Cleanup any mesh-related state.
980 	 */
981 	if (vap->iv_opmode == IEEE80211_M_MBSS)
982 		ieee80211_mesh_node_cleanup(ni);
983 #endif
984 	/*
985 	 * Clear any staging queue entries.
986 	 */
987 	ieee80211_ageq_drain_node(&ic->ic_stageq, ni);
988 
989 	/*
990 	 * Clear AREF flag that marks the authorization refcnt bump
991 	 * has happened.  This is probably not needed as the node
992 	 * should always be removed from the table so not found but
993 	 * do it just in case.
994 	 * Likewise clear the ASSOCID flag as these flags are intended
995 	 * to be managed in tandem.
996 	 */
997 	ni->ni_flags &= ~(IEEE80211_NODE_AREF | IEEE80211_NODE_ASSOCID);
998 
999 	/*
1000 	 * Drain power save queue and, if needed, clear TIM.
1001 	 */
1002 	if (ieee80211_node_psq_drain(ni) != 0 && vap->iv_set_tim != NULL)
1003 		vap->iv_set_tim(ni, 0);
1004 
1005 	ni->ni_associd = 0;
1006 	if (ni->ni_challenge != NULL) {
1007 		kfree(ni->ni_challenge, M_80211_NODE);
1008 		ni->ni_challenge = NULL;
1009 	}
1010 	/*
1011 	 * Preserve SSID, WPA, and WME ie's so the bss node is
1012 	 * reusable during a re-auth/re-assoc state transition.
1013 	 * If we remove these data they will not be recreated
1014 	 * because they come from a probe-response or beacon frame
1015 	 * which cannot be expected prior to the association-response.
1016 	 * This should not be an issue when operating in other modes
1017 	 * as stations leaving always go through a full state transition
1018 	 * which will rebuild this state.
1019 	 *
1020 	 * XXX does this leave us open to inheriting old state?
1021 	 */
1022 	for (i = 0; i < NELEM(ni->ni_rxfrag); i++)
1023 		if (ni->ni_rxfrag[i] != NULL) {
1024 			m_freem(ni->ni_rxfrag[i]);
1025 			ni->ni_rxfrag[i] = NULL;
1026 		}
1027 	/*
1028 	 * Must be careful here to remove any key map entry w/o a LOR.
1029 	 */
1030 	ieee80211_node_delucastkey(ni);
1031 }
1032 
1033 static void
1034 node_free(struct ieee80211_node *ni)
1035 {
1036 	struct ieee80211com *ic = ni->ni_ic;
1037 
1038 	ieee80211_ratectl_node_deinit(ni);
1039 	ic->ic_node_cleanup(ni);
1040 	ieee80211_ies_cleanup(&ni->ni_ies);
1041 	ieee80211_psq_cleanup(&ni->ni_psq);
1042 	kfree(ni, M_80211_NODE);
1043 }
1044 
1045 static void
1046 node_age(struct ieee80211_node *ni)
1047 {
1048 	struct ieee80211vap *vap = ni->ni_vap;
1049 
1050 	/*
1051 	 * Age frames on the power save queue.
1052 	 */
1053 	if (ieee80211_node_psq_age(ni) != 0 &&
1054 	    ni->ni_psq.psq_len == 0 && vap->iv_set_tim != NULL)
1055 		vap->iv_set_tim(ni, 0);
1056 	/*
1057 	 * Age out HT resources (e.g. frames on the
1058 	 * A-MPDU reorder queues).
1059 	 */
1060 	if (ni->ni_associd != 0 && (ni->ni_flags & IEEE80211_NODE_HT))
1061 		ieee80211_ht_node_age(ni);
1062 }
1063 
1064 static int8_t
1065 node_getrssi(const struct ieee80211_node *ni)
1066 {
1067 	uint32_t avgrssi = ni->ni_avgrssi;
1068 	int32_t rssi;
1069 
1070 	if (avgrssi == IEEE80211_RSSI_DUMMY_MARKER)
1071 		return 0;
1072 	rssi = IEEE80211_RSSI_GET(avgrssi);
1073 	return rssi < 0 ? 0 : rssi > 127 ? 127 : rssi;
1074 }
1075 
1076 static void
1077 node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
1078 {
1079 	*rssi = node_getrssi(ni);
1080 	*noise = ni->ni_noise;
1081 }
1082 
1083 static void
1084 node_getmimoinfo(const struct ieee80211_node *ni,
1085 	struct ieee80211_mimo_info *info)
1086 {
1087 	/* XXX zero data? */
1088 }
1089 
1090 struct ieee80211_node *
1091 ieee80211_alloc_node(struct ieee80211_node_table *nt,
1092 	struct ieee80211vap *vap, const uint8_t macaddr[IEEE80211_ADDR_LEN])
1093 {
1094 	struct ieee80211com *ic = nt->nt_ic;
1095 	struct ieee80211_node *ni;
1096 	int hash;
1097 #ifdef IEEE80211_DEBUG
1098 	char ethstr[ETHER_ADDRSTRLEN + 1];
1099 #endif
1100 
1101 	ni = ic->ic_node_alloc(vap, macaddr);
1102 	if (ni == NULL) {
1103 		vap->iv_stats.is_rx_nodealloc++;
1104 		return NULL;
1105 	}
1106 
1107 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1108 		"%s %p<%s> in %s table\n", __func__, ni,
1109 		kether_ntoa(macaddr, ethstr), nt->nt_name);
1110 
1111 	IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
1112 	hash = IEEE80211_NODE_HASH(ic, macaddr);
1113 	ieee80211_node_initref(ni);		/* mark referenced */
1114 	ni->ni_chan = IEEE80211_CHAN_ANYC;
1115 	ni->ni_authmode = IEEE80211_AUTH_OPEN;
1116 	ni->ni_txpower = ic->ic_txpowlimit;	/* max power */
1117 	ni->ni_txparms = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
1118 	ieee80211_crypto_resetkey(vap, &ni->ni_ucastkey, IEEE80211_KEYIX_NONE);
1119 	ni->ni_avgrssi = IEEE80211_RSSI_DUMMY_MARKER;
1120 	ni->ni_inact_reload = nt->nt_inact_init;
1121 	ni->ni_inact = ni->ni_inact_reload;
1122 	ni->ni_ath_defkeyix = 0x7fff;
1123 	ieee80211_psq_init(&ni->ni_psq, "unknown");
1124 #ifdef IEEE80211_SUPPORT_MESH
1125 	if (vap->iv_opmode == IEEE80211_M_MBSS)
1126 		ieee80211_mesh_node_init(vap, ni);
1127 #endif
1128 	TAILQ_INSERT_TAIL(&nt->nt_node, ni, ni_list);
1129 	LIST_INSERT_HEAD(&nt->nt_hash[hash], ni, ni_hash);
1130 	ni->ni_table = nt;
1131 	ni->ni_vap = vap;
1132 	ni->ni_ic = ic;
1133 
1134 	IEEE80211_NOTE(vap, IEEE80211_MSG_INACT, ni,
1135 	    "%s: inact_reload %u", __func__, ni->ni_inact_reload);
1136 
1137 	return ni;
1138 }
1139 
1140 /*
1141  * Craft a temporary node suitable for sending a management frame
1142  * to the specified station.  We craft only as much state as we
1143  * need to do the work since the node will be immediately reclaimed
1144  * once the send completes.
1145  */
1146 struct ieee80211_node *
1147 ieee80211_tmp_node(struct ieee80211vap *vap,
1148 	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1149 {
1150 	struct ieee80211com *ic = vap->iv_ic;
1151 	struct ieee80211_node *ni;
1152 #ifdef IEEE80211_DEBUG
1153 	char ethstr[ETHER_ADDRSTRLEN + 1];
1154 #endif
1155 
1156 	ni = ic->ic_node_alloc(vap, macaddr);
1157 	if (ni != NULL) {
1158 		struct ieee80211_node *bss = vap->iv_bss;
1159 
1160 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1161 		    "%s %p<%s>\n", __func__, ni, kether_ntoa(macaddr, ethstr));
1162 
1163 		ni->ni_table = NULL;		/* NB: pedantic */
1164 		ni->ni_ic = ic;			/* NB: needed to set channel */
1165 		ni->ni_vap = vap;
1166 
1167 		IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
1168 		IEEE80211_ADDR_COPY(ni->ni_bssid, bss->ni_bssid);
1169 		ieee80211_node_initref(ni);		/* mark referenced */
1170 		/* NB: required by ieee80211_fix_rate */
1171 		ieee80211_node_set_chan(ni, bss->ni_chan);
1172 		ieee80211_crypto_resetkey(vap, &ni->ni_ucastkey,
1173 			IEEE80211_KEYIX_NONE);
1174 		ni->ni_txpower = bss->ni_txpower;
1175 		/* XXX optimize away */
1176 		ieee80211_psq_init(&ni->ni_psq, "unknown");
1177 	} else {
1178 		/* XXX msg */
1179 		vap->iv_stats.is_rx_nodealloc++;
1180 	}
1181 	return ni;
1182 }
1183 
1184 struct ieee80211_node *
1185 ieee80211_dup_bss(struct ieee80211vap *vap,
1186 	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1187 {
1188 	struct ieee80211com *ic = vap->iv_ic;
1189 	struct ieee80211_node *ni;
1190 
1191 	ni = ieee80211_alloc_node(&ic->ic_sta, vap, macaddr);
1192 	if (ni != NULL) {
1193 		struct ieee80211_node *bss = vap->iv_bss;
1194 		/*
1195 		 * Inherit from iv_bss.
1196 		 */
1197 		copy_bss(ni, bss);
1198 		IEEE80211_ADDR_COPY(ni->ni_bssid, bss->ni_bssid);
1199 		ieee80211_node_set_chan(ni, bss->ni_chan);
1200 	}
1201 	return ni;
1202 }
1203 
1204 /*
1205  * Create a bss node for a legacy WDS vap.  The far end does
1206  * not associate so we just create create a new node and
1207  * simulate an association.  The caller is responsible for
1208  * installing the node as the bss node and handling any further
1209  * setup work like authorizing the port.
1210  */
1211 struct ieee80211_node *
1212 ieee80211_node_create_wds(struct ieee80211vap *vap,
1213 	const uint8_t bssid[IEEE80211_ADDR_LEN], struct ieee80211_channel *chan)
1214 {
1215 	struct ieee80211com *ic = vap->iv_ic;
1216 	struct ieee80211_node *ni;
1217 
1218 	/* XXX check if node already in sta table? */
1219 	ni = ieee80211_alloc_node(&ic->ic_sta, vap, bssid);
1220 	if (ni != NULL) {
1221 		ni->ni_wdsvap = vap;
1222 		IEEE80211_ADDR_COPY(ni->ni_bssid, bssid);
1223 		/*
1224 		 * Inherit any manually configured settings.
1225 		 */
1226 		copy_bss(ni, vap->iv_bss);
1227 		ieee80211_node_set_chan(ni, chan);
1228 		/* NB: propagate ssid so available to WPA supplicant */
1229 		ni->ni_esslen = vap->iv_des_ssid[0].len;
1230 		memcpy(ni->ni_essid, vap->iv_des_ssid[0].ssid, ni->ni_esslen);
1231 		/* NB: no associd for peer */
1232 		/*
1233 		 * There are no management frames to use to
1234 		 * discover neighbor capabilities, so blindly
1235 		 * propagate the local configuration.
1236 		 */
1237 		if (vap->iv_flags & IEEE80211_F_WME)
1238 			ni->ni_flags |= IEEE80211_NODE_QOS;
1239 #ifdef IEEE80211_SUPPORT_SUPERG
1240 		if (vap->iv_flags & IEEE80211_F_FF)
1241 			ni->ni_flags |= IEEE80211_NODE_FF;
1242 #endif
1243 		if ((ic->ic_htcaps & IEEE80211_HTC_HT) &&
1244 		    (vap->iv_flags_ht & IEEE80211_FHT_HT)) {
1245 			/*
1246 			 * Device is HT-capable and HT is enabled for
1247 			 * the vap; setup HT operation.  On return
1248 			 * ni_chan will be adjusted to an HT channel.
1249 			 */
1250 			ieee80211_ht_wds_init(ni);
1251 		} else {
1252 			struct ieee80211_channel *c = ni->ni_chan;
1253 			/*
1254 			 * Force a legacy channel to be used.
1255 			 */
1256 			c = ieee80211_find_channel(ic,
1257 			    c->ic_freq, c->ic_flags &~ IEEE80211_CHAN_HT);
1258 			KASSERT(c != NULL, ("no legacy channel, %u/%x",
1259 			    ni->ni_chan->ic_freq, ni->ni_chan->ic_flags));
1260 			ni->ni_chan = c;
1261 		}
1262 	}
1263 	return ni;
1264 }
1265 
1266 struct ieee80211_node *
1267 #ifdef IEEE80211_DEBUG_REFCNT
1268 ieee80211_find_node_locked_debug(struct ieee80211_node_table *nt,
1269 	const uint8_t macaddr[IEEE80211_ADDR_LEN], const char *func, int line)
1270 #else
1271 ieee80211_find_node_locked(struct ieee80211_node_table *nt,
1272 	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1273 #endif
1274 {
1275 	struct ieee80211_node *ni;
1276 	int hash;
1277 #ifdef IEEE80211_DEBUG_REFCNT
1278 	char ethstr[ETHER_ADDRSTRLEN + 1];
1279 #endif
1280 	hash = IEEE80211_NODE_HASH(nt->nt_ic, macaddr);
1281 	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1282 		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
1283 			ieee80211_ref_node(ni);	/* mark referenced */
1284 #ifdef IEEE80211_DEBUG_REFCNT
1285 			IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_NODE,
1286 			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1287 			    func, line,
1288 			    ni, kether_ntoa(ni->ni_macaddr, ethstr),
1289 			    ieee80211_node_refcnt(ni));
1290 #endif
1291 			return ni;
1292 		}
1293 	}
1294 	return NULL;
1295 }
1296 
1297 struct ieee80211_node *
1298 #ifdef IEEE80211_DEBUG_REFCNT
1299 ieee80211_find_node_debug(struct ieee80211_node_table *nt,
1300 	const uint8_t macaddr[IEEE80211_ADDR_LEN], const char *func, int line)
1301 #else
1302 ieee80211_find_node(struct ieee80211_node_table *nt,
1303 	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1304 #endif
1305 {
1306 	struct ieee80211_node *ni;
1307 
1308 	ni = ieee80211_find_node_locked(nt, macaddr);
1309 	return ni;
1310 }
1311 
1312 struct ieee80211_node *
1313 #ifdef IEEE80211_DEBUG_REFCNT
1314 ieee80211_find_vap_node_locked_debug(struct ieee80211_node_table *nt,
1315 	const struct ieee80211vap *vap,
1316 	const uint8_t macaddr[IEEE80211_ADDR_LEN], const char *func, int line)
1317 #else
1318 ieee80211_find_vap_node_locked(struct ieee80211_node_table *nt,
1319 	const struct ieee80211vap *vap,
1320 	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1321 #endif
1322 {
1323 	struct ieee80211_node *ni;
1324 	int hash;
1325 #ifdef IEEE80211_DEBUG_REFCNT
1326 	char ethstr[ETHER_ADDRSTRLEN + 1];
1327 #endif
1328 	hash = IEEE80211_NODE_HASH(nt->nt_ic, macaddr);
1329 	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1330 		if (ni->ni_vap == vap &&
1331 		    IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
1332 			ieee80211_ref_node(ni);	/* mark referenced */
1333 #ifdef IEEE80211_DEBUG_REFCNT
1334 			IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_NODE,
1335 			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1336 			    func, line,
1337 			    ni, kether_ntoa(ni->ni_macaddr, ethstr),
1338 			    ieee80211_node_refcnt(ni));
1339 #endif
1340 			return ni;
1341 		}
1342 	}
1343 	return NULL;
1344 }
1345 
1346 struct ieee80211_node *
1347 #ifdef IEEE80211_DEBUG_REFCNT
1348 ieee80211_find_vap_node_debug(struct ieee80211_node_table *nt,
1349 	const struct ieee80211vap *vap,
1350 	const uint8_t macaddr[IEEE80211_ADDR_LEN], const char *func, int line)
1351 #else
1352 ieee80211_find_vap_node(struct ieee80211_node_table *nt,
1353 	const struct ieee80211vap *vap,
1354 	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1355 #endif
1356 {
1357 	struct ieee80211_node *ni;
1358 
1359 	ni = ieee80211_find_vap_node_locked(nt, vap, macaddr);
1360 	return ni;
1361 }
1362 
1363 /*
1364  * Fake up a node; this handles node discovery in adhoc mode.
1365  * Note that for the driver's benefit we we treat this like
1366  * an association so the driver has an opportunity to setup
1367  * it's private state.
1368  */
1369 struct ieee80211_node *
1370 ieee80211_fakeup_adhoc_node(struct ieee80211vap *vap,
1371 	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1372 {
1373 	struct ieee80211_node *ni;
1374 #ifdef IEEE80211_DEBUG
1375 	char ethstr[ETHER_ADDRSTRLEN + 1];
1376 #endif
1377 
1378 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1379 	    "%s: mac<%s>\n", __func__, kether_ntoa(macaddr, ethstr));
1380 	ni = ieee80211_dup_bss(vap, macaddr);
1381 	if (ni != NULL) {
1382 		struct ieee80211com *ic = vap->iv_ic;
1383 
1384 		/* XXX no rate negotiation; just dup */
1385 		ni->ni_rates = vap->iv_bss->ni_rates;
1386 		if (ieee80211_iserp_rateset(&ni->ni_rates))
1387 			ni->ni_flags |= IEEE80211_NODE_ERP;
1388 		if (vap->iv_opmode == IEEE80211_M_AHDEMO) {
1389 			/*
1390 			 * In adhoc demo mode there are no management
1391 			 * frames to use to discover neighbor capabilities,
1392 			 * so blindly propagate the local configuration
1393 			 * so we can do interesting things (e.g. use
1394 			 * WME to disable ACK's).
1395 			 */
1396 			if (vap->iv_flags & IEEE80211_F_WME)
1397 				ni->ni_flags |= IEEE80211_NODE_QOS;
1398 #ifdef IEEE80211_SUPPORT_SUPERG
1399 			if (vap->iv_flags & IEEE80211_F_FF)
1400 				ni->ni_flags |= IEEE80211_NODE_FF;
1401 #endif
1402 		}
1403 		ieee80211_node_setuptxparms(ni);
1404 		if (ic->ic_newassoc != NULL)
1405 			ic->ic_newassoc(ni, 1);
1406 		/* XXX not right for 802.1x/WPA */
1407 		ieee80211_node_authorize(ni);
1408 	}
1409 	return ni;
1410 }
1411 
1412 void
1413 ieee80211_init_neighbor(struct ieee80211_node *ni,
1414 	const struct ieee80211_frame *wh,
1415 	const struct ieee80211_scanparams *sp)
1416 {
1417 	ni->ni_esslen = sp->ssid[1];
1418 	memcpy(ni->ni_essid, sp->ssid + 2, sp->ssid[1]);
1419 	IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
1420 	memcpy(ni->ni_tstamp.data, sp->tstamp, sizeof(ni->ni_tstamp));
1421 	ni->ni_intval = sp->bintval;
1422 	ni->ni_capinfo = sp->capinfo;
1423 	ni->ni_chan = ni->ni_ic->ic_curchan;
1424 	ni->ni_fhdwell = sp->fhdwell;
1425 	ni->ni_fhindex = sp->fhindex;
1426 	ni->ni_erp = sp->erp;
1427 	ni->ni_timoff = sp->timoff;
1428 #ifdef IEEE80211_SUPPORT_MESH
1429 	if (ni->ni_vap->iv_opmode == IEEE80211_M_MBSS)
1430 		ieee80211_mesh_init_neighbor(ni, wh, sp);
1431 #endif
1432 	if (ieee80211_ies_init(&ni->ni_ies, sp->ies, sp->ies_len)) {
1433 		ieee80211_ies_expand(&ni->ni_ies);
1434 		if (ni->ni_ies.wme_ie != NULL)
1435 			ni->ni_flags |= IEEE80211_NODE_QOS;
1436 		else
1437 			ni->ni_flags &= ~IEEE80211_NODE_QOS;
1438 #ifdef IEEE80211_SUPPORT_SUPERG
1439 		if (ni->ni_ies.ath_ie != NULL)
1440 			ieee80211_parse_ath(ni, ni->ni_ies.ath_ie);
1441 #endif
1442 	}
1443 
1444 	/* NB: must be after ni_chan is setup */
1445 	ieee80211_setup_rates(ni, sp->rates, sp->xrates,
1446 		IEEE80211_F_DOSORT | IEEE80211_F_DOFRATE |
1447 		IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
1448 }
1449 
1450 /*
1451  * Do node discovery in adhoc mode on receipt of a beacon
1452  * or probe response frame.  Note that for the driver's
1453  * benefit we we treat this like an association so the
1454  * driver has an opportunity to setup it's private state.
1455  */
1456 struct ieee80211_node *
1457 ieee80211_add_neighbor(struct ieee80211vap *vap,
1458 	const struct ieee80211_frame *wh,
1459 	const struct ieee80211_scanparams *sp)
1460 {
1461 	struct ieee80211_node *ni;
1462 #ifdef IEEE80211_DEBUG
1463 	char ethstr[ETHER_ADDRSTRLEN + 1];
1464 #endif
1465 
1466 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1467 	    "%s: mac<%s>\n", __func__, kether_ntoa(wh->i_addr2, ethstr));
1468 	ni = ieee80211_dup_bss(vap, wh->i_addr2);/* XXX alloc_node? */
1469 	if (ni != NULL) {
1470 		struct ieee80211com *ic = vap->iv_ic;
1471 
1472 		ieee80211_init_neighbor(ni, wh, sp);
1473 		if (ieee80211_iserp_rateset(&ni->ni_rates))
1474 			ni->ni_flags |= IEEE80211_NODE_ERP;
1475 		ieee80211_node_setuptxparms(ni);
1476 		if (ic->ic_newassoc != NULL)
1477 			ic->ic_newassoc(ni, 1);
1478 		/* XXX not right for 802.1x/WPA */
1479 		ieee80211_node_authorize(ni);
1480 	}
1481 	return ni;
1482 }
1483 
1484 #define	IS_PROBEREQ(wh) \
1485 	((wh->i_fc[0] & (IEEE80211_FC0_TYPE_MASK|IEEE80211_FC0_SUBTYPE_MASK)) \
1486 	    == (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_REQ))
1487 #define	IS_BCAST_PROBEREQ(wh) \
1488 	(IS_PROBEREQ(wh) && IEEE80211_IS_MULTICAST( \
1489 	    ((const struct ieee80211_frame *)(wh))->i_addr3))
1490 
1491 static __inline struct ieee80211_node *
1492 _find_rxnode(struct ieee80211_node_table *nt,
1493     const struct ieee80211_frame_min *wh)
1494 {
1495 	if (IS_BCAST_PROBEREQ(wh))
1496 		return NULL;		/* spam bcast probe req to all vap's */
1497 	return ieee80211_find_node_locked(nt, wh->i_addr2);
1498 }
1499 
1500 /*
1501  * Locate the node for sender, track state, and then pass the
1502  * (referenced) node up to the 802.11 layer for its use.  Note
1503  * we can return NULL if the sender is not in the table.
1504  */
1505 struct ieee80211_node *
1506 #ifdef IEEE80211_DEBUG_REFCNT
1507 ieee80211_find_rxnode_debug(struct ieee80211com *ic,
1508 	const struct ieee80211_frame_min *wh, const char *func, int line)
1509 #else
1510 ieee80211_find_rxnode(struct ieee80211com *ic,
1511 	const struct ieee80211_frame_min *wh)
1512 #endif
1513 {
1514 	struct ieee80211_node_table *nt;
1515 	struct ieee80211_node *ni;
1516 
1517 	nt = &ic->ic_sta;
1518 	ni = _find_rxnode(nt, wh);
1519 
1520 	return ni;
1521 }
1522 
1523 /*
1524  * Like ieee80211_find_rxnode but use the supplied h/w
1525  * key index as a hint to locate the node in the key
1526  * mapping table.  If an entry is present at the key
1527  * index we return it; otherwise do a normal lookup and
1528  * update the mapping table if the station has a unicast
1529  * key assigned to it.
1530  */
1531 struct ieee80211_node *
1532 #ifdef IEEE80211_DEBUG_REFCNT
1533 ieee80211_find_rxnode_withkey_debug(struct ieee80211com *ic,
1534 	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix,
1535 	const char *func, int line)
1536 #else
1537 ieee80211_find_rxnode_withkey(struct ieee80211com *ic,
1538 	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix)
1539 #endif
1540 {
1541 	struct ieee80211_node_table *nt;
1542 	struct ieee80211_node *ni;
1543 #ifdef IEEE80211_DEBUG
1544 	char ethstr[ETHER_ADDRSTRLEN + 1];
1545 #endif
1546 
1547 	nt = &ic->ic_sta;
1548 	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax)
1549 		ni = nt->nt_keyixmap[keyix];
1550 	else
1551 		ni = NULL;
1552 	if (ni == NULL) {
1553 		ni = _find_rxnode(nt, wh);
1554 		if (ni != NULL && nt->nt_keyixmap != NULL) {
1555 			/*
1556 			 * If the station has a unicast key cache slot
1557 			 * assigned update the key->node mapping table.
1558 			 */
1559 			keyix = ni->ni_ucastkey.wk_rxkeyix;
1560 			/* XXX can keyixmap[keyix] != NULL? */
1561 			if (keyix < nt->nt_keyixmax &&
1562 			    nt->nt_keyixmap[keyix] == NULL) {
1563 				IEEE80211_DPRINTF(ni->ni_vap,
1564 				    IEEE80211_MSG_NODE,
1565 				    "%s: add key map entry %p<%s> refcnt %d\n",
1566 				    __func__, ni, kether_ntoa(ni->ni_macaddr, ethstr),
1567 				    ieee80211_node_refcnt(ni)+1);
1568 				nt->nt_keyixmap[keyix] = ieee80211_ref_node(ni);
1569 			}
1570 		}
1571 	} else {
1572 		if (IS_BCAST_PROBEREQ(wh))
1573 			ni = NULL;	/* spam bcast probe req to all vap's */
1574 		else
1575 			ieee80211_ref_node(ni);
1576 	}
1577 	return ni;
1578 }
1579 #undef IS_BCAST_PROBEREQ
1580 #undef IS_PROBEREQ
1581 
1582 /*
1583  * Return a reference to the appropriate node for sending
1584  * a data frame.  This handles node discovery in adhoc networks.
1585  */
1586 struct ieee80211_node *
1587 #ifdef IEEE80211_DEBUG_REFCNT
1588 ieee80211_find_txnode_debug(struct ieee80211vap *vap,
1589 	const uint8_t macaddr[IEEE80211_ADDR_LEN],
1590 	const char *func, int line)
1591 #else
1592 ieee80211_find_txnode(struct ieee80211vap *vap,
1593 	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1594 #endif
1595 {
1596 	struct ieee80211_node_table *nt = &vap->iv_ic->ic_sta;
1597 	struct ieee80211_node *ni;
1598 
1599 	/*
1600 	 * The destination address should be in the node table
1601 	 * unless this is a multicast/broadcast frame.  We can
1602 	 * also optimize station mode operation, all frames go
1603 	 * to the bss node.
1604 	 */
1605 	/* XXX can't hold lock across dup_bss 'cuz of recursive locking */
1606 	if (vap->iv_opmode == IEEE80211_M_STA ||
1607 	    vap->iv_opmode == IEEE80211_M_WDS ||
1608 	    IEEE80211_IS_MULTICAST(macaddr))
1609 		ni = ieee80211_ref_node(vap->iv_bss);
1610 	else
1611 		ni = ieee80211_find_node_locked(nt, macaddr);
1612 
1613 	if (ni == NULL) {
1614 		if (vap->iv_opmode == IEEE80211_M_IBSS ||
1615 		    vap->iv_opmode == IEEE80211_M_AHDEMO) {
1616 			/*
1617 			 * In adhoc mode cons up a node for the destination.
1618 			 * Note that we need an additional reference for the
1619 			 * caller to be consistent with
1620 			 * ieee80211_find_node_locked.
1621 			 */
1622 			ni = ieee80211_fakeup_adhoc_node(vap, macaddr);
1623 			if (ni != NULL)
1624 				(void) ieee80211_ref_node(ni);
1625 		} else {
1626 			IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_OUTPUT, macaddr,
1627 			    "no node, discard frame (%s)", __func__);
1628 			vap->iv_stats.is_tx_nonode++;
1629 		}
1630 	}
1631 	return ni;
1632 }
1633 
1634 static void
1635 _ieee80211_free_node(struct ieee80211_node *ni)
1636 {
1637 	struct ieee80211_node_table *nt = ni->ni_table;
1638 
1639 	/*
1640 	 * NB: careful about referencing the vap as it may be
1641 	 * gone if the last reference was held by a driver.
1642 	 * We know the com will always be present so it's safe
1643 	 * to use ni_ic below to reclaim resources.
1644 	 */
1645 #if 0
1646 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1647 		"%s %p<%s> in %s table\n", __func__, ni,
1648 		kether_ntoa(ni->ni_macaddr, ethstr),
1649 		nt != NULL ? nt->nt_name : "<gone>");
1650 #endif
1651 	if (ni->ni_associd != 0) {
1652 		struct ieee80211vap *vap = ni->ni_vap;
1653 		if (vap->iv_aid_bitmap != NULL)
1654 			IEEE80211_AID_CLR(vap, ni->ni_associd);
1655 	}
1656 	if (nt != NULL) {
1657 		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1658 		LIST_REMOVE(ni, ni_hash);
1659 	}
1660 	ni->ni_ic->ic_node_free(ni);
1661 }
1662 
1663 void
1664 #ifdef IEEE80211_DEBUG_REFCNT
1665 ieee80211_free_node_debug(struct ieee80211_node *ni, const char *func, int line)
1666 #else
1667 ieee80211_free_node(struct ieee80211_node *ni)
1668 #endif
1669 {
1670 	struct ieee80211_node_table *nt = ni->ni_table;
1671 #ifdef IEEE80211_DEBUG
1672 	char ethstr[ETHER_ADDRSTRLEN + 1];
1673 #endif
1674 
1675 #ifdef IEEE80211_DEBUG_REFCNT
1676 	IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_NODE,
1677 		"%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line, ni,
1678 		kether_ntoa(ni->ni_macaddr, ethstr), ieee80211_node_refcnt(ni)-1);
1679 #endif
1680 	if (nt != NULL) {
1681 		if (ieee80211_node_dectestref(ni)) {
1682 			/*
1683 			 * Last reference, reclaim state.
1684 			 */
1685 			_ieee80211_free_node(ni);
1686 		} else if (ieee80211_node_refcnt(ni) == 1 &&
1687 		    nt->nt_keyixmap != NULL) {
1688 			ieee80211_keyix keyix;
1689 			/*
1690 			 * Check for a last reference in the key mapping table.
1691 			 */
1692 			keyix = ni->ni_ucastkey.wk_rxkeyix;
1693 			if (keyix < nt->nt_keyixmax &&
1694 			    nt->nt_keyixmap[keyix] == ni) {
1695 				IEEE80211_DPRINTF(ni->ni_vap,
1696 				    IEEE80211_MSG_NODE,
1697 				    "%s: %p<%s> clear key map entry", __func__,
1698 				    ni, kether_ntoa(ni->ni_macaddr, ethstr));
1699 				nt->nt_keyixmap[keyix] = NULL;
1700 				ieee80211_node_decref(ni); /* XXX needed? */
1701 				_ieee80211_free_node(ni);
1702 			}
1703 		}
1704 	} else {
1705 		if (ieee80211_node_dectestref(ni))
1706 			_ieee80211_free_node(ni);
1707 	}
1708 }
1709 
1710 /*
1711  * Reclaim a unicast key and clear any key cache state.
1712  */
1713 int
1714 ieee80211_node_delucastkey(struct ieee80211_node *ni)
1715 {
1716 	struct ieee80211com *ic = ni->ni_ic;
1717 	struct ieee80211_node_table *nt = &ic->ic_sta;
1718 	struct ieee80211_node *nikey;
1719 	ieee80211_keyix keyix;
1720 	int status;
1721 #ifdef IEEE80211_DEBUG
1722 	char ethstr[ETHER_ADDRSTRLEN + 1];
1723 #endif
1724 
1725 	/*
1726 	 * NB: We must beware of LOR here; deleting the key
1727 	 * can cause the crypto layer to block traffic updates
1728 	 * which can generate a LOR against the node table lock;
1729 	 * grab it here and stash the key index for our use below.
1730 	 *
1731 	 * Must also beware of recursion on the node table lock.
1732 	 * When called from node_cleanup we may already have
1733 	 * the node table lock held.  Unfortunately there's no
1734 	 * way to separate out this path so we must do this
1735 	 * conditionally.
1736 	 */
1737 	nikey = NULL;
1738 	status = 1;		/* NB: success */
1739 	if (ni->ni_ucastkey.wk_keyix != IEEE80211_KEYIX_NONE) {
1740 		keyix = ni->ni_ucastkey.wk_rxkeyix;
1741 		status = ieee80211_crypto_delkey(ni->ni_vap, &ni->ni_ucastkey);
1742 		if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax) {
1743 			nikey = nt->nt_keyixmap[keyix];
1744 			nt->nt_keyixmap[keyix] = NULL;
1745 		}
1746 	}
1747 
1748 	if (nikey != NULL) {
1749 		KASSERT(nikey == ni,
1750 			("key map out of sync, ni %p nikey %p", ni, nikey));
1751 		IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_NODE,
1752 			"%s: delete key map entry %p<%s> refcnt %d\n",
1753 			__func__, ni, kether_ntoa(ni->ni_macaddr, ethstr),
1754 			ieee80211_node_refcnt(ni)-1);
1755 		ieee80211_free_node(ni);
1756 	}
1757 	return status;
1758 }
1759 
1760 /*
1761  * Reclaim a node.  If this is the last reference count then
1762  * do the normal free work.  Otherwise remove it from the node
1763  * table and mark it gone by clearing the back-reference.
1764  */
1765 static void
1766 node_reclaim(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1767 {
1768 	ieee80211_keyix keyix;
1769 #ifdef IEEE80211_DEBUG
1770 	char ethstr[ETHER_ADDRSTRLEN + 1];
1771 #endif
1772 
1773 	IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_NODE,
1774 		"%s: remove %p<%s> from %s table, refcnt %d\n",
1775 		__func__, ni, kether_ntoa(ni->ni_macaddr, ethstr),
1776 		nt->nt_name, ieee80211_node_refcnt(ni)-1);
1777 	/*
1778 	 * Clear any entry in the unicast key mapping table.
1779 	 * We need to do it here so rx lookups don't find it
1780 	 * in the mapping table even if it's not in the hash
1781 	 * table.  We cannot depend on the mapping table entry
1782 	 * being cleared because the node may not be free'd.
1783 	 */
1784 	keyix = ni->ni_ucastkey.wk_rxkeyix;
1785 	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax &&
1786 	    nt->nt_keyixmap[keyix] == ni) {
1787 		IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_NODE,
1788 			"%s: %p<%s> clear key map entry %u\n",
1789 			__func__, ni, kether_ntoa(ni->ni_macaddr, ethstr), keyix);
1790 		nt->nt_keyixmap[keyix] = NULL;
1791 		ieee80211_node_decref(ni);	/* NB: don't need free */
1792 	}
1793 	if (!ieee80211_node_dectestref(ni)) {
1794 		/*
1795 		 * Other references are present, just remove the
1796 		 * node from the table so it cannot be found.  When
1797 		 * the references are dropped storage will be
1798 		 * reclaimed.
1799 		 */
1800 		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1801 		LIST_REMOVE(ni, ni_hash);
1802 		ni->ni_table = NULL;		/* clear reference */
1803 	} else
1804 		_ieee80211_free_node(ni);
1805 }
1806 
1807 /*
1808  * Node table support.
1809  */
1810 
1811 static void
1812 ieee80211_node_table_init(struct ieee80211com *ic,
1813 	struct ieee80211_node_table *nt,
1814 	const char *name, int inact, int keyixmax)
1815 {
1816 	nt->nt_ic = ic;
1817 	TAILQ_INIT(&nt->nt_node);
1818 	nt->nt_name = name;
1819 	nt->nt_scangen = 1;
1820 	nt->nt_inact_init = inact;
1821 	nt->nt_keyixmax = keyixmax;
1822 	if (nt->nt_keyixmax > 0) {
1823 		nt->nt_keyixmap = (struct ieee80211_node **) kmalloc(
1824 			keyixmax * sizeof(struct ieee80211_node *),
1825 			M_80211_NODE, M_INTWAIT | M_ZERO);
1826 		if (nt->nt_keyixmap == NULL)
1827 			if_printf(ic->ic_ifp,
1828 			    "Cannot allocate key index map with %u entries\n",
1829 			    keyixmax);
1830 	} else
1831 		nt->nt_keyixmap = NULL;
1832 }
1833 
1834 static void
1835 ieee80211_node_table_reset(struct ieee80211_node_table *nt,
1836 	struct ieee80211vap *match)
1837 {
1838 	struct ieee80211_node *ni, *next;
1839 
1840 	TAILQ_FOREACH_MUTABLE(ni, &nt->nt_node, ni_list, next) {
1841 		if (match != NULL && ni->ni_vap != match)
1842 			continue;
1843 		/* XXX can this happen?  if so need's work */
1844 		if (ni->ni_associd != 0) {
1845 			struct ieee80211vap *vap = ni->ni_vap;
1846 
1847 			if (vap->iv_auth->ia_node_leave != NULL)
1848 				vap->iv_auth->ia_node_leave(ni);
1849 			if (vap->iv_aid_bitmap != NULL)
1850 				IEEE80211_AID_CLR(vap, ni->ni_associd);
1851 		}
1852 		ni->ni_wdsvap = NULL;		/* clear reference */
1853 		node_reclaim(nt, ni);
1854 	}
1855 	if (match != NULL && match->iv_opmode == IEEE80211_M_WDS) {
1856 		/*
1857 		 * Make a separate pass to clear references to this vap
1858 		 * held by DWDS entries.  They will not be matched above
1859 		 * because ni_vap will point to the ap vap but we still
1860 		 * need to clear ni_wdsvap when the WDS vap is destroyed
1861 		 * and/or reset.
1862 		 */
1863 		TAILQ_FOREACH_MUTABLE(ni, &nt->nt_node, ni_list, next)
1864 			if (ni->ni_wdsvap == match)
1865 				ni->ni_wdsvap = NULL;
1866 	}
1867 }
1868 
1869 static void
1870 ieee80211_node_table_cleanup(struct ieee80211_node_table *nt)
1871 {
1872 	ieee80211_node_table_reset(nt, NULL);
1873 	if (nt->nt_keyixmap != NULL) {
1874 #ifdef DIAGNOSTIC
1875 		/* XXX verify all entries are NULL */
1876 		int i;
1877 		for (i = 0; i < nt->nt_keyixmax; i++)
1878 			if (nt->nt_keyixmap[i] != NULL)
1879 				kprintf("%s: %s[%u] still active\n", __func__,
1880 					nt->nt_name, i);
1881 #endif
1882 		kfree(nt->nt_keyixmap, M_80211_NODE);
1883 		nt->nt_keyixmap = NULL;
1884 	}
1885 }
1886 
1887 /*
1888  * Timeout inactive stations and do related housekeeping.
1889  * Note that we cannot hold the node lock while sending a
1890  * frame as this would lead to a LOR.  Instead we use a
1891  * generation number to mark nodes that we've scanned and
1892  * drop the lock and restart a scan if we have to time out
1893  * a node.  Since we are single-threaded by virtue of
1894  * controlling the inactivity timer we can be sure this will
1895  * process each node only once.
1896  */
1897 static void
1898 ieee80211_timeout_stations(struct ieee80211com *ic)
1899 {
1900 	struct ieee80211_node_table *nt = &ic->ic_sta;
1901 	struct ieee80211vap *vap;
1902 	struct ieee80211_node *ni;
1903 	int gen = 0;
1904 
1905 	gen = ++nt->nt_scangen;
1906 restart:
1907 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1908 		if (ni->ni_scangen == gen)	/* previously handled */
1909 			continue;
1910 		ni->ni_scangen = gen;
1911 		/*
1912 		 * Ignore entries for which have yet to receive an
1913 		 * authentication frame.  These are transient and
1914 		 * will be reclaimed when the last reference to them
1915 		 * goes away (when frame xmits complete).
1916 		 */
1917 		vap = ni->ni_vap;
1918 		/*
1919 		 * Only process stations when in RUN state.  This
1920 		 * insures, for example, that we don't timeout an
1921 		 * inactive station during CAC.  Note that CSA state
1922 		 * is actually handled in ieee80211_node_timeout as
1923 		 * it applies to more than timeout processing.
1924 		 */
1925 		if (vap->iv_state != IEEE80211_S_RUN)
1926 			continue;
1927 		/* XXX can vap be NULL? */
1928 		if ((vap->iv_opmode == IEEE80211_M_HOSTAP ||
1929 		     vap->iv_opmode == IEEE80211_M_STA) &&
1930 		    (ni->ni_flags & IEEE80211_NODE_AREF) == 0)
1931 			continue;
1932 		/*
1933 		 * Free fragment if not needed anymore
1934 		 * (last fragment older than 1s).
1935 		 * XXX doesn't belong here, move to node_age
1936 		 */
1937 		if (ni->ni_rxfrag[0] != NULL &&
1938 		    ticks > ni->ni_rxfragstamp + hz) {
1939 			m_freem(ni->ni_rxfrag[0]);
1940 			ni->ni_rxfrag[0] = NULL;
1941 		}
1942 		if (ni->ni_inact > 0) {
1943 			ni->ni_inact--;
1944 			IEEE80211_NOTE(vap, IEEE80211_MSG_INACT, ni,
1945 			    "%s: inact %u inact_reload %u nrates %u",
1946 			    __func__, ni->ni_inact, ni->ni_inact_reload,
1947 			    ni->ni_rates.rs_nrates);
1948 		}
1949 		/*
1950 		 * Special case ourself; we may be idle for extended periods
1951 		 * of time and regardless reclaiming our state is wrong.
1952 		 * XXX run ic_node_age
1953 		 */
1954 		if (ni == vap->iv_bss)
1955 			continue;
1956 		if (ni->ni_associd != 0 ||
1957 		    (vap->iv_opmode == IEEE80211_M_IBSS ||
1958 		     vap->iv_opmode == IEEE80211_M_AHDEMO)) {
1959 			/*
1960 			 * Age/drain resources held by the station.
1961 			 */
1962 			ic->ic_node_age(ni);
1963 			/*
1964 			 * Probe the station before time it out.  We
1965 			 * send a null data frame which may not be
1966 			 * universally supported by drivers (need it
1967 			 * for ps-poll support so it should be...).
1968 			 *
1969 			 * XXX don't probe the station unless we've
1970 			 *     received a frame from them (and have
1971 			 *     some idea of the rates they are capable
1972 			 *     of); this will get fixed more properly
1973 			 *     soon with better handling of the rate set.
1974 			 */
1975 			if ((vap->iv_flags_ext & IEEE80211_FEXT_INACT) &&
1976 			    (0 < ni->ni_inact &&
1977 			     ni->ni_inact <= vap->iv_inact_probe) &&
1978 			    ni->ni_rates.rs_nrates != 0) {
1979 				IEEE80211_NOTE(vap,
1980 				    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE,
1981 				    ni, "%s",
1982 				    "probe station due to inactivity");
1983 				/*
1984 				 * Grab a reference before unlocking the table
1985 				 * so the node cannot be reclaimed before we
1986 				 * send the frame. ieee80211_send_nulldata
1987 				 * understands we've done this and reclaims the
1988 				 * ref for us as needed.
1989 				 */
1990 				ieee80211_ref_node(ni);
1991 				ieee80211_send_nulldata(ni);
1992 				/* XXX stat? */
1993 				goto restart;
1994 			}
1995 		}
1996 		if ((vap->iv_flags_ext & IEEE80211_FEXT_INACT) &&
1997 		    ni->ni_inact <= 0) {
1998 			IEEE80211_NOTE(vap,
1999 			    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE, ni,
2000 			    "station timed out due to inactivity "
2001 			    "(refcnt %u)", ieee80211_node_refcnt(ni));
2002 			/*
2003 			 * Send a deauthenticate frame and drop the station.
2004 			 * This is somewhat complicated due to reference counts
2005 			 * and locking.  At this point a station will typically
2006 			 * have a reference count of 1.  ieee80211_node_leave
2007 			 * will do a "free" of the node which will drop the
2008 			 * reference count.  But in the meantime a reference
2009 			 * wil be held by the deauth frame.  The actual reclaim
2010 			 * of the node will happen either after the tx is
2011 			 * completed or by ieee80211_node_leave.
2012 			 *
2013 			 * Separately we must drop the node lock before sending
2014 			 * in case the driver takes a lock, as this can result
2015 			 * in a LOR between the node lock and the driver lock.
2016 			 */
2017 			ieee80211_ref_node(ni);
2018 			if (ni->ni_associd != 0) {
2019 				IEEE80211_SEND_MGMT(ni,
2020 				    IEEE80211_FC0_SUBTYPE_DEAUTH,
2021 				    IEEE80211_REASON_AUTH_EXPIRE);
2022 			}
2023 			ieee80211_node_leave(ni);
2024 			ieee80211_free_node(ni);
2025 			vap->iv_stats.is_node_timeout++;
2026 			goto restart;
2027 		}
2028 	}
2029 }
2030 
2031 /*
2032  * Aggressively reclaim resources.  This should be used
2033  * only in a critical situation to reclaim mbuf resources.
2034  */
2035 void
2036 ieee80211_drain(struct ieee80211com *ic)
2037 {
2038 	struct ieee80211_node_table *nt = &ic->ic_sta;
2039 	struct ieee80211vap *vap;
2040 	struct ieee80211_node *ni;
2041 
2042 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
2043 		/*
2044 		 * Ignore entries for which have yet to receive an
2045 		 * authentication frame.  These are transient and
2046 		 * will be reclaimed when the last reference to them
2047 		 * goes away (when frame xmits complete).
2048 		 */
2049 		vap = ni->ni_vap;
2050 		/*
2051 		 * Only process stations when in RUN state.  This
2052 		 * insures, for example, that we don't timeout an
2053 		 * inactive station during CAC.  Note that CSA state
2054 		 * is actually handled in ieee80211_node_timeout as
2055 		 * it applies to more than timeout processing.
2056 		 */
2057 		if (vap->iv_state != IEEE80211_S_RUN)
2058 			continue;
2059 		/* XXX can vap be NULL? */
2060 		if ((vap->iv_opmode == IEEE80211_M_HOSTAP ||
2061 		     vap->iv_opmode == IEEE80211_M_STA) &&
2062 		    (ni->ni_flags & IEEE80211_NODE_AREF) == 0)
2063 			continue;
2064 		/*
2065 		 * Free fragments.
2066 		 * XXX doesn't belong here, move to node_drain
2067 		 */
2068 		if (ni->ni_rxfrag[0] != NULL) {
2069 			m_freem(ni->ni_rxfrag[0]);
2070 			ni->ni_rxfrag[0] = NULL;
2071 		}
2072 		/*
2073 		 * Drain resources held by the station.
2074 		 */
2075 		ic->ic_node_drain(ni);
2076 	}
2077 }
2078 
2079 /*
2080  * Per-ieee80211com inactivity timer callback.
2081  */
2082 static void
2083 ieee80211_node_timeout_callout(void *arg)
2084 {
2085 	struct ieee80211com *ic = arg;
2086 
2087 	/*
2088 	 * Defer timeout processing if a channel switch is pending.
2089 	 * We typically need to be mute so not doing things that
2090 	 * might generate frames is good to handle in one place.
2091 	 * Supressing the station timeout processing may extend the
2092 	 * lifetime of inactive stations (by not decrementing their
2093 	 * idle counters) but this should be ok unless the CSA is
2094 	 * active for an unusually long time.
2095 	 */
2096 	wlan_serialize_enter();
2097 	if ((ic->ic_flags & IEEE80211_F_CSAPENDING) == 0) {
2098 		ieee80211_scan_timeout(ic);
2099 		ieee80211_timeout_stations(ic);
2100 		ieee80211_ageq_age(&ic->ic_stageq, IEEE80211_INACT_WAIT);
2101 
2102 		ieee80211_erp_timeout(ic);
2103 		ieee80211_ht_timeout(ic);
2104 	}
2105 	callout_reset(&ic->ic_inact, IEEE80211_INACT_WAIT*hz,
2106 		      ieee80211_node_timeout_callout, ic);
2107 	wlan_serialize_exit();
2108 }
2109 
2110 void
2111 ieee80211_iterate_nodes(struct ieee80211_node_table *nt,
2112 	ieee80211_iter_func *f, void *arg)
2113 {
2114 	struct ieee80211_node *ni;
2115 	u_int gen;
2116 
2117 	gen = ++nt->nt_scangen;
2118 restart:
2119 	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
2120 		if (ni->ni_scangen != gen) {
2121 			ni->ni_scangen = gen;
2122 			(void) ieee80211_ref_node(ni);
2123 			(*f)(arg, ni);
2124 			ieee80211_free_node(ni);
2125 			goto restart;
2126 		}
2127 	}
2128 }
2129 
2130 void
2131 ieee80211_dump_node(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
2132 {
2133 	char ethstr[ETHER_ADDRSTRLEN + 1];
2134 
2135 	kprintf("0x%p: mac %s refcnt %d\n", ni, kether_ntoa(ni->ni_macaddr, ethstr),
2136 		ieee80211_node_refcnt(ni));
2137 	kprintf("\tscangen %u authmode %u flags 0x%x\n",
2138 		ni->ni_scangen, ni->ni_authmode, ni->ni_flags);
2139 	kprintf("\tassocid 0x%x txpower %u vlan %u\n",
2140 		ni->ni_associd, ni->ni_txpower, ni->ni_vlan);
2141 	kprintf("\ttxseq %u rxseq %u fragno %u rxfragstamp %u\n",
2142 		ni->ni_txseqs[IEEE80211_NONQOS_TID],
2143 		ni->ni_rxseqs[IEEE80211_NONQOS_TID] >> IEEE80211_SEQ_SEQ_SHIFT,
2144 		ni->ni_rxseqs[IEEE80211_NONQOS_TID] & IEEE80211_SEQ_FRAG_MASK,
2145 		ni->ni_rxfragstamp);
2146 	kprintf("\trssi %d noise %d intval %u capinfo 0x%x\n",
2147 		node_getrssi(ni), ni->ni_noise,
2148 		ni->ni_intval, ni->ni_capinfo);
2149 	kprintf("\tbssid %s essid \"%.*s\" channel %u:0x%x\n",
2150 		kether_ntoa(ni->ni_bssid, ethstr),
2151 		ni->ni_esslen, ni->ni_essid,
2152 		ni->ni_chan->ic_freq, ni->ni_chan->ic_flags);
2153 	kprintf("\tinact %u inact_reload %u txrate %u\n",
2154 		ni->ni_inact, ni->ni_inact_reload, ni->ni_txrate);
2155 	kprintf("\thtcap %x htparam %x htctlchan %u ht2ndchan %u\n",
2156 		ni->ni_htcap, ni->ni_htparam,
2157 		ni->ni_htctlchan, ni->ni_ht2ndchan);
2158 	kprintf("\thtopmode %x htstbc %x chw %u\n",
2159 		ni->ni_htopmode, ni->ni_htstbc, ni->ni_chw);
2160 }
2161 
2162 void
2163 ieee80211_dump_nodes(struct ieee80211_node_table *nt)
2164 {
2165 	ieee80211_iterate_nodes(nt,
2166 		(ieee80211_iter_func *) ieee80211_dump_node, nt);
2167 }
2168 
2169 static void
2170 ieee80211_notify_erp_locked(struct ieee80211com *ic)
2171 {
2172 	struct ieee80211vap *vap;
2173 
2174 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
2175 		if (vap->iv_opmode == IEEE80211_M_HOSTAP)
2176 			ieee80211_beacon_notify(vap, IEEE80211_BEACON_ERP);
2177 }
2178 
2179 void
2180 ieee80211_notify_erp(struct ieee80211com *ic)
2181 {
2182 	ieee80211_notify_erp_locked(ic);
2183 }
2184 
2185 /*
2186  * Handle a station joining an 11g network.
2187  */
2188 static void
2189 ieee80211_node_join_11g(struct ieee80211_node *ni)
2190 {
2191 	struct ieee80211com *ic = ni->ni_ic;
2192 
2193 	/*
2194 	 * Station isn't capable of short slot time.  Bump
2195 	 * the count of long slot time stations and disable
2196 	 * use of short slot time.  Note that the actual switch
2197 	 * over to long slot time use may not occur until the
2198 	 * next beacon transmission (per sec. 7.3.1.4 of 11g).
2199 	 */
2200 	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
2201 		ic->ic_longslotsta++;
2202 		IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ASSOC, ni,
2203 		    "station needs long slot time, count %d",
2204 		    ic->ic_longslotsta);
2205 		/* XXX vap's w/ conflicting needs won't work */
2206 		if (!IEEE80211_IS_CHAN_108G(ic->ic_bsschan)) {
2207 			/*
2208 			 * Don't force slot time when switched to turbo
2209 			 * mode as non-ERP stations won't be present; this
2210 			 * need only be done when on the normal G channel.
2211 			 */
2212 			ieee80211_set_shortslottime(ic, 0);
2213 		}
2214 	}
2215 	/*
2216 	 * If the new station is not an ERP station
2217 	 * then bump the counter and enable protection
2218 	 * if configured.
2219 	 */
2220 	if (!ieee80211_iserp_rateset(&ni->ni_rates)) {
2221 		ic->ic_nonerpsta++;
2222 		IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ASSOC, ni,
2223 		    "station is !ERP, %d non-ERP stations associated",
2224 		    ic->ic_nonerpsta);
2225 		/*
2226 		 * If station does not support short preamble
2227 		 * then we must enable use of Barker preamble.
2228 		 */
2229 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE) == 0) {
2230 			IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ASSOC, ni,
2231 			    "%s", "station needs long preamble");
2232 			ic->ic_flags |= IEEE80211_F_USEBARKER;
2233 			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
2234 		}
2235 		/*
2236 		 * If protection is configured and this is the first
2237 		 * indication we should use protection, enable it.
2238 		 */
2239 		if (ic->ic_protmode != IEEE80211_PROT_NONE &&
2240 		    ic->ic_nonerpsta == 1 &&
2241 		    (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) == 0) {
2242 			IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_ASSOC,
2243 			    "%s: enable use of protection\n", __func__);
2244 			ic->ic_flags |= IEEE80211_F_USEPROT;
2245 			ieee80211_notify_erp_locked(ic);
2246 		}
2247 	} else
2248 		ni->ni_flags |= IEEE80211_NODE_ERP;
2249 }
2250 
2251 void
2252 ieee80211_node_join(struct ieee80211_node *ni, int resp)
2253 {
2254 	struct ieee80211com *ic = ni->ni_ic;
2255 	struct ieee80211vap *vap = ni->ni_vap;
2256 	int newassoc;
2257 
2258 	if (ni->ni_associd == 0) {
2259 		uint16_t aid;
2260 
2261 		KASSERT(vap->iv_aid_bitmap != NULL, ("no aid bitmap"));
2262 		/*
2263 		 * It would be good to search the bitmap
2264 		 * more efficiently, but this will do for now.
2265 		 */
2266 		for (aid = 1; aid < vap->iv_max_aid; aid++) {
2267 			if (!IEEE80211_AID_ISSET(vap, aid))
2268 				break;
2269 		}
2270 		if (aid >= vap->iv_max_aid) {
2271 			IEEE80211_SEND_MGMT(ni, resp, IEEE80211_STATUS_TOOMANY);
2272 			ieee80211_node_leave(ni);
2273 			return;
2274 		}
2275 		ni->ni_associd = aid | 0xc000;
2276 		ni->ni_jointime = time_uptime;
2277 		IEEE80211_AID_SET(vap, ni->ni_associd);
2278 		vap->iv_sta_assoc++;
2279 		ic->ic_sta_assoc++;
2280 
2281 		if (IEEE80211_IS_CHAN_HT(ic->ic_bsschan))
2282 			ieee80211_ht_node_join(ni);
2283 		if (IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan) &&
2284 		    IEEE80211_IS_CHAN_FULL(ic->ic_bsschan))
2285 			ieee80211_node_join_11g(ni);
2286 
2287 		newassoc = 1;
2288 	} else
2289 		newassoc = 0;
2290 
2291 	IEEE80211_NOTE(vap, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG, ni,
2292 	    "station associated at aid %d: %s preamble, %s slot time%s%s%s%s%s%s%s%s",
2293 	    IEEE80211_NODE_AID(ni),
2294 	    ic->ic_flags & IEEE80211_F_SHPREAMBLE ? "short" : "long",
2295 	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long",
2296 	    ic->ic_flags & IEEE80211_F_USEPROT ? ", protection" : "",
2297 	    ni->ni_flags & IEEE80211_NODE_QOS ? ", QoS" : "",
2298 	    ni->ni_flags & IEEE80211_NODE_HT ?
2299 		(ni->ni_chw == 40 ? ", HT40" : ", HT20") : "",
2300 	    ni->ni_flags & IEEE80211_NODE_AMPDU ? " (+AMPDU)" : "",
2301 	    ni->ni_flags & IEEE80211_NODE_MIMO_RTS ? " (+SMPS-DYN)" :
2302 	        ni->ni_flags & IEEE80211_NODE_MIMO_PS ? " (+SMPS)" : "",
2303 	    ni->ni_flags & IEEE80211_NODE_RIFS ? " (+RIFS)" : "",
2304 	    IEEE80211_ATH_CAP(vap, ni, IEEE80211_NODE_FF) ?
2305 		", fast-frames" : "",
2306 	    IEEE80211_ATH_CAP(vap, ni, IEEE80211_NODE_TURBOP) ?
2307 		", turbo" : ""
2308 	);
2309 
2310 	ieee80211_node_setuptxparms(ni);
2311 	/* give driver a chance to setup state like ni_txrate */
2312 	if (ic->ic_newassoc != NULL)
2313 		ic->ic_newassoc(ni, newassoc);
2314 	IEEE80211_SEND_MGMT(ni, resp, IEEE80211_STATUS_SUCCESS);
2315 	/* tell the authenticator about new station */
2316 	if (vap->iv_auth->ia_node_join != NULL)
2317 		vap->iv_auth->ia_node_join(ni);
2318 	ieee80211_notify_node_join(ni,
2319 	    resp == IEEE80211_FC0_SUBTYPE_ASSOC_RESP);
2320 }
2321 
2322 static void
2323 disable_protection(struct ieee80211com *ic)
2324 {
2325 	KASSERT(ic->ic_nonerpsta == 0 &&
2326 	    (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) == 0,
2327 	   ("%d non ERP stations, flags 0x%x", ic->ic_nonerpsta,
2328 	   ic->ic_flags_ext));
2329 
2330 	ic->ic_flags &= ~IEEE80211_F_USEPROT;
2331 	/* XXX verify mode? */
2332 	if (ic->ic_caps & IEEE80211_C_SHPREAMBLE) {
2333 		ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
2334 		ic->ic_flags &= ~IEEE80211_F_USEBARKER;
2335 	}
2336 	ieee80211_notify_erp_locked(ic);
2337 }
2338 
2339 /*
2340  * Handle a station leaving an 11g network.
2341  */
2342 static void
2343 ieee80211_node_leave_11g(struct ieee80211_node *ni)
2344 {
2345 	struct ieee80211com *ic = ni->ni_ic;
2346 
2347 	KASSERT(IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan),
2348 	     ("not in 11g, bss %u:0x%x", ic->ic_bsschan->ic_freq,
2349 	      ic->ic_bsschan->ic_flags));
2350 
2351 	/*
2352 	 * If a long slot station do the slot time bookkeeping.
2353 	 */
2354 	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
2355 		KASSERT(ic->ic_longslotsta > 0,
2356 		    ("bogus long slot station count %d", ic->ic_longslotsta));
2357 		ic->ic_longslotsta--;
2358 		IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ASSOC, ni,
2359 		    "long slot time station leaves, count now %d",
2360 		    ic->ic_longslotsta);
2361 		if (ic->ic_longslotsta == 0) {
2362 			/*
2363 			 * Re-enable use of short slot time if supported
2364 			 * and not operating in IBSS mode (per spec).
2365 			 */
2366 			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
2367 			    ic->ic_opmode != IEEE80211_M_IBSS) {
2368 				IEEE80211_DPRINTF(ni->ni_vap,
2369 				    IEEE80211_MSG_ASSOC,
2370 				    "%s: re-enable use of short slot time\n",
2371 				    __func__);
2372 				ieee80211_set_shortslottime(ic, 1);
2373 			}
2374 		}
2375 	}
2376 	/*
2377 	 * If a non-ERP station do the protection-related bookkeeping.
2378 	 */
2379 	if ((ni->ni_flags & IEEE80211_NODE_ERP) == 0) {
2380 		KASSERT(ic->ic_nonerpsta > 0,
2381 		    ("bogus non-ERP station count %d", ic->ic_nonerpsta));
2382 		ic->ic_nonerpsta--;
2383 		IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ASSOC, ni,
2384 		    "non-ERP station leaves, count now %d%s", ic->ic_nonerpsta,
2385 		    (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) ?
2386 			" (non-ERP sta present)" : "");
2387 		if (ic->ic_nonerpsta == 0 &&
2388 		    (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) == 0) {
2389 			IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_ASSOC,
2390 				"%s: disable use of protection\n", __func__);
2391 			disable_protection(ic);
2392 		}
2393 	}
2394 }
2395 
2396 /*
2397  * Time out presence of an overlapping bss with non-ERP
2398  * stations.  When operating in hostap mode we listen for
2399  * beacons from other stations and if we identify a non-ERP
2400  * station is present we enable protection.  To identify
2401  * when all non-ERP stations are gone we time out this
2402  * condition.
2403  */
2404 static void
2405 ieee80211_erp_timeout(struct ieee80211com *ic)
2406 {
2407 	if ((ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) &&
2408 	    time_after(ticks, ic->ic_lastnonerp + IEEE80211_NONERP_PRESENT_AGE)) {
2409 #if 0
2410 		IEEE80211_NOTE(vap, IEEE80211_MSG_ASSOC, ni,
2411 		    "%s", "age out non-ERP sta present on channel");
2412 #endif
2413 		ic->ic_flags_ext &= ~IEEE80211_FEXT_NONERP_PR;
2414 		if (ic->ic_nonerpsta == 0)
2415 			disable_protection(ic);
2416 	}
2417 }
2418 
2419 /*
2420  * Handle bookkeeping for station deauthentication/disassociation
2421  * when operating as an ap.
2422  */
2423 void
2424 ieee80211_node_leave(struct ieee80211_node *ni)
2425 {
2426 	struct ieee80211com *ic = ni->ni_ic;
2427 	struct ieee80211vap *vap = ni->ni_vap;
2428 	struct ieee80211_node_table *nt = ni->ni_table;
2429 
2430 	IEEE80211_NOTE(vap, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG, ni,
2431 	    "station with aid %d leaves", IEEE80211_NODE_AID(ni));
2432 
2433 	KASSERT(vap->iv_opmode != IEEE80211_M_STA,
2434 		("unexpected operating mode %u", vap->iv_opmode));
2435 	/*
2436 	 * If node wasn't previously associated all
2437 	 * we need to do is reclaim the reference.
2438 	 */
2439 	/* XXX ibss mode bypasses 11g and notification */
2440 	if (ni->ni_associd == 0)
2441 		goto done;
2442 	/*
2443 	 * Tell the authenticator the station is leaving.
2444 	 * Note that we must do this before yanking the
2445 	 * association id as the authenticator uses the
2446 	 * associd to locate it's state block.
2447 	 */
2448 	if (vap->iv_auth->ia_node_leave != NULL)
2449 		vap->iv_auth->ia_node_leave(ni);
2450 
2451 	IEEE80211_AID_CLR(vap, ni->ni_associd);
2452 	ni->ni_associd = 0;
2453 	vap->iv_sta_assoc--;
2454 	ic->ic_sta_assoc--;
2455 
2456 	if (IEEE80211_IS_CHAN_HT(ic->ic_bsschan))
2457 		ieee80211_ht_node_leave(ni);
2458 	if (IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan) &&
2459 	    IEEE80211_IS_CHAN_FULL(ic->ic_bsschan))
2460 		ieee80211_node_leave_11g(ni);
2461 	/*
2462 	 * Cleanup station state.  In particular clear various
2463 	 * state that might otherwise be reused if the node
2464 	 * is reused before the reference count goes to zero
2465 	 * (and memory is reclaimed).
2466 	 */
2467 	ieee80211_sta_leave(ni);
2468 done:
2469 	/*
2470 	 * Remove the node from any table it's recorded in and
2471 	 * drop the caller's reference.  Removal from the table
2472 	 * is important to insure the node is not reprocessed
2473 	 * for inactivity.
2474 	 */
2475 	if (nt != NULL) {
2476 		node_reclaim(nt, ni);
2477 	} else
2478 		ieee80211_free_node(ni);
2479 }
2480 
2481 struct rssiinfo {
2482 	struct ieee80211vap *vap;
2483 	int	rssi_samples;
2484 	uint32_t rssi_total;
2485 };
2486 
2487 static void
2488 get_hostap_rssi(void *arg, struct ieee80211_node *ni)
2489 {
2490 	struct rssiinfo *info = arg;
2491 	struct ieee80211vap *vap = ni->ni_vap;
2492 	int8_t rssi;
2493 
2494 	if (info->vap != vap)
2495 		return;
2496 	/* only associated stations */
2497 	if (ni->ni_associd == 0)
2498 		return;
2499 	rssi = vap->iv_ic->ic_node_getrssi(ni);
2500 	if (rssi != 0) {
2501 		info->rssi_samples++;
2502 		info->rssi_total += rssi;
2503 	}
2504 }
2505 
2506 static void
2507 get_adhoc_rssi(void *arg, struct ieee80211_node *ni)
2508 {
2509 	struct rssiinfo *info = arg;
2510 	struct ieee80211vap *vap = ni->ni_vap;
2511 	int8_t rssi;
2512 
2513 	if (info->vap != vap)
2514 		return;
2515 	/* only neighbors */
2516 	/* XXX check bssid */
2517 	if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
2518 		return;
2519 	rssi = vap->iv_ic->ic_node_getrssi(ni);
2520 	if (rssi != 0) {
2521 		info->rssi_samples++;
2522 		info->rssi_total += rssi;
2523 	}
2524 }
2525 
2526 #ifdef IEEE80211_SUPPORT_MESH
2527 static void
2528 get_mesh_rssi(void *arg, struct ieee80211_node *ni)
2529 {
2530 	struct rssiinfo *info = arg;
2531 	struct ieee80211vap *vap = ni->ni_vap;
2532 	int8_t rssi;
2533 
2534 	if (info->vap != vap)
2535 		return;
2536 	/* only neighbors that peered successfully */
2537 	if (ni->ni_mlstate != IEEE80211_NODE_MESH_ESTABLISHED)
2538 		return;
2539 	rssi = vap->iv_ic->ic_node_getrssi(ni);
2540 	if (rssi != 0) {
2541 		info->rssi_samples++;
2542 		info->rssi_total += rssi;
2543 	}
2544 }
2545 #endif /* IEEE80211_SUPPORT_MESH */
2546 
2547 int8_t
2548 ieee80211_getrssi(struct ieee80211vap *vap)
2549 {
2550 #define	NZ(x)	((x) == 0 ? 1 : (x))
2551 	struct ieee80211com *ic = vap->iv_ic;
2552 	struct rssiinfo info;
2553 
2554 	info.rssi_total = 0;
2555 	info.rssi_samples = 0;
2556 	info.vap = vap;
2557 	switch (vap->iv_opmode) {
2558 	case IEEE80211_M_IBSS:		/* average of all ibss neighbors */
2559 	case IEEE80211_M_AHDEMO:	/* average of all neighbors */
2560 		ieee80211_iterate_nodes(&ic->ic_sta, get_adhoc_rssi, &info);
2561 		break;
2562 	case IEEE80211_M_HOSTAP:	/* average of all associated stations */
2563 		ieee80211_iterate_nodes(&ic->ic_sta, get_hostap_rssi, &info);
2564 		break;
2565 #ifdef IEEE80211_SUPPORT_MESH
2566 	case IEEE80211_M_MBSS:		/* average of all mesh neighbors */
2567 		ieee80211_iterate_nodes(&ic->ic_sta, get_mesh_rssi, &info);
2568 		break;
2569 #endif
2570 	case IEEE80211_M_MONITOR:	/* XXX */
2571 	case IEEE80211_M_STA:		/* use stats from associated ap */
2572 	default:
2573 		if (vap->iv_bss != NULL)
2574 			info.rssi_total = ic->ic_node_getrssi(vap->iv_bss);
2575 		info.rssi_samples = 1;
2576 		break;
2577 	}
2578 	return info.rssi_total / NZ(info.rssi_samples);
2579 #undef NZ
2580 }
2581 
2582 void
2583 ieee80211_getsignal(struct ieee80211vap *vap, int8_t *rssi, int8_t *noise)
2584 {
2585 
2586 	if (vap->iv_bss == NULL)		/* NB: shouldn't happen */
2587 		return;
2588 	vap->iv_ic->ic_node_getsignal(vap->iv_bss, rssi, noise);
2589 	/* for non-station mode return avg'd rssi accounting */
2590 	if (vap->iv_opmode != IEEE80211_M_STA)
2591 		*rssi = ieee80211_getrssi(vap);
2592 }
2593