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