ieee80211_node.c revision 173273
1/*-
2 * Copyright (c) 2001 Atsushi Onoe
3 * Copyright (c) 2002-2007 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: head/sys/net80211/ieee80211_node.c 173273 2007-11-02 05:22:25Z sam $");
29
30#include <sys/param.h>
31#include <sys/systm.h>
32#include <sys/mbuf.h>
33#include <sys/malloc.h>
34#include <sys/kernel.h>
35
36#include <sys/socket.h>
37
38#include <net/if.h>
39#include <net/if_media.h>
40#include <net/ethernet.h>
41
42#include <net80211/ieee80211_var.h>
43
44#include <net/bpf.h>
45
46/*
47 * Association id's are managed with a bit vector.
48 */
49#define	IEEE80211_AID_SET(b, w) \
50	((w)[IEEE80211_AID(b) / 32] |= (1 << (IEEE80211_AID(b) % 32)))
51#define	IEEE80211_AID_CLR(b, w) \
52	((w)[IEEE80211_AID(b) / 32] &= ~(1 << (IEEE80211_AID(b) % 32)))
53#define	IEEE80211_AID_ISSET(b, w) \
54	((w)[IEEE80211_AID(b) / 32] & (1 << (IEEE80211_AID(b) % 32)))
55
56#ifdef IEEE80211_DEBUG_REFCNT
57#define REFCNT_LOC "%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line
58#else
59#define REFCNT_LOC "%s %p<%s> refcnt %d\n", __func__
60#endif
61
62static int ieee80211_sta_join1(struct ieee80211_node *);
63
64static struct ieee80211_node *node_alloc(struct ieee80211_node_table *);
65static void node_cleanup(struct ieee80211_node *);
66static void node_free(struct ieee80211_node *);
67static int8_t node_getrssi(const struct ieee80211_node *);
68static void node_getsignal(const struct ieee80211_node *, int8_t *, int8_t *);
69
70static void ieee80211_setup_node(struct ieee80211_node_table *,
71		struct ieee80211_node *, const uint8_t *);
72static void _ieee80211_free_node(struct ieee80211_node *);
73
74static void ieee80211_node_table_init(struct ieee80211com *ic,
75	struct ieee80211_node_table *nt, const char *name,
76	int inact, int keymaxix);
77static void ieee80211_node_table_reset(struct ieee80211_node_table *);
78static void ieee80211_node_table_cleanup(struct ieee80211_node_table *nt);
79static void ieee80211_erp_timeout(struct ieee80211com *);
80
81MALLOC_DEFINE(M_80211_NODE, "80211node", "802.11 node state");
82
83void
84ieee80211_node_attach(struct ieee80211com *ic)
85{
86
87	ic->ic_node_alloc = node_alloc;
88	ic->ic_node_free = node_free;
89	ic->ic_node_cleanup = node_cleanup;
90	ic->ic_node_getrssi = node_getrssi;
91	ic->ic_node_getsignal = node_getsignal;
92
93	/* default station inactivity timer setings */
94	ic->ic_inact_init = IEEE80211_INACT_INIT;
95	ic->ic_inact_auth = IEEE80211_INACT_AUTH;
96	ic->ic_inact_run = IEEE80211_INACT_RUN;
97	ic->ic_inact_probe = IEEE80211_INACT_PROBE;
98
99	callout_init(&ic->ic_inact, CALLOUT_MPSAFE);
100
101	/* NB: driver should override */
102	ic->ic_max_aid = IEEE80211_AID_DEF;
103
104	ic->ic_flags_ext |= IEEE80211_FEXT_INACT; /* inactivity processing */
105}
106
107void
108ieee80211_node_lateattach(struct ieee80211com *ic)
109{
110	struct ieee80211_rsnparms *rsn;
111
112	if (ic->ic_max_aid > IEEE80211_AID_MAX)
113		ic->ic_max_aid = IEEE80211_AID_MAX;
114	MALLOC(ic->ic_aid_bitmap, uint32_t *,
115		howmany(ic->ic_max_aid, 32) * sizeof(uint32_t),
116		M_80211_NODE, M_NOWAIT | M_ZERO);
117	if (ic->ic_aid_bitmap == NULL) {
118		/* XXX no way to recover */
119		printf("%s: no memory for AID bitmap!\n", __func__);
120		ic->ic_max_aid = 0;
121	}
122
123	ieee80211_node_table_init(ic, &ic->ic_sta, "station",
124		IEEE80211_INACT_INIT, ic->ic_crypto.cs_max_keyix);
125
126	ieee80211_reset_bss(ic);
127	/*
128	 * Setup "global settings" in the bss node so that
129	 * each new station automatically inherits them.
130	 */
131	rsn = &ic->ic_bss->ni_rsn;
132	/* WEP, TKIP, and AES-CCM are always supported */
133	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_WEP;
134	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_TKIP;
135	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_AES_CCM;
136	if (ic->ic_caps & IEEE80211_C_AES)
137		rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_AES_OCB;
138	if (ic->ic_caps & IEEE80211_C_CKIP)
139		rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_CKIP;
140	/*
141	 * Default unicast cipher to WEP for 802.1x use.  If
142	 * WPA is enabled the management code will set these
143	 * values to reflect.
144	 */
145	rsn->rsn_ucastcipher = IEEE80211_CIPHER_WEP;
146	rsn->rsn_ucastkeylen = 104 / NBBY;
147	/*
148	 * WPA says the multicast cipher is the lowest unicast
149	 * cipher supported.  But we skip WEP which would
150	 * otherwise be used based on this criteria.
151	 */
152	rsn->rsn_mcastcipher = IEEE80211_CIPHER_TKIP;
153	rsn->rsn_mcastkeylen = 128 / NBBY;
154
155	/*
156	 * We support both WPA-PSK and 802.1x; the one used
157	 * is determined by the authentication mode and the
158	 * setting of the PSK state.
159	 */
160	rsn->rsn_keymgmtset = WPA_ASE_8021X_UNSPEC | WPA_ASE_8021X_PSK;
161	rsn->rsn_keymgmt = WPA_ASE_8021X_PSK;
162
163	ic->ic_auth = ieee80211_authenticator_get(ic->ic_bss->ni_authmode);
164}
165
166void
167ieee80211_node_detach(struct ieee80211com *ic)
168{
169
170	if (ic->ic_bss != NULL) {
171		ieee80211_free_node(ic->ic_bss);
172		ic->ic_bss = NULL;
173	}
174	ieee80211_node_table_cleanup(&ic->ic_sta);
175	if (ic->ic_aid_bitmap != NULL) {
176		FREE(ic->ic_aid_bitmap, M_80211_NODE);
177		ic->ic_aid_bitmap = NULL;
178	}
179}
180
181/*
182 * Port authorize/unauthorize interfaces for use by an authenticator.
183 */
184
185void
186ieee80211_node_authorize(struct ieee80211_node *ni)
187{
188	struct ieee80211com *ic = ni->ni_ic;
189
190	ni->ni_flags |= IEEE80211_NODE_AUTH;
191	ni->ni_inact_reload = ic->ic_inact_run;
192	ni->ni_inact = ni->ni_inact_reload;
193}
194
195void
196ieee80211_node_unauthorize(struct ieee80211_node *ni)
197{
198	struct ieee80211com *ic = ni->ni_ic;
199
200	ni->ni_flags &= ~IEEE80211_NODE_AUTH;
201	ni->ni_inact_reload = ic->ic_inact_auth;
202	if (ni->ni_inact > ni->ni_inact_reload)
203		ni->ni_inact = ni->ni_inact_reload;
204}
205
206/*
207 * Set/change the channel.  The rate set is also updated as
208 * to insure a consistent view by drivers.
209 */
210static void
211ieee80211_node_set_chan(struct ieee80211com *ic, struct ieee80211_node *ni)
212{
213	struct ieee80211_channel *chan = ic->ic_bsschan;
214
215#if 0
216	KASSERT(chan != IEEE80211_CHAN_ANYC, ("bss channel not setup"));
217#else
218	if (chan == IEEE80211_CHAN_ANYC)	/* XXX while scanning */
219		chan = ic->ic_curchan;
220#endif
221	ni->ni_chan = chan;
222	if (IEEE80211_IS_CHAN_HT(chan)) {
223		/*
224		 * XXX Gotta be careful here; the rate set returned by
225		 * ieee80211_get_suprates is actually any HT rate
226		 * set so blindly copying it will be bad.  We must
227		 * install the legacy rate est in ni_rates and the
228		 * HT rate set in ni_htrates.
229		 */
230		ni->ni_htrates = *ieee80211_get_suphtrates(ic, chan);
231	}
232	ni->ni_rates = *ieee80211_get_suprates(ic, chan);
233}
234
235/*
236 * Probe the curent channel, if allowed, while scanning.
237 * If the channel is not marked passive-only then send
238 * a probe request immediately.  Otherwise mark state and
239 * listen for beacons on the channel; if we receive something
240 * then we'll transmit a probe request.
241 */
242void
243ieee80211_probe_curchan(struct ieee80211com *ic, int force)
244{
245	struct ifnet *ifp = ic->ic_ifp;
246
247	if ((ic->ic_curchan->ic_flags & IEEE80211_CHAN_PASSIVE) == 0 || force) {
248		/*
249		 * XXX send both broadcast+directed probe request
250		 */
251		ieee80211_send_probereq(ic->ic_bss,
252			ic->ic_myaddr, ifp->if_broadcastaddr,
253			ifp->if_broadcastaddr,
254			ic->ic_des_ssid[0].ssid, ic->ic_des_ssid[0].len,
255			ic->ic_opt_ie, ic->ic_opt_ie_len);
256	} else
257		ic->ic_flags_ext |= IEEE80211_FEXT_PROBECHAN;
258}
259
260static __inline void
261copy_bss(struct ieee80211_node *nbss, const struct ieee80211_node *obss)
262{
263	/* propagate useful state */
264	nbss->ni_authmode = obss->ni_authmode;
265	nbss->ni_txpower = obss->ni_txpower;
266	nbss->ni_vlan = obss->ni_vlan;
267	nbss->ni_rsn = obss->ni_rsn;
268	/* XXX statistics? */
269}
270
271void
272ieee80211_create_ibss(struct ieee80211com* ic, struct ieee80211_channel *chan)
273{
274	struct ieee80211_node_table *nt;
275	struct ieee80211_node *ni;
276
277	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
278		"%s: creating ibss\n", __func__);
279
280	/*
281	 * Create the station/neighbor table.  Note that for adhoc
282	 * mode we make the initial inactivity timer longer since
283	 * we create nodes only through discovery and they typically
284	 * are long-lived associations.
285	 */
286	nt = &ic->ic_sta;
287	IEEE80211_NODE_LOCK(nt);
288	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
289		nt->nt_name = "station";
290		nt->nt_inact_init = ic->ic_inact_init;
291	} else {
292		nt->nt_name = "neighbor";
293		nt->nt_inact_init = ic->ic_inact_run;
294	}
295	IEEE80211_NODE_UNLOCK(nt);
296
297	ni = ieee80211_alloc_node(&ic->ic_sta, ic->ic_myaddr);
298	if (ni == NULL) {
299		/* XXX recovery? */
300		return;
301	}
302	IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_myaddr);
303	ni->ni_esslen = ic->ic_des_ssid[0].len;
304	memcpy(ni->ni_essid, ic->ic_des_ssid[0].ssid, ni->ni_esslen);
305	if (ic->ic_bss != NULL)
306		copy_bss(ni, ic->ic_bss);
307	ni->ni_intval = ic->ic_bintval;
308	if (ic->ic_flags & IEEE80211_F_PRIVACY)
309		ni->ni_capinfo |= IEEE80211_CAPINFO_PRIVACY;
310	if (ic->ic_phytype == IEEE80211_T_FH) {
311		ni->ni_fhdwell = 200;	/* XXX */
312		ni->ni_fhindex = 1;
313	}
314	if (ic->ic_opmode == IEEE80211_M_IBSS) {
315		ic->ic_flags |= IEEE80211_F_SIBSS;
316		ni->ni_capinfo |= IEEE80211_CAPINFO_IBSS;	/* XXX */
317		if (ic->ic_flags & IEEE80211_F_DESBSSID)
318			IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_des_bssid);
319		else {
320			get_random_bytes(ni->ni_bssid, IEEE80211_ADDR_LEN);
321			/* clear group bit, add local bit */
322			ni->ni_bssid[0] = (ni->ni_bssid[0] &~ 0x01) | 0x02;
323		}
324	} else if (ic->ic_opmode == IEEE80211_M_AHDEMO) {
325		if (ic->ic_flags & IEEE80211_F_DESBSSID)
326			IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_des_bssid);
327		else
328			memset(ni->ni_bssid, 0, IEEE80211_ADDR_LEN);
329	}
330	/*
331	 * Fix the channel and related attributes.
332	 */
333	ic->ic_bsschan = chan;
334	ieee80211_node_set_chan(ic, ni);
335	ic->ic_curmode = ieee80211_chan2mode(chan);
336	/*
337	 * Do mode-specific rate setup.
338	 */
339	if (IEEE80211_IS_CHAN_FULL(chan)) {
340		if (IEEE80211_IS_CHAN_ANYG(chan)) {
341			/*
342			 * Use a mixed 11b/11g rate set.
343			 */
344			ieee80211_set11gbasicrates(&ni->ni_rates,
345				IEEE80211_MODE_11G);
346		} else if (IEEE80211_IS_CHAN_B(chan)) {
347			/*
348			 * Force pure 11b rate set.
349			 */
350			ieee80211_set11gbasicrates(&ni->ni_rates,
351				IEEE80211_MODE_11B);
352		}
353	}
354
355	(void) ieee80211_sta_join1(ieee80211_ref_node(ni));
356}
357
358/*
359 * Reset bss state on transition to the INIT state.
360 * Clear any stations from the table (they have been
361 * deauth'd) and reset the bss node (clears key, rate
362 * etc. state).
363 */
364void
365ieee80211_reset_bss(struct ieee80211com *ic)
366{
367	struct ieee80211_node *ni, *obss;
368
369	callout_drain(&ic->ic_inact);
370	ieee80211_node_table_reset(&ic->ic_sta);
371	ieee80211_reset_erp(ic);
372
373	ni = ieee80211_alloc_node(&ic->ic_sta, ic->ic_myaddr);
374	KASSERT(ni != NULL, ("unable to setup inital BSS node"));
375	obss = ic->ic_bss;
376	ic->ic_bss = ieee80211_ref_node(ni);
377	if (obss != NULL) {
378		copy_bss(ni, obss);
379		ni->ni_intval = ic->ic_bintval;
380		ieee80211_free_node(obss);
381	}
382}
383
384static int
385match_ssid(const struct ieee80211_node *ni,
386	int nssid, const struct ieee80211_scan_ssid ssids[])
387{
388	int i;
389
390	for (i = 0; i < nssid; i++) {
391		if (ni->ni_esslen == ssids[i].len &&
392		     memcmp(ni->ni_essid, ssids[i].ssid, ni->ni_esslen) == 0)
393			return 1;
394	}
395	return 0;
396}
397
398/*
399 * Test a node for suitability/compatibility.
400 */
401static int
402check_bss(struct ieee80211com *ic, struct ieee80211_node *ni)
403{
404        uint8_t rate;
405
406	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
407		return 0;
408	if (ic->ic_opmode == IEEE80211_M_IBSS) {
409		if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
410			return 0;
411	} else {
412		if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
413			return 0;
414	}
415	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
416		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
417			return 0;
418	} else {
419		/* XXX does this mean privacy is supported or required? */
420		if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
421			return 0;
422	}
423	rate = ieee80211_fix_rate(ni, &ni->ni_rates,
424	    IEEE80211_F_JOIN | IEEE80211_F_DONEGO | IEEE80211_F_DOFRATE);
425	if (rate & IEEE80211_RATE_BASIC)
426		return 0;
427	if (ic->ic_des_nssid != 0 &&
428	    !match_ssid(ni, ic->ic_des_nssid, ic->ic_des_ssid))
429		return 0;
430	if ((ic->ic_flags & IEEE80211_F_DESBSSID) &&
431	    !IEEE80211_ADDR_EQ(ic->ic_des_bssid, ni->ni_bssid))
432		return 0;
433	return 1;
434}
435
436#ifdef IEEE80211_DEBUG
437/*
438 * Display node suitability/compatibility.
439 */
440static void
441check_bss_debug(struct ieee80211com *ic, struct ieee80211_node *ni)
442{
443        uint8_t rate;
444        int fail;
445
446	fail = 0;
447	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
448		fail |= 0x01;
449	if (ic->ic_opmode == IEEE80211_M_IBSS) {
450		if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
451			fail |= 0x02;
452	} else {
453		if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
454			fail |= 0x02;
455	}
456	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
457		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
458			fail |= 0x04;
459	} else {
460		/* XXX does this mean privacy is supported or required? */
461		if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
462			fail |= 0x04;
463	}
464	rate = ieee80211_fix_rate(ni, &ni->ni_rates,
465	     IEEE80211_F_JOIN | IEEE80211_F_DONEGO | IEEE80211_F_DOFRATE);
466	if (rate & IEEE80211_RATE_BASIC)
467		fail |= 0x08;
468	if (ic->ic_des_nssid != 0 &&
469	    !match_ssid(ni, ic->ic_des_nssid, ic->ic_des_ssid))
470		fail |= 0x10;
471	if ((ic->ic_flags & IEEE80211_F_DESBSSID) &&
472	    !IEEE80211_ADDR_EQ(ic->ic_des_bssid, ni->ni_bssid))
473		fail |= 0x20;
474
475	printf(" %c %s", fail ? '-' : '+', ether_sprintf(ni->ni_macaddr));
476	printf(" %s%c", ether_sprintf(ni->ni_bssid), fail & 0x20 ? '!' : ' ');
477	printf(" %3d%c",
478	    ieee80211_chan2ieee(ic, ni->ni_chan), fail & 0x01 ? '!' : ' ');
479	printf(" %+4d", ni->ni_rssi);
480	printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
481	    fail & 0x08 ? '!' : ' ');
482	printf(" %4s%c",
483	    (ni->ni_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
484	    (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
485	    "????",
486	    fail & 0x02 ? '!' : ' ');
487	printf(" %3s%c ",
488	    (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) ?  "wep" : "no",
489	    fail & 0x04 ? '!' : ' ');
490	ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
491	printf("%s\n", fail & 0x10 ? "!" : "");
492}
493#endif /* IEEE80211_DEBUG */
494
495/*
496 * Handle 802.11 ad hoc network merge.  The
497 * convention, set by the Wireless Ethernet Compatibility Alliance
498 * (WECA), is that an 802.11 station will change its BSSID to match
499 * the "oldest" 802.11 ad hoc network, on the same channel, that
500 * has the station's desired SSID.  The "oldest" 802.11 network
501 * sends beacons with the greatest TSF timestamp.
502 *
503 * The caller is assumed to validate TSF's before attempting a merge.
504 *
505 * Return !0 if the BSSID changed, 0 otherwise.
506 */
507int
508ieee80211_ibss_merge(struct ieee80211_node *ni)
509{
510	struct ieee80211com *ic = ni->ni_ic;
511
512	if (ni == ic->ic_bss ||
513	    IEEE80211_ADDR_EQ(ni->ni_bssid, ic->ic_bss->ni_bssid)) {
514		/* unchanged, nothing to do */
515		return 0;
516	}
517	if (!check_bss(ic, ni)) {
518		/* capabilities mismatch */
519		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
520		    "%s: merge failed, capabilities mismatch\n", __func__);
521#ifdef IEEE80211_DEBUG
522		if (ieee80211_msg_assoc(ic))
523			check_bss_debug(ic, ni);
524#endif
525		ic->ic_stats.is_ibss_capmismatch++;
526		return 0;
527	}
528	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
529		"%s: new bssid %s: %s preamble, %s slot time%s\n", __func__,
530		ether_sprintf(ni->ni_bssid),
531		ic->ic_flags&IEEE80211_F_SHPREAMBLE ? "short" : "long",
532		ic->ic_flags&IEEE80211_F_SHSLOT ? "short" : "long",
533		ic->ic_flags&IEEE80211_F_USEPROT ? ", protection" : ""
534	);
535	return ieee80211_sta_join1(ieee80211_ref_node(ni));
536}
537
538/*
539 * Change the bss channel.
540 */
541void
542ieee80211_setbsschan(struct ieee80211com *ic, struct ieee80211_channel *c)
543{
544	ic->ic_bsschan = c;
545	ic->ic_curchan = ic->ic_bsschan;
546	ic->ic_curmode = ieee80211_chan2mode(ic->ic_curchan);
547	ic->ic_set_channel(ic);
548}
549
550/*
551 * Join the specified IBSS/BSS network.  The node is assumed to
552 * be passed in with a held reference.
553 */
554static int
555ieee80211_sta_join1(struct ieee80211_node *selbs)
556{
557	struct ieee80211com *ic = selbs->ni_ic;
558	struct ieee80211_node *obss;
559	int canreassoc;
560
561	if (ic->ic_opmode == IEEE80211_M_IBSS) {
562		struct ieee80211_node_table *nt;
563		/*
564		 * Fillin the neighbor table; it will already
565		 * exist if we are simply switching mastership.
566		 * XXX ic_sta always setup so this is unnecessary?
567		 */
568		nt = &ic->ic_sta;
569		IEEE80211_NODE_LOCK(nt);
570		nt->nt_name = "neighbor";
571		nt->nt_inact_init = ic->ic_inact_run;
572		IEEE80211_NODE_UNLOCK(nt);
573	}
574
575	/*
576	 * Committed to selbs, setup state.
577	 */
578	obss = ic->ic_bss;
579	/*
580	 * Check if old+new node have the same address in which
581	 * case we can reassociate when operating in sta mode.
582	 */
583	canreassoc = (obss != NULL &&
584		ic->ic_state == IEEE80211_S_RUN &&
585		IEEE80211_ADDR_EQ(obss->ni_macaddr, selbs->ni_macaddr));
586	ic->ic_bss = selbs;		/* NB: caller assumed to bump refcnt */
587	if (obss != NULL) {
588		copy_bss(selbs, obss);
589		ieee80211_free_node(obss);
590	}
591
592	/*
593	 * Delete unusable rates; we've already checked
594	 * that the negotiated rate set is acceptable.
595	 */
596	ieee80211_fix_rate(ic->ic_bss, &ic->ic_bss->ni_rates,
597		IEEE80211_F_DODEL | IEEE80211_F_JOIN);
598
599	ieee80211_setbsschan(ic, selbs->ni_chan);
600	/*
601	 * Set the erp state (mostly the slot time) to deal with
602	 * the auto-select case; this should be redundant if the
603	 * mode is locked.
604	 */
605	ieee80211_reset_erp(ic);
606	ieee80211_wme_initparams(ic);
607
608	if (ic->ic_opmode == IEEE80211_M_STA) {
609		if (canreassoc) {
610			/* Reassociate */
611			ieee80211_new_state(ic, IEEE80211_S_ASSOC, 1);
612		} else {
613			/*
614			 * Act as if we received a DEAUTH frame in case we
615			 * are invoked from the RUN state.  This will cause
616			 * us to try to re-authenticate if we are operating
617			 * as a station.
618			 */
619			ieee80211_new_state(ic, IEEE80211_S_AUTH,
620				IEEE80211_FC0_SUBTYPE_DEAUTH);
621		}
622	} else
623		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
624	return 1;
625}
626
627int
628ieee80211_sta_join(struct ieee80211com *ic,
629	const struct ieee80211_scan_entry *se)
630{
631	struct ieee80211_node *ni;
632
633	ni = ieee80211_alloc_node(&ic->ic_sta, se->se_macaddr);
634	if (ni == NULL) {
635		/* XXX msg */
636		return 0;
637	}
638	/*
639	 * Expand scan state into node's format.
640	 * XXX may not need all this stuff
641	 */
642	IEEE80211_ADDR_COPY(ni->ni_bssid, se->se_bssid);
643	ni->ni_esslen = se->se_ssid[1];
644	memcpy(ni->ni_essid, se->se_ssid+2, ni->ni_esslen);
645	ni->ni_rstamp = se->se_rstamp;
646	ni->ni_tstamp.tsf = se->se_tstamp.tsf;
647	ni->ni_intval = se->se_intval;
648	ni->ni_capinfo = se->se_capinfo;
649	ni->ni_chan = se->se_chan;
650	ni->ni_timoff = se->se_timoff;
651	ni->ni_fhdwell = se->se_fhdwell;
652	ni->ni_fhindex = se->se_fhindex;
653	ni->ni_erp = se->se_erp;
654	ni->ni_rssi = se->se_rssi;
655	ni->ni_noise = se->se_noise;
656	if (se->se_htcap_ie != NULL)
657		ieee80211_saveie(&ni->ni_htcap_ie, se->se_htcap_ie);
658	if (se->se_wpa_ie != NULL)
659		ieee80211_saveie(&ni->ni_wpa_ie, se->se_wpa_ie);
660	if (se->se_rsn_ie != NULL)
661		ieee80211_saveie(&ni->ni_rsn_ie, se->se_rsn_ie);
662	if (se->se_wme_ie != NULL)
663		ieee80211_saveie(&ni->ni_wme_ie, se->se_wme_ie);
664	if (se->se_ath_ie != NULL)
665		ieee80211_saveath(ni, se->se_ath_ie);
666
667	ic->ic_dtim_period = se->se_dtimperiod;
668	ic->ic_dtim_count = 0;
669
670	/* NB: must be after ni_chan is setup */
671	ieee80211_setup_rates(ni, se->se_rates, se->se_xrates,
672		IEEE80211_F_DOSORT);
673
674	return ieee80211_sta_join1(ieee80211_ref_node(ni));
675}
676
677/*
678 * Leave the specified IBSS/BSS network.  The node is assumed to
679 * be passed in with a held reference.
680 */
681void
682ieee80211_sta_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
683{
684	ic->ic_node_cleanup(ni);
685	ieee80211_notify_node_leave(ic, ni);
686}
687
688static struct ieee80211_node *
689node_alloc(struct ieee80211_node_table *nt)
690{
691	struct ieee80211_node *ni;
692
693	MALLOC(ni, struct ieee80211_node *, sizeof(struct ieee80211_node),
694		M_80211_NODE, M_NOWAIT | M_ZERO);
695	return ni;
696}
697
698/*
699 * Reclaim any resources in a node and reset any critical
700 * state.  Typically nodes are free'd immediately after,
701 * but in some cases the storage may be reused so we need
702 * to insure consistent state (should probably fix that).
703 */
704static void
705node_cleanup(struct ieee80211_node *ni)
706{
707#define	N(a)	(sizeof(a)/sizeof(a[0]))
708	struct ieee80211com *ic = ni->ni_ic;
709	int i;
710
711	/* NB: preserve ni_table */
712	if (ni->ni_flags & IEEE80211_NODE_PWR_MGT) {
713		if (ic->ic_opmode != IEEE80211_M_STA)
714			ic->ic_ps_sta--;
715		ni->ni_flags &= ~IEEE80211_NODE_PWR_MGT;
716		IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
717		    "[%s] power save mode off, %u sta's in ps mode\n",
718		    ether_sprintf(ni->ni_macaddr), ic->ic_ps_sta);
719	}
720	/*
721	 * Cleanup any HT-related state.
722	 */
723	if (ni->ni_flags & IEEE80211_NODE_HT)
724		ieee80211_ht_node_cleanup(ni);
725	/*
726	 * Clear AREF flag that marks the authorization refcnt bump
727	 * has happened.  This is probably not needed as the node
728	 * should always be removed from the table so not found but
729	 * do it just in case.
730	 */
731	ni->ni_flags &= ~IEEE80211_NODE_AREF;
732
733	/*
734	 * Drain power save queue and, if needed, clear TIM.
735	 */
736	if (ieee80211_node_saveq_drain(ni) != 0 && ic->ic_set_tim != NULL)
737		ic->ic_set_tim(ni, 0);
738
739	ni->ni_associd = 0;
740	if (ni->ni_challenge != NULL) {
741		FREE(ni->ni_challenge, M_80211_NODE);
742		ni->ni_challenge = NULL;
743	}
744	/*
745	 * Preserve SSID, WPA, and WME ie's so the bss node is
746	 * reusable during a re-auth/re-assoc state transition.
747	 * If we remove these data they will not be recreated
748	 * because they come from a probe-response or beacon frame
749	 * which cannot be expected prior to the association-response.
750	 * This should not be an issue when operating in other modes
751	 * as stations leaving always go through a full state transition
752	 * which will rebuild this state.
753	 *
754	 * XXX does this leave us open to inheriting old state?
755	 */
756	for (i = 0; i < N(ni->ni_rxfrag); i++)
757		if (ni->ni_rxfrag[i] != NULL) {
758			m_freem(ni->ni_rxfrag[i]);
759			ni->ni_rxfrag[i] = NULL;
760		}
761	/*
762	 * Must be careful here to remove any key map entry w/o a LOR.
763	 */
764	ieee80211_node_delucastkey(ni);
765#undef N
766}
767
768static void
769node_free(struct ieee80211_node *ni)
770{
771	struct ieee80211com *ic = ni->ni_ic;
772
773	ic->ic_node_cleanup(ni);
774	if (ni->ni_wpa_ie != NULL)
775		FREE(ni->ni_wpa_ie, M_80211_NODE);
776	if (ni->ni_rsn_ie != NULL)
777		FREE(ni->ni_rsn_ie, M_80211_NODE);
778	if (ni->ni_wme_ie != NULL)
779		FREE(ni->ni_wme_ie, M_80211_NODE);
780	if (ni->ni_ath_ie != NULL)
781		FREE(ni->ni_ath_ie, M_80211_NODE);
782	IEEE80211_NODE_SAVEQ_DESTROY(ni);
783	FREE(ni, M_80211_NODE);
784}
785
786static int8_t
787node_getrssi(const struct ieee80211_node *ni)
788{
789	return ni->ni_rssi;
790}
791
792static void
793node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
794{
795	*rssi = ni->ni_rssi;
796	*noise = ni->ni_noise;
797}
798
799static void
800ieee80211_setup_node(struct ieee80211_node_table *nt,
801	struct ieee80211_node *ni, const uint8_t *macaddr)
802{
803	struct ieee80211com *ic = nt->nt_ic;
804	int hash;
805
806	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
807		"%s %p<%s> in %s table\n", __func__, ni,
808		ether_sprintf(macaddr), nt->nt_name);
809
810	IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
811	hash = IEEE80211_NODE_HASH(macaddr);
812	ieee80211_node_initref(ni);		/* mark referenced */
813	ni->ni_chan = IEEE80211_CHAN_ANYC;
814	ni->ni_authmode = IEEE80211_AUTH_OPEN;
815	ni->ni_txpower = ic->ic_txpowlimit;	/* max power */
816	ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey, IEEE80211_KEYIX_NONE);
817	ni->ni_inact_reload = nt->nt_inact_init;
818	ni->ni_inact = ni->ni_inact_reload;
819	ni->ni_ath_defkeyix = 0x7fff;
820	IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
821
822	IEEE80211_NODE_LOCK(nt);
823	TAILQ_INSERT_TAIL(&nt->nt_node, ni, ni_list);
824	LIST_INSERT_HEAD(&nt->nt_hash[hash], ni, ni_hash);
825	ni->ni_table = nt;
826	ni->ni_ic = ic;
827	IEEE80211_NODE_UNLOCK(nt);
828}
829
830struct ieee80211_node *
831ieee80211_alloc_node(struct ieee80211_node_table *nt, const uint8_t *macaddr)
832{
833	struct ieee80211com *ic = nt->nt_ic;
834	struct ieee80211_node *ni;
835
836	ni = ic->ic_node_alloc(nt);
837	if (ni != NULL)
838		ieee80211_setup_node(nt, ni, macaddr);
839	else
840		ic->ic_stats.is_rx_nodealloc++;
841	return ni;
842}
843
844/*
845 * Craft a temporary node suitable for sending a management frame
846 * to the specified station.  We craft only as much state as we
847 * need to do the work since the node will be immediately reclaimed
848 * once the send completes.
849 */
850struct ieee80211_node *
851ieee80211_tmp_node(struct ieee80211com *ic, const uint8_t *macaddr)
852{
853	struct ieee80211_node *ni;
854
855	ni = ic->ic_node_alloc(&ic->ic_sta);
856	if (ni != NULL) {
857		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
858			"%s %p<%s>\n", __func__, ni, ether_sprintf(macaddr));
859
860		IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
861		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
862		ieee80211_node_initref(ni);		/* mark referenced */
863		ni->ni_txpower = ic->ic_bss->ni_txpower;
864		/* NB: required by ieee80211_fix_rate */
865		ieee80211_node_set_chan(ic, ni);
866		ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey,
867			IEEE80211_KEYIX_NONE);
868		/* XXX optimize away */
869		IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
870
871		ni->ni_table = NULL;		/* NB: pedantic */
872		ni->ni_ic = ic;
873	} else {
874		/* XXX msg */
875		ic->ic_stats.is_rx_nodealloc++;
876	}
877	return ni;
878}
879
880struct ieee80211_node *
881ieee80211_dup_bss(struct ieee80211_node_table *nt, const uint8_t *macaddr)
882{
883	struct ieee80211com *ic = nt->nt_ic;
884	struct ieee80211_node *ni;
885
886	ni = ic->ic_node_alloc(nt);
887	if (ni != NULL) {
888		ieee80211_setup_node(nt, ni, macaddr);
889		/*
890		 * Inherit from ic_bss.
891		 */
892		ni->ni_authmode = ic->ic_bss->ni_authmode;
893		ni->ni_txpower = ic->ic_bss->ni_txpower;
894		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
895		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
896		ieee80211_node_set_chan(ic, ni);
897		ni->ni_rsn = ic->ic_bss->ni_rsn;
898	} else
899		ic->ic_stats.is_rx_nodealloc++;
900	return ni;
901}
902
903static struct ieee80211_node *
904#ifdef IEEE80211_DEBUG_REFCNT
905_ieee80211_find_node_debug(struct ieee80211_node_table *nt,
906	const uint8_t *macaddr, const char *func, int line)
907#else
908_ieee80211_find_node(struct ieee80211_node_table *nt,
909	const uint8_t *macaddr)
910#endif
911{
912	struct ieee80211_node *ni;
913	int hash;
914
915	IEEE80211_NODE_LOCK_ASSERT(nt);
916
917	hash = IEEE80211_NODE_HASH(macaddr);
918	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
919		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
920			ieee80211_ref_node(ni);	/* mark referenced */
921#ifdef IEEE80211_DEBUG_REFCNT
922			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
923			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
924			    func, line,
925			    ni, ether_sprintf(ni->ni_macaddr),
926			    ieee80211_node_refcnt(ni));
927#endif
928			return ni;
929		}
930	}
931	return NULL;
932}
933#ifdef IEEE80211_DEBUG_REFCNT
934#define	_ieee80211_find_node(nt, mac) \
935	_ieee80211_find_node_debug(nt, mac, func, line)
936#endif
937
938struct ieee80211_node *
939#ifdef IEEE80211_DEBUG_REFCNT
940ieee80211_find_node_debug(struct ieee80211_node_table *nt,
941	const uint8_t *macaddr, const char *func, int line)
942#else
943ieee80211_find_node(struct ieee80211_node_table *nt, const uint8_t *macaddr)
944#endif
945{
946	struct ieee80211_node *ni;
947
948	IEEE80211_NODE_LOCK(nt);
949	ni = _ieee80211_find_node(nt, macaddr);
950	IEEE80211_NODE_UNLOCK(nt);
951	return ni;
952}
953
954/*
955 * Fake up a node; this handles node discovery in adhoc mode.
956 * Note that for the driver's benefit we we treat this like
957 * an association so the driver has an opportunity to setup
958 * it's private state.
959 */
960struct ieee80211_node *
961ieee80211_fakeup_adhoc_node(struct ieee80211_node_table *nt,
962	const uint8_t macaddr[IEEE80211_ADDR_LEN])
963{
964	struct ieee80211com *ic = nt->nt_ic;
965	struct ieee80211_node *ni;
966
967	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
968	    "%s: mac<%s>\n", __func__, ether_sprintf(macaddr));
969	ni = ieee80211_dup_bss(nt, macaddr);
970	if (ni != NULL) {
971		/* XXX no rate negotiation; just dup */
972		ni->ni_rates = ic->ic_bss->ni_rates;
973		if (ic->ic_newassoc != NULL)
974			ic->ic_newassoc(ni, 1);
975		if (ic->ic_opmode == IEEE80211_M_AHDEMO) {
976			/*
977			 * In adhoc demo mode there are no management
978			 * frames to use to discover neighbor capabilities,
979			 * so blindly propagate the local configuration
980			 * so we can do interesting things (e.g. use
981			 * WME to disable ACK's).
982			 */
983			if (ic->ic_flags & IEEE80211_F_WME)
984				ni->ni_flags |= IEEE80211_NODE_QOS;
985			if (ic->ic_flags & IEEE80211_F_FF)
986				ni->ni_flags |= IEEE80211_NODE_FF;
987		}
988		/* XXX not right for 802.1x/WPA */
989		ieee80211_node_authorize(ni);
990	}
991	return ni;
992}
993
994void
995ieee80211_init_neighbor(struct ieee80211_node *ni,
996	const struct ieee80211_frame *wh,
997	const struct ieee80211_scanparams *sp)
998{
999	ni->ni_esslen = sp->ssid[1];
1000	memcpy(ni->ni_essid, sp->ssid + 2, sp->ssid[1]);
1001	IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
1002	memcpy(ni->ni_tstamp.data, sp->tstamp, sizeof(ni->ni_tstamp));
1003	ni->ni_intval = sp->bintval;
1004	ni->ni_capinfo = sp->capinfo;
1005	ni->ni_chan = ni->ni_ic->ic_curchan;
1006	ni->ni_fhdwell = sp->fhdwell;
1007	ni->ni_fhindex = sp->fhindex;
1008	ni->ni_erp = sp->erp;
1009	ni->ni_timoff = sp->timoff;
1010	if (sp->wme != NULL)
1011		ieee80211_saveie(&ni->ni_wme_ie, sp->wme);
1012	if (sp->wpa != NULL)
1013		ieee80211_saveie(&ni->ni_wpa_ie, sp->wpa);
1014	if (sp->rsn != NULL)
1015		ieee80211_saveie(&ni->ni_rsn_ie, sp->rsn);
1016	if (sp->ath != NULL)
1017		ieee80211_saveath(ni, sp->ath);
1018
1019	/* NB: must be after ni_chan is setup */
1020	ieee80211_setup_rates(ni, sp->rates, sp->xrates,
1021		IEEE80211_F_DOSORT | IEEE80211_F_DOFRATE |
1022		IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
1023}
1024
1025/*
1026 * Do node discovery in adhoc mode on receipt of a beacon
1027 * or probe response frame.  Note that for the driver's
1028 * benefit we we treat this like an association so the
1029 * driver has an opportunity to setup it's private state.
1030 */
1031struct ieee80211_node *
1032ieee80211_add_neighbor(struct ieee80211com *ic,
1033	const struct ieee80211_frame *wh,
1034	const struct ieee80211_scanparams *sp)
1035{
1036	struct ieee80211_node *ni;
1037
1038	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1039	    "%s: mac<%s>\n", __func__, ether_sprintf(wh->i_addr2));
1040	ni = ieee80211_dup_bss(&ic->ic_sta, wh->i_addr2);/* XXX alloc_node? */
1041	if (ni != NULL) {
1042		ieee80211_init_neighbor(ni, wh, sp);
1043		if (ic->ic_newassoc != NULL)
1044			ic->ic_newassoc(ni, 1);
1045		/* XXX not right for 802.1x/WPA */
1046		ieee80211_node_authorize(ni);
1047	}
1048	return ni;
1049}
1050
1051#define	IS_CTL(wh) \
1052	((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_CTL)
1053#define	IS_PSPOLL(wh) \
1054	((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_PS_POLL)
1055#define	IS_BAR(wh) \
1056	((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_BAR)
1057
1058/*
1059 * Locate the node for sender, track state, and then pass the
1060 * (referenced) node up to the 802.11 layer for its use.  We
1061 * are required to pass some node so we fall back to ic_bss
1062 * when this frame is from an unknown sender.  The 802.11 layer
1063 * knows this means the sender wasn't in the node table and
1064 * acts accordingly.
1065 */
1066struct ieee80211_node *
1067#ifdef IEEE80211_DEBUG_REFCNT
1068ieee80211_find_rxnode_debug(struct ieee80211com *ic,
1069	const struct ieee80211_frame_min *wh, const char *func, int line)
1070#else
1071ieee80211_find_rxnode(struct ieee80211com *ic,
1072	const struct ieee80211_frame_min *wh)
1073#endif
1074{
1075	struct ieee80211_node_table *nt;
1076	struct ieee80211_node *ni;
1077
1078	/* XXX check ic_bss first in station mode */
1079	/* XXX 4-address frames? */
1080	nt = &ic->ic_sta;
1081	IEEE80211_NODE_LOCK(nt);
1082	if (IS_CTL(wh) && !IS_PSPOLL(wh) && !IS_BAR(wh) /*&& !IS_RTS(ah)*/)
1083		ni = _ieee80211_find_node(nt, wh->i_addr1);
1084	else
1085		ni = _ieee80211_find_node(nt, wh->i_addr2);
1086	if (ni == NULL)
1087		ni = ieee80211_ref_node(ic->ic_bss);
1088	IEEE80211_NODE_UNLOCK(nt);
1089
1090	return ni;
1091}
1092
1093/*
1094 * Like ieee80211_find_rxnode but use the supplied h/w
1095 * key index as a hint to locate the node in the key
1096 * mapping table.  If an entry is present at the key
1097 * index we return it; otherwise do a normal lookup and
1098 * update the mapping table if the station has a unicast
1099 * key assigned to it.
1100 */
1101struct ieee80211_node *
1102#ifdef IEEE80211_DEBUG_REFCNT
1103ieee80211_find_rxnode_withkey_debug(struct ieee80211com *ic,
1104	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix,
1105	const char *func, int line)
1106#else
1107ieee80211_find_rxnode_withkey(struct ieee80211com *ic,
1108	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix)
1109#endif
1110{
1111	struct ieee80211_node_table *nt;
1112	struct ieee80211_node *ni;
1113
1114	nt = &ic->ic_sta;
1115	IEEE80211_NODE_LOCK(nt);
1116	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax)
1117		ni = nt->nt_keyixmap[keyix];
1118	else
1119		ni = NULL;
1120	if (ni == NULL) {
1121		if (IS_CTL(wh) && !IS_PSPOLL(wh) && !IS_BAR(wh) /*&& !IS_RTS(ah)*/)
1122			ni = _ieee80211_find_node(nt, wh->i_addr1);
1123		else
1124			ni = _ieee80211_find_node(nt, wh->i_addr2);
1125		if (ni == NULL)
1126			ni = ieee80211_ref_node(ic->ic_bss);
1127		if (nt->nt_keyixmap != NULL) {
1128			/*
1129			 * If the station has a unicast key cache slot
1130			 * assigned update the key->node mapping table.
1131			 */
1132			keyix = ni->ni_ucastkey.wk_rxkeyix;
1133			/* XXX can keyixmap[keyix] != NULL? */
1134			if (keyix < nt->nt_keyixmax &&
1135			    nt->nt_keyixmap[keyix] == NULL) {
1136				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1137				    "%s: add key map entry %p<%s> refcnt %d\n",
1138				    __func__, ni, ether_sprintf(ni->ni_macaddr),
1139				    ieee80211_node_refcnt(ni)+1);
1140				nt->nt_keyixmap[keyix] = ieee80211_ref_node(ni);
1141			}
1142		}
1143	} else
1144		ieee80211_ref_node(ni);
1145	IEEE80211_NODE_UNLOCK(nt);
1146
1147	return ni;
1148}
1149#undef IS_BAR
1150#undef IS_PSPOLL
1151#undef IS_CTL
1152
1153/*
1154 * Return a reference to the appropriate node for sending
1155 * a data frame.  This handles node discovery in adhoc networks.
1156 */
1157struct ieee80211_node *
1158#ifdef IEEE80211_DEBUG_REFCNT
1159ieee80211_find_txnode_debug(struct ieee80211com *ic, const uint8_t *macaddr,
1160	const char *func, int line)
1161#else
1162ieee80211_find_txnode(struct ieee80211com *ic, const uint8_t *macaddr)
1163#endif
1164{
1165	struct ieee80211_node_table *nt = &ic->ic_sta;
1166	struct ieee80211_node *ni;
1167
1168	/*
1169	 * The destination address should be in the node table
1170	 * unless this is a multicast/broadcast frame.  We can
1171	 * also optimize station mode operation, all frames go
1172	 * to the bss node.
1173	 */
1174	/* XXX can't hold lock across dup_bss 'cuz of recursive locking */
1175	IEEE80211_NODE_LOCK(nt);
1176	if (ic->ic_opmode == IEEE80211_M_STA || IEEE80211_IS_MULTICAST(macaddr))
1177		ni = ieee80211_ref_node(ic->ic_bss);
1178	else {
1179		ni = _ieee80211_find_node(nt, macaddr);
1180		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
1181		    (ni != NULL && ni->ni_associd == 0)) {
1182			/*
1183			 * Station is not associated; don't permit the
1184			 * data frame to be sent by returning NULL.  This
1185			 * is kinda a kludge but the least intrusive way
1186			 * to add this check into all drivers.
1187			 */
1188			ieee80211_unref_node(&ni);	/* NB: null's ni */
1189		}
1190	}
1191	IEEE80211_NODE_UNLOCK(nt);
1192
1193	if (ni == NULL) {
1194		if (ic->ic_opmode == IEEE80211_M_IBSS ||
1195		    ic->ic_opmode == IEEE80211_M_AHDEMO) {
1196			/*
1197			 * In adhoc mode cons up a node for the destination.
1198			 * Note that we need an additional reference for the
1199			 * caller to be consistent with _ieee80211_find_node.
1200			 */
1201			ni = ieee80211_fakeup_adhoc_node(nt, macaddr);
1202			if (ni != NULL)
1203				(void) ieee80211_ref_node(ni);
1204		} else {
1205			IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
1206				"[%s] no node, discard frame (%s)\n",
1207				ether_sprintf(macaddr), __func__);
1208			ic->ic_stats.is_tx_nonode++;
1209		}
1210	}
1211	return ni;
1212}
1213
1214/*
1215 * Like find but search based on the ssid too.
1216 */
1217struct ieee80211_node *
1218#ifdef IEEE80211_DEBUG_REFCNT
1219ieee80211_find_node_with_ssid_debug(struct ieee80211_node_table *nt,
1220	const uint8_t *macaddr, u_int ssidlen, const uint8_t *ssid,
1221	const char *func, int line)
1222#else
1223ieee80211_find_node_with_ssid(struct ieee80211_node_table *nt,
1224	const uint8_t *macaddr, u_int ssidlen, const uint8_t *ssid)
1225#endif
1226{
1227#define	MATCH_SSID(ni, ssid, ssidlen) \
1228	(ni->ni_esslen == ssidlen && memcmp(ni->ni_essid, ssid, ssidlen) == 0)
1229	static const uint8_t zeromac[IEEE80211_ADDR_LEN];
1230	struct ieee80211_node *ni;
1231	int hash;
1232
1233	IEEE80211_NODE_LOCK(nt);
1234	/*
1235	 * A mac address that is all zero means match only the ssid;
1236	 * otherwise we must match both.
1237	 */
1238	if (IEEE80211_ADDR_EQ(macaddr, zeromac)) {
1239		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1240			if (MATCH_SSID(ni, ssid, ssidlen))
1241				break;
1242		}
1243	} else {
1244		hash = IEEE80211_NODE_HASH(macaddr);
1245		LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1246			if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1247			    MATCH_SSID(ni, ssid, ssidlen))
1248				break;
1249		}
1250	}
1251	if (ni != NULL) {
1252		ieee80211_ref_node(ni);	/* mark referenced */
1253		IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1254		     REFCNT_LOC, ni, ether_sprintf(ni->ni_macaddr),
1255		     ieee80211_node_refcnt(ni));
1256	}
1257	IEEE80211_NODE_UNLOCK(nt);
1258	return ni;
1259#undef MATCH_SSID
1260}
1261
1262static void
1263_ieee80211_free_node(struct ieee80211_node *ni)
1264{
1265	struct ieee80211com *ic = ni->ni_ic;
1266	struct ieee80211_node_table *nt = ni->ni_table;
1267
1268	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1269		"%s %p<%s> in %s table\n", __func__, ni,
1270		ether_sprintf(ni->ni_macaddr),
1271		nt != NULL ? nt->nt_name : "<gone>");
1272
1273	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1274	if (nt != NULL) {
1275		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1276		LIST_REMOVE(ni, ni_hash);
1277	}
1278	ic->ic_node_free(ni);
1279}
1280
1281void
1282#ifdef IEEE80211_DEBUG_REFCNT
1283ieee80211_free_node_debug(struct ieee80211_node *ni, const char *func, int line)
1284#else
1285ieee80211_free_node(struct ieee80211_node *ni)
1286#endif
1287{
1288	struct ieee80211_node_table *nt = ni->ni_table;
1289
1290#ifdef IEEE80211_DEBUG_REFCNT
1291	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1292		"%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line, ni,
1293		 ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)-1);
1294#endif
1295	if (nt != NULL) {
1296		IEEE80211_NODE_LOCK(nt);
1297		if (ieee80211_node_dectestref(ni)) {
1298			/*
1299			 * Last reference, reclaim state.
1300			 */
1301			_ieee80211_free_node(ni);
1302		} else if (ieee80211_node_refcnt(ni) == 1 &&
1303		    nt->nt_keyixmap != NULL) {
1304			ieee80211_keyix keyix;
1305			/*
1306			 * Check for a last reference in the key mapping table.
1307			 */
1308			keyix = ni->ni_ucastkey.wk_rxkeyix;
1309			if (keyix < nt->nt_keyixmax &&
1310			    nt->nt_keyixmap[keyix] == ni) {
1311				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1312				    "%s: %p<%s> clear key map entry", __func__,
1313				    ni, ether_sprintf(ni->ni_macaddr));
1314				nt->nt_keyixmap[keyix] = NULL;
1315				ieee80211_node_decref(ni); /* XXX needed? */
1316				_ieee80211_free_node(ni);
1317			}
1318		}
1319		IEEE80211_NODE_UNLOCK(nt);
1320	} else {
1321		if (ieee80211_node_dectestref(ni))
1322			_ieee80211_free_node(ni);
1323	}
1324}
1325
1326/*
1327 * Reclaim a unicast key and clear any key cache state.
1328 */
1329int
1330ieee80211_node_delucastkey(struct ieee80211_node *ni)
1331{
1332	struct ieee80211com *ic = ni->ni_ic;
1333	struct ieee80211_node_table *nt = &ic->ic_sta;
1334	struct ieee80211_node *nikey;
1335	ieee80211_keyix keyix;
1336	int isowned, status;
1337
1338	/*
1339	 * NB: We must beware of LOR here; deleting the key
1340	 * can cause the crypto layer to block traffic updates
1341	 * which can generate a LOR against the node table lock;
1342	 * grab it here and stash the key index for our use below.
1343	 *
1344	 * Must also beware of recursion on the node table lock.
1345	 * When called from node_cleanup we may already have
1346	 * the node table lock held.  Unfortunately there's no
1347	 * way to separate out this path so we must do this
1348	 * conditionally.
1349	 */
1350	isowned = IEEE80211_NODE_IS_LOCKED(nt);
1351	if (!isowned)
1352		IEEE80211_NODE_LOCK(nt);
1353	keyix = ni->ni_ucastkey.wk_rxkeyix;
1354	status = ieee80211_crypto_delkey(ic, &ni->ni_ucastkey);
1355	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax) {
1356		nikey = nt->nt_keyixmap[keyix];
1357		nt->nt_keyixmap[keyix] = NULL;;
1358	} else
1359		nikey = NULL;
1360	if (!isowned)
1361		IEEE80211_NODE_UNLOCK(&ic->ic_sta);
1362
1363	if (nikey != NULL) {
1364		KASSERT(nikey == ni,
1365			("key map out of sync, ni %p nikey %p", ni, nikey));
1366		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1367			"%s: delete key map entry %p<%s> refcnt %d\n",
1368			__func__, ni, ether_sprintf(ni->ni_macaddr),
1369			ieee80211_node_refcnt(ni)-1);
1370		ieee80211_free_node(ni);
1371	}
1372	return status;
1373}
1374
1375/*
1376 * Reclaim a node.  If this is the last reference count then
1377 * do the normal free work.  Otherwise remove it from the node
1378 * table and mark it gone by clearing the back-reference.
1379 */
1380static void
1381node_reclaim(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1382{
1383	ieee80211_keyix keyix;
1384
1385	IEEE80211_NODE_LOCK_ASSERT(nt);
1386
1387	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1388		"%s: remove %p<%s> from %s table, refcnt %d\n",
1389		__func__, ni, ether_sprintf(ni->ni_macaddr),
1390		nt->nt_name, ieee80211_node_refcnt(ni)-1);
1391	/*
1392	 * Clear any entry in the unicast key mapping table.
1393	 * We need to do it here so rx lookups don't find it
1394	 * in the mapping table even if it's not in the hash
1395	 * table.  We cannot depend on the mapping table entry
1396	 * being cleared because the node may not be free'd.
1397	 */
1398	keyix = ni->ni_ucastkey.wk_rxkeyix;
1399	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax &&
1400	    nt->nt_keyixmap[keyix] == ni) {
1401		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1402			"%s: %p<%s> clear key map entry\n",
1403			__func__, ni, ether_sprintf(ni->ni_macaddr));
1404		nt->nt_keyixmap[keyix] = NULL;
1405		ieee80211_node_decref(ni);	/* NB: don't need free */
1406	}
1407	if (!ieee80211_node_dectestref(ni)) {
1408		/*
1409		 * Other references are present, just remove the
1410		 * node from the table so it cannot be found.  When
1411		 * the references are dropped storage will be
1412		 * reclaimed.
1413		 */
1414		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1415		LIST_REMOVE(ni, ni_hash);
1416		ni->ni_table = NULL;		/* clear reference */
1417	} else
1418		_ieee80211_free_node(ni);
1419}
1420
1421static void
1422ieee80211_free_allnodes_locked(struct ieee80211_node_table *nt)
1423{
1424	struct ieee80211com *ic = nt->nt_ic;
1425	struct ieee80211_node *ni;
1426
1427	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1428		"%s: free all nodes in %s table\n", __func__, nt->nt_name);
1429
1430	while ((ni = TAILQ_FIRST(&nt->nt_node)) != NULL) {
1431		if (ni->ni_associd != 0) {
1432			if (ic->ic_auth->ia_node_leave != NULL)
1433				ic->ic_auth->ia_node_leave(ic, ni);
1434			IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1435		}
1436		node_reclaim(nt, ni);
1437	}
1438}
1439
1440/*
1441 * Timeout inactive stations and do related housekeeping.
1442 * Note that we cannot hold the node lock while sending a
1443 * frame as this would lead to a LOR.  Instead we use a
1444 * generation number to mark nodes that we've scanned and
1445 * drop the lock and restart a scan if we have to time out
1446 * a node.  Since we are single-threaded by virtue of
1447 * controlling the inactivity timer we can be sure this will
1448 * process each node only once.
1449 */
1450static void
1451ieee80211_timeout_stations(struct ieee80211_node_table *nt)
1452{
1453	struct ieee80211com *ic = nt->nt_ic;
1454	struct ieee80211_node *ni;
1455	u_int gen;
1456	int isadhoc;
1457
1458	isadhoc = (ic->ic_opmode == IEEE80211_M_IBSS ||
1459		   ic->ic_opmode == IEEE80211_M_AHDEMO);
1460	IEEE80211_SCAN_LOCK(nt);
1461	gen = ++nt->nt_scangen;
1462restart:
1463	IEEE80211_NODE_LOCK(nt);
1464	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1465		if (ni->ni_scangen == gen)	/* previously handled */
1466			continue;
1467		ni->ni_scangen = gen;
1468		/*
1469		 * Ignore entries for which have yet to receive an
1470		 * authentication frame.  These are transient and
1471		 * will be reclaimed when the last reference to them
1472		 * goes away (when frame xmits complete).
1473		 */
1474		if ((ic->ic_opmode == IEEE80211_M_HOSTAP ||
1475		     ic->ic_opmode == IEEE80211_M_STA) &&
1476		    (ni->ni_flags & IEEE80211_NODE_AREF) == 0)
1477			continue;
1478		/*
1479		 * Free fragment if not needed anymore
1480		 * (last fragment older than 1s).
1481		 * XXX doesn't belong here
1482		 */
1483		if (ni->ni_rxfrag[0] != NULL &&
1484		    ticks > ni->ni_rxfragstamp + hz) {
1485			m_freem(ni->ni_rxfrag[0]);
1486			ni->ni_rxfrag[0] = NULL;
1487		}
1488		if (ni->ni_inact > 0)
1489			ni->ni_inact--;
1490		/*
1491		 * Special case ourself; we may be idle for extended periods
1492		 * of time and regardless reclaiming our state is wrong.
1493		 */
1494		if (ni == ic->ic_bss)
1495			continue;
1496		if (ni->ni_associd != 0 || isadhoc) {
1497			/*
1498			 * Age frames on the power save queue.
1499			 */
1500			if (ieee80211_node_saveq_age(ni) != 0 &&
1501			    IEEE80211_NODE_SAVEQ_QLEN(ni) == 0 &&
1502			    ic->ic_set_tim != NULL)
1503				ic->ic_set_tim(ni, 0);
1504			/*
1505			 * Probe the station before time it out.  We
1506			 * send a null data frame which may not be
1507			 * universally supported by drivers (need it
1508			 * for ps-poll support so it should be...).
1509			 *
1510			 * XXX don't probe the station unless we've
1511			 *     received a frame from them (and have
1512			 *     some idea of the rates they are capable
1513			 *     of); this will get fixed more properly
1514			 *     soon with better handling of the rate set.
1515			 */
1516			if ((ic->ic_flags_ext & IEEE80211_FEXT_INACT) &&
1517			    (0 < ni->ni_inact &&
1518			     ni->ni_inact <= ic->ic_inact_probe) &&
1519			    ni->ni_rates.rs_nrates != 0) {
1520				IEEE80211_NOTE(ic,
1521				    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE,
1522				    ni, "%s",
1523				    "probe station due to inactivity");
1524				/*
1525				 * Grab a reference before unlocking the table
1526				 * so the node cannot be reclaimed before we
1527				 * send the frame. ieee80211_send_nulldata
1528				 * understands we've done this and reclaims the
1529				 * ref for us as needed.
1530				 */
1531				ieee80211_ref_node(ni);
1532				IEEE80211_NODE_UNLOCK(nt);
1533				ieee80211_send_nulldata(ni);
1534				/* XXX stat? */
1535				goto restart;
1536			}
1537		}
1538		if ((ic->ic_flags_ext & IEEE80211_FEXT_INACT) &&
1539		    ni->ni_inact <= 0) {
1540			IEEE80211_NOTE(ic,
1541			    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE, ni,
1542			    "station timed out due to inactivity "
1543			    "(refcnt %u)", ieee80211_node_refcnt(ni));
1544			/*
1545			 * Send a deauthenticate frame and drop the station.
1546			 * This is somewhat complicated due to reference counts
1547			 * and locking.  At this point a station will typically
1548			 * have a reference count of 1.  ieee80211_node_leave
1549			 * will do a "free" of the node which will drop the
1550			 * reference count.  But in the meantime a reference
1551			 * wil be held by the deauth frame.  The actual reclaim
1552			 * of the node will happen either after the tx is
1553			 * completed or by ieee80211_node_leave.
1554			 *
1555			 * Separately we must drop the node lock before sending
1556			 * in case the driver takes a lock, as this can result
1557			 * in a LOR between the node lock and the driver lock.
1558			 */
1559			ieee80211_ref_node(ni);
1560			IEEE80211_NODE_UNLOCK(nt);
1561			if (ni->ni_associd != 0) {
1562				IEEE80211_SEND_MGMT(ic, ni,
1563				    IEEE80211_FC0_SUBTYPE_DEAUTH,
1564				    IEEE80211_REASON_AUTH_EXPIRE);
1565			}
1566			ieee80211_node_leave(ic, ni);
1567			ieee80211_free_node(ni);
1568			ic->ic_stats.is_node_timeout++;
1569			goto restart;
1570		}
1571	}
1572	IEEE80211_NODE_UNLOCK(nt);
1573
1574	IEEE80211_SCAN_UNLOCK(nt);
1575}
1576
1577void
1578ieee80211_node_timeout(void *arg)
1579{
1580	struct ieee80211com *ic = arg;
1581
1582	ieee80211_scan_timeout(ic);
1583	ieee80211_timeout_stations(&ic->ic_sta);
1584
1585	IEEE80211_LOCK(ic);
1586	ieee80211_erp_timeout(ic);
1587	ieee80211_ht_timeout(ic);
1588	IEEE80211_UNLOCK(ic);
1589
1590	callout_reset(&ic->ic_inact, IEEE80211_INACT_WAIT*hz,
1591		ieee80211_node_timeout, ic);
1592}
1593
1594void
1595ieee80211_iterate_nodes(struct ieee80211_node_table *nt, ieee80211_iter_func *f, void *arg)
1596{
1597	struct ieee80211_node *ni;
1598	u_int gen;
1599
1600	IEEE80211_SCAN_LOCK(nt);
1601	gen = ++nt->nt_scangen;
1602restart:
1603	IEEE80211_NODE_LOCK(nt);
1604	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1605		if (ni->ni_scangen != gen) {
1606			ni->ni_scangen = gen;
1607			(void) ieee80211_ref_node(ni);
1608			IEEE80211_NODE_UNLOCK(nt);
1609			(*f)(arg, ni);
1610			ieee80211_free_node(ni);
1611			goto restart;
1612		}
1613	}
1614	IEEE80211_NODE_UNLOCK(nt);
1615
1616	IEEE80211_SCAN_UNLOCK(nt);
1617}
1618
1619void
1620ieee80211_dump_node(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1621{
1622	printf("0x%p: mac %s refcnt %d\n", ni,
1623		ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni));
1624	printf("\tscangen %u authmode %u flags 0x%x\n",
1625		ni->ni_scangen, ni->ni_authmode, ni->ni_flags);
1626	printf("\tassocid 0x%x txpower %u vlan %u\n",
1627		ni->ni_associd, ni->ni_txpower, ni->ni_vlan);
1628	printf("\ttxseq %u rxseq %u fragno %u rxfragstamp %u\n",
1629		ni->ni_txseqs[IEEE80211_NONQOS_TID],
1630		ni->ni_rxseqs[IEEE80211_NONQOS_TID] >> IEEE80211_SEQ_SEQ_SHIFT,
1631		ni->ni_rxseqs[IEEE80211_NONQOS_TID] & IEEE80211_SEQ_FRAG_MASK,
1632		ni->ni_rxfragstamp);
1633	printf("\trstamp %u rssi %d noise %d intval %u capinfo 0x%x\n",
1634		ni->ni_rstamp, ni->ni_rssi, ni->ni_noise,
1635		ni->ni_intval, ni->ni_capinfo);
1636	printf("\tbssid %s essid \"%.*s\" channel %u:0x%x\n",
1637		ether_sprintf(ni->ni_bssid),
1638		ni->ni_esslen, ni->ni_essid,
1639		ni->ni_chan->ic_freq, ni->ni_chan->ic_flags);
1640	printf("\tfails %u inact %u txrate %u\n",
1641		ni->ni_fails, ni->ni_inact, ni->ni_txrate);
1642	printf("\thtcap %x htparam %x htctlchan %u ht2ndchan %u\n",
1643		ni->ni_htcap, ni->ni_htparam,
1644		ni->ni_htctlchan, ni->ni_ht2ndchan);
1645	printf("\thtopmode %x htstbc %x chw %u\n",
1646		ni->ni_htopmode, ni->ni_htstbc, ni->ni_chw);
1647}
1648
1649void
1650ieee80211_dump_nodes(struct ieee80211_node_table *nt)
1651{
1652	ieee80211_iterate_nodes(nt,
1653		(ieee80211_iter_func *) ieee80211_dump_node, nt);
1654}
1655
1656void
1657ieee80211_notify_erp(struct ieee80211com *ic)
1658{
1659	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1660		ieee80211_beacon_notify(ic, IEEE80211_BEACON_ERP);
1661}
1662
1663/*
1664 * Handle a station joining an 11g network.
1665 */
1666static void
1667ieee80211_node_join_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
1668{
1669
1670	IEEE80211_LOCK_ASSERT(ic);
1671
1672	/*
1673	 * Station isn't capable of short slot time.  Bump
1674	 * the count of long slot time stations and disable
1675	 * use of short slot time.  Note that the actual switch
1676	 * over to long slot time use may not occur until the
1677	 * next beacon transmission (per sec. 7.3.1.4 of 11g).
1678	 */
1679	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
1680		ic->ic_longslotsta++;
1681		IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC, ni,
1682		    "station needs long slot time, count %d",
1683		    ic->ic_longslotsta);
1684		/* XXX vap's w/ conflicting needs won't work */
1685		if (!IEEE80211_IS_CHAN_108G(ic->ic_bsschan)) {
1686			/*
1687			 * Don't force slot time when switched to turbo
1688			 * mode as non-ERP stations won't be present; this
1689			 * need only be done when on the normal G channel.
1690			 */
1691			ieee80211_set_shortslottime(ic, 0);
1692		}
1693	}
1694	/*
1695	 * If the new station is not an ERP station
1696	 * then bump the counter and enable protection
1697	 * if configured.
1698	 */
1699	if (!ieee80211_iserp_rateset(ic, &ni->ni_rates)) {
1700		ic->ic_nonerpsta++;
1701		IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC, ni,
1702		    "station is !ERP, %d non-ERP stations associated",
1703		    ic->ic_nonerpsta);
1704		/*
1705		 * If station does not support short preamble
1706		 * then we must enable use of Barker preamble.
1707		 */
1708		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE) == 0) {
1709			IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC, ni,
1710			    "%s", "station needs long preamble");
1711			ic->ic_flags |= IEEE80211_F_USEBARKER;
1712			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
1713		}
1714		/*
1715		 * If protection is configured, enable it.
1716		 */
1717		if (ic->ic_protmode != IEEE80211_PROT_NONE &&
1718		    ic->ic_nonerpsta == 1 &&
1719		    (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) == 0) {
1720			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1721			    "%s: enable use of protection\n", __func__);
1722			ic->ic_flags |= IEEE80211_F_USEPROT;
1723			ieee80211_notify_erp(ic);
1724		}
1725	} else
1726		ni->ni_flags |= IEEE80211_NODE_ERP;
1727}
1728
1729void
1730ieee80211_node_join(struct ieee80211com *ic, struct ieee80211_node *ni, int resp)
1731{
1732	int newassoc;
1733
1734	if (ni->ni_associd == 0) {
1735		uint16_t aid;
1736
1737		IEEE80211_LOCK(ic);
1738		/*
1739		 * It would be good to search the bitmap
1740		 * more efficiently, but this will do for now.
1741		 */
1742		for (aid = 1; aid < ic->ic_max_aid; aid++) {
1743			if (!IEEE80211_AID_ISSET(aid,
1744			    ic->ic_aid_bitmap))
1745				break;
1746		}
1747		if (aid >= ic->ic_max_aid) {
1748			IEEE80211_UNLOCK(ic);
1749			IEEE80211_SEND_MGMT(ic, ni, resp,
1750			    IEEE80211_REASON_ASSOC_TOOMANY);
1751			ieee80211_node_leave(ic, ni);
1752			return;
1753		}
1754		ni->ni_associd = aid | 0xc000;
1755		ni->ni_jointime = time_uptime;
1756		IEEE80211_AID_SET(ni->ni_associd, ic->ic_aid_bitmap);
1757		ic->ic_sta_assoc++;
1758
1759		if (IEEE80211_IS_CHAN_HT(ic->ic_bsschan))
1760			ieee80211_ht_node_join(ni);
1761		if (IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan) &&
1762		    IEEE80211_IS_CHAN_FULL(ic->ic_bsschan))
1763			ieee80211_node_join_11g(ic, ni);
1764		IEEE80211_UNLOCK(ic);
1765
1766		newassoc = 1;
1767	} else
1768		newassoc = 0;
1769
1770	IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG, ni,
1771	    "station %sassociated at aid %d: %s preamble, %s slot time%s%s%s%s%s%s",
1772	    newassoc ? "" : "re",
1773	    IEEE80211_NODE_AID(ni),
1774	    ic->ic_flags & IEEE80211_F_SHPREAMBLE ? "short" : "long",
1775	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long",
1776	    ic->ic_flags & IEEE80211_F_USEPROT ? ", protection" : "",
1777	    ni->ni_flags & IEEE80211_NODE_QOS ? ", QoS" : "",
1778	    ni->ni_flags & IEEE80211_NODE_HT ?
1779		(ni->ni_chw == 20 ? ", HT20" : ", HT40") : "",
1780	    ni->ni_flags & IEEE80211_NODE_AMPDU ? " (+AMPDU)" : "",
1781	    IEEE80211_ATH_CAP(ic, ni, IEEE80211_NODE_FF) ?
1782		", fast-frames" : "",
1783	    IEEE80211_ATH_CAP(ic, ni, IEEE80211_NODE_TURBOP) ?
1784		", turbo" : ""
1785	);
1786
1787	/* give driver a chance to setup state like ni_txrate */
1788	if (ic->ic_newassoc != NULL)
1789		ic->ic_newassoc(ni, newassoc);
1790	IEEE80211_SEND_MGMT(ic, ni, resp, IEEE80211_STATUS_SUCCESS);
1791	/* tell the authenticator about new station */
1792	if (ic->ic_auth->ia_node_join != NULL)
1793		ic->ic_auth->ia_node_join(ic, ni);
1794	ieee80211_notify_node_join(ic, ni, newassoc);
1795}
1796
1797static void
1798disable_protection(struct ieee80211com *ic)
1799{
1800	KASSERT(ic->ic_nonerpsta == 0 &&
1801	    (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) == 0,
1802	   ("%d non ERP stations, flags 0x%x", ic->ic_nonerpsta,
1803	   ic->ic_flags_ext));
1804
1805	ic->ic_flags &= ~IEEE80211_F_USEPROT;
1806	/* XXX verify mode? */
1807	if (ic->ic_caps & IEEE80211_C_SHPREAMBLE) {
1808		ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
1809		ic->ic_flags &= ~IEEE80211_F_USEBARKER;
1810	}
1811	ieee80211_notify_erp(ic);
1812}
1813
1814/*
1815 * Handle a station leaving an 11g network.
1816 */
1817static void
1818ieee80211_node_leave_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
1819{
1820
1821	IEEE80211_LOCK_ASSERT(ic);
1822
1823	KASSERT(IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan),
1824	     ("not in 11g, bss %u:0x%x, curmode %u", ic->ic_bsschan->ic_freq,
1825	      ic->ic_bsschan->ic_flags, ic->ic_curmode));
1826
1827	/*
1828	 * If a long slot station do the slot time bookkeeping.
1829	 */
1830	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
1831		KASSERT(ic->ic_longslotsta > 0,
1832		    ("bogus long slot station count %d", ic->ic_longslotsta));
1833		ic->ic_longslotsta--;
1834		IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC, ni,
1835		    "long slot time station leaves, count now %d",
1836		    ic->ic_longslotsta);
1837		if (ic->ic_longslotsta == 0) {
1838			/*
1839			 * Re-enable use of short slot time if supported
1840			 * and not operating in IBSS mode (per spec).
1841			 */
1842			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
1843			    ic->ic_opmode != IEEE80211_M_IBSS) {
1844				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1845				    "%s: re-enable use of short slot time\n",
1846				    __func__);
1847				ieee80211_set_shortslottime(ic, 1);
1848			}
1849		}
1850	}
1851	/*
1852	 * If a non-ERP station do the protection-related bookkeeping.
1853	 */
1854	if ((ni->ni_flags & IEEE80211_NODE_ERP) == 0) {
1855		KASSERT(ic->ic_nonerpsta > 0,
1856		    ("bogus non-ERP station count %d", ic->ic_nonerpsta));
1857		ic->ic_nonerpsta--;
1858		IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC, ni,
1859		    "non-ERP station leaves, count now %d%s", ic->ic_nonerpsta,
1860		    (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) ?
1861			" (non-ERP sta present)" : "");
1862		if (ic->ic_nonerpsta == 0 &&
1863		    (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) == 0) {
1864			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1865				"%s: disable use of protection\n", __func__);
1866			disable_protection(ic);
1867		}
1868	}
1869}
1870
1871/*
1872 * Time out presence of an overlapping bss with non-ERP
1873 * stations.  When operating in hostap mode we listen for
1874 * beacons from other stations and if we identify a non-ERP
1875 * station is present we enable protection.  To identify
1876 * when all non-ERP stations are gone we time out this
1877 * condition.
1878 */
1879static void
1880ieee80211_erp_timeout(struct ieee80211com *ic)
1881{
1882
1883	IEEE80211_LOCK_ASSERT(ic);
1884
1885	if ((ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) &&
1886	    time_after(ticks, ic->ic_lastnonerp + IEEE80211_NONERP_PRESENT_AGE)) {
1887		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1888		    "%s\n", "age out non-ERP sta present on channel");
1889		ic->ic_flags_ext &= ~IEEE80211_FEXT_NONERP_PR;
1890		if (ic->ic_nonerpsta == 0)
1891			disable_protection(ic);
1892	}
1893}
1894
1895/*
1896 * Handle bookkeeping for station deauthentication/disassociation
1897 * when operating as an ap.
1898 */
1899void
1900ieee80211_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
1901{
1902	struct ieee80211_node_table *nt = ni->ni_table;
1903
1904	IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG, ni,
1905	    "station with aid %d leaves", IEEE80211_NODE_AID(ni));
1906
1907	KASSERT(ic->ic_opmode != IEEE80211_M_STA,
1908		("unexpected operating mode %u", ic->ic_opmode));
1909	/*
1910	 * If node wasn't previously associated all
1911	 * we need to do is reclaim the reference.
1912	 */
1913	/* XXX ibss mode bypasses 11g and notification */
1914	if (ni->ni_associd == 0)
1915		goto done;
1916	/*
1917	 * Tell the authenticator the station is leaving.
1918	 * Note that we must do this before yanking the
1919	 * association id as the authenticator uses the
1920	 * associd to locate it's state block.
1921	 */
1922	if (ic->ic_auth->ia_node_leave != NULL)
1923		ic->ic_auth->ia_node_leave(ic, ni);
1924
1925	IEEE80211_LOCK(ic);
1926	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1927	ni->ni_associd = 0;
1928	ic->ic_sta_assoc--;
1929
1930	if (IEEE80211_IS_CHAN_HT(ic->ic_bsschan))
1931		ieee80211_ht_node_leave(ni);
1932	if (IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan) &&
1933	    IEEE80211_IS_CHAN_FULL(ic->ic_bsschan))
1934		ieee80211_node_leave_11g(ic, ni);
1935	IEEE80211_UNLOCK(ic);
1936	/*
1937	 * Cleanup station state.  In particular clear various
1938	 * state that might otherwise be reused if the node
1939	 * is reused before the reference count goes to zero
1940	 * (and memory is reclaimed).
1941	 */
1942	ieee80211_sta_leave(ic, ni);
1943done:
1944	/*
1945	 * Remove the node from any table it's recorded in and
1946	 * drop the caller's reference.  Removal from the table
1947	 * is important to insure the node is not reprocessed
1948	 * for inactivity.
1949	 */
1950	if (nt != NULL) {
1951		IEEE80211_NODE_LOCK(nt);
1952		node_reclaim(nt, ni);
1953		IEEE80211_NODE_UNLOCK(nt);
1954	} else
1955		ieee80211_free_node(ni);
1956}
1957
1958int8_t
1959ieee80211_getrssi(struct ieee80211com *ic)
1960{
1961#define	NZ(x)	((x) == 0 ? 1 : (x))
1962	struct ieee80211_node_table *nt = &ic->ic_sta;
1963	int rssi_samples;
1964	int32_t rssi_total;
1965	struct ieee80211_node *ni;
1966
1967	rssi_total = 0;
1968	rssi_samples = 0;
1969	switch (ic->ic_opmode) {
1970	case IEEE80211_M_IBSS:		/* average of all ibss neighbors */
1971	case IEEE80211_M_AHDEMO:	/* average of all neighbors */
1972	case IEEE80211_M_HOSTAP:	/* average of all associated stations */
1973		/* XXX locking */
1974		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
1975			if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
1976			    (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS)) {
1977				int8_t rssi = ic->ic_node_getrssi(ni);
1978				if (rssi != 0) {
1979					rssi_samples++;
1980					rssi_total += rssi;
1981				}
1982			}
1983		break;
1984	case IEEE80211_M_MONITOR:	/* XXX */
1985	case IEEE80211_M_STA:		/* use stats from associated ap */
1986	default:
1987		if (ic->ic_bss != NULL)
1988			rssi_total = ic->ic_node_getrssi(ic->ic_bss);
1989		rssi_samples = 1;
1990		break;
1991	}
1992	return rssi_total / NZ(rssi_samples);
1993#undef NZ
1994}
1995
1996void
1997ieee80211_getsignal(struct ieee80211com *ic, int8_t *rssi, int8_t *noise)
1998{
1999
2000	if (ic->ic_bss == NULL)		/* NB: shouldn't happen */
2001		return;
2002	ic->ic_node_getsignal(ic->ic_bss, rssi, noise);
2003	/* for non-station mode return avg'd rssi accounting */
2004	if (ic->ic_opmode != IEEE80211_M_STA)
2005		*rssi = ieee80211_getrssi(ic);
2006}
2007
2008/*
2009 * Node table support.
2010 */
2011
2012static void
2013ieee80211_node_table_init(struct ieee80211com *ic,
2014	struct ieee80211_node_table *nt,
2015	const char *name, int inact, int keyixmax)
2016{
2017
2018	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
2019		"%s %s table, inact %u\n", __func__, name, inact);
2020
2021	nt->nt_ic = ic;
2022	/* XXX need unit */
2023	IEEE80211_NODE_LOCK_INIT(nt, ic->ic_ifp->if_xname);
2024	IEEE80211_SCAN_LOCK_INIT(nt, ic->ic_ifp->if_xname);
2025	TAILQ_INIT(&nt->nt_node);
2026	nt->nt_name = name;
2027	nt->nt_scangen = 1;
2028	nt->nt_inact_init = inact;
2029	nt->nt_keyixmax = keyixmax;
2030	if (nt->nt_keyixmax > 0) {
2031		MALLOC(nt->nt_keyixmap, struct ieee80211_node **,
2032			keyixmax * sizeof(struct ieee80211_node *),
2033			M_80211_NODE, M_NOWAIT | M_ZERO);
2034		if (nt->nt_keyixmap == NULL)
2035			if_printf(ic->ic_ifp,
2036			    "Cannot allocate key index map with %u entries\n",
2037			    keyixmax);
2038	} else
2039		nt->nt_keyixmap = NULL;
2040}
2041
2042static void
2043ieee80211_node_table_reset(struct ieee80211_node_table *nt)
2044{
2045
2046	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
2047		"%s %s table\n", __func__, nt->nt_name);
2048
2049	IEEE80211_NODE_LOCK(nt);
2050	ieee80211_free_allnodes_locked(nt);
2051	IEEE80211_NODE_UNLOCK(nt);
2052}
2053
2054static void
2055ieee80211_node_table_cleanup(struct ieee80211_node_table *nt)
2056{
2057
2058	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
2059		"%s %s table\n", __func__, nt->nt_name);
2060
2061	IEEE80211_NODE_LOCK(nt);
2062	ieee80211_free_allnodes_locked(nt);
2063	if (nt->nt_keyixmap != NULL) {
2064		/* XXX verify all entries are NULL */
2065		int i;
2066		for (i = 0; i < nt->nt_keyixmax; i++)
2067			if (nt->nt_keyixmap[i] != NULL)
2068				printf("%s: %s[%u] still active\n", __func__,
2069					nt->nt_name, i);
2070		FREE(nt->nt_keyixmap, M_80211_NODE);
2071		nt->nt_keyixmap = NULL;
2072	}
2073	IEEE80211_SCAN_LOCK_DESTROY(nt);
2074	IEEE80211_NODE_LOCK_DESTROY(nt);
2075}
2076