ieee80211_node.c revision 148777
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 148777 2005-08-06 04:56:49Z 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
950/*
951 * Craft a temporary node suitable for sending a management frame
952 * to the specified station.  We craft only as much state as we
953 * need to do the work since the node will be immediately reclaimed
954 * once the send completes.
955 */
956struct ieee80211_node *
957ieee80211_tmp_node(struct ieee80211com *ic, const u_int8_t *macaddr)
958{
959	struct ieee80211_node *ni;
960
961	ni = ic->ic_node_alloc(&ic->ic_sta);
962	if (ni != NULL) {
963		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
964			"%s %p<%s>\n", __func__, ni, ether_sprintf(macaddr));
965
966		IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
967		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
968		ieee80211_node_initref(ni);		/* mark referenced */
969		ni->ni_txpower = ic->ic_bss->ni_txpower;
970		/* NB: required by ieee80211_fix_rate */
971		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
972		ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey,
973			IEEE80211_KEYIX_NONE);
974		/* XXX optimize away */
975		IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
976
977		ni->ni_table = NULL;		/* NB: pedantic */
978		ni->ni_ic = ic;
979	} else {
980		/* XXX msg */
981		ic->ic_stats.is_rx_nodealloc++;
982	}
983	return ni;
984}
985
986struct ieee80211_node *
987ieee80211_dup_bss(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
988{
989	struct ieee80211com *ic = nt->nt_ic;
990	struct ieee80211_node *ni;
991
992	ni = ic->ic_node_alloc(nt);
993	if (ni != NULL) {
994		ieee80211_setup_node(nt, ni, macaddr);
995		/*
996		 * Inherit from ic_bss.
997		 */
998		ni->ni_authmode = ic->ic_bss->ni_authmode;
999		ni->ni_txpower = ic->ic_bss->ni_txpower;
1000		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
1001		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
1002		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
1003		ni->ni_rsn = ic->ic_bss->ni_rsn;
1004	} else
1005		ic->ic_stats.is_rx_nodealloc++;
1006	return ni;
1007}
1008
1009static struct ieee80211_node *
1010#ifdef IEEE80211_DEBUG_REFCNT
1011_ieee80211_find_node_debug(struct ieee80211_node_table *nt,
1012	const u_int8_t *macaddr, const char *func, int line)
1013#else
1014_ieee80211_find_node(struct ieee80211_node_table *nt,
1015	const u_int8_t *macaddr)
1016#endif
1017{
1018	struct ieee80211_node *ni;
1019	int hash;
1020
1021	IEEE80211_NODE_LOCK_ASSERT(nt);
1022
1023	hash = IEEE80211_NODE_HASH(macaddr);
1024	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1025		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
1026			ieee80211_ref_node(ni);	/* mark referenced */
1027#ifdef IEEE80211_DEBUG_REFCNT
1028			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1029			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1030			    func, line,
1031			    ni, ether_sprintf(ni->ni_macaddr),
1032			    ieee80211_node_refcnt(ni));
1033#endif
1034			return ni;
1035		}
1036	}
1037	return NULL;
1038}
1039#ifdef IEEE80211_DEBUG_REFCNT
1040#define	_ieee80211_find_node(nt, mac) \
1041	_ieee80211_find_node_debug(nt, mac, func, line)
1042#endif
1043
1044struct ieee80211_node *
1045#ifdef IEEE80211_DEBUG_REFCNT
1046ieee80211_find_node_debug(struct ieee80211_node_table *nt,
1047	const u_int8_t *macaddr, const char *func, int line)
1048#else
1049ieee80211_find_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
1050#endif
1051{
1052	struct ieee80211_node *ni;
1053
1054	IEEE80211_NODE_LOCK(nt);
1055	ni = _ieee80211_find_node(nt, macaddr);
1056	IEEE80211_NODE_UNLOCK(nt);
1057	return ni;
1058}
1059
1060/*
1061 * Fake up a node; this handles node discovery in adhoc mode.
1062 * Note that for the driver's benefit we we treat this like
1063 * an association so the driver has an opportunity to setup
1064 * it's private state.
1065 */
1066struct ieee80211_node *
1067ieee80211_fakeup_adhoc_node(struct ieee80211_node_table *nt,
1068	const u_int8_t macaddr[IEEE80211_ADDR_LEN])
1069{
1070	struct ieee80211com *ic = nt->nt_ic;
1071	struct ieee80211_node *ni;
1072
1073	ni = ieee80211_dup_bss(nt, macaddr);
1074	if (ni != NULL) {
1075		/* XXX no rate negotiation; just dup */
1076		ni->ni_rates = ic->ic_bss->ni_rates;
1077		if (ic->ic_newassoc != NULL)
1078			ic->ic_newassoc(ni, 1);
1079		/* XXX not right for 802.1x/WPA */
1080		ieee80211_node_authorize(ni);
1081	}
1082	return ni;
1083}
1084
1085/*
1086 * Locate the node for sender, track state, and then pass the
1087 * (referenced) node up to the 802.11 layer for its use.  We
1088 * are required to pass some node so we fall back to ic_bss
1089 * when this frame is from an unknown sender.  The 802.11 layer
1090 * knows this means the sender wasn't in the node table and
1091 * acts accordingly.
1092 */
1093struct ieee80211_node *
1094#ifdef IEEE80211_DEBUG_REFCNT
1095ieee80211_find_rxnode_debug(struct ieee80211com *ic,
1096	const struct ieee80211_frame_min *wh, const char *func, int line)
1097#else
1098ieee80211_find_rxnode(struct ieee80211com *ic,
1099	const struct ieee80211_frame_min *wh)
1100#endif
1101{
1102#define	IS_CTL(wh) \
1103	((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_CTL)
1104#define	IS_PSPOLL(wh) \
1105	((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_PS_POLL)
1106	struct ieee80211_node_table *nt;
1107	struct ieee80211_node *ni;
1108
1109	/* XXX may want scanned nodes in the neighbor table for adhoc */
1110	if (ic->ic_opmode == IEEE80211_M_STA ||
1111	    ic->ic_opmode == IEEE80211_M_MONITOR ||
1112	    (ic->ic_flags & IEEE80211_F_SCAN))
1113		nt = &ic->ic_scan;
1114	else
1115		nt = &ic->ic_sta;
1116	/* XXX check ic_bss first in station mode */
1117	/* XXX 4-address frames? */
1118	IEEE80211_NODE_LOCK(nt);
1119	if (IS_CTL(wh) && !IS_PSPOLL(wh) /*&& !IS_RTS(ah)*/)
1120		ni = _ieee80211_find_node(nt, wh->i_addr1);
1121	else
1122		ni = _ieee80211_find_node(nt, wh->i_addr2);
1123	IEEE80211_NODE_UNLOCK(nt);
1124
1125	return (ni != NULL ? ni : ieee80211_ref_node(ic->ic_bss));
1126#undef IS_PSPOLL
1127#undef IS_CTL
1128}
1129
1130/*
1131 * Return a reference to the appropriate node for sending
1132 * a data frame.  This handles node discovery in adhoc networks.
1133 */
1134struct ieee80211_node *
1135#ifdef IEEE80211_DEBUG_REFCNT
1136ieee80211_find_txnode_debug(struct ieee80211com *ic, const u_int8_t *macaddr,
1137	const char *func, int line)
1138#else
1139ieee80211_find_txnode(struct ieee80211com *ic, const u_int8_t *macaddr)
1140#endif
1141{
1142	struct ieee80211_node_table *nt = &ic->ic_sta;
1143	struct ieee80211_node *ni;
1144
1145	/*
1146	 * The destination address should be in the node table
1147	 * unless we are operating in station mode or this is a
1148	 * multicast/broadcast frame.
1149	 */
1150	if (ic->ic_opmode == IEEE80211_M_STA || IEEE80211_IS_MULTICAST(macaddr))
1151		return ieee80211_ref_node(ic->ic_bss);
1152
1153	/* XXX can't hold lock across dup_bss 'cuz of recursive locking */
1154	IEEE80211_NODE_LOCK(nt);
1155	ni = _ieee80211_find_node(nt, macaddr);
1156	IEEE80211_NODE_UNLOCK(nt);
1157
1158	if (ni == NULL) {
1159		if (ic->ic_opmode == IEEE80211_M_IBSS ||
1160		    ic->ic_opmode == IEEE80211_M_AHDEMO) {
1161			/*
1162			 * In adhoc mode cons up a node for the destination.
1163			 * Note that we need an additional reference for the
1164			 * caller to be consistent with _ieee80211_find_node.
1165			 */
1166			ni = ieee80211_fakeup_adhoc_node(nt, macaddr);
1167			if (ni != NULL)
1168				(void) ieee80211_ref_node(ni);
1169		} else {
1170			IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
1171				"[%s] no node, discard frame (%s)\n",
1172				ether_sprintf(macaddr), __func__);
1173			ic->ic_stats.is_tx_nonode++;
1174		}
1175	}
1176	return ni;
1177}
1178
1179/*
1180 * Like find but search based on the channel too.
1181 */
1182struct ieee80211_node *
1183#ifdef IEEE80211_DEBUG_REFCNT
1184ieee80211_find_node_with_channel_debug(struct ieee80211_node_table *nt,
1185	const u_int8_t *macaddr, struct ieee80211_channel *chan,
1186	const char *func, int line)
1187#else
1188ieee80211_find_node_with_channel(struct ieee80211_node_table *nt,
1189	const u_int8_t *macaddr, struct ieee80211_channel *chan)
1190#endif
1191{
1192	struct ieee80211_node *ni;
1193	int hash;
1194
1195	hash = IEEE80211_NODE_HASH(macaddr);
1196	IEEE80211_NODE_LOCK(nt);
1197	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1198		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1199		    ni->ni_chan == chan) {
1200			ieee80211_ref_node(ni);		/* mark referenced */
1201			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1202#ifdef IEEE80211_DEBUG_REFCNT
1203			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1204			    func, line,
1205#else
1206			    "%s %p<%s> refcnt %d\n", __func__,
1207#endif
1208			    ni, ether_sprintf(ni->ni_macaddr),
1209			    ieee80211_node_refcnt(ni));
1210			break;
1211		}
1212	}
1213	IEEE80211_NODE_UNLOCK(nt);
1214	return ni;
1215}
1216
1217/*
1218 * Like find but search based on the ssid too.
1219 */
1220struct ieee80211_node *
1221#ifdef IEEE80211_DEBUG_REFCNT
1222ieee80211_find_node_with_ssid_debug(struct ieee80211_node_table *nt,
1223	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid,
1224	const char *func, int line)
1225#else
1226ieee80211_find_node_with_ssid(struct ieee80211_node_table *nt,
1227	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid)
1228#endif
1229{
1230#define	MATCH_SSID(ni, ssid, ssidlen) \
1231	(ni->ni_esslen == ssidlen && memcmp(ni->ni_essid, ssid, ssidlen) == 0)
1232	static const u_int8_t zeromac[IEEE80211_ADDR_LEN];
1233	struct ieee80211com *ic = nt->nt_ic;
1234	struct ieee80211_node *ni;
1235	int hash;
1236
1237	IEEE80211_NODE_LOCK(nt);
1238	/*
1239	 * A mac address that is all zero means match only the ssid;
1240	 * otherwise we must match both.
1241	 */
1242	if (IEEE80211_ADDR_EQ(macaddr, zeromac)) {
1243		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1244			if (MATCH_SSID(ni, ssid, ssidlen))
1245				break;
1246		}
1247	} else {
1248		hash = IEEE80211_NODE_HASH(macaddr);
1249		LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1250			if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1251			    MATCH_SSID(ni, ssid, ssidlen))
1252				break;
1253		}
1254	}
1255	if (ni != NULL) {
1256		ieee80211_ref_node(ni);	/* mark referenced */
1257		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1258#ifdef IEEE80211_DEBUG_REFCNT
1259		    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1260		    func, line,
1261#else
1262		    "%s %p<%s> refcnt %d\n", __func__,
1263#endif
1264		     ni, ether_sprintf(ni->ni_macaddr),
1265		     ieee80211_node_refcnt(ni));
1266	}
1267	IEEE80211_NODE_UNLOCK(nt);
1268	return ni;
1269#undef MATCH_SSID
1270}
1271
1272static void
1273_ieee80211_free_node(struct ieee80211_node *ni)
1274{
1275	struct ieee80211com *ic = ni->ni_ic;
1276	struct ieee80211_node_table *nt = ni->ni_table;
1277
1278	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1279		"%s %p<%s> in %s table\n", __func__, ni,
1280		ether_sprintf(ni->ni_macaddr),
1281		nt != NULL ? nt->nt_name : "<gone>");
1282
1283	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1284	if (nt != NULL) {
1285		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1286		LIST_REMOVE(ni, ni_hash);
1287	}
1288	ic->ic_node_free(ni);
1289}
1290
1291void
1292#ifdef IEEE80211_DEBUG_REFCNT
1293ieee80211_free_node_debug(struct ieee80211_node *ni, const char *func, int line)
1294#else
1295ieee80211_free_node(struct ieee80211_node *ni)
1296#endif
1297{
1298	struct ieee80211_node_table *nt = ni->ni_table;
1299
1300#ifdef IEEE80211_DEBUG_REFCNT
1301	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1302		"%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line, ni,
1303		 ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)-1);
1304#endif
1305	if (ieee80211_node_dectestref(ni)) {
1306		/*
1307		 * Beware; if the node is marked gone then it's already
1308		 * been removed from the table and we cannot assume the
1309		 * table still exists.  Regardless, there's no need to lock
1310		 * the table.
1311		 */
1312		if (ni->ni_table != NULL) {
1313			IEEE80211_NODE_LOCK(nt);
1314			_ieee80211_free_node(ni);
1315			IEEE80211_NODE_UNLOCK(nt);
1316		} else
1317			_ieee80211_free_node(ni);
1318	}
1319}
1320
1321/*
1322 * Reclaim a node.  If this is the last reference count then
1323 * do the normal free work.  Otherwise remove it from the node
1324 * table and mark it gone by clearing the back-reference.
1325 */
1326static void
1327node_reclaim(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1328{
1329
1330	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1331		"%s: remove %p<%s> from %s table, refcnt %d\n",
1332		__func__, ni, ether_sprintf(ni->ni_macaddr),
1333		nt->nt_name, ieee80211_node_refcnt(ni)-1);
1334	if (!ieee80211_node_dectestref(ni)) {
1335		/*
1336		 * Other references are present, just remove the
1337		 * node from the table so it cannot be found.  When
1338		 * the references are dropped storage will be
1339		 * reclaimed.
1340		 */
1341		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1342		LIST_REMOVE(ni, ni_hash);
1343		ni->ni_table = NULL;		/* clear reference */
1344	} else
1345		_ieee80211_free_node(ni);
1346}
1347
1348static void
1349ieee80211_free_allnodes_locked(struct ieee80211_node_table *nt)
1350{
1351	struct ieee80211com *ic = nt->nt_ic;
1352	struct ieee80211_node *ni;
1353
1354	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1355		"%s: free all nodes in %s table\n", __func__, nt->nt_name);
1356
1357	while ((ni = TAILQ_FIRST(&nt->nt_node)) != NULL) {
1358		if (ni->ni_associd != 0) {
1359			if (ic->ic_auth->ia_node_leave != NULL)
1360				ic->ic_auth->ia_node_leave(ic, ni);
1361			IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1362		}
1363		node_reclaim(nt, ni);
1364	}
1365	ieee80211_reset_erp(ic);
1366}
1367
1368static void
1369ieee80211_free_allnodes(struct ieee80211_node_table *nt)
1370{
1371
1372	IEEE80211_NODE_LOCK(nt);
1373	ieee80211_free_allnodes_locked(nt);
1374	IEEE80211_NODE_UNLOCK(nt);
1375}
1376
1377/*
1378 * Timeout entries in the scan cache.
1379 */
1380static void
1381ieee80211_timeout_scan_candidates(struct ieee80211_node_table *nt)
1382{
1383	struct ieee80211com *ic = nt->nt_ic;
1384	struct ieee80211_node *ni, *tni;
1385
1386	IEEE80211_NODE_LOCK(nt);
1387	ni = ic->ic_bss;
1388	/* XXX belongs elsewhere */
1389	if (ni->ni_rxfrag[0] != NULL && ticks > ni->ni_rxfragstamp + hz) {
1390		m_freem(ni->ni_rxfrag[0]);
1391		ni->ni_rxfrag[0] = NULL;
1392	}
1393	TAILQ_FOREACH_SAFE(ni, &nt->nt_node, ni_list, tni) {
1394		if (ni->ni_inact && --ni->ni_inact == 0) {
1395			IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1396			    "[%s] scan candidate purged from cache "
1397			    "(refcnt %u)\n", ether_sprintf(ni->ni_macaddr),
1398			    ieee80211_node_refcnt(ni));
1399			node_reclaim(nt, ni);
1400		}
1401	}
1402	IEEE80211_NODE_UNLOCK(nt);
1403
1404	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
1405}
1406
1407/*
1408 * Timeout inactive stations and do related housekeeping.
1409 * Note that we cannot hold the node lock while sending a
1410 * frame as this would lead to a LOR.  Instead we use a
1411 * generation number to mark nodes that we've scanned and
1412 * drop the lock and restart a scan if we have to time out
1413 * a node.  Since we are single-threaded by virtue of
1414 * controlling the inactivity timer we can be sure this will
1415 * process each node only once.
1416 */
1417static void
1418ieee80211_timeout_stations(struct ieee80211_node_table *nt)
1419{
1420	struct ieee80211com *ic = nt->nt_ic;
1421	struct ieee80211_node *ni;
1422	u_int gen;
1423	int isadhoc;
1424
1425	isadhoc = (ic->ic_opmode == IEEE80211_M_IBSS ||
1426		   ic->ic_opmode == IEEE80211_M_AHDEMO);
1427	IEEE80211_SCAN_LOCK(nt);
1428	gen = nt->nt_scangen++;
1429	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1430		"%s: %s scangen %u\n", __func__, nt->nt_name, gen);
1431restart:
1432	IEEE80211_NODE_LOCK(nt);
1433	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1434		if (ni->ni_scangen == gen)	/* previously handled */
1435			continue;
1436		ni->ni_scangen = gen;
1437		/*
1438		 * Ignore entries for which have yet to receive an
1439		 * authentication frame.  These are transient and
1440		 * will be reclaimed when the last reference to them
1441		 * goes away (when frame xmits complete).
1442		 */
1443		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
1444		    (ni->ni_flags & IEEE80211_NODE_AREF) == 0)
1445			continue;
1446		/*
1447		 * Free fragment if not needed anymore
1448		 * (last fragment older than 1s).
1449		 * XXX doesn't belong here
1450		 */
1451		if (ni->ni_rxfrag[0] != NULL &&
1452		    ticks > ni->ni_rxfragstamp + hz) {
1453			m_freem(ni->ni_rxfrag[0]);
1454			ni->ni_rxfrag[0] = NULL;
1455		}
1456		/*
1457		 * Special case ourself; we may be idle for extended periods
1458		 * of time and regardless reclaiming our state is wrong.
1459		 */
1460		if (ni == ic->ic_bss)
1461			continue;
1462		ni->ni_inact--;
1463		if (ni->ni_associd != 0 || isadhoc) {
1464			/*
1465			 * Age frames on the power save queue. The
1466			 * aging interval is 4 times the listen
1467			 * interval specified by the station.  This
1468			 * number is factored into the age calculations
1469			 * when the frame is placed on the queue.  We
1470			 * store ages as time differences we can check
1471			 * and/or adjust only the head of the list.
1472			 */
1473			if (IEEE80211_NODE_SAVEQ_QLEN(ni) != 0) {
1474				struct mbuf *m;
1475				int discard = 0;
1476
1477				IEEE80211_NODE_SAVEQ_LOCK(ni);
1478				while (IF_POLL(&ni->ni_savedq, m) != NULL &&
1479				     M_AGE_GET(m) < IEEE80211_INACT_WAIT) {
1480IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER, "[%s] discard frame, age %u\n", ether_sprintf(ni->ni_macaddr), M_AGE_GET(m));/*XXX*/
1481					_IEEE80211_NODE_SAVEQ_DEQUEUE_HEAD(ni, m);
1482					m_freem(m);
1483					discard++;
1484				}
1485				if (m != NULL)
1486					M_AGE_SUB(m, IEEE80211_INACT_WAIT);
1487				IEEE80211_NODE_SAVEQ_UNLOCK(ni);
1488
1489				if (discard != 0) {
1490					IEEE80211_DPRINTF(ic,
1491					    IEEE80211_MSG_POWER,
1492					    "[%s] discard %u frames for age\n",
1493					    ether_sprintf(ni->ni_macaddr),
1494					    discard);
1495					IEEE80211_NODE_STAT_ADD(ni,
1496						ps_discard, discard);
1497					if (IEEE80211_NODE_SAVEQ_QLEN(ni) == 0)
1498						ic->ic_set_tim(ni, 0);
1499				}
1500			}
1501			/*
1502			 * Probe the station before time it out.  We
1503			 * send a null data frame which may not be
1504			 * universally supported by drivers (need it
1505			 * for ps-poll support so it should be...).
1506			 */
1507			if (0 < ni->ni_inact &&
1508			    ni->ni_inact <= ic->ic_inact_probe) {
1509				IEEE80211_NOTE(ic,
1510				    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE,
1511				    ni, "%s",
1512				    "probe station due to inactivity");
1513				/*
1514				 * Grab a reference before unlocking the table
1515				 * so the node cannot be reclaimed before we
1516				 * send the frame. ieee80211_send_nulldata
1517				 * understands we've done this and reclaims the
1518				 * ref for us as needed.
1519				 */
1520				ieee80211_ref_node(ni);
1521				IEEE80211_NODE_UNLOCK(nt);
1522				ieee80211_send_nulldata(ni);
1523				/* XXX stat? */
1524				goto restart;
1525			}
1526		}
1527		if (ni->ni_inact <= 0) {
1528			IEEE80211_NOTE(ic,
1529			    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE, ni,
1530			    "station timed out due to inactivity "
1531			    "(refcnt %u)", ieee80211_node_refcnt(ni));
1532			/*
1533			 * Send a deauthenticate frame and drop the station.
1534			 * This is somewhat complicated due to reference counts
1535			 * and locking.  At this point a station will typically
1536			 * have a reference count of 1.  ieee80211_node_leave
1537			 * will do a "free" of the node which will drop the
1538			 * reference count.  But in the meantime a reference
1539			 * wil be held by the deauth frame.  The actual reclaim
1540			 * of the node will happen either after the tx is
1541			 * completed or by ieee80211_node_leave.
1542			 *
1543			 * Separately we must drop the node lock before sending
1544			 * in case the driver takes a lock, as this will result
1545			 * in  LOR between the node lock and the driver lock.
1546			 */
1547			IEEE80211_NODE_UNLOCK(nt);
1548			if (ni->ni_associd != 0) {
1549				IEEE80211_SEND_MGMT(ic, ni,
1550				    IEEE80211_FC0_SUBTYPE_DEAUTH,
1551				    IEEE80211_REASON_AUTH_EXPIRE);
1552			}
1553			ieee80211_node_leave(ic, ni);
1554			ic->ic_stats.is_node_timeout++;
1555			goto restart;
1556		}
1557	}
1558	IEEE80211_NODE_UNLOCK(nt);
1559
1560	IEEE80211_SCAN_UNLOCK(nt);
1561
1562	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
1563}
1564
1565void
1566ieee80211_iterate_nodes(struct ieee80211_node_table *nt, ieee80211_iter_func *f, void *arg)
1567{
1568	struct ieee80211_node *ni;
1569	u_int gen;
1570
1571	IEEE80211_SCAN_LOCK(nt);
1572	gen = nt->nt_scangen++;
1573restart:
1574	IEEE80211_NODE_LOCK(nt);
1575	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1576		if (ni->ni_scangen != gen) {
1577			ni->ni_scangen = gen;
1578			(void) ieee80211_ref_node(ni);
1579			IEEE80211_NODE_UNLOCK(nt);
1580			(*f)(arg, ni);
1581			ieee80211_free_node(ni);
1582			goto restart;
1583		}
1584	}
1585	IEEE80211_NODE_UNLOCK(nt);
1586
1587	IEEE80211_SCAN_UNLOCK(nt);
1588}
1589
1590void
1591ieee80211_dump_node(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1592{
1593	printf("0x%p: mac %s refcnt %d\n", ni,
1594		ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni));
1595	printf("\tscangen %u authmode %u flags 0x%x\n",
1596		ni->ni_scangen, ni->ni_authmode, ni->ni_flags);
1597	printf("\tassocid 0x%x txpower %u vlan %u\n",
1598		ni->ni_associd, ni->ni_txpower, ni->ni_vlan);
1599	printf("\ttxseq %u rxseq %u fragno %u rxfragstamp %u\n",
1600		ni->ni_txseqs[0],
1601		ni->ni_rxseqs[0] >> IEEE80211_SEQ_SEQ_SHIFT,
1602		ni->ni_rxseqs[0] & IEEE80211_SEQ_FRAG_MASK,
1603		ni->ni_rxfragstamp);
1604	printf("\trstamp %u rssi %u intval %u capinfo 0x%x\n",
1605		ni->ni_rstamp, ni->ni_rssi, ni->ni_intval, ni->ni_capinfo);
1606	printf("\tbssid %s essid \"%.*s\" channel %u:0x%x\n",
1607		ether_sprintf(ni->ni_bssid),
1608		ni->ni_esslen, ni->ni_essid,
1609		ni->ni_chan->ic_freq, ni->ni_chan->ic_flags);
1610	printf("\tfails %u inact %u txrate %u\n",
1611		ni->ni_fails, ni->ni_inact, ni->ni_txrate);
1612}
1613
1614void
1615ieee80211_dump_nodes(struct ieee80211_node_table *nt)
1616{
1617	ieee80211_iterate_nodes(nt,
1618		(ieee80211_iter_func *) ieee80211_dump_node, nt);
1619}
1620
1621/*
1622 * Handle a station joining an 11g network.
1623 */
1624static void
1625ieee80211_node_join_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
1626{
1627
1628	/*
1629	 * Station isn't capable of short slot time.  Bump
1630	 * the count of long slot time stations and disable
1631	 * use of short slot time.  Note that the actual switch
1632	 * over to long slot time use may not occur until the
1633	 * next beacon transmission (per sec. 7.3.1.4 of 11g).
1634	 */
1635	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
1636		ic->ic_longslotsta++;
1637		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1638		    "[%s] station needs long slot time, count %d\n",
1639		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
1640		/* XXX vap's w/ conflicting needs won't work */
1641		ieee80211_set_shortslottime(ic, 0);
1642	}
1643	/*
1644	 * If the new station is not an ERP station
1645	 * then bump the counter and enable protection
1646	 * if configured.
1647	 */
1648	if (!ieee80211_iserp_rateset(ic, &ni->ni_rates)) {
1649		ic->ic_nonerpsta++;
1650		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1651		    "[%s] station is !ERP, %d non-ERP stations associated\n",
1652		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
1653		/*
1654		 * If protection is configured, enable it.
1655		 */
1656		if (ic->ic_protmode != IEEE80211_PROT_NONE) {
1657			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1658			    "%s: enable use of protection\n", __func__);
1659			ic->ic_flags |= IEEE80211_F_USEPROT;
1660		}
1661		/*
1662		 * If station does not support short preamble
1663		 * then we must enable use of Barker preamble.
1664		 */
1665		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE) == 0) {
1666			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1667			    "[%s] station needs long preamble\n",
1668			    ether_sprintf(ni->ni_macaddr));
1669			ic->ic_flags |= IEEE80211_F_USEBARKER;
1670			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
1671		}
1672	} else
1673		ni->ni_flags |= IEEE80211_NODE_ERP;
1674}
1675
1676void
1677ieee80211_node_join(struct ieee80211com *ic, struct ieee80211_node *ni, int resp)
1678{
1679	int newassoc;
1680
1681	if (ni->ni_associd == 0) {
1682		u_int16_t aid;
1683
1684		/*
1685		 * It would be good to search the bitmap
1686		 * more efficiently, but this will do for now.
1687		 */
1688		for (aid = 1; aid < ic->ic_max_aid; aid++) {
1689			if (!IEEE80211_AID_ISSET(aid,
1690			    ic->ic_aid_bitmap))
1691				break;
1692		}
1693		if (aid >= ic->ic_max_aid) {
1694			IEEE80211_SEND_MGMT(ic, ni, resp,
1695			    IEEE80211_REASON_ASSOC_TOOMANY);
1696			ieee80211_node_leave(ic, ni);
1697			return;
1698		}
1699		ni->ni_associd = aid | 0xc000;
1700		IEEE80211_AID_SET(ni->ni_associd, ic->ic_aid_bitmap);
1701		ic->ic_sta_assoc++;
1702		newassoc = 1;
1703		if (ic->ic_curmode == IEEE80211_MODE_11G ||
1704		    ic->ic_curmode == IEEE80211_MODE_TURBO_G)
1705			ieee80211_node_join_11g(ic, ni);
1706	} else
1707		newassoc = 0;
1708
1709	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
1710	    "[%s] station %sassociated at aid %d: %s preamble, %s slot time%s%s\n",
1711	    ether_sprintf(ni->ni_macaddr), newassoc ? "" : "re",
1712	    IEEE80211_NODE_AID(ni),
1713	    ic->ic_flags & IEEE80211_F_SHPREAMBLE ? "short" : "long",
1714	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long",
1715	    ic->ic_flags & IEEE80211_F_USEPROT ? ", protection" : "",
1716	    ni->ni_flags & IEEE80211_NODE_QOS ? ", QoS" : ""
1717	);
1718
1719	/* give driver a chance to setup state like ni_txrate */
1720	if (ic->ic_newassoc != NULL)
1721		ic->ic_newassoc(ni, newassoc);
1722	ni->ni_inact_reload = ic->ic_inact_auth;
1723	ni->ni_inact = ni->ni_inact_reload;
1724	IEEE80211_SEND_MGMT(ic, ni, resp, IEEE80211_STATUS_SUCCESS);
1725	/* tell the authenticator about new station */
1726	if (ic->ic_auth->ia_node_join != NULL)
1727		ic->ic_auth->ia_node_join(ic, ni);
1728	ieee80211_notify_node_join(ic, ni, newassoc);
1729}
1730
1731/*
1732 * Handle a station leaving an 11g network.
1733 */
1734static void
1735ieee80211_node_leave_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
1736{
1737
1738	KASSERT(ic->ic_curmode == IEEE80211_MODE_11G ||
1739		ic->ic_curmode == IEEE80211_MODE_TURBO_G,
1740		("not in 11g, curmode %x", ic->ic_curmode));
1741
1742	/*
1743	 * If a long slot station do the slot time bookkeeping.
1744	 */
1745	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
1746		KASSERT(ic->ic_longslotsta > 0,
1747		    ("bogus long slot station count %d", ic->ic_longslotsta));
1748		ic->ic_longslotsta--;
1749		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1750		    "[%s] long slot time station leaves, count now %d\n",
1751		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
1752		if (ic->ic_longslotsta == 0) {
1753			/*
1754			 * Re-enable use of short slot time if supported
1755			 * and not operating in IBSS mode (per spec).
1756			 */
1757			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
1758			    ic->ic_opmode != IEEE80211_M_IBSS) {
1759				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1760				    "%s: re-enable use of short slot time\n",
1761				    __func__);
1762				ieee80211_set_shortslottime(ic, 1);
1763			}
1764		}
1765	}
1766	/*
1767	 * If a non-ERP station do the protection-related bookkeeping.
1768	 */
1769	if ((ni->ni_flags & IEEE80211_NODE_ERP) == 0) {
1770		KASSERT(ic->ic_nonerpsta > 0,
1771		    ("bogus non-ERP station count %d", ic->ic_nonerpsta));
1772		ic->ic_nonerpsta--;
1773		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1774		    "[%s] non-ERP station leaves, count now %d\n",
1775		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
1776		if (ic->ic_nonerpsta == 0) {
1777			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1778				"%s: disable use of protection\n", __func__);
1779			ic->ic_flags &= ~IEEE80211_F_USEPROT;
1780			/* XXX verify mode? */
1781			if (ic->ic_caps & IEEE80211_C_SHPREAMBLE) {
1782				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1783				    "%s: re-enable use of short preamble\n",
1784				    __func__);
1785				ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
1786				ic->ic_flags &= ~IEEE80211_F_USEBARKER;
1787			}
1788		}
1789	}
1790}
1791
1792/*
1793 * Handle bookkeeping for station deauthentication/disassociation
1794 * when operating as an ap.
1795 */
1796void
1797ieee80211_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
1798{
1799	struct ieee80211_node_table *nt = ni->ni_table;
1800
1801	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
1802	    "[%s] station with aid %d leaves\n",
1803	    ether_sprintf(ni->ni_macaddr), IEEE80211_NODE_AID(ni));
1804
1805	KASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
1806		ic->ic_opmode == IEEE80211_M_IBSS ||
1807		ic->ic_opmode == IEEE80211_M_AHDEMO,
1808		("unexpected operating mode %u", ic->ic_opmode));
1809	/*
1810	 * If node wasn't previously associated all
1811	 * we need to do is reclaim the reference.
1812	 */
1813	/* XXX ibss mode bypasses 11g and notification */
1814	if (ni->ni_associd == 0)
1815		goto done;
1816	/*
1817	 * Tell the authenticator the station is leaving.
1818	 * Note that we must do this before yanking the
1819	 * association id as the authenticator uses the
1820	 * associd to locate it's state block.
1821	 */
1822	if (ic->ic_auth->ia_node_leave != NULL)
1823		ic->ic_auth->ia_node_leave(ic, ni);
1824	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1825	ni->ni_associd = 0;
1826	ic->ic_sta_assoc--;
1827
1828	if (ic->ic_curmode == IEEE80211_MODE_11G ||
1829	    ic->ic_curmode == IEEE80211_MODE_TURBO_G)
1830		ieee80211_node_leave_11g(ic, ni);
1831	/*
1832	 * Cleanup station state.  In particular clear various
1833	 * state that might otherwise be reused if the node
1834	 * is reused before the reference count goes to zero
1835	 * (and memory is reclaimed).
1836	 */
1837	ieee80211_sta_leave(ic, ni);
1838done:
1839	/*
1840	 * Remove the node from any table it's recorded in and
1841	 * drop the caller's reference.  Removal from the table
1842	 * is important to insure the node is not reprocessed
1843	 * for inactivity.
1844	 */
1845	if (nt != NULL) {
1846		IEEE80211_NODE_LOCK(nt);
1847		node_reclaim(nt, ni);
1848		IEEE80211_NODE_UNLOCK(nt);
1849	} else
1850		ieee80211_free_node(ni);
1851}
1852
1853u_int8_t
1854ieee80211_getrssi(struct ieee80211com *ic)
1855{
1856#define	NZ(x)	((x) == 0 ? 1 : (x))
1857	struct ieee80211_node_table *nt = &ic->ic_sta;
1858	u_int32_t rssi_samples, rssi_total;
1859	struct ieee80211_node *ni;
1860
1861	rssi_total = 0;
1862	rssi_samples = 0;
1863	switch (ic->ic_opmode) {
1864	case IEEE80211_M_IBSS:		/* average of all ibss neighbors */
1865		/* XXX locking */
1866		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
1867			if (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) {
1868				rssi_samples++;
1869				rssi_total += ic->ic_node_getrssi(ni);
1870			}
1871		break;
1872	case IEEE80211_M_AHDEMO:	/* average of all neighbors */
1873		/* XXX locking */
1874		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1875			rssi_samples++;
1876			rssi_total += ic->ic_node_getrssi(ni);
1877		}
1878		break;
1879	case IEEE80211_M_HOSTAP:	/* average of all associated stations */
1880		/* XXX locking */
1881		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
1882			if (IEEE80211_AID(ni->ni_associd) != 0) {
1883				rssi_samples++;
1884				rssi_total += ic->ic_node_getrssi(ni);
1885			}
1886		break;
1887	case IEEE80211_M_MONITOR:	/* XXX */
1888	case IEEE80211_M_STA:		/* use stats from associated ap */
1889	default:
1890		if (ic->ic_bss != NULL)
1891			rssi_total = ic->ic_node_getrssi(ic->ic_bss);
1892		rssi_samples = 1;
1893		break;
1894	}
1895	return rssi_total / NZ(rssi_samples);
1896#undef NZ
1897}
1898
1899/*
1900 * Indicate whether there are frames queued for a station in power-save mode.
1901 */
1902static void
1903ieee80211_set_tim(struct ieee80211_node *ni, int set)
1904{
1905	struct ieee80211com *ic = ni->ni_ic;
1906	u_int16_t aid;
1907
1908	KASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
1909		ic->ic_opmode == IEEE80211_M_IBSS,
1910		("operating mode %u", ic->ic_opmode));
1911
1912	aid = IEEE80211_AID(ni->ni_associd);
1913	KASSERT(aid < ic->ic_max_aid,
1914		("bogus aid %u, max %u", aid, ic->ic_max_aid));
1915
1916	IEEE80211_BEACON_LOCK(ic);
1917	if (set != (isset(ic->ic_tim_bitmap, aid) != 0)) {
1918		if (set) {
1919			setbit(ic->ic_tim_bitmap, aid);
1920			ic->ic_ps_pending++;
1921		} else {
1922			clrbit(ic->ic_tim_bitmap, aid);
1923			ic->ic_ps_pending--;
1924		}
1925		ic->ic_flags |= IEEE80211_F_TIMUPDATE;
1926	}
1927	IEEE80211_BEACON_UNLOCK(ic);
1928}
1929
1930/*
1931 * Node table support.
1932 */
1933
1934static void
1935ieee80211_node_table_init(struct ieee80211com *ic,
1936	struct ieee80211_node_table *nt,
1937	const char *name, int inact,
1938	void (*timeout)(struct ieee80211_node_table *))
1939{
1940
1941	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1942		"%s %s table, inact %u\n", __func__, name, inact);
1943
1944	nt->nt_ic = ic;
1945	/* XXX need unit */
1946	IEEE80211_NODE_LOCK_INIT(nt, ic->ic_ifp->if_xname);
1947	IEEE80211_SCAN_LOCK_INIT(nt, ic->ic_ifp->if_xname);
1948	TAILQ_INIT(&nt->nt_node);
1949	nt->nt_name = name;
1950	nt->nt_scangen = 1;
1951	nt->nt_inact_init = inact;
1952	nt->nt_timeout = timeout;
1953}
1954
1955void
1956ieee80211_node_table_reset(struct ieee80211_node_table *nt)
1957{
1958
1959	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1960		"%s %s table\n", __func__, nt->nt_name);
1961
1962	IEEE80211_NODE_LOCK(nt);
1963	nt->nt_inact_timer = 0;
1964	ieee80211_free_allnodes_locked(nt);
1965	IEEE80211_NODE_UNLOCK(nt);
1966}
1967
1968static void
1969ieee80211_node_table_cleanup(struct ieee80211_node_table *nt)
1970{
1971
1972	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1973		"%s %s table\n", __func__, nt->nt_name);
1974
1975	ieee80211_free_allnodes_locked(nt);
1976	IEEE80211_SCAN_LOCK_DESTROY(nt);
1977	IEEE80211_NODE_LOCK_DESTROY(nt);
1978}
1979