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