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