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