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