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