ieee80211_node.c revision 165569
1/*-
2 * Copyright (c) 2001 Atsushi Onoe
3 * Copyright (c) 2002-2005 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 * 3. The name of the author may not be used to endorse or promote products
15 *    derived from this software without specific prior written permission.
16 *
17 * Alternatively, this software may be distributed under the terms of the
18 * GNU General Public License ("GPL") version 2 as published by the Free
19 * Software Foundation.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
23 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 */
32
33#include <sys/cdefs.h>
34__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_node.c 165569 2006-12-27 18:46:18Z sam $");
35
36#include <sys/param.h>
37#include <sys/systm.h>
38#include <sys/mbuf.h>
39#include <sys/malloc.h>
40#include <sys/kernel.h>
41
42#include <sys/socket.h>
43
44#include <net/if.h>
45#include <net/if_media.h>
46#include <net/ethernet.h>
47
48#include <net80211/ieee80211_var.h>
49
50#include <net/bpf.h>
51
52/*
53 * Association id's are managed with a bit vector.
54 */
55#define	IEEE80211_AID_SET(b, w) \
56	((w)[IEEE80211_AID(b) / 32] |= (1 << (IEEE80211_AID(b) % 32)))
57#define	IEEE80211_AID_CLR(b, w) \
58	((w)[IEEE80211_AID(b) / 32] &= ~(1 << (IEEE80211_AID(b) % 32)))
59#define	IEEE80211_AID_ISSET(b, w) \
60	((w)[IEEE80211_AID(b) / 32] & (1 << (IEEE80211_AID(b) % 32)))
61
62#ifdef IEEE80211_DEBUG_REFCNT
63#define REFCNT_LOC "%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line
64#else
65#define REFCNT_LOC "%s %p<%s> refcnt %d\n", __func__
66#endif
67
68static struct ieee80211_node *node_alloc(struct ieee80211_node_table *);
69static void node_cleanup(struct ieee80211_node *);
70static void node_free(struct ieee80211_node *);
71static u_int8_t node_getrssi(const struct ieee80211_node *);
72
73static void ieee80211_setup_node(struct ieee80211_node_table *,
74		struct ieee80211_node *, const u_int8_t *);
75static void _ieee80211_free_node(struct ieee80211_node *);
76static void ieee80211_free_allnodes(struct ieee80211_node_table *);
77
78static void ieee80211_timeout_scan_candidates(struct ieee80211_node_table *);
79static void ieee80211_timeout_stations(struct ieee80211_node_table *);
80
81static void ieee80211_set_tim(struct ieee80211_node *, int set);
82
83static void ieee80211_node_table_init(struct ieee80211com *ic,
84	struct ieee80211_node_table *nt, const char *name,
85	int inact, int keyixmax,
86	void (*timeout)(struct ieee80211_node_table *));
87static void ieee80211_node_table_cleanup(struct ieee80211_node_table *nt);
88
89MALLOC_DEFINE(M_80211_NODE, "80211node", "802.11 node state");
90
91void
92ieee80211_node_attach(struct ieee80211com *ic)
93{
94
95	ic->ic_node_alloc = node_alloc;
96	ic->ic_node_free = node_free;
97	ic->ic_node_cleanup = node_cleanup;
98	ic->ic_node_getrssi = node_getrssi;
99
100	/* default station inactivity timer setings */
101	ic->ic_inact_init = IEEE80211_INACT_INIT;
102	ic->ic_inact_auth = IEEE80211_INACT_AUTH;
103	ic->ic_inact_run = IEEE80211_INACT_RUN;
104	ic->ic_inact_probe = IEEE80211_INACT_PROBE;
105
106	/* NB: driver should override */
107	ic->ic_max_aid = IEEE80211_AID_DEF;
108	ic->ic_set_tim = ieee80211_set_tim;
109}
110
111void
112ieee80211_node_lateattach(struct ieee80211com *ic)
113{
114	struct ieee80211_rsnparms *rsn;
115
116	if (ic->ic_max_aid > IEEE80211_AID_MAX)
117		ic->ic_max_aid = IEEE80211_AID_MAX;
118	MALLOC(ic->ic_aid_bitmap, u_int32_t *,
119		howmany(ic->ic_max_aid, 32) * sizeof(u_int32_t),
120		M_DEVBUF, M_NOWAIT | M_ZERO);
121	if (ic->ic_aid_bitmap == NULL) {
122		/* XXX no way to recover */
123		printf("%s: no memory for AID bitmap!\n", __func__);
124		ic->ic_max_aid = 0;
125	}
126
127	/* XXX defer until using hostap/ibss mode */
128	ic->ic_tim_len = howmany(ic->ic_max_aid, 8) * sizeof(u_int8_t);
129	MALLOC(ic->ic_tim_bitmap, u_int8_t *, ic->ic_tim_len,
130		M_DEVBUF, M_NOWAIT | M_ZERO);
131	if (ic->ic_tim_bitmap == NULL) {
132		/* XXX no way to recover */
133		printf("%s: no memory for TIM bitmap!\n", __func__);
134	}
135
136	ieee80211_node_table_init(ic, &ic->ic_sta, "station",
137		IEEE80211_INACT_INIT, ic->ic_crypto.cs_max_keyix,
138		ieee80211_timeout_stations);
139	ieee80211_node_table_init(ic, &ic->ic_scan, "scan",
140		IEEE80211_INACT_SCAN, 0,
141		ieee80211_timeout_scan_candidates);
142
143	ieee80211_reset_bss(ic);
144	/*
145	 * Setup "global settings" in the bss node so that
146	 * each new station automatically inherits them.
147	 */
148	rsn = &ic->ic_bss->ni_rsn;
149	/* WEP, TKIP, and AES-CCM are always supported */
150	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_WEP;
151	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_TKIP;
152	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_AES_CCM;
153	if (ic->ic_caps & IEEE80211_C_AES)
154		rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_AES_OCB;
155	if (ic->ic_caps & IEEE80211_C_CKIP)
156		rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_CKIP;
157	/*
158	 * Default unicast cipher to WEP for 802.1x use.  If
159	 * WPA is enabled the management code will set these
160	 * values to reflect.
161	 */
162	rsn->rsn_ucastcipher = IEEE80211_CIPHER_WEP;
163	rsn->rsn_ucastkeylen = 104 / NBBY;
164	/*
165	 * WPA says the multicast cipher is the lowest unicast
166	 * cipher supported.  But we skip WEP which would
167	 * otherwise be used based on this criteria.
168	 */
169	rsn->rsn_mcastcipher = IEEE80211_CIPHER_TKIP;
170	rsn->rsn_mcastkeylen = 128 / NBBY;
171
172	/*
173	 * We support both WPA-PSK and 802.1x; the one used
174	 * is determined by the authentication mode and the
175	 * setting of the PSK state.
176	 */
177	rsn->rsn_keymgmtset = WPA_ASE_8021X_UNSPEC | WPA_ASE_8021X_PSK;
178	rsn->rsn_keymgmt = WPA_ASE_8021X_PSK;
179
180	ic->ic_auth = ieee80211_authenticator_get(ic->ic_bss->ni_authmode);
181}
182
183void
184ieee80211_node_detach(struct ieee80211com *ic)
185{
186
187	if (ic->ic_bss != NULL) {
188		ieee80211_free_node(ic->ic_bss);
189		ic->ic_bss = NULL;
190	}
191	ieee80211_node_table_cleanup(&ic->ic_scan);
192	ieee80211_node_table_cleanup(&ic->ic_sta);
193	if (ic->ic_aid_bitmap != NULL) {
194		FREE(ic->ic_aid_bitmap, M_DEVBUF);
195		ic->ic_aid_bitmap = NULL;
196	}
197	if (ic->ic_tim_bitmap != NULL) {
198		FREE(ic->ic_tim_bitmap, M_DEVBUF);
199		ic->ic_tim_bitmap = NULL;
200	}
201}
202
203/*
204 * Port authorize/unauthorize interfaces for use by an authenticator.
205 */
206
207void
208ieee80211_node_authorize(struct ieee80211_node *ni)
209{
210	struct ieee80211com *ic = ni->ni_ic;
211
212	ni->ni_flags |= IEEE80211_NODE_AUTH;
213	ni->ni_inact_reload = ic->ic_inact_run;
214}
215
216void
217ieee80211_node_unauthorize(struct ieee80211_node *ni)
218{
219	ni->ni_flags &= ~IEEE80211_NODE_AUTH;
220}
221
222/*
223 * Set/change the channel.  The rate set is also updated as
224 * to insure a consistent view by drivers.
225 */
226static void
227ieee80211_set_chan(struct ieee80211com *ic,
228	struct ieee80211_node *ni, struct ieee80211_channel *chan)
229{
230	if (chan == IEEE80211_CHAN_ANYC)	/* XXX while scanning */
231		chan = ic->ic_curchan;
232	ni->ni_chan = chan;
233	ni->ni_rates = *ieee80211_get_suprates(ic, chan);
234}
235
236/*
237 * AP scanning support.
238 */
239
240#ifdef IEEE80211_DEBUG
241static void
242dump_chanlist(const u_char chans[])
243{
244	const char *sep;
245	int i;
246
247	sep = " ";
248	for (i = 0; i < IEEE80211_CHAN_MAX; i++)
249		if (isset(chans, i)) {
250			printf("%s%u", sep, i);
251			sep = ", ";
252		}
253}
254#endif /* IEEE80211_DEBUG */
255
256/*
257 * Initialize the channel set to scan based on the
258 * of available channels and the current PHY mode.
259 */
260static void
261ieee80211_reset_scan(struct ieee80211com *ic)
262{
263
264	/* XXX ic_des_chan should be handled with ic_chan_active */
265	if (ic->ic_des_chan != IEEE80211_CHAN_ANYC) {
266		memset(ic->ic_chan_scan, 0, sizeof(ic->ic_chan_scan));
267		setbit(ic->ic_chan_scan,
268			ieee80211_chan2ieee(ic, ic->ic_des_chan));
269	} else
270		memcpy(ic->ic_chan_scan, ic->ic_chan_active,
271			sizeof(ic->ic_chan_active));
272#ifdef IEEE80211_DEBUG
273	if (ieee80211_msg_scan(ic)) {
274		printf("%s: scan set:", __func__);
275		dump_chanlist(ic->ic_chan_scan);
276		printf(" start chan %u\n",
277			ieee80211_chan2ieee(ic, ic->ic_curchan));
278	}
279#endif /* IEEE80211_DEBUG */
280}
281
282/*
283 * Begin an active scan.
284 */
285void
286ieee80211_begin_scan(struct ieee80211com *ic, int reset)
287{
288
289	ic->ic_scan.nt_scangen++;
290	/*
291	 * In all but hostap mode scanning starts off in
292	 * an active mode before switching to passive.
293	 */
294	if (ic->ic_opmode != IEEE80211_M_HOSTAP) {
295		ic->ic_flags |= IEEE80211_F_ASCAN;
296		ic->ic_stats.is_scan_active++;
297	} else
298		ic->ic_stats.is_scan_passive++;
299	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
300		"begin %s scan in %s mode, scangen %u\n",
301		(ic->ic_flags & IEEE80211_F_ASCAN) ?  "active" : "passive",
302		ieee80211_phymode_name[ic->ic_curmode], ic->ic_scan.nt_scangen);
303	/*
304	 * Clear scan state and flush any previously seen AP's.
305	 */
306	ieee80211_reset_scan(ic);
307	if (reset)
308		ieee80211_free_allnodes(&ic->ic_scan);
309
310	ic->ic_flags |= IEEE80211_F_SCAN;
311
312	/* Scan the next channel. */
313	ieee80211_next_scan(ic);
314}
315
316/*
317 * Switch to the next channel marked for scanning.
318 */
319int
320ieee80211_next_scan(struct ieee80211com *ic)
321{
322	struct ieee80211_channel *chan;
323
324	/*
325	 * Insure any previous mgt frame timeouts don't fire.
326	 * This assumes the driver does the right thing in
327	 * flushing anything queued in the driver and below.
328	 */
329	ic->ic_mgt_timer = 0;
330	ic->ic_flags_ext &= ~IEEE80211_FEXT_PROBECHAN;
331
332	chan = ic->ic_curchan;
333	do {
334		if (++chan > &ic->ic_channels[IEEE80211_CHAN_MAX])
335			chan = &ic->ic_channels[0];
336		if (isset(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan))) {
337			clrbit(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan));
338			IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
339			    "%s: chan %d->%d\n", __func__,
340			    ieee80211_chan2ieee(ic, ic->ic_curchan),
341			    ieee80211_chan2ieee(ic, chan));
342			ic->ic_curchan = chan;
343			/*
344			 * XXX drivers should do this as needed,
345			 * XXX for now maintain compatibility
346			 */
347			ic->ic_bss->ni_rates = *ieee80211_get_suprates(ic, chan);
348			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
349			return 1;
350		}
351	} while (chan != ic->ic_curchan);
352	ieee80211_end_scan(ic);
353	return 0;
354}
355
356/*
357 * Probe the curent channel, if allowed, while scanning.
358 * If the channel is not marked passive-only then send
359 * a probe request immediately.  Otherwise mark state and
360 * listen for beacons on the channel; if we receive something
361 * then we'll transmit a probe request.
362 */
363void
364ieee80211_probe_curchan(struct ieee80211com *ic, int force)
365{
366	struct ifnet *ifp = ic->ic_ifp;
367
368	if ((ic->ic_curchan->ic_flags & IEEE80211_CHAN_PASSIVE) == 0 || force) {
369		/*
370		 * XXX send both broadcast+directed probe request
371		 */
372		ieee80211_send_probereq(ic->ic_bss,
373			ic->ic_myaddr, ifp->if_broadcastaddr,
374			ifp->if_broadcastaddr,
375			ic->ic_des_essid, ic->ic_des_esslen,
376			ic->ic_opt_ie, ic->ic_opt_ie_len);
377	} else
378		ic->ic_flags_ext |= IEEE80211_FEXT_PROBECHAN;
379}
380
381static __inline void
382copy_bss(struct ieee80211_node *nbss, const struct ieee80211_node *obss)
383{
384	/* propagate useful state */
385	nbss->ni_authmode = obss->ni_authmode;
386	nbss->ni_txpower = obss->ni_txpower;
387	nbss->ni_vlan = obss->ni_vlan;
388	nbss->ni_rsn = obss->ni_rsn;
389	/* XXX statistics? */
390}
391
392void
393ieee80211_create_ibss(struct ieee80211com* ic, struct ieee80211_channel *chan)
394{
395	struct ieee80211_node_table *nt;
396	struct ieee80211_node *ni;
397
398	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
399		"%s: creating ibss\n", __func__);
400
401	/*
402	 * Create the station/neighbor table.  Note that for adhoc
403	 * mode we make the initial inactivity timer longer since
404	 * we create nodes only through discovery and they typically
405	 * are long-lived associations.
406	 */
407	nt = &ic->ic_sta;
408	IEEE80211_NODE_LOCK(nt);
409	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
410		nt->nt_name = "station";
411		nt->nt_inact_init = ic->ic_inact_init;
412	} else {
413		nt->nt_name = "neighbor";
414		nt->nt_inact_init = ic->ic_inact_run;
415	}
416	IEEE80211_NODE_UNLOCK(nt);
417
418	ni = ieee80211_alloc_node(&ic->ic_sta, ic->ic_myaddr);
419	if (ni == NULL) {
420		/* XXX recovery? */
421		return;
422	}
423	IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_myaddr);
424	ni->ni_esslen = ic->ic_des_esslen;
425	memcpy(ni->ni_essid, ic->ic_des_essid, ni->ni_esslen);
426	copy_bss(ni, ic->ic_bss);
427	ni->ni_intval = ic->ic_bintval;
428	if (ic->ic_flags & IEEE80211_F_PRIVACY)
429		ni->ni_capinfo |= IEEE80211_CAPINFO_PRIVACY;
430	if (ic->ic_phytype == IEEE80211_T_FH) {
431		ni->ni_fhdwell = 200;	/* XXX */
432		ni->ni_fhindex = 1;
433	}
434	if (ic->ic_opmode == IEEE80211_M_IBSS) {
435		ic->ic_flags |= IEEE80211_F_SIBSS;
436		ni->ni_capinfo |= IEEE80211_CAPINFO_IBSS;	/* XXX */
437		if (ic->ic_flags & IEEE80211_F_DESBSSID)
438			IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_des_bssid);
439		else
440			ni->ni_bssid[0] |= 0x02;	/* local bit for IBSS */
441	} else if (ic->ic_opmode == IEEE80211_M_AHDEMO) {
442		if (ic->ic_flags & IEEE80211_F_DESBSSID)
443			IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_des_bssid);
444		else
445			memset(ni->ni_bssid, 0, IEEE80211_ADDR_LEN);
446	}
447	/*
448	 * Fix the channel and related attributes.
449	 */
450	ieee80211_set_chan(ic, ni, chan);
451	ic->ic_curchan = chan;
452	ic->ic_curmode = ieee80211_chan2mode(ic, chan);
453	/*
454	 * Do mode-specific rate setup.
455	 */
456	if (ic->ic_curmode == IEEE80211_MODE_11G) {
457		/*
458		 * Use a mixed 11b/11g rate set.
459		 */
460		ieee80211_set11gbasicrates(&ni->ni_rates, IEEE80211_MODE_11G);
461	} else if (ic->ic_curmode == IEEE80211_MODE_11B) {
462		/*
463		 * Force pure 11b rate set.
464		 */
465		ieee80211_set11gbasicrates(&ni->ni_rates, IEEE80211_MODE_11B);
466	}
467
468	(void) ieee80211_sta_join(ic, ieee80211_ref_node(ni));
469}
470
471void
472ieee80211_reset_bss(struct ieee80211com *ic)
473{
474	struct ieee80211_node *ni, *obss;
475
476	ieee80211_node_table_reset(&ic->ic_scan);
477	ieee80211_node_table_reset(&ic->ic_sta);
478
479	ni = ieee80211_alloc_node(&ic->ic_scan, ic->ic_myaddr);
480	KASSERT(ni != NULL, ("unable to setup inital BSS node"));
481	obss = ic->ic_bss;
482	ic->ic_bss = ieee80211_ref_node(ni);
483	if (obss != NULL) {
484		copy_bss(ni, obss);
485		ni->ni_intval = ic->ic_bintval;
486		ieee80211_free_node(obss);
487	}
488}
489
490/* XXX tunable */
491#define	STA_FAILS_MAX	2		/* assoc failures before ignored */
492
493static int
494ieee80211_match_bss(struct ieee80211com *ic, struct ieee80211_node *ni)
495{
496        u_int8_t rate;
497        int fail;
498
499	fail = 0;
500	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
501		fail |= 0x01;
502	if (ic->ic_des_chan != IEEE80211_CHAN_ANYC &&
503	    ni->ni_chan != ic->ic_des_chan)
504		fail |= 0x01;
505	if (ic->ic_opmode == IEEE80211_M_IBSS) {
506		if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
507			fail |= 0x02;
508	} else {
509		if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
510			fail |= 0x02;
511	}
512	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
513		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
514			fail |= 0x04;
515	} else {
516		/* XXX does this mean privacy is supported or required? */
517		if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
518			fail |= 0x04;
519	}
520	rate = ieee80211_fix_rate(ni, IEEE80211_F_DONEGO | IEEE80211_F_DOFRATE);
521	if (rate & IEEE80211_RATE_BASIC)
522		fail |= 0x08;
523	if (ic->ic_des_esslen != 0 &&
524	    (ni->ni_esslen != ic->ic_des_esslen ||
525	     memcmp(ni->ni_essid, ic->ic_des_essid, ic->ic_des_esslen) != 0))
526		fail |= 0x10;
527	if ((ic->ic_flags & IEEE80211_F_DESBSSID) &&
528	    !IEEE80211_ADDR_EQ(ic->ic_des_bssid, ni->ni_bssid))
529		fail |= 0x20;
530	if (ni->ni_fails >= STA_FAILS_MAX)
531		fail |= 0x40;
532#ifdef IEEE80211_DEBUG
533	if (ieee80211_msg_scan(ic)) {
534		printf(" %c %s",
535		    fail & 0x40 ? '=' : fail & 0x80 ? '^' : fail ? '-' : '+',
536		    ether_sprintf(ni->ni_macaddr));
537		printf(" %s%c", ether_sprintf(ni->ni_bssid),
538		    fail & 0x20 ? '!' : ' ');
539		printf(" %3d%c", ieee80211_chan2ieee(ic, ni->ni_chan),
540			fail & 0x01 ? '!' : ' ');
541		printf(" %+4d", ni->ni_rssi);
542		printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
543		    fail & 0x08 ? '!' : ' ');
544		printf(" %4s%c",
545		    (ni->ni_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
546		    (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
547		    "????",
548		    fail & 0x02 ? '!' : ' ');
549		printf(" %3s%c ",
550		    (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) ?
551		    "wep" : "no",
552		    fail & 0x04 ? '!' : ' ');
553		ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
554		printf("%s\n", fail & 0x10 ? "!" : "");
555	}
556#endif
557	return fail;
558}
559
560static __inline u_int8_t
561maxrate(const struct ieee80211_node *ni)
562{
563	const struct ieee80211_rateset *rs = &ni->ni_rates;
564	/* NB: assumes rate set is sorted (happens on frame receive) */
565	return rs->rs_rates[rs->rs_nrates-1] & IEEE80211_RATE_VAL;
566}
567
568/*
569 * Compare the capabilities of two nodes and decide which is
570 * more desirable (return >0 if a is considered better).  Note
571 * that we assume compatibility/usability has already been checked
572 * so we don't need to (e.g. validate whether privacy is supported).
573 * Used to select the best scan candidate for association in a BSS.
574 */
575static int
576ieee80211_node_compare(struct ieee80211com *ic,
577		       const struct ieee80211_node *a,
578		       const struct ieee80211_node *b)
579{
580	u_int8_t maxa, maxb;
581	u_int8_t rssia, rssib;
582	int weight;
583
584	/* privacy support preferred */
585	if ((a->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) &&
586	    (b->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
587		return 1;
588	if ((a->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0 &&
589	    (b->ni_capinfo & IEEE80211_CAPINFO_PRIVACY))
590		return -1;
591
592	/* compare count of previous failures */
593	weight = b->ni_fails - a->ni_fails;
594	if (abs(weight) > 1)
595		return weight;
596
597	rssia = ic->ic_node_getrssi(a);
598	rssib = ic->ic_node_getrssi(b);
599	if (abs(rssib - rssia) < 5) {
600		/* best/max rate preferred if signal level close enough XXX */
601		maxa = maxrate(a);
602		maxb = maxrate(b);
603		if (maxa != maxb)
604			return maxa - maxb;
605		/* XXX use freq for channel preference */
606		/* for now just prefer 5Ghz band to all other bands */
607		if (IEEE80211_IS_CHAN_5GHZ(a->ni_chan) &&
608		   !IEEE80211_IS_CHAN_5GHZ(b->ni_chan))
609			return 1;
610		if (!IEEE80211_IS_CHAN_5GHZ(a->ni_chan) &&
611		     IEEE80211_IS_CHAN_5GHZ(b->ni_chan))
612			return -1;
613	}
614	/* all things being equal, use signal level */
615	return rssia - rssib;
616}
617
618/*
619 * Mark an ongoing scan stopped.
620 */
621void
622ieee80211_cancel_scan(struct ieee80211com *ic)
623{
624
625	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN, "%s: end %s scan\n",
626		__func__,
627		(ic->ic_flags & IEEE80211_F_ASCAN) ?  "active" : "passive");
628
629	ic->ic_flags &= ~(IEEE80211_F_SCAN | IEEE80211_F_ASCAN);
630	ic->ic_flags_ext &= ~IEEE80211_FEXT_PROBECHAN;
631}
632
633/*
634 * Complete a scan of potential channels.
635 */
636void
637ieee80211_end_scan(struct ieee80211com *ic)
638{
639	struct ieee80211_node_table *nt = &ic->ic_scan;
640	struct ieee80211_node *ni, *selbs;
641
642	ieee80211_cancel_scan(ic);
643	ieee80211_notify_scan_done(ic);
644
645	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
646		u_int8_t maxrssi[IEEE80211_CHAN_MAX];	/* XXX off stack? */
647		int i, bestchan;
648		u_int8_t rssi;
649
650		/*
651		 * The passive scan to look for existing AP's completed,
652		 * select a channel to camp on.  Identify the channels
653		 * that already have one or more AP's and try to locate
654		 * an unoccupied one.  If that fails, pick a channel that
655		 * looks to be quietest.
656		 */
657		memset(maxrssi, 0, sizeof(maxrssi));
658		IEEE80211_NODE_LOCK(nt);
659		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
660			rssi = ic->ic_node_getrssi(ni);
661			i = ieee80211_chan2ieee(ic, ni->ni_chan);
662			if (rssi > maxrssi[i])
663				maxrssi[i] = rssi;
664		}
665		IEEE80211_NODE_UNLOCK(nt);
666		/* XXX select channel more intelligently */
667		bestchan = -1;
668		for (i = 0; i < IEEE80211_CHAN_MAX; i++)
669			if (isset(ic->ic_chan_active, i)) {
670				/*
671				 * If the channel is unoccupied the max rssi
672				 * should be zero; just take it.  Otherwise
673				 * track the channel with the lowest rssi and
674				 * use that when all channels appear occupied.
675				 */
676				if (maxrssi[i] == 0) {
677					bestchan = i;
678					break;
679				}
680				if (bestchan == -1 ||
681				    maxrssi[i] < maxrssi[bestchan])
682					bestchan = i;
683			}
684		if (bestchan != -1) {
685			ieee80211_create_ibss(ic, &ic->ic_channels[bestchan]);
686			return;
687		}
688		/* no suitable channel, should not happen */
689	}
690
691	/*
692	 * When manually sequencing the state machine; scan just once
693	 * regardless of whether we have a candidate or not.  The
694	 * controlling application is expected to setup state and
695	 * initiate an association.
696	 */
697	if (ic->ic_roaming == IEEE80211_ROAMING_MANUAL)
698		return;
699	/*
700	 * Automatic sequencing; look for a candidate and
701	 * if found join the network.
702	 */
703	/* NB: unlocked read should be ok */
704	if (TAILQ_FIRST(&nt->nt_node) == NULL) {
705		IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
706			"%s: no scan candidate\n", __func__);
707  notfound:
708		if (ic->ic_opmode == IEEE80211_M_IBSS &&
709		    (ic->ic_flags & IEEE80211_F_IBSSON) &&
710		    ic->ic_des_esslen != 0) {
711			ieee80211_create_ibss(ic, ic->ic_ibss_chan);
712			return;
713		}
714		/*
715		 * Decrement the failure counts so entries will be
716		 * reconsidered the next time around.  We really want
717		 * to do this only for sta's where we've previously
718		 * had some success.
719		 */
720		IEEE80211_NODE_LOCK(nt);
721		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
722			if (ni->ni_fails)
723				ni->ni_fails--;
724		IEEE80211_NODE_UNLOCK(nt);
725		/*
726		 * Reset the list of channels to scan and start again.
727		 */
728		ieee80211_reset_scan(ic);
729		ic->ic_flags |= IEEE80211_F_SCAN;
730		ieee80211_next_scan(ic);
731		return;
732	}
733	selbs = NULL;
734	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN, "\t%s\n",
735	    "macaddr          bssid         chan  rssi rate flag  wep  essid");
736	IEEE80211_NODE_LOCK(nt);
737	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
738		if (ieee80211_match_bss(ic, ni) == 0) {
739			if (selbs == NULL)
740				selbs = ni;
741			else if (ieee80211_node_compare(ic, ni, selbs) > 0)
742				selbs = ni;
743		}
744	}
745	if (selbs != NULL)		/* NB: grab ref while dropping lock */
746		(void) ieee80211_ref_node(selbs);
747	IEEE80211_NODE_UNLOCK(nt);
748	if (selbs == NULL)
749		goto notfound;
750	if (!ieee80211_sta_join(ic, selbs)) {
751		ieee80211_free_node(selbs);
752		goto notfound;
753	}
754}
755
756/*
757 * Handle 802.11 ad hoc network merge.  The
758 * convention, set by the Wireless Ethernet Compatibility Alliance
759 * (WECA), is that an 802.11 station will change its BSSID to match
760 * the "oldest" 802.11 ad hoc network, on the same channel, that
761 * has the station's desired SSID.  The "oldest" 802.11 network
762 * sends beacons with the greatest TSF timestamp.
763 *
764 * The caller is assumed to validate TSF's before attempting a merge.
765 *
766 * Return !0 if the BSSID changed, 0 otherwise.
767 */
768int
769ieee80211_ibss_merge(struct ieee80211_node *ni)
770{
771	struct ieee80211com *ic = ni->ni_ic;
772
773	if (ni == ic->ic_bss ||
774	    IEEE80211_ADDR_EQ(ni->ni_bssid, ic->ic_bss->ni_bssid)) {
775		/* unchanged, nothing to do */
776		return 0;
777	}
778	if (ieee80211_match_bss(ic, ni) != 0) {	/* capabilities mismatch */
779		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
780		    "%s: merge failed, capabilities mismatch\n", __func__);
781		ic->ic_stats.is_ibss_capmismatch++;
782		return 0;
783	}
784	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
785		"%s: new bssid %s: %s preamble, %s slot time%s\n", __func__,
786		ether_sprintf(ni->ni_bssid),
787		ic->ic_flags&IEEE80211_F_SHPREAMBLE ? "short" : "long",
788		ic->ic_flags&IEEE80211_F_SHSLOT ? "short" : "long",
789		ic->ic_flags&IEEE80211_F_USEPROT ? ", protection" : ""
790	);
791	return ieee80211_sta_join(ic, ieee80211_ref_node(ni));
792}
793
794/*
795 * Join the specified IBSS/BSS network.  The node is assumed to
796 * be passed in with a held reference.
797 */
798int
799ieee80211_sta_join(struct ieee80211com *ic, struct ieee80211_node *selbs)
800{
801	struct ieee80211_node *obss;
802
803	if (ic->ic_opmode == IEEE80211_M_IBSS) {
804		struct ieee80211_node_table *nt;
805		/*
806		 * Delete unusable rates; we've already checked
807		 * that the negotiated rate set is acceptable.
808		 */
809		ieee80211_fix_rate(selbs, IEEE80211_F_DODEL);
810		/*
811		 * Fillin the neighbor table; it will already
812		 * exist if we are simply switching mastership.
813		 * XXX ic_sta always setup so this is unnecessary?
814		 */
815		nt = &ic->ic_sta;
816		IEEE80211_NODE_LOCK(nt);
817		nt->nt_name = "neighbor";
818		nt->nt_inact_init = ic->ic_inact_run;
819		IEEE80211_NODE_UNLOCK(nt);
820	}
821
822	/*
823	 * Committed to selbs, setup state.
824	 */
825	obss = ic->ic_bss;
826	ic->ic_bss = selbs;		/* NB: caller assumed to bump refcnt */
827	if (obss != NULL) {
828		copy_bss(selbs, obss);
829		ieee80211_free_node(obss);
830	}
831	/*
832	 * Set the erp state (mostly the slot time) to deal with
833	 * the auto-select case; this should be redundant if the
834	 * mode is locked.
835	 */
836	ic->ic_curmode = ieee80211_chan2mode(ic, selbs->ni_chan);
837	ic->ic_curchan = selbs->ni_chan;
838	ieee80211_reset_erp(ic);
839	ieee80211_wme_initparams(ic);
840
841	if (ic->ic_opmode == IEEE80211_M_STA)
842		ieee80211_new_state(ic, IEEE80211_S_AUTH, -1);
843	else
844		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
845	return 1;
846}
847
848/*
849 * Leave the specified IBSS/BSS network.  The node is assumed to
850 * be passed in with a held reference.
851 */
852void
853ieee80211_sta_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
854{
855	ic->ic_node_cleanup(ni);
856	ieee80211_notify_node_leave(ic, ni);
857}
858
859static struct ieee80211_node *
860node_alloc(struct ieee80211_node_table *nt)
861{
862	struct ieee80211_node *ni;
863
864	MALLOC(ni, struct ieee80211_node *, sizeof(struct ieee80211_node),
865		M_80211_NODE, M_NOWAIT | M_ZERO);
866	return ni;
867}
868
869/*
870 * Reclaim any resources in a node and reset any critical
871 * state.  Typically nodes are free'd immediately after,
872 * but in some cases the storage may be reused so we need
873 * to insure consistent state (should probably fix that).
874 */
875static void
876node_cleanup(struct ieee80211_node *ni)
877{
878#define	N(a)	(sizeof(a)/sizeof(a[0]))
879	struct ieee80211com *ic = ni->ni_ic;
880	int i, qlen;
881
882	/* NB: preserve ni_table */
883	if (ni->ni_flags & IEEE80211_NODE_PWR_MGT) {
884		ic->ic_ps_sta--;
885		ni->ni_flags &= ~IEEE80211_NODE_PWR_MGT;
886		IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
887		    "[%s] power save mode off, %u sta's in ps mode\n",
888		    ether_sprintf(ni->ni_macaddr), ic->ic_ps_sta);
889	}
890	/*
891	 * Clear AREF flag that marks the authorization refcnt bump
892	 * has happened.  This is probably not needed as the node
893	 * should always be removed from the table so not found but
894	 * do it just in case.
895	 */
896	ni->ni_flags &= ~IEEE80211_NODE_AREF;
897
898	/*
899	 * Drain power save queue and, if needed, clear TIM.
900	 */
901	IEEE80211_NODE_SAVEQ_DRAIN(ni, qlen);
902	if (qlen != 0 && ic->ic_set_tim != NULL)
903		ic->ic_set_tim(ni, 0);
904
905	ni->ni_associd = 0;
906	if (ni->ni_challenge != NULL) {
907		FREE(ni->ni_challenge, M_DEVBUF);
908		ni->ni_challenge = NULL;
909	}
910	/*
911	 * Preserve SSID, WPA, and WME ie's so the bss node is
912	 * reusable during a re-auth/re-assoc state transition.
913	 * If we remove these data they will not be recreated
914	 * because they come from a probe-response or beacon frame
915	 * which cannot be expected prior to the association-response.
916	 * This should not be an issue when operating in other modes
917	 * as stations leaving always go through a full state transition
918	 * which will rebuild this state.
919	 *
920	 * XXX does this leave us open to inheriting old state?
921	 */
922	for (i = 0; i < N(ni->ni_rxfrag); i++)
923		if (ni->ni_rxfrag[i] != NULL) {
924			m_freem(ni->ni_rxfrag[i]);
925			ni->ni_rxfrag[i] = NULL;
926		}
927	/*
928	 * Must be careful here to remove any key map entry w/o a LOR.
929	 */
930	ieee80211_node_delucastkey(ni);
931#undef N
932}
933
934static void
935node_free(struct ieee80211_node *ni)
936{
937	struct ieee80211com *ic = ni->ni_ic;
938
939	ic->ic_node_cleanup(ni);
940	if (ni->ni_wpa_ie != NULL)
941		FREE(ni->ni_wpa_ie, M_DEVBUF);
942	if (ni->ni_wme_ie != NULL)
943		FREE(ni->ni_wme_ie, M_DEVBUF);
944	IEEE80211_NODE_SAVEQ_DESTROY(ni);
945	FREE(ni, M_80211_NODE);
946}
947
948static u_int8_t
949node_getrssi(const struct ieee80211_node *ni)
950{
951	return ni->ni_rssi;
952}
953
954static void
955ieee80211_setup_node(struct ieee80211_node_table *nt,
956	struct ieee80211_node *ni, const u_int8_t *macaddr)
957{
958	struct ieee80211com *ic = nt->nt_ic;
959	int hash;
960
961	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
962		"%s %p<%s> in %s table\n", __func__, ni,
963		ether_sprintf(macaddr), nt->nt_name);
964
965	IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
966	hash = IEEE80211_NODE_HASH(macaddr);
967	ieee80211_node_initref(ni);		/* mark referenced */
968	ni->ni_chan = IEEE80211_CHAN_ANYC;
969	ni->ni_authmode = IEEE80211_AUTH_OPEN;
970	ni->ni_txpower = ic->ic_txpowlimit;	/* max power */
971	ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey, IEEE80211_KEYIX_NONE);
972	ni->ni_inact_reload = nt->nt_inact_init;
973	ni->ni_inact = ni->ni_inact_reload;
974	IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
975
976	IEEE80211_NODE_LOCK(nt);
977	TAILQ_INSERT_TAIL(&nt->nt_node, ni, ni_list);
978	LIST_INSERT_HEAD(&nt->nt_hash[hash], ni, ni_hash);
979	ni->ni_table = nt;
980	ni->ni_ic = ic;
981	IEEE80211_NODE_UNLOCK(nt);
982}
983
984struct ieee80211_node *
985ieee80211_alloc_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
986{
987	struct ieee80211com *ic = nt->nt_ic;
988	struct ieee80211_node *ni;
989
990	ni = ic->ic_node_alloc(nt);
991	if (ni != NULL)
992		ieee80211_setup_node(nt, ni, macaddr);
993	else
994		ic->ic_stats.is_rx_nodealloc++;
995	return ni;
996}
997
998/*
999 * Craft a temporary node suitable for sending a management frame
1000 * to the specified station.  We craft only as much state as we
1001 * need to do the work since the node will be immediately reclaimed
1002 * once the send completes.
1003 */
1004struct ieee80211_node *
1005ieee80211_tmp_node(struct ieee80211com *ic, const u_int8_t *macaddr)
1006{
1007	struct ieee80211_node *ni;
1008
1009	ni = ic->ic_node_alloc(&ic->ic_sta);
1010	if (ni != NULL) {
1011		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1012			"%s %p<%s>\n", __func__, ni, ether_sprintf(macaddr));
1013
1014		IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
1015		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
1016		ieee80211_node_initref(ni);		/* mark referenced */
1017		ni->ni_txpower = ic->ic_bss->ni_txpower;
1018		/* NB: required by ieee80211_fix_rate */
1019		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
1020		ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey,
1021			IEEE80211_KEYIX_NONE);
1022		/* XXX optimize away */
1023		IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
1024
1025		ni->ni_table = NULL;		/* NB: pedantic */
1026		ni->ni_ic = ic;
1027	} else {
1028		/* XXX msg */
1029		ic->ic_stats.is_rx_nodealloc++;
1030	}
1031	return ni;
1032}
1033
1034struct ieee80211_node *
1035ieee80211_dup_bss(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
1036{
1037	struct ieee80211com *ic = nt->nt_ic;
1038	struct ieee80211_node *ni;
1039
1040	ni = ic->ic_node_alloc(nt);
1041	if (ni != NULL) {
1042		ieee80211_setup_node(nt, ni, macaddr);
1043		/*
1044		 * Inherit from ic_bss.
1045		 */
1046		ni->ni_authmode = ic->ic_bss->ni_authmode;
1047		ni->ni_txpower = ic->ic_bss->ni_txpower;
1048		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
1049		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
1050		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
1051		ni->ni_rsn = ic->ic_bss->ni_rsn;
1052	} else
1053		ic->ic_stats.is_rx_nodealloc++;
1054	return ni;
1055}
1056
1057static struct ieee80211_node *
1058#ifdef IEEE80211_DEBUG_REFCNT
1059_ieee80211_find_node_debug(struct ieee80211_node_table *nt,
1060	const u_int8_t *macaddr, const char *func, int line)
1061#else
1062_ieee80211_find_node(struct ieee80211_node_table *nt,
1063	const u_int8_t *macaddr)
1064#endif
1065{
1066	struct ieee80211_node *ni;
1067	int hash;
1068
1069	IEEE80211_NODE_LOCK_ASSERT(nt);
1070
1071	hash = IEEE80211_NODE_HASH(macaddr);
1072	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1073		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
1074			ieee80211_ref_node(ni);	/* mark referenced */
1075#ifdef IEEE80211_DEBUG_REFCNT
1076			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1077			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1078			    func, line,
1079			    ni, ether_sprintf(ni->ni_macaddr),
1080			    ieee80211_node_refcnt(ni));
1081#endif
1082			return ni;
1083		}
1084	}
1085	return NULL;
1086}
1087#ifdef IEEE80211_DEBUG_REFCNT
1088#define	_ieee80211_find_node(nt, mac) \
1089	_ieee80211_find_node_debug(nt, mac, func, line)
1090#endif
1091
1092struct ieee80211_node *
1093#ifdef IEEE80211_DEBUG_REFCNT
1094ieee80211_find_node_debug(struct ieee80211_node_table *nt,
1095	const u_int8_t *macaddr, const char *func, int line)
1096#else
1097ieee80211_find_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
1098#endif
1099{
1100	struct ieee80211_node *ni;
1101
1102	IEEE80211_NODE_LOCK(nt);
1103	ni = _ieee80211_find_node(nt, macaddr);
1104	IEEE80211_NODE_UNLOCK(nt);
1105	return ni;
1106}
1107
1108/*
1109 * Fake up a node; this handles node discovery in adhoc mode.
1110 * Note that for the driver's benefit we we treat this like
1111 * an association so the driver has an opportunity to setup
1112 * it's private state.
1113 */
1114struct ieee80211_node *
1115ieee80211_fakeup_adhoc_node(struct ieee80211_node_table *nt,
1116	const u_int8_t macaddr[IEEE80211_ADDR_LEN])
1117{
1118	struct ieee80211com *ic = nt->nt_ic;
1119	struct ieee80211_node *ni;
1120
1121	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1122	    "%s: mac<%s>\n", __func__, ether_sprintf(macaddr));
1123	ni = ieee80211_dup_bss(nt, macaddr);
1124	if (ni != NULL) {
1125		/* XXX no rate negotiation; just dup */
1126		ni->ni_rates = ic->ic_bss->ni_rates;
1127		if (ic->ic_newassoc != NULL)
1128			ic->ic_newassoc(ni, 1);
1129		/* XXX not right for 802.1x/WPA */
1130		ieee80211_node_authorize(ni);
1131		if (ic->ic_opmode == IEEE80211_M_AHDEMO) {
1132			/*
1133			 * Blindly propagate capabilities based on the
1134			 * local configuration.  In particular this permits
1135			 * us to use QoS to disable ACK's.
1136			 */
1137			if (ic->ic_flags & IEEE80211_F_WME)
1138				ni->ni_flags |= IEEE80211_NODE_QOS;
1139		}
1140	}
1141	return ni;
1142}
1143
1144#ifdef IEEE80211_DEBUG
1145static void
1146dump_probe_beacon(u_int8_t subtype, int isnew,
1147	const u_int8_t mac[IEEE80211_ADDR_LEN],
1148	const struct ieee80211_scanparams *sp)
1149{
1150
1151	printf("[%s] %s%s on chan %u (bss chan %u) ",
1152	    ether_sprintf(mac), isnew ? "new " : "",
1153	    ieee80211_mgt_subtype_name[subtype >> IEEE80211_FC0_SUBTYPE_SHIFT],
1154	    sp->chan, sp->bchan);
1155	ieee80211_print_essid(sp->ssid + 2, sp->ssid[1]);
1156	printf("\n");
1157
1158	if (isnew) {
1159		printf("[%s] caps 0x%x bintval %u erp 0x%x",
1160			ether_sprintf(mac), sp->capinfo, sp->bintval, sp->erp);
1161		if (sp->country != NULL) {
1162#ifdef __FreeBSD__
1163			printf(" country info %*D",
1164				sp->country[1], sp->country+2, " ");
1165#else
1166			int i;
1167			printf(" country info");
1168			for (i = 0; i < sp->country[1]; i++)
1169				printf(" %02x", sp->country[i+2]);
1170#endif
1171		}
1172		printf("\n");
1173	}
1174}
1175#endif /* IEEE80211_DEBUG */
1176
1177static void
1178saveie(u_int8_t **iep, const u_int8_t *ie)
1179{
1180
1181	if (ie == NULL)
1182		*iep = NULL;
1183	else
1184		ieee80211_saveie(iep, ie);
1185}
1186
1187/*
1188 * Process a beacon or probe response frame.
1189 */
1190void
1191ieee80211_add_scan(struct ieee80211com *ic,
1192	const struct ieee80211_scanparams *sp,
1193	const struct ieee80211_frame *wh,
1194	int subtype, int rssi, int rstamp)
1195{
1196#define	ISPROBE(_st)	((_st) == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1197	struct ieee80211_node_table *nt = &ic->ic_scan;
1198	struct ieee80211_node *ni;
1199	int newnode = 0;
1200
1201	ni = ieee80211_find_node(nt, wh->i_addr2);
1202	if (ni == NULL) {
1203		/*
1204		 * Create a new entry.
1205		 */
1206		ni = ic->ic_node_alloc(nt);
1207		if (ni == NULL) {
1208			ic->ic_stats.is_rx_nodealloc++;
1209			return;
1210		}
1211		ieee80211_setup_node(nt, ni, wh->i_addr2);
1212		/*
1213		 * XXX inherit from ic_bss.
1214		 */
1215		ni->ni_authmode = ic->ic_bss->ni_authmode;
1216		ni->ni_txpower = ic->ic_bss->ni_txpower;
1217		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
1218		ieee80211_set_chan(ic, ni, ic->ic_curchan);
1219		ni->ni_rsn = ic->ic_bss->ni_rsn;
1220		newnode = 1;
1221	}
1222#ifdef IEEE80211_DEBUG
1223	if (ieee80211_msg_scan(ic) && (ic->ic_flags & IEEE80211_F_SCAN))
1224		dump_probe_beacon(subtype, newnode, wh->i_addr2, sp);
1225#endif
1226	/* XXX ap beaconing multiple ssid w/ same bssid */
1227	if (sp->ssid[1] != 0 &&
1228	    (ISPROBE(subtype) || ni->ni_esslen == 0)) {
1229		ni->ni_esslen = sp->ssid[1];
1230		memset(ni->ni_essid, 0, sizeof(ni->ni_essid));
1231		memcpy(ni->ni_essid, sp->ssid + 2, sp->ssid[1]);
1232	}
1233	ni->ni_scangen = ic->ic_scan.nt_scangen;
1234	IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
1235	ni->ni_rssi = rssi;
1236	ni->ni_rstamp = rstamp;
1237	memcpy(ni->ni_tstamp.data, sp->tstamp, sizeof(ni->ni_tstamp));
1238	ni->ni_intval = sp->bintval;
1239	ni->ni_capinfo = sp->capinfo;
1240	ni->ni_chan = &ic->ic_channels[sp->chan];
1241	ni->ni_fhdwell = sp->fhdwell;
1242	ni->ni_fhindex = sp->fhindex;
1243	ni->ni_erp = sp->erp;
1244	if (sp->tim != NULL) {
1245		struct ieee80211_tim_ie *ie =
1246		    (struct ieee80211_tim_ie *) sp->tim;
1247
1248		ni->ni_dtim_count = ie->tim_count;
1249		ni->ni_dtim_period = ie->tim_period;
1250	}
1251	/*
1252	 * Record the byte offset from the mac header to
1253	 * the start of the TIM information element for
1254	 * use by hardware and/or to speedup software
1255	 * processing of beacon frames.
1256	 */
1257	ni->ni_timoff = sp->timoff;
1258	/*
1259	 * Record optional information elements that might be
1260	 * used by applications or drivers.
1261	 */
1262	saveie(&ni->ni_wme_ie, sp->wme);
1263	saveie(&ni->ni_wpa_ie, sp->wpa);
1264
1265	/* NB: must be after ni_chan is setup */
1266	ieee80211_setup_rates(ni, sp->rates, sp->xrates, IEEE80211_F_DOSORT);
1267
1268	if (!newnode)
1269		ieee80211_free_node(ni);
1270#undef ISPROBE
1271}
1272
1273void
1274ieee80211_init_neighbor(struct ieee80211_node *ni,
1275	const struct ieee80211_frame *wh,
1276	const struct ieee80211_scanparams *sp)
1277{
1278
1279	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1280	    "%s: %p<%s>\n", __func__, ni, ether_sprintf(ni->ni_macaddr));
1281	ni->ni_esslen = sp->ssid[1];
1282	memcpy(ni->ni_essid, sp->ssid + 2, sp->ssid[1]);
1283	IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
1284	memcpy(ni->ni_tstamp.data, sp->tstamp, sizeof(ni->ni_tstamp));
1285	ni->ni_intval = sp->bintval;
1286	ni->ni_capinfo = sp->capinfo;
1287	ni->ni_chan = ni->ni_ic->ic_curchan;
1288	ni->ni_fhdwell = sp->fhdwell;
1289	ni->ni_fhindex = sp->fhindex;
1290	ni->ni_erp = sp->erp;
1291	ni->ni_timoff = sp->timoff;
1292	if (sp->wme != NULL)
1293		ieee80211_saveie(&ni->ni_wme_ie, sp->wme);
1294	if (sp->wpa != NULL)
1295		ieee80211_saveie(&ni->ni_wpa_ie, sp->wpa);
1296
1297	/* NB: must be after ni_chan is setup */
1298	ieee80211_setup_rates(ni, sp->rates, sp->xrates, IEEE80211_F_DOSORT);
1299}
1300
1301/*
1302 * Do node discovery in adhoc mode on receipt of a beacon
1303 * or probe response frame.  Note that for the driver's
1304 * benefit we we treat this like an association so the
1305 * driver has an opportunity to setup it's private state.
1306 */
1307struct ieee80211_node *
1308ieee80211_add_neighbor(struct ieee80211com *ic,
1309	const struct ieee80211_frame *wh,
1310	const struct ieee80211_scanparams *sp)
1311{
1312	struct ieee80211_node *ni;
1313
1314	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1315	    "%s: mac<%s>\n", __func__, ether_sprintf(wh->i_addr2));
1316	ni = ieee80211_dup_bss(&ic->ic_sta, wh->i_addr2);/* XXX alloc_node? */
1317	if (ni != NULL) {
1318		ieee80211_init_neighbor(ni, wh, sp);
1319		if (ic->ic_newassoc != NULL)
1320			ic->ic_newassoc(ni, 1);
1321		/* XXX not right for 802.1x/WPA */
1322		ieee80211_node_authorize(ni);
1323	}
1324	return ni;
1325}
1326
1327#define	IS_CTL(wh) \
1328	((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_CTL)
1329#define	IS_PSPOLL(wh) \
1330	((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_PS_POLL)
1331/*
1332 * Locate the node for sender, track state, and then pass the
1333 * (referenced) node up to the 802.11 layer for its use.  We
1334 * are required to pass some node so we fall back to ic_bss
1335 * when this frame is from an unknown sender.  The 802.11 layer
1336 * knows this means the sender wasn't in the node table and
1337 * acts accordingly.
1338 */
1339struct ieee80211_node *
1340#ifdef IEEE80211_DEBUG_REFCNT
1341ieee80211_find_rxnode_debug(struct ieee80211com *ic,
1342	const struct ieee80211_frame_min *wh, const char *func, int line)
1343#else
1344ieee80211_find_rxnode(struct ieee80211com *ic,
1345	const struct ieee80211_frame_min *wh)
1346#endif
1347{
1348	struct ieee80211_node_table *nt;
1349	struct ieee80211_node *ni;
1350
1351	/* XXX may want scanned nodes in the neighbor table for adhoc */
1352	if (ic->ic_opmode == IEEE80211_M_STA ||
1353	    ic->ic_opmode == IEEE80211_M_MONITOR ||
1354	    (ic->ic_flags & IEEE80211_F_SCAN))
1355		nt = &ic->ic_scan;
1356	else
1357		nt = &ic->ic_sta;
1358	/* XXX check ic_bss first in station mode */
1359	/* XXX 4-address frames? */
1360	IEEE80211_NODE_LOCK(nt);
1361	if (IS_CTL(wh) && !IS_PSPOLL(wh) /*&& !IS_RTS(ah)*/)
1362		ni = _ieee80211_find_node(nt, wh->i_addr1);
1363	else
1364		ni = _ieee80211_find_node(nt, wh->i_addr2);
1365	if (ni == NULL)
1366		ni = ieee80211_ref_node(ic->ic_bss);
1367	IEEE80211_NODE_UNLOCK(nt);
1368
1369	return ni;
1370}
1371
1372/*
1373 * Like ieee80211_find_rxnode but use the supplied h/w
1374 * key index as a hint to locate the node in the key
1375 * mapping table.  If an entry is present at the key
1376 * index we return it; otherwise do a normal lookup and
1377 * update the mapping table if the station has a unicast
1378 * key assigned to it.
1379 */
1380struct ieee80211_node *
1381#ifdef IEEE80211_DEBUG_REFCNT
1382ieee80211_find_rxnode_withkey_debug(struct ieee80211com *ic,
1383	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix,
1384	const char *func, int line)
1385#else
1386ieee80211_find_rxnode_withkey(struct ieee80211com *ic,
1387	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix)
1388#endif
1389{
1390	struct ieee80211_node_table *nt;
1391	struct ieee80211_node *ni;
1392
1393	if (ic->ic_opmode == IEEE80211_M_STA ||
1394	    ic->ic_opmode == IEEE80211_M_MONITOR ||
1395	    (ic->ic_flags & IEEE80211_F_SCAN))
1396		nt = &ic->ic_scan;
1397	else
1398		nt = &ic->ic_sta;
1399	IEEE80211_NODE_LOCK(nt);
1400	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax)
1401		ni = nt->nt_keyixmap[keyix];
1402	else
1403		ni = NULL;
1404	if (ni == NULL) {
1405		if (IS_CTL(wh) && !IS_PSPOLL(wh) /*&& !IS_RTS(ah)*/)
1406			ni = _ieee80211_find_node(nt, wh->i_addr1);
1407		else
1408			ni = _ieee80211_find_node(nt, wh->i_addr2);
1409		if (ni == NULL)
1410			ni = ieee80211_ref_node(ic->ic_bss);
1411		if (nt->nt_keyixmap != NULL) {
1412			/*
1413			 * If the station has a unicast key cache slot
1414			 * assigned update the key->node mapping table.
1415			 */
1416			keyix = ni->ni_ucastkey.wk_rxkeyix;
1417			/* XXX can keyixmap[keyix] != NULL? */
1418			if (keyix < nt->nt_keyixmax &&
1419			    nt->nt_keyixmap[keyix] == NULL) {
1420				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1421				    "%s: add key map entry %p<%s> refcnt %d\n",
1422				    __func__, ni, ether_sprintf(ni->ni_macaddr),
1423				    ieee80211_node_refcnt(ni)+1);
1424				nt->nt_keyixmap[keyix] = ieee80211_ref_node(ni);
1425			}
1426		}
1427	} else {
1428		ieee80211_ref_node(ni);
1429	}
1430	IEEE80211_NODE_UNLOCK(nt);
1431
1432	return ni;
1433}
1434#undef IS_PSPOLL
1435#undef IS_CTL
1436
1437/*
1438 * Return a reference to the appropriate node for sending
1439 * a data frame.  This handles node discovery in adhoc networks.
1440 */
1441struct ieee80211_node *
1442#ifdef IEEE80211_DEBUG_REFCNT
1443ieee80211_find_txnode_debug(struct ieee80211com *ic, const u_int8_t *macaddr,
1444	const char *func, int line)
1445#else
1446ieee80211_find_txnode(struct ieee80211com *ic, const u_int8_t *macaddr)
1447#endif
1448{
1449	struct ieee80211_node_table *nt = &ic->ic_sta;
1450	struct ieee80211_node *ni;
1451
1452	/*
1453	 * The destination address should be in the node table
1454	 * unless this is a multicast/broadcast frame.  We can
1455	 * also optimize station mode operation, all frames go
1456	 * to the bss node.
1457	 */
1458	/* XXX can't hold lock across dup_bss 'cuz of recursive locking */
1459	IEEE80211_NODE_LOCK(nt);
1460	if (ic->ic_opmode == IEEE80211_M_STA || IEEE80211_IS_MULTICAST(macaddr))
1461		ni = ieee80211_ref_node(ic->ic_bss);
1462	else {
1463		ni = _ieee80211_find_node(nt, macaddr);
1464		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
1465		    (ni != NULL && ni->ni_associd == 0)) {
1466			/*
1467			 * Station is not associated; don't permit the
1468			 * data frame to be sent by returning NULL.  This
1469			 * is kinda a kludge but the least intrusive way
1470			 * to add this check into all drivers.
1471			 */
1472			ieee80211_unref_node(&ni);	/* NB: null's ni */
1473		}
1474	}
1475	IEEE80211_NODE_UNLOCK(nt);
1476
1477	if (ni == NULL) {
1478		if (ic->ic_opmode == IEEE80211_M_IBSS ||
1479		    ic->ic_opmode == IEEE80211_M_AHDEMO) {
1480			/*
1481			 * In adhoc mode cons up a node for the destination.
1482			 * Note that we need an additional reference for the
1483			 * caller to be consistent with _ieee80211_find_node.
1484			 */
1485			ni = ieee80211_fakeup_adhoc_node(nt, macaddr);
1486			if (ni != NULL)
1487				(void) ieee80211_ref_node(ni);
1488		} else {
1489			IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
1490				"[%s] no node, discard frame (%s)\n",
1491				ether_sprintf(macaddr), __func__);
1492			ic->ic_stats.is_tx_nonode++;
1493		}
1494	}
1495	return ni;
1496}
1497
1498/*
1499 * Like find but search based on the channel too.
1500 */
1501struct ieee80211_node *
1502#ifdef IEEE80211_DEBUG_REFCNT
1503ieee80211_find_node_with_channel_debug(struct ieee80211_node_table *nt,
1504	const u_int8_t *macaddr, struct ieee80211_channel *chan,
1505	const char *func, int line)
1506#else
1507ieee80211_find_node_with_channel(struct ieee80211_node_table *nt,
1508	const u_int8_t *macaddr, struct ieee80211_channel *chan)
1509#endif
1510{
1511	struct ieee80211_node *ni;
1512	int hash;
1513
1514	hash = IEEE80211_NODE_HASH(macaddr);
1515	IEEE80211_NODE_LOCK(nt);
1516	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1517		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1518		    ni->ni_chan == chan) {
1519			ieee80211_ref_node(ni);		/* mark referenced */
1520			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1521			    REFCNT_LOC, ni, ether_sprintf(ni->ni_macaddr),
1522			    ieee80211_node_refcnt(ni));
1523			break;
1524		}
1525	}
1526	IEEE80211_NODE_UNLOCK(nt);
1527	return ni;
1528}
1529
1530/*
1531 * Like find but search based on the ssid too.
1532 */
1533struct ieee80211_node *
1534#ifdef IEEE80211_DEBUG_REFCNT
1535ieee80211_find_node_with_ssid_debug(struct ieee80211_node_table *nt,
1536	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid,
1537	const char *func, int line)
1538#else
1539ieee80211_find_node_with_ssid(struct ieee80211_node_table *nt,
1540	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid)
1541#endif
1542{
1543#define	MATCH_SSID(ni, ssid, ssidlen) \
1544	(ni->ni_esslen == ssidlen && memcmp(ni->ni_essid, ssid, ssidlen) == 0)
1545	static const u_int8_t zeromac[IEEE80211_ADDR_LEN];
1546	struct ieee80211com *ic = nt->nt_ic;
1547	struct ieee80211_node *ni;
1548	int hash;
1549
1550	IEEE80211_NODE_LOCK(nt);
1551	/*
1552	 * A mac address that is all zero means match only the ssid;
1553	 * otherwise we must match both.
1554	 */
1555	if (IEEE80211_ADDR_EQ(macaddr, zeromac)) {
1556		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1557			if (MATCH_SSID(ni, ssid, ssidlen))
1558				break;
1559		}
1560	} else {
1561		hash = IEEE80211_NODE_HASH(macaddr);
1562		LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1563			if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1564			    MATCH_SSID(ni, ssid, ssidlen))
1565				break;
1566		}
1567	}
1568	if (ni != NULL) {
1569		ieee80211_ref_node(ni);	/* mark referenced */
1570		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1571		     REFCNT_LOC, ni, ether_sprintf(ni->ni_macaddr),
1572		     ieee80211_node_refcnt(ni));
1573	}
1574	IEEE80211_NODE_UNLOCK(nt);
1575	return ni;
1576#undef MATCH_SSID
1577}
1578
1579static void
1580_ieee80211_free_node(struct ieee80211_node *ni)
1581{
1582	struct ieee80211com *ic = ni->ni_ic;
1583	struct ieee80211_node_table *nt = ni->ni_table;
1584
1585	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1586		"%s %p<%s> in %s table\n", __func__, ni,
1587		ether_sprintf(ni->ni_macaddr),
1588		nt != NULL ? nt->nt_name : "<gone>");
1589
1590	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1591	if (nt != NULL) {
1592		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1593		LIST_REMOVE(ni, ni_hash);
1594	}
1595	ic->ic_node_free(ni);
1596}
1597
1598void
1599#ifdef IEEE80211_DEBUG_REFCNT
1600ieee80211_free_node_debug(struct ieee80211_node *ni, const char *func, int line)
1601#else
1602ieee80211_free_node(struct ieee80211_node *ni)
1603#endif
1604{
1605	struct ieee80211_node_table *nt = ni->ni_table;
1606
1607#ifdef IEEE80211_DEBUG_REFCNT
1608	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1609		"%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line, ni,
1610		 ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)-1);
1611#endif
1612	if (nt != NULL) {
1613		IEEE80211_NODE_LOCK(nt);
1614		if (ieee80211_node_dectestref(ni)) {
1615			/*
1616			 * Last reference, reclaim state.
1617			 */
1618			_ieee80211_free_node(ni);
1619		} else if (ieee80211_node_refcnt(ni) == 1 &&
1620		    nt->nt_keyixmap != NULL) {
1621			ieee80211_keyix keyix;
1622			/*
1623			 * Check for a last reference in the key mapping table.
1624			 */
1625			keyix = ni->ni_ucastkey.wk_rxkeyix;
1626			if (keyix < nt->nt_keyixmax &&
1627			    nt->nt_keyixmap[keyix] == ni) {
1628				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1629				    "%s: %p<%s> clear key map entry", __func__,
1630				    ni, ether_sprintf(ni->ni_macaddr));
1631				nt->nt_keyixmap[keyix] = NULL;
1632				ieee80211_node_decref(ni); /* XXX needed? */
1633				_ieee80211_free_node(ni);
1634			}
1635		}
1636		IEEE80211_NODE_UNLOCK(nt);
1637	} else {
1638		if (ieee80211_node_dectestref(ni))
1639			_ieee80211_free_node(ni);
1640	}
1641}
1642
1643/*
1644 * Reclaim a unicast key and clear any key cache state.
1645 */
1646int
1647ieee80211_node_delucastkey(struct ieee80211_node *ni)
1648{
1649	struct ieee80211com *ic = ni->ni_ic;
1650	struct ieee80211_node_table *nt = &ic->ic_sta;
1651	struct ieee80211_node *nikey;
1652	ieee80211_keyix keyix;
1653	int isowned, status;
1654
1655	/*
1656	 * NB: We must beware of LOR here; deleting the key
1657	 * can cause the crypto layer to block traffic updates
1658	 * which can generate a LOR against the node table lock;
1659	 * grab it here and stash the key index for our use below.
1660	 *
1661	 * Must also beware of recursion on the node table lock.
1662	 * When called from node_cleanup we may already have
1663	 * the node table lock held.  Unfortunately there's no
1664	 * way to separate out this path so we must do this
1665	 * conditionally.
1666	 */
1667	isowned = IEEE80211_NODE_IS_LOCKED(nt);
1668	if (!isowned)
1669		IEEE80211_NODE_LOCK(nt);
1670	keyix = ni->ni_ucastkey.wk_rxkeyix;
1671	status = ieee80211_crypto_delkey(ic, &ni->ni_ucastkey);
1672	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax) {
1673		nikey = nt->nt_keyixmap[keyix];
1674		nt->nt_keyixmap[keyix] = NULL;;
1675	} else
1676		nikey = NULL;
1677	if (!isowned)
1678		IEEE80211_NODE_UNLOCK(&ic->ic_sta);
1679
1680	if (nikey != NULL) {
1681		KASSERT(nikey == ni,
1682			("key map out of sync, ni %p nikey %p", ni, nikey));
1683		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1684			"%s: delete key map entry %p<%s> refcnt %d\n",
1685			__func__, ni, ether_sprintf(ni->ni_macaddr),
1686			ieee80211_node_refcnt(ni)-1);
1687		ieee80211_free_node(ni);
1688	}
1689	return status;
1690}
1691
1692/*
1693 * Reclaim a node.  If this is the last reference count then
1694 * do the normal free work.  Otherwise remove it from the node
1695 * table and mark it gone by clearing the back-reference.
1696 */
1697static void
1698node_reclaim(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1699{
1700	ieee80211_keyix keyix;
1701
1702	IEEE80211_NODE_LOCK_ASSERT(nt);
1703
1704	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1705		"%s: remove %p<%s> from %s table, refcnt %d\n",
1706		__func__, ni, ether_sprintf(ni->ni_macaddr),
1707		nt->nt_name, ieee80211_node_refcnt(ni)-1);
1708	/*
1709	 * Clear any entry in the unicast key mapping table.
1710	 * We need to do it here so rx lookups don't find it
1711	 * in the mapping table even if it's not in the hash
1712	 * table.  We cannot depend on the mapping table entry
1713	 * being cleared because the node may not be free'd.
1714	 */
1715	keyix = ni->ni_ucastkey.wk_rxkeyix;
1716	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax &&
1717	    nt->nt_keyixmap[keyix] == ni) {
1718		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1719			"%s: %p<%s> clear key map entry\n",
1720			__func__, ni, ether_sprintf(ni->ni_macaddr));
1721		nt->nt_keyixmap[keyix] = NULL;
1722		ieee80211_node_decref(ni);	/* NB: don't need free */
1723	}
1724	if (!ieee80211_node_dectestref(ni)) {
1725		/*
1726		 * Other references are present, just remove the
1727		 * node from the table so it cannot be found.  When
1728		 * the references are dropped storage will be
1729		 * reclaimed.
1730		 */
1731		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1732		LIST_REMOVE(ni, ni_hash);
1733		ni->ni_table = NULL;		/* clear reference */
1734	} else
1735		_ieee80211_free_node(ni);
1736}
1737
1738static void
1739ieee80211_free_allnodes_locked(struct ieee80211_node_table *nt)
1740{
1741	struct ieee80211com *ic = nt->nt_ic;
1742	struct ieee80211_node *ni;
1743
1744	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1745		"%s: free all nodes in %s table\n", __func__, nt->nt_name);
1746
1747	while ((ni = TAILQ_FIRST(&nt->nt_node)) != NULL) {
1748		if (ni->ni_associd != 0) {
1749			if (ic->ic_auth->ia_node_leave != NULL)
1750				ic->ic_auth->ia_node_leave(ic, ni);
1751			IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1752		}
1753		node_reclaim(nt, ni);
1754	}
1755	ieee80211_reset_erp(ic);
1756}
1757
1758static void
1759ieee80211_free_allnodes(struct ieee80211_node_table *nt)
1760{
1761
1762	IEEE80211_NODE_LOCK(nt);
1763	ieee80211_free_allnodes_locked(nt);
1764	IEEE80211_NODE_UNLOCK(nt);
1765}
1766
1767/*
1768 * Timeout entries in the scan cache.
1769 */
1770static void
1771ieee80211_timeout_scan_candidates(struct ieee80211_node_table *nt)
1772{
1773	struct ieee80211com *ic = nt->nt_ic;
1774	struct ieee80211_node *ni, *tni;
1775
1776	IEEE80211_NODE_LOCK(nt);
1777	ni = ic->ic_bss;
1778	/* XXX belongs elsewhere */
1779	if (ni->ni_rxfrag[0] != NULL && ticks > ni->ni_rxfragstamp + hz) {
1780		m_freem(ni->ni_rxfrag[0]);
1781		ni->ni_rxfrag[0] = NULL;
1782	}
1783	TAILQ_FOREACH_SAFE(ni, &nt->nt_node, ni_list, tni) {
1784		if (ni->ni_inact && --ni->ni_inact == 0) {
1785			IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1786			    "[%s] scan candidate purged from cache "
1787			    "(refcnt %u)\n", ether_sprintf(ni->ni_macaddr),
1788			    ieee80211_node_refcnt(ni));
1789			node_reclaim(nt, ni);
1790		}
1791	}
1792	IEEE80211_NODE_UNLOCK(nt);
1793
1794	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
1795}
1796
1797/*
1798 * Timeout inactive stations and do related housekeeping.
1799 * Note that we cannot hold the node lock while sending a
1800 * frame as this would lead to a LOR.  Instead we use a
1801 * generation number to mark nodes that we've scanned and
1802 * drop the lock and restart a scan if we have to time out
1803 * a node.  Since we are single-threaded by virtue of
1804 * controlling the inactivity timer we can be sure this will
1805 * process each node only once.
1806 */
1807static void
1808ieee80211_timeout_stations(struct ieee80211_node_table *nt)
1809{
1810	struct ieee80211com *ic = nt->nt_ic;
1811	struct ieee80211_node *ni;
1812	u_int gen;
1813	int isadhoc;
1814
1815	isadhoc = (ic->ic_opmode == IEEE80211_M_IBSS ||
1816		   ic->ic_opmode == IEEE80211_M_AHDEMO);
1817	IEEE80211_SCAN_LOCK(nt);
1818	gen = ++nt->nt_scangen;
1819	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1820		"%s: %s scangen %u\n", __func__, nt->nt_name, gen);
1821restart:
1822	IEEE80211_NODE_LOCK(nt);
1823	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1824		if (ni->ni_scangen == gen)	/* previously handled */
1825			continue;
1826		ni->ni_scangen = gen;
1827		/*
1828		 * Ignore entries for which have yet to receive an
1829		 * authentication frame.  These are transient and
1830		 * will be reclaimed when the last reference to them
1831		 * goes away (when frame xmits complete).
1832		 */
1833		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
1834		    (ni->ni_flags & IEEE80211_NODE_AREF) == 0)
1835			continue;
1836		/*
1837		 * Free fragment if not needed anymore
1838		 * (last fragment older than 1s).
1839		 * XXX doesn't belong here
1840		 */
1841		if (ni->ni_rxfrag[0] != NULL &&
1842		    ticks > ni->ni_rxfragstamp + hz) {
1843			m_freem(ni->ni_rxfrag[0]);
1844			ni->ni_rxfrag[0] = NULL;
1845		}
1846		/*
1847		 * Special case ourself; we may be idle for extended periods
1848		 * of time and regardless reclaiming our state is wrong.
1849		 */
1850		if (ni == ic->ic_bss)
1851			continue;
1852		ni->ni_inact--;
1853		if (ni->ni_associd != 0 || isadhoc) {
1854			/*
1855			 * Age frames on the power save queue. The
1856			 * aging interval is 4 times the listen
1857			 * interval specified by the station.  This
1858			 * number is factored into the age calculations
1859			 * when the frame is placed on the queue.  We
1860			 * store ages as time differences we can check
1861			 * and/or adjust only the head of the list.
1862			 */
1863			if (IEEE80211_NODE_SAVEQ_QLEN(ni) != 0) {
1864				struct mbuf *m;
1865				int discard = 0;
1866
1867				IEEE80211_NODE_SAVEQ_LOCK(ni);
1868				while (IF_POLL(&ni->ni_savedq, m) != NULL &&
1869				     M_AGE_GET(m) < IEEE80211_INACT_WAIT) {
1870IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER, "[%s] discard frame, age %u\n", ether_sprintf(ni->ni_macaddr), M_AGE_GET(m));/*XXX*/
1871					_IEEE80211_NODE_SAVEQ_DEQUEUE_HEAD(ni, m);
1872					m_freem(m);
1873					discard++;
1874				}
1875				if (m != NULL)
1876					M_AGE_SUB(m, IEEE80211_INACT_WAIT);
1877				IEEE80211_NODE_SAVEQ_UNLOCK(ni);
1878
1879				if (discard != 0) {
1880					IEEE80211_DPRINTF(ic,
1881					    IEEE80211_MSG_POWER,
1882					    "[%s] discard %u frames for age\n",
1883					    ether_sprintf(ni->ni_macaddr),
1884					    discard);
1885					IEEE80211_NODE_STAT_ADD(ni,
1886						ps_discard, discard);
1887					if (IEEE80211_NODE_SAVEQ_QLEN(ni) == 0)
1888						ic->ic_set_tim(ni, 0);
1889				}
1890			}
1891			/*
1892			 * Probe the station before time it out.  We
1893			 * send a null data frame which may not be
1894			 * universally supported by drivers (need it
1895			 * for ps-poll support so it should be...).
1896			 */
1897			if (0 < ni->ni_inact &&
1898			    ni->ni_inact <= ic->ic_inact_probe) {
1899				IEEE80211_NOTE(ic,
1900				    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE,
1901				    ni, "%s",
1902				    "probe station due to inactivity");
1903				/*
1904				 * Grab a reference before unlocking the table
1905				 * so the node cannot be reclaimed before we
1906				 * send the frame. ieee80211_send_nulldata
1907				 * understands we've done this and reclaims the
1908				 * ref for us as needed.
1909				 */
1910				ieee80211_ref_node(ni);
1911				IEEE80211_NODE_UNLOCK(nt);
1912				ieee80211_send_nulldata(ni);
1913				/* XXX stat? */
1914				goto restart;
1915			}
1916		}
1917		if (ni->ni_inact <= 0) {
1918			IEEE80211_NOTE(ic,
1919			    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE, ni,
1920			    "station timed out due to inactivity "
1921			    "(refcnt %u)", ieee80211_node_refcnt(ni));
1922			/*
1923			 * Send a deauthenticate frame and drop the station.
1924			 * This is somewhat complicated due to reference counts
1925			 * and locking.  At this point a station will typically
1926			 * have a reference count of 1.  ieee80211_node_leave
1927			 * will do a "free" of the node which will drop the
1928			 * reference count.  But in the meantime a reference
1929			 * wil be held by the deauth frame.  The actual reclaim
1930			 * of the node will happen either after the tx is
1931			 * completed or by ieee80211_node_leave.
1932			 *
1933			 * Separately we must drop the node lock before sending
1934			 * in case the driver takes a lock, as this will result
1935			 * in  LOR between the node lock and the driver lock.
1936			 */
1937			IEEE80211_NODE_UNLOCK(nt);
1938			if (ni->ni_associd != 0) {
1939				IEEE80211_SEND_MGMT(ic, ni,
1940				    IEEE80211_FC0_SUBTYPE_DEAUTH,
1941				    IEEE80211_REASON_AUTH_EXPIRE);
1942			}
1943			ieee80211_node_leave(ic, ni);
1944			ic->ic_stats.is_node_timeout++;
1945			goto restart;
1946		}
1947	}
1948	IEEE80211_NODE_UNLOCK(nt);
1949
1950	IEEE80211_SCAN_UNLOCK(nt);
1951
1952	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
1953}
1954
1955void
1956ieee80211_iterate_nodes(struct ieee80211_node_table *nt, ieee80211_iter_func *f, void *arg)
1957{
1958	struct ieee80211_node *ni;
1959	u_int gen;
1960
1961	IEEE80211_SCAN_LOCK(nt);
1962	gen = ++nt->nt_scangen;
1963restart:
1964	IEEE80211_NODE_LOCK(nt);
1965	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1966		if (ni->ni_scangen != gen) {
1967			ni->ni_scangen = gen;
1968			(void) ieee80211_ref_node(ni);
1969			IEEE80211_NODE_UNLOCK(nt);
1970			(*f)(arg, ni);
1971			ieee80211_free_node(ni);
1972			goto restart;
1973		}
1974	}
1975	IEEE80211_NODE_UNLOCK(nt);
1976
1977	IEEE80211_SCAN_UNLOCK(nt);
1978}
1979
1980void
1981ieee80211_dump_node(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1982{
1983	printf("0x%p: mac %s refcnt %d\n", ni,
1984		ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni));
1985	printf("\tscangen %u authmode %u flags 0x%x\n",
1986		ni->ni_scangen, ni->ni_authmode, ni->ni_flags);
1987	printf("\tassocid 0x%x txpower %u vlan %u\n",
1988		ni->ni_associd, ni->ni_txpower, ni->ni_vlan);
1989	printf("\ttxseq %u rxseq %u fragno %u rxfragstamp %u\n",
1990		ni->ni_txseqs[0],
1991		ni->ni_rxseqs[0] >> IEEE80211_SEQ_SEQ_SHIFT,
1992		ni->ni_rxseqs[0] & IEEE80211_SEQ_FRAG_MASK,
1993		ni->ni_rxfragstamp);
1994	printf("\trstamp %u rssi %u intval %u capinfo 0x%x\n",
1995		ni->ni_rstamp, ni->ni_rssi, ni->ni_intval, ni->ni_capinfo);
1996	printf("\tbssid %s essid \"%.*s\" channel %u:0x%x\n",
1997		ether_sprintf(ni->ni_bssid),
1998		ni->ni_esslen, ni->ni_essid,
1999		ni->ni_chan->ic_freq, ni->ni_chan->ic_flags);
2000	printf("\tfails %u inact %u txrate %u\n",
2001		ni->ni_fails, ni->ni_inact, ni->ni_txrate);
2002}
2003
2004void
2005ieee80211_dump_nodes(struct ieee80211_node_table *nt)
2006{
2007	ieee80211_iterate_nodes(nt,
2008		(ieee80211_iter_func *) ieee80211_dump_node, nt);
2009}
2010
2011/*
2012 * Handle a station joining an 11g network.
2013 */
2014static void
2015ieee80211_node_join_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
2016{
2017
2018	/*
2019	 * Station isn't capable of short slot time.  Bump
2020	 * the count of long slot time stations and disable
2021	 * use of short slot time.  Note that the actual switch
2022	 * over to long slot time use may not occur until the
2023	 * next beacon transmission (per sec. 7.3.1.4 of 11g).
2024	 */
2025	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
2026		ic->ic_longslotsta++;
2027		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2028		    "[%s] station needs long slot time, count %d\n",
2029		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
2030		/* XXX vap's w/ conflicting needs won't work */
2031		ieee80211_set_shortslottime(ic, 0);
2032	}
2033	/*
2034	 * If the new station is not an ERP station
2035	 * then bump the counter and enable protection
2036	 * if configured.
2037	 */
2038	if (!ieee80211_iserp_rateset(ic, &ni->ni_rates)) {
2039		ic->ic_nonerpsta++;
2040		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2041		    "[%s] station is !ERP, %d non-ERP stations associated\n",
2042		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
2043		/*
2044		 * If protection is configured, enable it.
2045		 */
2046		if (ic->ic_protmode != IEEE80211_PROT_NONE) {
2047			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2048			    "%s: enable use of protection\n", __func__);
2049			ic->ic_flags |= IEEE80211_F_USEPROT;
2050		}
2051		/*
2052		 * If station does not support short preamble
2053		 * then we must enable use of Barker preamble.
2054		 */
2055		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE) == 0) {
2056			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2057			    "[%s] station needs long preamble\n",
2058			    ether_sprintf(ni->ni_macaddr));
2059			ic->ic_flags |= IEEE80211_F_USEBARKER;
2060			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
2061		}
2062		if (ic->ic_nonerpsta == 1)
2063			ic->ic_flags_ext |= IEEE80211_FEXT_ERPUPDATE;
2064	} else
2065		ni->ni_flags |= IEEE80211_NODE_ERP;
2066}
2067
2068void
2069ieee80211_node_join(struct ieee80211com *ic, struct ieee80211_node *ni, int resp)
2070{
2071	int newassoc;
2072
2073	if (ni->ni_associd == 0) {
2074		u_int16_t aid;
2075
2076		/*
2077		 * It would be good to search the bitmap
2078		 * more efficiently, but this will do for now.
2079		 */
2080		for (aid = 1; aid < ic->ic_max_aid; aid++) {
2081			if (!IEEE80211_AID_ISSET(aid,
2082			    ic->ic_aid_bitmap))
2083				break;
2084		}
2085		if (aid >= ic->ic_max_aid) {
2086			IEEE80211_SEND_MGMT(ic, ni, resp,
2087			    IEEE80211_REASON_ASSOC_TOOMANY);
2088			ieee80211_node_leave(ic, ni);
2089			return;
2090		}
2091		ni->ni_associd = aid | 0xc000;
2092		IEEE80211_AID_SET(ni->ni_associd, ic->ic_aid_bitmap);
2093		ic->ic_sta_assoc++;
2094		newassoc = 1;
2095		if (ic->ic_curmode == IEEE80211_MODE_11G)
2096			ieee80211_node_join_11g(ic, ni);
2097	} else
2098		newassoc = 0;
2099
2100	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
2101	    "[%s] station %sassociated at aid %d: %s preamble, %s slot time%s%s\n",
2102	    ether_sprintf(ni->ni_macaddr), newassoc ? "" : "re",
2103	    IEEE80211_NODE_AID(ni),
2104	    ic->ic_flags & IEEE80211_F_SHPREAMBLE ? "short" : "long",
2105	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long",
2106	    ic->ic_flags & IEEE80211_F_USEPROT ? ", protection" : "",
2107	    ni->ni_flags & IEEE80211_NODE_QOS ? ", QoS" : ""
2108	);
2109
2110	/* give driver a chance to setup state like ni_txrate */
2111	if (ic->ic_newassoc != NULL)
2112		ic->ic_newassoc(ni, newassoc);
2113	ni->ni_inact_reload = ic->ic_inact_auth;
2114	ni->ni_inact = ni->ni_inact_reload;
2115	IEEE80211_SEND_MGMT(ic, ni, resp, IEEE80211_STATUS_SUCCESS);
2116	/* tell the authenticator about new station */
2117	if (ic->ic_auth->ia_node_join != NULL)
2118		ic->ic_auth->ia_node_join(ic, ni);
2119	ieee80211_notify_node_join(ic, ni, newassoc);
2120}
2121
2122/*
2123 * Handle a station leaving an 11g network.
2124 */
2125static void
2126ieee80211_node_leave_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
2127{
2128
2129	KASSERT(ic->ic_curmode == IEEE80211_MODE_11G,
2130	     ("not in 11g, bss %u:0x%x, curmode %u", ni->ni_chan->ic_freq,
2131	      ni->ni_chan->ic_flags, ic->ic_curmode));
2132
2133	/*
2134	 * If a long slot station do the slot time bookkeeping.
2135	 */
2136	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
2137		KASSERT(ic->ic_longslotsta > 0,
2138		    ("bogus long slot station count %d", ic->ic_longslotsta));
2139		ic->ic_longslotsta--;
2140		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2141		    "[%s] long slot time station leaves, count now %d\n",
2142		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
2143		if (ic->ic_longslotsta == 0) {
2144			/*
2145			 * Re-enable use of short slot time if supported
2146			 * and not operating in IBSS mode (per spec).
2147			 */
2148			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
2149			    ic->ic_opmode != IEEE80211_M_IBSS) {
2150				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2151				    "%s: re-enable use of short slot time\n",
2152				    __func__);
2153				ieee80211_set_shortslottime(ic, 1);
2154			}
2155		}
2156	}
2157	/*
2158	 * If a non-ERP station do the protection-related bookkeeping.
2159	 */
2160	if ((ni->ni_flags & IEEE80211_NODE_ERP) == 0) {
2161		KASSERT(ic->ic_nonerpsta > 0,
2162		    ("bogus non-ERP station count %d", ic->ic_nonerpsta));
2163		ic->ic_nonerpsta--;
2164		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2165		    "[%s] non-ERP station leaves, count now %d\n",
2166		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
2167		if (ic->ic_nonerpsta == 0) {
2168			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2169				"%s: disable use of protection\n", __func__);
2170			ic->ic_flags &= ~IEEE80211_F_USEPROT;
2171			/* XXX verify mode? */
2172			if (ic->ic_caps & IEEE80211_C_SHPREAMBLE) {
2173				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2174				    "%s: re-enable use of short preamble\n",
2175				    __func__);
2176				ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
2177				ic->ic_flags &= ~IEEE80211_F_USEBARKER;
2178			}
2179			ic->ic_flags_ext |= IEEE80211_FEXT_ERPUPDATE;
2180		}
2181	}
2182}
2183
2184/*
2185 * Handle bookkeeping for station deauthentication/disassociation
2186 * when operating as an ap.
2187 */
2188void
2189ieee80211_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
2190{
2191	struct ieee80211_node_table *nt = ni->ni_table;
2192
2193	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
2194	    "[%s] station with aid %d leaves\n",
2195	    ether_sprintf(ni->ni_macaddr), IEEE80211_NODE_AID(ni));
2196
2197	KASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
2198		ic->ic_opmode == IEEE80211_M_IBSS ||
2199		ic->ic_opmode == IEEE80211_M_AHDEMO,
2200		("unexpected operating mode %u", ic->ic_opmode));
2201	/*
2202	 * If node wasn't previously associated all
2203	 * we need to do is reclaim the reference.
2204	 */
2205	/* XXX ibss mode bypasses 11g and notification */
2206	if (ni->ni_associd == 0)
2207		goto done;
2208	/*
2209	 * Tell the authenticator the station is leaving.
2210	 * Note that we must do this before yanking the
2211	 * association id as the authenticator uses the
2212	 * associd to locate it's state block.
2213	 */
2214	if (ic->ic_auth->ia_node_leave != NULL)
2215		ic->ic_auth->ia_node_leave(ic, ni);
2216	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
2217	ni->ni_associd = 0;
2218	ic->ic_sta_assoc--;
2219
2220	if (ic->ic_curmode == IEEE80211_MODE_11G)
2221		ieee80211_node_leave_11g(ic, ni);
2222	/*
2223	 * Cleanup station state.  In particular clear various
2224	 * state that might otherwise be reused if the node
2225	 * is reused before the reference count goes to zero
2226	 * (and memory is reclaimed).
2227	 */
2228	ieee80211_sta_leave(ic, ni);
2229done:
2230	/*
2231	 * Remove the node from any table it's recorded in and
2232	 * drop the caller's reference.  Removal from the table
2233	 * is important to insure the node is not reprocessed
2234	 * for inactivity.
2235	 */
2236	if (nt != NULL) {
2237		IEEE80211_NODE_LOCK(nt);
2238		node_reclaim(nt, ni);
2239		IEEE80211_NODE_UNLOCK(nt);
2240	} else
2241		ieee80211_free_node(ni);
2242}
2243
2244u_int8_t
2245ieee80211_getrssi(struct ieee80211com *ic)
2246{
2247#define	NZ(x)	((x) == 0 ? 1 : (x))
2248	struct ieee80211_node_table *nt = &ic->ic_sta;
2249	u_int32_t rssi_samples, rssi_total;
2250	struct ieee80211_node *ni;
2251
2252	rssi_total = 0;
2253	rssi_samples = 0;
2254	switch (ic->ic_opmode) {
2255	case IEEE80211_M_IBSS:		/* average of all ibss neighbors */
2256		/* XXX locking */
2257		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
2258			if (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) {
2259				rssi_samples++;
2260				rssi_total += ic->ic_node_getrssi(ni);
2261			}
2262		break;
2263	case IEEE80211_M_AHDEMO:	/* average of all neighbors */
2264		/* XXX locking */
2265		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
2266			rssi_samples++;
2267			rssi_total += ic->ic_node_getrssi(ni);
2268		}
2269		break;
2270	case IEEE80211_M_HOSTAP:	/* average of all associated stations */
2271		/* XXX locking */
2272		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
2273			if (IEEE80211_AID(ni->ni_associd) != 0) {
2274				rssi_samples++;
2275				rssi_total += ic->ic_node_getrssi(ni);
2276			}
2277		break;
2278	case IEEE80211_M_MONITOR:	/* XXX */
2279	case IEEE80211_M_STA:		/* use stats from associated ap */
2280	default:
2281		if (ic->ic_bss != NULL)
2282			rssi_total = ic->ic_node_getrssi(ic->ic_bss);
2283		rssi_samples = 1;
2284		break;
2285	}
2286	return rssi_total / NZ(rssi_samples);
2287#undef NZ
2288}
2289
2290/*
2291 * Indicate whether there are frames queued for a station in power-save mode.
2292 */
2293static void
2294ieee80211_set_tim(struct ieee80211_node *ni, int set)
2295{
2296	struct ieee80211com *ic = ni->ni_ic;
2297	u_int16_t aid;
2298
2299	KASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
2300		ic->ic_opmode == IEEE80211_M_IBSS,
2301		("operating mode %u", ic->ic_opmode));
2302
2303	aid = IEEE80211_AID(ni->ni_associd);
2304	KASSERT(aid < ic->ic_max_aid,
2305		("bogus aid %u, max %u", aid, ic->ic_max_aid));
2306
2307	IEEE80211_BEACON_LOCK(ic);
2308	if (set != (isset(ic->ic_tim_bitmap, aid) != 0)) {
2309		if (set) {
2310			setbit(ic->ic_tim_bitmap, aid);
2311			ic->ic_ps_pending++;
2312		} else {
2313			clrbit(ic->ic_tim_bitmap, aid);
2314			ic->ic_ps_pending--;
2315		}
2316		ic->ic_flags |= IEEE80211_F_TIMUPDATE;
2317	}
2318	IEEE80211_BEACON_UNLOCK(ic);
2319}
2320
2321/*
2322 * Node table support.
2323 */
2324
2325static void
2326ieee80211_node_table_init(struct ieee80211com *ic,
2327	struct ieee80211_node_table *nt,
2328	const char *name, int inact, int keyixmax,
2329	void (*timeout)(struct ieee80211_node_table *))
2330{
2331
2332	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
2333		"%s %s table, inact %u\n", __func__, name, inact);
2334
2335	nt->nt_ic = ic;
2336	/* XXX need unit */
2337	IEEE80211_NODE_LOCK_INIT(nt, ic->ic_ifp->if_xname);
2338	IEEE80211_SCAN_LOCK_INIT(nt, ic->ic_ifp->if_xname);
2339	TAILQ_INIT(&nt->nt_node);
2340	nt->nt_name = name;
2341	nt->nt_scangen = 1;
2342	nt->nt_inact_init = inact;
2343	nt->nt_timeout = timeout;
2344	nt->nt_keyixmax = keyixmax;
2345	if (nt->nt_keyixmax > 0) {
2346		MALLOC(nt->nt_keyixmap, struct ieee80211_node **,
2347			keyixmax * sizeof(struct ieee80211_node *),
2348			M_80211_NODE, M_NOWAIT | M_ZERO);
2349		if (nt->nt_keyixmap == NULL)
2350			if_printf(ic->ic_ifp,
2351			    "Cannot allocate key index map with %u entries\n",
2352			    keyixmax);
2353	} else
2354		nt->nt_keyixmap = NULL;
2355}
2356
2357void
2358ieee80211_node_table_reset(struct ieee80211_node_table *nt)
2359{
2360
2361	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
2362		"%s %s table\n", __func__, nt->nt_name);
2363
2364	IEEE80211_NODE_LOCK(nt);
2365	nt->nt_inact_timer = 0;
2366	ieee80211_free_allnodes_locked(nt);
2367	IEEE80211_NODE_UNLOCK(nt);
2368}
2369
2370static void
2371ieee80211_node_table_cleanup(struct ieee80211_node_table *nt)
2372{
2373
2374	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
2375		"%s %s table\n", __func__, nt->nt_name);
2376
2377	IEEE80211_NODE_LOCK(nt);
2378	ieee80211_free_allnodes_locked(nt);
2379	if (nt->nt_keyixmap != NULL) {
2380		/* XXX verify all entries are NULL */
2381		int i;
2382		for (i = 0; i < nt->nt_keyixmax; i++)
2383			if (nt->nt_keyixmap[i] != NULL)
2384				printf("%s: %s[%u] still active\n", __func__,
2385					nt->nt_name, i);
2386		FREE(nt->nt_keyixmap, M_80211_NODE);
2387		nt->nt_keyixmap = NULL;
2388	}
2389	IEEE80211_SCAN_LOCK_DESTROY(nt);
2390	IEEE80211_NODE_LOCK_DESTROY(nt);
2391}
2392