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