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