ieee80211_node.c revision 172228
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 172228 2007-09-18 20:55:51Z 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 * Join the specified IBSS/BSS network.  The node is assumed to
540 * be passed in with a held reference.
541 */
542static int
543ieee80211_sta_join1(struct ieee80211_node *selbs)
544{
545	struct ieee80211com *ic = selbs->ni_ic;
546	struct ieee80211_node *obss;
547	int canreassoc;
548
549	if (ic->ic_opmode == IEEE80211_M_IBSS) {
550		struct ieee80211_node_table *nt;
551		/*
552		 * Fillin the neighbor table; it will already
553		 * exist if we are simply switching mastership.
554		 * XXX ic_sta always setup so this is unnecessary?
555		 */
556		nt = &ic->ic_sta;
557		IEEE80211_NODE_LOCK(nt);
558		nt->nt_name = "neighbor";
559		nt->nt_inact_init = ic->ic_inact_run;
560		IEEE80211_NODE_UNLOCK(nt);
561	}
562
563	/*
564	 * Committed to selbs, setup state.
565	 */
566	obss = ic->ic_bss;
567	/*
568	 * Check if old+new node have the same address in which
569	 * case we can reassociate when operating in sta mode.
570	 */
571	canreassoc = (obss != NULL &&
572		ic->ic_state == IEEE80211_S_RUN &&
573		IEEE80211_ADDR_EQ(obss->ni_macaddr, selbs->ni_macaddr));
574	ic->ic_bss = selbs;		/* NB: caller assumed to bump refcnt */
575	if (obss != NULL) {
576		copy_bss(selbs, obss);
577		ieee80211_free_node(obss);
578	}
579
580	/*
581	 * Delete unusable rates; we've already checked
582	 * that the negotiated rate set is acceptable.
583	 */
584	ieee80211_fix_rate(ic->ic_bss, &ic->ic_bss->ni_rates,
585		IEEE80211_F_DODEL | IEEE80211_F_JOIN);
586
587	ic->ic_bsschan = selbs->ni_chan;
588	ic->ic_curchan = ic->ic_bsschan;
589	ic->ic_curmode = ieee80211_chan2mode(ic->ic_curchan);
590	ic->ic_set_channel(ic);
591	/*
592	 * Set the erp state (mostly the slot time) to deal with
593	 * the auto-select case; this should be redundant if the
594	 * mode is locked.
595	 */
596	ieee80211_reset_erp(ic);
597	ieee80211_wme_initparams(ic);
598
599	if (ic->ic_opmode == IEEE80211_M_STA) {
600		if (canreassoc) {
601			/* Reassociate */
602			ieee80211_new_state(ic, IEEE80211_S_ASSOC, 1);
603		} else {
604			/*
605			 * Act as if we received a DEAUTH frame in case we
606			 * are invoked from the RUN state.  This will cause
607			 * us to try to re-authenticate if we are operating
608			 * as a station.
609			 */
610			ieee80211_new_state(ic, IEEE80211_S_AUTH,
611				IEEE80211_FC0_SUBTYPE_DEAUTH);
612		}
613	} else
614		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
615	return 1;
616}
617
618int
619ieee80211_sta_join(struct ieee80211com *ic,
620	const struct ieee80211_scan_entry *se)
621{
622	struct ieee80211_node *ni;
623
624	ni = ieee80211_alloc_node(&ic->ic_sta, se->se_macaddr);
625	if (ni == NULL) {
626		/* XXX msg */
627		return 0;
628	}
629	/*
630	 * Expand scan state into node's format.
631	 * XXX may not need all this stuff
632	 */
633	IEEE80211_ADDR_COPY(ni->ni_bssid, se->se_bssid);
634	ni->ni_esslen = se->se_ssid[1];
635	memcpy(ni->ni_essid, se->se_ssid+2, ni->ni_esslen);
636	ni->ni_rstamp = se->se_rstamp;
637	ni->ni_tstamp.tsf = se->se_tstamp.tsf;
638	ni->ni_intval = se->se_intval;
639	ni->ni_capinfo = se->se_capinfo;
640	/* XXX shift to 11n channel if htinfo present */
641	ni->ni_chan = se->se_chan;
642	ni->ni_timoff = se->se_timoff;
643	ni->ni_fhdwell = se->se_fhdwell;
644	ni->ni_fhindex = se->se_fhindex;
645	ni->ni_erp = se->se_erp;
646	ni->ni_rssi = se->se_rssi;
647	ni->ni_noise = se->se_noise;
648	if (se->se_htcap_ie != NULL)
649		ieee80211_ht_node_init(ni, se->se_htcap_ie);
650	if (se->se_htinfo_ie != NULL)
651		ieee80211_parse_htinfo(ni, se->se_htinfo_ie);
652	if (se->se_wpa_ie != NULL)
653		ieee80211_saveie(&ni->ni_wpa_ie, se->se_wpa_ie);
654	if (se->se_rsn_ie != NULL)
655		ieee80211_saveie(&ni->ni_rsn_ie, se->se_rsn_ie);
656	if (se->se_wme_ie != NULL)
657		ieee80211_saveie(&ni->ni_wme_ie, se->se_wme_ie);
658	if (se->se_ath_ie != NULL)
659		ieee80211_saveath(ni, se->se_ath_ie);
660
661	ic->ic_dtim_period = se->se_dtimperiod;
662	ic->ic_dtim_count = 0;
663
664	/* NB: must be after ni_chan is setup */
665	ieee80211_setup_rates(ni, se->se_rates, se->se_xrates,
666		IEEE80211_F_DOSORT);
667	if (se->se_htcap_ie != NULL)
668		ieee80211_setup_htrates(ni, se->se_htcap_ie, IEEE80211_F_JOIN);
669	if (se->se_htinfo_ie != NULL)
670		ieee80211_setup_basic_htrates(ni, se->se_htinfo_ie);
671
672	return ieee80211_sta_join1(ieee80211_ref_node(ni));
673}
674
675/*
676 * Leave the specified IBSS/BSS network.  The node is assumed to
677 * be passed in with a held reference.
678 */
679void
680ieee80211_sta_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
681{
682	ic->ic_node_cleanup(ni);
683	ieee80211_notify_node_leave(ic, ni);
684}
685
686static struct ieee80211_node *
687node_alloc(struct ieee80211_node_table *nt)
688{
689	struct ieee80211_node *ni;
690
691	MALLOC(ni, struct ieee80211_node *, sizeof(struct ieee80211_node),
692		M_80211_NODE, M_NOWAIT | M_ZERO);
693	return ni;
694}
695
696/*
697 * Reclaim any resources in a node and reset any critical
698 * state.  Typically nodes are free'd immediately after,
699 * but in some cases the storage may be reused so we need
700 * to insure consistent state (should probably fix that).
701 */
702static void
703node_cleanup(struct ieee80211_node *ni)
704{
705#define	N(a)	(sizeof(a)/sizeof(a[0]))
706	struct ieee80211com *ic = ni->ni_ic;
707	int i;
708
709	/* NB: preserve ni_table */
710	if (ni->ni_flags & IEEE80211_NODE_PWR_MGT) {
711		if (ic->ic_opmode != IEEE80211_M_STA)
712			ic->ic_ps_sta--;
713		ni->ni_flags &= ~IEEE80211_NODE_PWR_MGT;
714		IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
715		    "[%s] power save mode off, %u sta's in ps mode\n",
716		    ether_sprintf(ni->ni_macaddr), ic->ic_ps_sta);
717	}
718	/*
719	 * Clear AREF flag that marks the authorization refcnt bump
720	 * has happened.  This is probably not needed as the node
721	 * should always be removed from the table so not found but
722	 * do it just in case.
723	 */
724	ni->ni_flags &= ~IEEE80211_NODE_AREF;
725
726	/*
727	 * Drain power save queue and, if needed, clear TIM.
728	 */
729	if (ieee80211_node_saveq_drain(ni) != 0 && ic->ic_set_tim != NULL)
730		ic->ic_set_tim(ni, 0);
731
732	ni->ni_associd = 0;
733	if (ni->ni_challenge != NULL) {
734		FREE(ni->ni_challenge, M_80211_NODE);
735		ni->ni_challenge = NULL;
736	}
737	/*
738	 * Preserve SSID, WPA, and WME ie's so the bss node is
739	 * reusable during a re-auth/re-assoc state transition.
740	 * If we remove these data they will not be recreated
741	 * because they come from a probe-response or beacon frame
742	 * which cannot be expected prior to the association-response.
743	 * This should not be an issue when operating in other modes
744	 * as stations leaving always go through a full state transition
745	 * which will rebuild this state.
746	 *
747	 * XXX does this leave us open to inheriting old state?
748	 */
749	for (i = 0; i < N(ni->ni_rxfrag); i++)
750		if (ni->ni_rxfrag[i] != NULL) {
751			m_freem(ni->ni_rxfrag[i]);
752			ni->ni_rxfrag[i] = NULL;
753		}
754	/*
755	 * Must be careful here to remove any key map entry w/o a LOR.
756	 */
757	ieee80211_node_delucastkey(ni);
758#undef N
759}
760
761static void
762node_free(struct ieee80211_node *ni)
763{
764	struct ieee80211com *ic = ni->ni_ic;
765
766	ic->ic_node_cleanup(ni);
767	if (ni->ni_wpa_ie != NULL)
768		FREE(ni->ni_wpa_ie, M_80211_NODE);
769	if (ni->ni_rsn_ie != NULL)
770		FREE(ni->ni_rsn_ie, M_80211_NODE);
771	if (ni->ni_wme_ie != NULL)
772		FREE(ni->ni_wme_ie, M_80211_NODE);
773	if (ni->ni_ath_ie != NULL)
774		FREE(ni->ni_ath_ie, M_80211_NODE);
775	IEEE80211_NODE_SAVEQ_DESTROY(ni);
776	FREE(ni, M_80211_NODE);
777}
778
779static int8_t
780node_getrssi(const struct ieee80211_node *ni)
781{
782	return ni->ni_rssi;
783}
784
785static void
786node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
787{
788	*rssi = ni->ni_rssi;
789	*noise = ni->ni_noise;
790}
791
792static void
793ieee80211_setup_node(struct ieee80211_node_table *nt,
794	struct ieee80211_node *ni, const uint8_t *macaddr)
795{
796	struct ieee80211com *ic = nt->nt_ic;
797	int hash;
798
799	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
800		"%s %p<%s> in %s table\n", __func__, ni,
801		ether_sprintf(macaddr), nt->nt_name);
802
803	IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
804	hash = IEEE80211_NODE_HASH(macaddr);
805	ieee80211_node_initref(ni);		/* mark referenced */
806	ni->ni_chan = IEEE80211_CHAN_ANYC;
807	ni->ni_authmode = IEEE80211_AUTH_OPEN;
808	ni->ni_txpower = ic->ic_txpowlimit;	/* max power */
809	ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey, IEEE80211_KEYIX_NONE);
810	ni->ni_inact_reload = nt->nt_inact_init;
811	ni->ni_inact = ni->ni_inact_reload;
812	ni->ni_ath_defkeyix = 0x7fff;
813	IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
814
815	IEEE80211_NODE_LOCK(nt);
816	TAILQ_INSERT_TAIL(&nt->nt_node, ni, ni_list);
817	LIST_INSERT_HEAD(&nt->nt_hash[hash], ni, ni_hash);
818	ni->ni_table = nt;
819	ni->ni_ic = ic;
820	IEEE80211_NODE_UNLOCK(nt);
821}
822
823struct ieee80211_node *
824ieee80211_alloc_node(struct ieee80211_node_table *nt, const uint8_t *macaddr)
825{
826	struct ieee80211com *ic = nt->nt_ic;
827	struct ieee80211_node *ni;
828
829	ni = ic->ic_node_alloc(nt);
830	if (ni != NULL)
831		ieee80211_setup_node(nt, ni, macaddr);
832	else
833		ic->ic_stats.is_rx_nodealloc++;
834	return ni;
835}
836
837/*
838 * Craft a temporary node suitable for sending a management frame
839 * to the specified station.  We craft only as much state as we
840 * need to do the work since the node will be immediately reclaimed
841 * once the send completes.
842 */
843struct ieee80211_node *
844ieee80211_tmp_node(struct ieee80211com *ic, const uint8_t *macaddr)
845{
846	struct ieee80211_node *ni;
847
848	ni = ic->ic_node_alloc(&ic->ic_sta);
849	if (ni != NULL) {
850		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
851			"%s %p<%s>\n", __func__, ni, ether_sprintf(macaddr));
852
853		IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
854		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
855		ieee80211_node_initref(ni);		/* mark referenced */
856		ni->ni_txpower = ic->ic_bss->ni_txpower;
857		/* NB: required by ieee80211_fix_rate */
858		ieee80211_node_set_chan(ic, ni);
859		ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey,
860			IEEE80211_KEYIX_NONE);
861		/* XXX optimize away */
862		IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
863
864		ni->ni_table = NULL;		/* NB: pedantic */
865		ni->ni_ic = ic;
866	} else {
867		/* XXX msg */
868		ic->ic_stats.is_rx_nodealloc++;
869	}
870	return ni;
871}
872
873struct ieee80211_node *
874ieee80211_dup_bss(struct ieee80211_node_table *nt, const uint8_t *macaddr)
875{
876	struct ieee80211com *ic = nt->nt_ic;
877	struct ieee80211_node *ni;
878
879	ni = ic->ic_node_alloc(nt);
880	if (ni != NULL) {
881		ieee80211_setup_node(nt, ni, macaddr);
882		/*
883		 * Inherit from ic_bss.
884		 */
885		ni->ni_authmode = ic->ic_bss->ni_authmode;
886		ni->ni_txpower = ic->ic_bss->ni_txpower;
887		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
888		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
889		ieee80211_node_set_chan(ic, ni);
890		ni->ni_rsn = ic->ic_bss->ni_rsn;
891	} else
892		ic->ic_stats.is_rx_nodealloc++;
893	return ni;
894}
895
896static struct ieee80211_node *
897#ifdef IEEE80211_DEBUG_REFCNT
898_ieee80211_find_node_debug(struct ieee80211_node_table *nt,
899	const uint8_t *macaddr, const char *func, int line)
900#else
901_ieee80211_find_node(struct ieee80211_node_table *nt,
902	const uint8_t *macaddr)
903#endif
904{
905	struct ieee80211_node *ni;
906	int hash;
907
908	IEEE80211_NODE_LOCK_ASSERT(nt);
909
910	hash = IEEE80211_NODE_HASH(macaddr);
911	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
912		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
913			ieee80211_ref_node(ni);	/* mark referenced */
914#ifdef IEEE80211_DEBUG_REFCNT
915			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
916			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
917			    func, line,
918			    ni, ether_sprintf(ni->ni_macaddr),
919			    ieee80211_node_refcnt(ni));
920#endif
921			return ni;
922		}
923	}
924	return NULL;
925}
926#ifdef IEEE80211_DEBUG_REFCNT
927#define	_ieee80211_find_node(nt, mac) \
928	_ieee80211_find_node_debug(nt, mac, func, line)
929#endif
930
931struct ieee80211_node *
932#ifdef IEEE80211_DEBUG_REFCNT
933ieee80211_find_node_debug(struct ieee80211_node_table *nt,
934	const uint8_t *macaddr, const char *func, int line)
935#else
936ieee80211_find_node(struct ieee80211_node_table *nt, const uint8_t *macaddr)
937#endif
938{
939	struct ieee80211_node *ni;
940
941	IEEE80211_NODE_LOCK(nt);
942	ni = _ieee80211_find_node(nt, macaddr);
943	IEEE80211_NODE_UNLOCK(nt);
944	return ni;
945}
946
947/*
948 * Fake up a node; this handles node discovery in adhoc mode.
949 * Note that for the driver's benefit we we treat this like
950 * an association so the driver has an opportunity to setup
951 * it's private state.
952 */
953struct ieee80211_node *
954ieee80211_fakeup_adhoc_node(struct ieee80211_node_table *nt,
955	const uint8_t macaddr[IEEE80211_ADDR_LEN])
956{
957	struct ieee80211com *ic = nt->nt_ic;
958	struct ieee80211_node *ni;
959
960	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
961	    "%s: mac<%s>\n", __func__, ether_sprintf(macaddr));
962	ni = ieee80211_dup_bss(nt, macaddr);
963	if (ni != NULL) {
964		/* XXX no rate negotiation; just dup */
965		ni->ni_rates = ic->ic_bss->ni_rates;
966		if (ic->ic_newassoc != NULL)
967			ic->ic_newassoc(ni, 1);
968		if (ic->ic_opmode == IEEE80211_M_AHDEMO) {
969			/*
970			 * In adhoc demo mode there are no management
971			 * frames to use to discover neighbor capabilities,
972			 * so blindly propagate the local configuration
973			 * so we can do interesting things (e.g. use
974			 * WME to disable ACK's).
975			 */
976			if (ic->ic_flags & IEEE80211_F_WME)
977				ni->ni_flags |= IEEE80211_NODE_QOS;
978			if (ic->ic_flags & IEEE80211_F_FF)
979				ni->ni_flags |= IEEE80211_NODE_FF;
980		}
981		/* XXX not right for 802.1x/WPA */
982		ieee80211_node_authorize(ni);
983	}
984	return ni;
985}
986
987void
988ieee80211_init_neighbor(struct ieee80211_node *ni,
989	const struct ieee80211_frame *wh,
990	const struct ieee80211_scanparams *sp)
991{
992	ni->ni_esslen = sp->ssid[1];
993	memcpy(ni->ni_essid, sp->ssid + 2, sp->ssid[1]);
994	IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
995	memcpy(ni->ni_tstamp.data, sp->tstamp, sizeof(ni->ni_tstamp));
996	ni->ni_intval = sp->bintval;
997	ni->ni_capinfo = sp->capinfo;
998	ni->ni_chan = ni->ni_ic->ic_curchan;
999	ni->ni_fhdwell = sp->fhdwell;
1000	ni->ni_fhindex = sp->fhindex;
1001	ni->ni_erp = sp->erp;
1002	ni->ni_timoff = sp->timoff;
1003	if (sp->wme != NULL)
1004		ieee80211_saveie(&ni->ni_wme_ie, sp->wme);
1005	if (sp->wpa != NULL)
1006		ieee80211_saveie(&ni->ni_wpa_ie, sp->wpa);
1007	if (sp->rsn != NULL)
1008		ieee80211_saveie(&ni->ni_rsn_ie, sp->rsn);
1009	if (sp->ath != NULL)
1010		ieee80211_saveath(ni, sp->ath);
1011
1012	/* NB: must be after ni_chan is setup */
1013	ieee80211_setup_rates(ni, sp->rates, sp->xrates,
1014		IEEE80211_F_DOSORT | IEEE80211_F_DOFRATE |
1015		IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
1016}
1017
1018/*
1019 * Do node discovery in adhoc mode on receipt of a beacon
1020 * or probe response frame.  Note that for the driver's
1021 * benefit we we treat this like an association so the
1022 * driver has an opportunity to setup it's private state.
1023 */
1024struct ieee80211_node *
1025ieee80211_add_neighbor(struct ieee80211com *ic,
1026	const struct ieee80211_frame *wh,
1027	const struct ieee80211_scanparams *sp)
1028{
1029	struct ieee80211_node *ni;
1030
1031	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1032	    "%s: mac<%s>\n", __func__, ether_sprintf(wh->i_addr2));
1033	ni = ieee80211_dup_bss(&ic->ic_sta, wh->i_addr2);/* XXX alloc_node? */
1034	if (ni != NULL) {
1035		ieee80211_init_neighbor(ni, wh, sp);
1036		if (ic->ic_newassoc != NULL)
1037			ic->ic_newassoc(ni, 1);
1038		/* XXX not right for 802.1x/WPA */
1039		ieee80211_node_authorize(ni);
1040	}
1041	return ni;
1042}
1043
1044#define	IS_CTL(wh) \
1045	((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_CTL)
1046#define	IS_PSPOLL(wh) \
1047	((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_PS_POLL)
1048#define	IS_BAR(wh) \
1049	((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_BAR)
1050
1051/*
1052 * Locate the node for sender, track state, and then pass the
1053 * (referenced) node up to the 802.11 layer for its use.  We
1054 * are required to pass some node so we fall back to ic_bss
1055 * when this frame is from an unknown sender.  The 802.11 layer
1056 * knows this means the sender wasn't in the node table and
1057 * acts accordingly.
1058 */
1059struct ieee80211_node *
1060#ifdef IEEE80211_DEBUG_REFCNT
1061ieee80211_find_rxnode_debug(struct ieee80211com *ic,
1062	const struct ieee80211_frame_min *wh, const char *func, int line)
1063#else
1064ieee80211_find_rxnode(struct ieee80211com *ic,
1065	const struct ieee80211_frame_min *wh)
1066#endif
1067{
1068	struct ieee80211_node_table *nt;
1069	struct ieee80211_node *ni;
1070
1071	/* XXX check ic_bss first in station mode */
1072	/* XXX 4-address frames? */
1073	nt = &ic->ic_sta;
1074	IEEE80211_NODE_LOCK(nt);
1075	if (IS_CTL(wh) && !IS_PSPOLL(wh) && !IS_BAR(wh) /*&& !IS_RTS(ah)*/)
1076		ni = _ieee80211_find_node(nt, wh->i_addr1);
1077	else
1078		ni = _ieee80211_find_node(nt, wh->i_addr2);
1079	if (ni == NULL)
1080		ni = ieee80211_ref_node(ic->ic_bss);
1081	IEEE80211_NODE_UNLOCK(nt);
1082
1083	return ni;
1084}
1085
1086/*
1087 * Like ieee80211_find_rxnode but use the supplied h/w
1088 * key index as a hint to locate the node in the key
1089 * mapping table.  If an entry is present at the key
1090 * index we return it; otherwise do a normal lookup and
1091 * update the mapping table if the station has a unicast
1092 * key assigned to it.
1093 */
1094struct ieee80211_node *
1095#ifdef IEEE80211_DEBUG_REFCNT
1096ieee80211_find_rxnode_withkey_debug(struct ieee80211com *ic,
1097	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix,
1098	const char *func, int line)
1099#else
1100ieee80211_find_rxnode_withkey(struct ieee80211com *ic,
1101	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix)
1102#endif
1103{
1104	struct ieee80211_node_table *nt;
1105	struct ieee80211_node *ni;
1106
1107	nt = &ic->ic_sta;
1108	IEEE80211_NODE_LOCK(nt);
1109	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax)
1110		ni = nt->nt_keyixmap[keyix];
1111	else
1112		ni = NULL;
1113	if (ni == NULL) {
1114		if (IS_CTL(wh) && !IS_PSPOLL(wh) && !IS_BAR(wh) /*&& !IS_RTS(ah)*/)
1115			ni = _ieee80211_find_node(nt, wh->i_addr1);
1116		else
1117			ni = _ieee80211_find_node(nt, wh->i_addr2);
1118		if (ni == NULL)
1119			ni = ieee80211_ref_node(ic->ic_bss);
1120		if (nt->nt_keyixmap != NULL) {
1121			/*
1122			 * If the station has a unicast key cache slot
1123			 * assigned update the key->node mapping table.
1124			 */
1125			keyix = ni->ni_ucastkey.wk_rxkeyix;
1126			/* XXX can keyixmap[keyix] != NULL? */
1127			if (keyix < nt->nt_keyixmax &&
1128			    nt->nt_keyixmap[keyix] == NULL) {
1129				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1130				    "%s: add key map entry %p<%s> refcnt %d\n",
1131				    __func__, ni, ether_sprintf(ni->ni_macaddr),
1132				    ieee80211_node_refcnt(ni)+1);
1133				nt->nt_keyixmap[keyix] = ieee80211_ref_node(ni);
1134			}
1135		}
1136	} else
1137		ieee80211_ref_node(ni);
1138	IEEE80211_NODE_UNLOCK(nt);
1139
1140	return ni;
1141}
1142#undef IS_BAR
1143#undef IS_PSPOLL
1144#undef IS_CTL
1145
1146/*
1147 * Return a reference to the appropriate node for sending
1148 * a data frame.  This handles node discovery in adhoc networks.
1149 */
1150struct ieee80211_node *
1151#ifdef IEEE80211_DEBUG_REFCNT
1152ieee80211_find_txnode_debug(struct ieee80211com *ic, const uint8_t *macaddr,
1153	const char *func, int line)
1154#else
1155ieee80211_find_txnode(struct ieee80211com *ic, const uint8_t *macaddr)
1156#endif
1157{
1158	struct ieee80211_node_table *nt = &ic->ic_sta;
1159	struct ieee80211_node *ni;
1160
1161	/*
1162	 * The destination address should be in the node table
1163	 * unless this is a multicast/broadcast frame.  We can
1164	 * also optimize station mode operation, all frames go
1165	 * to the bss node.
1166	 */
1167	/* XXX can't hold lock across dup_bss 'cuz of recursive locking */
1168	IEEE80211_NODE_LOCK(nt);
1169	if (ic->ic_opmode == IEEE80211_M_STA || IEEE80211_IS_MULTICAST(macaddr))
1170		ni = ieee80211_ref_node(ic->ic_bss);
1171	else {
1172		ni = _ieee80211_find_node(nt, macaddr);
1173		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
1174		    (ni != NULL && ni->ni_associd == 0)) {
1175			/*
1176			 * Station is not associated; don't permit the
1177			 * data frame to be sent by returning NULL.  This
1178			 * is kinda a kludge but the least intrusive way
1179			 * to add this check into all drivers.
1180			 */
1181			ieee80211_unref_node(&ni);	/* NB: null's ni */
1182		}
1183	}
1184	IEEE80211_NODE_UNLOCK(nt);
1185
1186	if (ni == NULL) {
1187		if (ic->ic_opmode == IEEE80211_M_IBSS ||
1188		    ic->ic_opmode == IEEE80211_M_AHDEMO) {
1189			/*
1190			 * In adhoc mode cons up a node for the destination.
1191			 * Note that we need an additional reference for the
1192			 * caller to be consistent with _ieee80211_find_node.
1193			 */
1194			ni = ieee80211_fakeup_adhoc_node(nt, macaddr);
1195			if (ni != NULL)
1196				(void) ieee80211_ref_node(ni);
1197		} else {
1198			IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
1199				"[%s] no node, discard frame (%s)\n",
1200				ether_sprintf(macaddr), __func__);
1201			ic->ic_stats.is_tx_nonode++;
1202		}
1203	}
1204	return ni;
1205}
1206
1207/*
1208 * Like find but search based on the ssid too.
1209 */
1210struct ieee80211_node *
1211#ifdef IEEE80211_DEBUG_REFCNT
1212ieee80211_find_node_with_ssid_debug(struct ieee80211_node_table *nt,
1213	const uint8_t *macaddr, u_int ssidlen, const uint8_t *ssid,
1214	const char *func, int line)
1215#else
1216ieee80211_find_node_with_ssid(struct ieee80211_node_table *nt,
1217	const uint8_t *macaddr, u_int ssidlen, const uint8_t *ssid)
1218#endif
1219{
1220#define	MATCH_SSID(ni, ssid, ssidlen) \
1221	(ni->ni_esslen == ssidlen && memcmp(ni->ni_essid, ssid, ssidlen) == 0)
1222	static const uint8_t zeromac[IEEE80211_ADDR_LEN];
1223	struct ieee80211_node *ni;
1224	int hash;
1225
1226	IEEE80211_NODE_LOCK(nt);
1227	/*
1228	 * A mac address that is all zero means match only the ssid;
1229	 * otherwise we must match both.
1230	 */
1231	if (IEEE80211_ADDR_EQ(macaddr, zeromac)) {
1232		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1233			if (MATCH_SSID(ni, ssid, ssidlen))
1234				break;
1235		}
1236	} else {
1237		hash = IEEE80211_NODE_HASH(macaddr);
1238		LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1239			if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1240			    MATCH_SSID(ni, ssid, ssidlen))
1241				break;
1242		}
1243	}
1244	if (ni != NULL) {
1245		ieee80211_ref_node(ni);	/* mark referenced */
1246		IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1247		     REFCNT_LOC, ni, ether_sprintf(ni->ni_macaddr),
1248		     ieee80211_node_refcnt(ni));
1249	}
1250	IEEE80211_NODE_UNLOCK(nt);
1251	return ni;
1252#undef MATCH_SSID
1253}
1254
1255static void
1256_ieee80211_free_node(struct ieee80211_node *ni)
1257{
1258	struct ieee80211com *ic = ni->ni_ic;
1259	struct ieee80211_node_table *nt = ni->ni_table;
1260
1261	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1262		"%s %p<%s> in %s table\n", __func__, ni,
1263		ether_sprintf(ni->ni_macaddr),
1264		nt != NULL ? nt->nt_name : "<gone>");
1265
1266	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1267	if (nt != NULL) {
1268		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1269		LIST_REMOVE(ni, ni_hash);
1270	}
1271	ic->ic_node_free(ni);
1272}
1273
1274void
1275#ifdef IEEE80211_DEBUG_REFCNT
1276ieee80211_free_node_debug(struct ieee80211_node *ni, const char *func, int line)
1277#else
1278ieee80211_free_node(struct ieee80211_node *ni)
1279#endif
1280{
1281	struct ieee80211_node_table *nt = ni->ni_table;
1282
1283#ifdef IEEE80211_DEBUG_REFCNT
1284	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1285		"%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line, ni,
1286		 ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)-1);
1287#endif
1288	if (nt != NULL) {
1289		IEEE80211_NODE_LOCK(nt);
1290		if (ieee80211_node_dectestref(ni)) {
1291			/*
1292			 * Last reference, reclaim state.
1293			 */
1294			_ieee80211_free_node(ni);
1295		} else if (ieee80211_node_refcnt(ni) == 1 &&
1296		    nt->nt_keyixmap != NULL) {
1297			ieee80211_keyix keyix;
1298			/*
1299			 * Check for a last reference in the key mapping table.
1300			 */
1301			keyix = ni->ni_ucastkey.wk_rxkeyix;
1302			if (keyix < nt->nt_keyixmax &&
1303			    nt->nt_keyixmap[keyix] == ni) {
1304				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1305				    "%s: %p<%s> clear key map entry", __func__,
1306				    ni, ether_sprintf(ni->ni_macaddr));
1307				nt->nt_keyixmap[keyix] = NULL;
1308				ieee80211_node_decref(ni); /* XXX needed? */
1309				_ieee80211_free_node(ni);
1310			}
1311		}
1312		IEEE80211_NODE_UNLOCK(nt);
1313	} else {
1314		if (ieee80211_node_dectestref(ni))
1315			_ieee80211_free_node(ni);
1316	}
1317}
1318
1319/*
1320 * Reclaim a unicast key and clear any key cache state.
1321 */
1322int
1323ieee80211_node_delucastkey(struct ieee80211_node *ni)
1324{
1325	struct ieee80211com *ic = ni->ni_ic;
1326	struct ieee80211_node_table *nt = &ic->ic_sta;
1327	struct ieee80211_node *nikey;
1328	ieee80211_keyix keyix;
1329	int isowned, status;
1330
1331	/*
1332	 * NB: We must beware of LOR here; deleting the key
1333	 * can cause the crypto layer to block traffic updates
1334	 * which can generate a LOR against the node table lock;
1335	 * grab it here and stash the key index for our use below.
1336	 *
1337	 * Must also beware of recursion on the node table lock.
1338	 * When called from node_cleanup we may already have
1339	 * the node table lock held.  Unfortunately there's no
1340	 * way to separate out this path so we must do this
1341	 * conditionally.
1342	 */
1343	isowned = IEEE80211_NODE_IS_LOCKED(nt);
1344	if (!isowned)
1345		IEEE80211_NODE_LOCK(nt);
1346	keyix = ni->ni_ucastkey.wk_rxkeyix;
1347	status = ieee80211_crypto_delkey(ic, &ni->ni_ucastkey);
1348	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax) {
1349		nikey = nt->nt_keyixmap[keyix];
1350		nt->nt_keyixmap[keyix] = NULL;;
1351	} else
1352		nikey = NULL;
1353	if (!isowned)
1354		IEEE80211_NODE_UNLOCK(&ic->ic_sta);
1355
1356	if (nikey != NULL) {
1357		KASSERT(nikey == ni,
1358			("key map out of sync, ni %p nikey %p", ni, nikey));
1359		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1360			"%s: delete key map entry %p<%s> refcnt %d\n",
1361			__func__, ni, ether_sprintf(ni->ni_macaddr),
1362			ieee80211_node_refcnt(ni)-1);
1363		ieee80211_free_node(ni);
1364	}
1365	return status;
1366}
1367
1368/*
1369 * Reclaim a node.  If this is the last reference count then
1370 * do the normal free work.  Otherwise remove it from the node
1371 * table and mark it gone by clearing the back-reference.
1372 */
1373static void
1374node_reclaim(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1375{
1376	ieee80211_keyix keyix;
1377
1378	IEEE80211_NODE_LOCK_ASSERT(nt);
1379
1380	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1381		"%s: remove %p<%s> from %s table, refcnt %d\n",
1382		__func__, ni, ether_sprintf(ni->ni_macaddr),
1383		nt->nt_name, ieee80211_node_refcnt(ni)-1);
1384	/*
1385	 * Clear any entry in the unicast key mapping table.
1386	 * We need to do it here so rx lookups don't find it
1387	 * in the mapping table even if it's not in the hash
1388	 * table.  We cannot depend on the mapping table entry
1389	 * being cleared because the node may not be free'd.
1390	 */
1391	keyix = ni->ni_ucastkey.wk_rxkeyix;
1392	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax &&
1393	    nt->nt_keyixmap[keyix] == ni) {
1394		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1395			"%s: %p<%s> clear key map entry\n",
1396			__func__, ni, ether_sprintf(ni->ni_macaddr));
1397		nt->nt_keyixmap[keyix] = NULL;
1398		ieee80211_node_decref(ni);	/* NB: don't need free */
1399	}
1400	if (!ieee80211_node_dectestref(ni)) {
1401		/*
1402		 * Other references are present, just remove the
1403		 * node from the table so it cannot be found.  When
1404		 * the references are dropped storage will be
1405		 * reclaimed.
1406		 */
1407		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1408		LIST_REMOVE(ni, ni_hash);
1409		ni->ni_table = NULL;		/* clear reference */
1410	} else
1411		_ieee80211_free_node(ni);
1412}
1413
1414static void
1415ieee80211_free_allnodes_locked(struct ieee80211_node_table *nt)
1416{
1417	struct ieee80211com *ic = nt->nt_ic;
1418	struct ieee80211_node *ni;
1419
1420	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1421		"%s: free all nodes in %s table\n", __func__, nt->nt_name);
1422
1423	while ((ni = TAILQ_FIRST(&nt->nt_node)) != NULL) {
1424		if (ni->ni_associd != 0) {
1425			if (ic->ic_auth->ia_node_leave != NULL)
1426				ic->ic_auth->ia_node_leave(ic, ni);
1427			IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1428		}
1429		node_reclaim(nt, ni);
1430	}
1431}
1432
1433/*
1434 * Timeout inactive stations and do related housekeeping.
1435 * Note that we cannot hold the node lock while sending a
1436 * frame as this would lead to a LOR.  Instead we use a
1437 * generation number to mark nodes that we've scanned and
1438 * drop the lock and restart a scan if we have to time out
1439 * a node.  Since we are single-threaded by virtue of
1440 * controlling the inactivity timer we can be sure this will
1441 * process each node only once.
1442 */
1443static void
1444ieee80211_timeout_stations(struct ieee80211_node_table *nt)
1445{
1446	struct ieee80211com *ic = nt->nt_ic;
1447	struct ieee80211_node *ni;
1448	u_int gen;
1449	int isadhoc;
1450
1451	isadhoc = (ic->ic_opmode == IEEE80211_M_IBSS ||
1452		   ic->ic_opmode == IEEE80211_M_AHDEMO);
1453	IEEE80211_SCAN_LOCK(nt);
1454	gen = ++nt->nt_scangen;
1455restart:
1456	IEEE80211_NODE_LOCK(nt);
1457	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1458		if (ni->ni_scangen == gen)	/* previously handled */
1459			continue;
1460		ni->ni_scangen = gen;
1461		/*
1462		 * Ignore entries for which have yet to receive an
1463		 * authentication frame.  These are transient and
1464		 * will be reclaimed when the last reference to them
1465		 * goes away (when frame xmits complete).
1466		 */
1467		if ((ic->ic_opmode == IEEE80211_M_HOSTAP ||
1468		     ic->ic_opmode == IEEE80211_M_STA) &&
1469		    (ni->ni_flags & IEEE80211_NODE_AREF) == 0)
1470			continue;
1471		/*
1472		 * Free fragment if not needed anymore
1473		 * (last fragment older than 1s).
1474		 * XXX doesn't belong here
1475		 */
1476		if (ni->ni_rxfrag[0] != NULL &&
1477		    ticks > ni->ni_rxfragstamp + hz) {
1478			m_freem(ni->ni_rxfrag[0]);
1479			ni->ni_rxfrag[0] = NULL;
1480		}
1481		if (ni->ni_inact > 0)
1482			ni->ni_inact--;
1483		/*
1484		 * Special case ourself; we may be idle for extended periods
1485		 * of time and regardless reclaiming our state is wrong.
1486		 */
1487		if (ni == ic->ic_bss)
1488			continue;
1489		if (ni->ni_associd != 0 || isadhoc) {
1490			/*
1491			 * Age frames on the power save queue.
1492			 */
1493			if (ieee80211_node_saveq_age(ni) != 0 &&
1494			    IEEE80211_NODE_SAVEQ_QLEN(ni) == 0 &&
1495			    ic->ic_set_tim != NULL)
1496				ic->ic_set_tim(ni, 0);
1497			/*
1498			 * Probe the station before time it out.  We
1499			 * send a null data frame which may not be
1500			 * universally supported by drivers (need it
1501			 * for ps-poll support so it should be...).
1502			 *
1503			 * XXX don't probe the station unless we've
1504			 *     received a frame from them (and have
1505			 *     some idea of the rates they are capable
1506			 *     of); this will get fixed more properly
1507			 *     soon with better handling of the rate set.
1508			 */
1509			if ((ic->ic_flags_ext & IEEE80211_FEXT_INACT) &&
1510			    (0 < ni->ni_inact &&
1511			     ni->ni_inact <= ic->ic_inact_probe) &&
1512			    ni->ni_rates.rs_nrates != 0) {
1513				IEEE80211_NOTE(ic,
1514				    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE,
1515				    ni, "%s",
1516				    "probe station due to inactivity");
1517				/*
1518				 * Grab a reference before unlocking the table
1519				 * so the node cannot be reclaimed before we
1520				 * send the frame. ieee80211_send_nulldata
1521				 * understands we've done this and reclaims the
1522				 * ref for us as needed.
1523				 */
1524				ieee80211_ref_node(ni);
1525				IEEE80211_NODE_UNLOCK(nt);
1526				ieee80211_send_nulldata(ni);
1527				/* XXX stat? */
1528				goto restart;
1529			}
1530		}
1531		if ((ic->ic_flags_ext & IEEE80211_FEXT_INACT) &&
1532		    ni->ni_inact <= 0) {
1533			IEEE80211_NOTE(ic,
1534			    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE, ni,
1535			    "station timed out due to inactivity "
1536			    "(refcnt %u)", ieee80211_node_refcnt(ni));
1537			/*
1538			 * Send a deauthenticate frame and drop the station.
1539			 * This is somewhat complicated due to reference counts
1540			 * and locking.  At this point a station will typically
1541			 * have a reference count of 1.  ieee80211_node_leave
1542			 * will do a "free" of the node which will drop the
1543			 * reference count.  But in the meantime a reference
1544			 * wil be held by the deauth frame.  The actual reclaim
1545			 * of the node will happen either after the tx is
1546			 * completed or by ieee80211_node_leave.
1547			 *
1548			 * Separately we must drop the node lock before sending
1549			 * in case the driver takes a lock, as this can result
1550			 * in a LOR between the node lock and the driver lock.
1551			 */
1552			IEEE80211_NODE_UNLOCK(nt);
1553			if (ni->ni_associd != 0) {
1554				IEEE80211_SEND_MGMT(ic, ni,
1555				    IEEE80211_FC0_SUBTYPE_DEAUTH,
1556				    IEEE80211_REASON_AUTH_EXPIRE);
1557			}
1558			ieee80211_node_leave(ic, ni);
1559			ic->ic_stats.is_node_timeout++;
1560			goto restart;
1561		}
1562	}
1563	IEEE80211_NODE_UNLOCK(nt);
1564
1565	IEEE80211_SCAN_UNLOCK(nt);
1566}
1567
1568void
1569ieee80211_node_timeout(void *arg)
1570{
1571	struct ieee80211com *ic = arg;
1572
1573	ieee80211_scan_timeout(ic);
1574	ieee80211_timeout_stations(&ic->ic_sta);
1575
1576	IEEE80211_LOCK(ic);
1577	ieee80211_erp_timeout(ic);
1578	IEEE80211_UNLOCK(ic);
1579
1580	callout_reset(&ic->ic_inact, IEEE80211_INACT_WAIT*hz,
1581		ieee80211_node_timeout, ic);
1582}
1583
1584void
1585ieee80211_iterate_nodes(struct ieee80211_node_table *nt, ieee80211_iter_func *f, void *arg)
1586{
1587	struct ieee80211_node *ni;
1588	u_int gen;
1589
1590	IEEE80211_SCAN_LOCK(nt);
1591	gen = ++nt->nt_scangen;
1592restart:
1593	IEEE80211_NODE_LOCK(nt);
1594	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1595		if (ni->ni_scangen != gen) {
1596			ni->ni_scangen = gen;
1597			(void) ieee80211_ref_node(ni);
1598			IEEE80211_NODE_UNLOCK(nt);
1599			(*f)(arg, ni);
1600			ieee80211_free_node(ni);
1601			goto restart;
1602		}
1603	}
1604	IEEE80211_NODE_UNLOCK(nt);
1605
1606	IEEE80211_SCAN_UNLOCK(nt);
1607}
1608
1609void
1610ieee80211_dump_node(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1611{
1612	printf("0x%p: mac %s refcnt %d\n", ni,
1613		ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni));
1614	printf("\tscangen %u authmode %u flags 0x%x\n",
1615		ni->ni_scangen, ni->ni_authmode, ni->ni_flags);
1616	printf("\tassocid 0x%x txpower %u vlan %u\n",
1617		ni->ni_associd, ni->ni_txpower, ni->ni_vlan);
1618	printf("\ttxseq %u rxseq %u fragno %u rxfragstamp %u\n",
1619		ni->ni_txseqs[IEEE80211_NONQOS_TID],
1620		ni->ni_rxseqs[IEEE80211_NONQOS_TID] >> IEEE80211_SEQ_SEQ_SHIFT,
1621		ni->ni_rxseqs[IEEE80211_NONQOS_TID] & IEEE80211_SEQ_FRAG_MASK,
1622		ni->ni_rxfragstamp);
1623	printf("\trstamp %u rssi %d noise %d intval %u capinfo 0x%x\n",
1624		ni->ni_rstamp, ni->ni_rssi, ni->ni_noise,
1625		ni->ni_intval, ni->ni_capinfo);
1626	printf("\tbssid %s essid \"%.*s\" channel %u:0x%x\n",
1627		ether_sprintf(ni->ni_bssid),
1628		ni->ni_esslen, ni->ni_essid,
1629		ni->ni_chan->ic_freq, ni->ni_chan->ic_flags);
1630	printf("\tfails %u inact %u txrate %u\n",
1631		ni->ni_fails, ni->ni_inact, ni->ni_txrate);
1632	printf("\thtcap %x htparam %x htctlchan %u ht2ndchan %u\n",
1633		ni->ni_htcap, ni->ni_htparam,
1634		ni->ni_htctlchan, ni->ni_ht2ndchan);
1635	printf("\thtopmode %x htstbc %x chw %u\n",
1636		ni->ni_htopmode, ni->ni_htstbc, ni->ni_chw);
1637}
1638
1639void
1640ieee80211_dump_nodes(struct ieee80211_node_table *nt)
1641{
1642	ieee80211_iterate_nodes(nt,
1643		(ieee80211_iter_func *) ieee80211_dump_node, nt);
1644}
1645
1646void
1647ieee80211_notify_erp(struct ieee80211com *ic)
1648{
1649	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1650		ieee80211_beacon_notify(ic, IEEE80211_BEACON_ERP);
1651}
1652
1653/*
1654 * Handle a station joining an 11g network.
1655 */
1656static void
1657ieee80211_node_join_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
1658{
1659
1660	/*
1661	 * Station isn't capable of short slot time.  Bump
1662	 * the count of long slot time stations and disable
1663	 * use of short slot time.  Note that the actual switch
1664	 * over to long slot time use may not occur until the
1665	 * next beacon transmission (per sec. 7.3.1.4 of 11g).
1666	 */
1667	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
1668		ic->ic_longslotsta++;
1669		IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC, ni,
1670		    "station needs long slot time, count %d",
1671		    ic->ic_longslotsta);
1672		/* XXX vap's w/ conflicting needs won't work */
1673		if (!IEEE80211_IS_CHAN_108G(ic->ic_bsschan)) {
1674			/*
1675			 * Don't force slot time when switched to turbo
1676			 * mode as non-ERP stations won't be present; this
1677			 * need only be done when on the normal G channel.
1678			 */
1679			ieee80211_set_shortslottime(ic, 0);
1680		}
1681	}
1682	/*
1683	 * If the new station is not an ERP station
1684	 * then bump the counter and enable protection
1685	 * if configured.
1686	 */
1687	if (!ieee80211_iserp_rateset(ic, &ni->ni_rates)) {
1688		ic->ic_nonerpsta++;
1689		IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC, ni,
1690		    "station is !ERP, %d non-ERP stations associated",
1691		    ic->ic_nonerpsta);
1692		/*
1693		 * If station does not support short preamble
1694		 * then we must enable use of Barker preamble.
1695		 */
1696		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE) == 0) {
1697			IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC, ni,
1698			    "%s", "station needs long preamble");
1699			ic->ic_flags |= IEEE80211_F_USEBARKER;
1700			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
1701		}
1702		/*
1703		 * If protection is configured, enable it.
1704		 */
1705		if (ic->ic_protmode != IEEE80211_PROT_NONE &&
1706		    ic->ic_nonerpsta == 1 &&
1707		    (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) == 0) {
1708			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1709			    "%s: enable use of protection\n", __func__);
1710			ic->ic_flags |= IEEE80211_F_USEPROT;
1711			ieee80211_notify_erp(ic);
1712		}
1713	} else
1714		ni->ni_flags |= IEEE80211_NODE_ERP;
1715}
1716
1717void
1718ieee80211_node_join(struct ieee80211com *ic, struct ieee80211_node *ni, int resp)
1719{
1720	int newassoc;
1721
1722	if (ni->ni_associd == 0) {
1723		uint16_t aid;
1724
1725		/*
1726		 * It would be good to search the bitmap
1727		 * more efficiently, but this will do for now.
1728		 */
1729		for (aid = 1; aid < ic->ic_max_aid; aid++) {
1730			if (!IEEE80211_AID_ISSET(aid,
1731			    ic->ic_aid_bitmap))
1732				break;
1733		}
1734		if (aid >= ic->ic_max_aid) {
1735			IEEE80211_SEND_MGMT(ic, ni, resp,
1736			    IEEE80211_REASON_ASSOC_TOOMANY);
1737			ieee80211_node_leave(ic, ni);
1738			return;
1739		}
1740		ni->ni_associd = aid | 0xc000;
1741		IEEE80211_AID_SET(ni->ni_associd, ic->ic_aid_bitmap);
1742		ic->ic_sta_assoc++;
1743		newassoc = 1;
1744		if (IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan) &&
1745		    IEEE80211_IS_CHAN_FULL(ic->ic_bsschan))
1746			ieee80211_node_join_11g(ic, ni);
1747	} else
1748		newassoc = 0;
1749
1750	IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG, ni,
1751	    "station %sassociated at aid %d: %s preamble, %s slot time%s%s%s%s%s",
1752	    newassoc ? "" : "re",
1753	    IEEE80211_NODE_AID(ni),
1754	    ic->ic_flags & IEEE80211_F_SHPREAMBLE ? "short" : "long",
1755	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long",
1756	    ic->ic_flags & IEEE80211_F_USEPROT ? ", protection" : "",
1757	    ni->ni_flags & IEEE80211_NODE_QOS ? ", QoS" : "",
1758	    ni->ni_flags & IEEE80211_NODE_HT ?
1759		(ni->ni_chw == 20 ? ", HT20" : ", HT40") : "",
1760	    IEEE80211_ATH_CAP(ic, ni, IEEE80211_NODE_FF) ?
1761		", fast-frames" : "",
1762	    IEEE80211_ATH_CAP(ic, ni, IEEE80211_NODE_TURBOP) ?
1763		", turbo" : ""
1764	);
1765
1766	/* give driver a chance to setup state like ni_txrate */
1767	if (ic->ic_newassoc != NULL)
1768		ic->ic_newassoc(ni, newassoc);
1769	IEEE80211_SEND_MGMT(ic, ni, resp, IEEE80211_STATUS_SUCCESS);
1770	/* tell the authenticator about new station */
1771	if (ic->ic_auth->ia_node_join != NULL)
1772		ic->ic_auth->ia_node_join(ic, ni);
1773	ieee80211_notify_node_join(ic, ni, newassoc);
1774}
1775
1776static void
1777disable_protection(struct ieee80211com *ic)
1778{
1779	KASSERT(ic->ic_nonerpsta == 0 &&
1780	    (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) == 0,
1781	   ("%d non ERP stations, flags 0x%x", ic->ic_nonerpsta,
1782	   ic->ic_flags_ext));
1783
1784	ic->ic_flags &= ~IEEE80211_F_USEPROT;
1785	/* XXX verify mode? */
1786	if (ic->ic_caps & IEEE80211_C_SHPREAMBLE) {
1787		ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
1788		ic->ic_flags &= ~IEEE80211_F_USEBARKER;
1789	}
1790	ieee80211_notify_erp(ic);
1791}
1792
1793/*
1794 * Handle a station leaving an 11g network.
1795 */
1796static void
1797ieee80211_node_leave_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
1798{
1799
1800	KASSERT(IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan),
1801	     ("not in 11g, bss %u:0x%x, curmode %u", ic->ic_bsschan->ic_freq,
1802	      ic->ic_bsschan->ic_flags, ic->ic_curmode));
1803
1804	/*
1805	 * If a long slot station do the slot time bookkeeping.
1806	 */
1807	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
1808		KASSERT(ic->ic_longslotsta > 0,
1809		    ("bogus long slot station count %d", ic->ic_longslotsta));
1810		ic->ic_longslotsta--;
1811		IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC, ni,
1812		    "long slot time station leaves, count now %d",
1813		    ic->ic_longslotsta);
1814		if (ic->ic_longslotsta == 0) {
1815			/*
1816			 * Re-enable use of short slot time if supported
1817			 * and not operating in IBSS mode (per spec).
1818			 */
1819			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
1820			    ic->ic_opmode != IEEE80211_M_IBSS) {
1821				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1822				    "%s: re-enable use of short slot time\n",
1823				    __func__);
1824				ieee80211_set_shortslottime(ic, 1);
1825			}
1826		}
1827	}
1828	/*
1829	 * If a non-ERP station do the protection-related bookkeeping.
1830	 */
1831	if ((ni->ni_flags & IEEE80211_NODE_ERP) == 0) {
1832		KASSERT(ic->ic_nonerpsta > 0,
1833		    ("bogus non-ERP station count %d", ic->ic_nonerpsta));
1834		ic->ic_nonerpsta--;
1835		IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC, ni,
1836		    "non-ERP station leaves, count now %d%s", ic->ic_nonerpsta,
1837		    (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) ?
1838			" (non-ERP sta present)" : "");
1839		if (ic->ic_nonerpsta == 0 &&
1840		    (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) == 0) {
1841			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1842				"%s: disable use of protection\n", __func__);
1843			disable_protection(ic);
1844		}
1845	}
1846}
1847
1848/*
1849 * Time out presence of an overlapping bss with non-ERP
1850 * stations.  When operating in hostap mode we listen for
1851 * beacons from other stations and if we identify a non-ERP
1852 * station is present we enable protection.  To identify
1853 * when all non-ERP stations are gone we time out this
1854 * condition.
1855 */
1856static void
1857ieee80211_erp_timeout(struct ieee80211com *ic)
1858{
1859
1860	IEEE80211_LOCK_ASSERT(ic);
1861
1862	if ((ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) &&
1863	    time_after(ticks, ic->ic_lastnonerp + IEEE80211_NONERP_PRESENT_AGE)) {
1864		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1865		    "%s\n", "age out non-ERP sta present on channel");
1866		ic->ic_flags_ext &= ~IEEE80211_FEXT_NONERP_PR;
1867		if (ic->ic_nonerpsta == 0)
1868			disable_protection(ic);
1869	}
1870}
1871
1872/*
1873 * Handle bookkeeping for station deauthentication/disassociation
1874 * when operating as an ap.
1875 */
1876void
1877ieee80211_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
1878{
1879	struct ieee80211_node_table *nt = ni->ni_table;
1880
1881	IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG, ni,
1882	    "station with aid %d leaves", IEEE80211_NODE_AID(ni));
1883
1884	KASSERT(ic->ic_opmode != IEEE80211_M_STA,
1885		("unexpected operating mode %u", ic->ic_opmode));
1886	/*
1887	 * If node wasn't previously associated all
1888	 * we need to do is reclaim the reference.
1889	 */
1890	/* XXX ibss mode bypasses 11g and notification */
1891	if (ni->ni_associd == 0)
1892		goto done;
1893	/*
1894	 * Tell the authenticator the station is leaving.
1895	 * Note that we must do this before yanking the
1896	 * association id as the authenticator uses the
1897	 * associd to locate it's state block.
1898	 */
1899	if (ic->ic_auth->ia_node_leave != NULL)
1900		ic->ic_auth->ia_node_leave(ic, ni);
1901	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1902	ni->ni_associd = 0;
1903	ic->ic_sta_assoc--;
1904
1905	if (IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan) &&
1906	    IEEE80211_IS_CHAN_FULL(ic->ic_bsschan))
1907		ieee80211_node_leave_11g(ic, ni);
1908	/*
1909	 * Cleanup station state.  In particular clear various
1910	 * state that might otherwise be reused if the node
1911	 * is reused before the reference count goes to zero
1912	 * (and memory is reclaimed).
1913	 */
1914	ieee80211_sta_leave(ic, ni);
1915done:
1916	/*
1917	 * Remove the node from any table it's recorded in and
1918	 * drop the caller's reference.  Removal from the table
1919	 * is important to insure the node is not reprocessed
1920	 * for inactivity.
1921	 */
1922	if (nt != NULL) {
1923		IEEE80211_NODE_LOCK(nt);
1924		node_reclaim(nt, ni);
1925		IEEE80211_NODE_UNLOCK(nt);
1926	} else
1927		ieee80211_free_node(ni);
1928}
1929
1930int8_t
1931ieee80211_getrssi(struct ieee80211com *ic)
1932{
1933#define	NZ(x)	((x) == 0 ? 1 : (x))
1934	struct ieee80211_node_table *nt = &ic->ic_sta;
1935	int rssi_samples;
1936	int32_t rssi_total;
1937	struct ieee80211_node *ni;
1938
1939	rssi_total = 0;
1940	rssi_samples = 0;
1941	switch (ic->ic_opmode) {
1942	case IEEE80211_M_IBSS:		/* average of all ibss neighbors */
1943	case IEEE80211_M_AHDEMO:	/* average of all neighbors */
1944	case IEEE80211_M_HOSTAP:	/* average of all associated stations */
1945		/* XXX locking */
1946		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
1947			if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
1948			    (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS)) {
1949				int8_t rssi = ic->ic_node_getrssi(ni);
1950				if (rssi != 0) {
1951					rssi_samples++;
1952					rssi_total += rssi;
1953				}
1954			}
1955		break;
1956	case IEEE80211_M_MONITOR:	/* XXX */
1957	case IEEE80211_M_STA:		/* use stats from associated ap */
1958	default:
1959		if (ic->ic_bss != NULL)
1960			rssi_total = ic->ic_node_getrssi(ic->ic_bss);
1961		rssi_samples = 1;
1962		break;
1963	}
1964	return rssi_total / NZ(rssi_samples);
1965#undef NZ
1966}
1967
1968void
1969ieee80211_getsignal(struct ieee80211com *ic, int8_t *rssi, int8_t *noise)
1970{
1971
1972	if (ic->ic_bss == NULL)		/* NB: shouldn't happen */
1973		return;
1974	ic->ic_node_getsignal(ic->ic_bss, rssi, noise);
1975	/* for non-station mode return avg'd rssi accounting */
1976	if (ic->ic_opmode != IEEE80211_M_STA)
1977		*rssi = ieee80211_getrssi(ic);
1978}
1979
1980/*
1981 * Node table support.
1982 */
1983
1984static void
1985ieee80211_node_table_init(struct ieee80211com *ic,
1986	struct ieee80211_node_table *nt,
1987	const char *name, int inact, int keyixmax)
1988{
1989
1990	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1991		"%s %s table, inact %u\n", __func__, name, inact);
1992
1993	nt->nt_ic = ic;
1994	/* XXX need unit */
1995	IEEE80211_NODE_LOCK_INIT(nt, ic->ic_ifp->if_xname);
1996	IEEE80211_SCAN_LOCK_INIT(nt, ic->ic_ifp->if_xname);
1997	TAILQ_INIT(&nt->nt_node);
1998	nt->nt_name = name;
1999	nt->nt_scangen = 1;
2000	nt->nt_inact_init = inact;
2001	nt->nt_keyixmax = keyixmax;
2002	if (nt->nt_keyixmax > 0) {
2003		MALLOC(nt->nt_keyixmap, struct ieee80211_node **,
2004			keyixmax * sizeof(struct ieee80211_node *),
2005			M_80211_NODE, M_NOWAIT | M_ZERO);
2006		if (nt->nt_keyixmap == NULL)
2007			if_printf(ic->ic_ifp,
2008			    "Cannot allocate key index map with %u entries\n",
2009			    keyixmax);
2010	} else
2011		nt->nt_keyixmap = NULL;
2012}
2013
2014static void
2015ieee80211_node_table_reset(struct ieee80211_node_table *nt)
2016{
2017
2018	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
2019		"%s %s table\n", __func__, nt->nt_name);
2020
2021	IEEE80211_NODE_LOCK(nt);
2022	ieee80211_free_allnodes_locked(nt);
2023	IEEE80211_NODE_UNLOCK(nt);
2024}
2025
2026static void
2027ieee80211_node_table_cleanup(struct ieee80211_node_table *nt)
2028{
2029
2030	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
2031		"%s %s table\n", __func__, nt->nt_name);
2032
2033	IEEE80211_NODE_LOCK(nt);
2034	ieee80211_free_allnodes_locked(nt);
2035	if (nt->nt_keyixmap != NULL) {
2036		/* XXX verify all entries are NULL */
2037		int i;
2038		for (i = 0; i < nt->nt_keyixmax; i++)
2039			if (nt->nt_keyixmap[i] != NULL)
2040				printf("%s: %s[%u] still active\n", __func__,
2041					nt->nt_name, i);
2042		FREE(nt->nt_keyixmap, M_80211_NODE);
2043		nt->nt_keyixmap = NULL;
2044	}
2045	IEEE80211_SCAN_LOCK_DESTROY(nt);
2046	IEEE80211_NODE_LOCK_DESTROY(nt);
2047}
2048