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