ieee80211_node.c revision 148863
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 148863 2005-08-08 18:46:36Z sam $");
35
36#include <sys/param.h>
37#include <sys/systm.h>
38#include <sys/mbuf.h>
39#include <sys/malloc.h>
40#include <sys/kernel.h>
41
42#include <sys/socket.h>
43
44#include <net/if.h>
45#include <net/if_media.h>
46#include <net/ethernet.h>
47
48#include <net80211/ieee80211_var.h>
49
50#include <net/bpf.h>
51
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,
79	int inact, int keyixmax,
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	ic->ic_node_alloc = node_alloc;
90	ic->ic_node_free = node_free;
91	ic->ic_node_cleanup = node_cleanup;
92	ic->ic_node_getrssi = node_getrssi;
93
94	/* default station inactivity timer setings */
95	ic->ic_inact_init = IEEE80211_INACT_INIT;
96	ic->ic_inact_auth = IEEE80211_INACT_AUTH;
97	ic->ic_inact_run = IEEE80211_INACT_RUN;
98	ic->ic_inact_probe = IEEE80211_INACT_PROBE;
99
100	/* NB: driver should override */
101	ic->ic_max_aid = IEEE80211_AID_DEF;
102	ic->ic_set_tim = ieee80211_set_tim;
103}
104
105void
106ieee80211_node_lateattach(struct ieee80211com *ic)
107{
108	struct ieee80211_rsnparms *rsn;
109
110	if (ic->ic_max_aid > IEEE80211_AID_MAX)
111		ic->ic_max_aid = IEEE80211_AID_MAX;
112	MALLOC(ic->ic_aid_bitmap, u_int32_t *,
113		howmany(ic->ic_max_aid, 32) * sizeof(u_int32_t),
114		M_DEVBUF, M_NOWAIT | M_ZERO);
115	if (ic->ic_aid_bitmap == NULL) {
116		/* XXX no way to recover */
117		printf("%s: no memory for AID bitmap!\n", __func__);
118		ic->ic_max_aid = 0;
119	}
120
121	/* XXX defer until using hostap/ibss mode */
122	ic->ic_tim_len = howmany(ic->ic_max_aid, 8) * sizeof(u_int8_t);
123	MALLOC(ic->ic_tim_bitmap, u_int8_t *, ic->ic_tim_len,
124		M_DEVBUF, M_NOWAIT | M_ZERO);
125	if (ic->ic_tim_bitmap == NULL) {
126		/* XXX no way to recover */
127		printf("%s: no memory for TIM bitmap!\n", __func__);
128	}
129
130	ieee80211_node_table_init(ic, &ic->ic_sta, "station",
131		IEEE80211_INACT_INIT, ic->ic_crypto.cs_max_keyix,
132		ieee80211_timeout_stations);
133	ieee80211_node_table_init(ic, &ic->ic_scan, "scan",
134		IEEE80211_INACT_SCAN, 0,
135		ieee80211_timeout_scan_candidates);
136
137	ieee80211_reset_bss(ic);
138	/*
139	 * Setup "global settings" in the bss node so that
140	 * each new station automatically inherits them.
141	 */
142	rsn = &ic->ic_bss->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_auth = ieee80211_authenticator_get(ic->ic_bss->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(&ic->ic_sta, 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_bintval;
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_bintval;
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	/*
883	 * Must be careful here to remove any key map entry w/o a LOR.
884	 */
885	ieee80211_node_delucastkey(ni);
886#undef N
887}
888
889static void
890node_free(struct ieee80211_node *ni)
891{
892	struct ieee80211com *ic = ni->ni_ic;
893
894	ic->ic_node_cleanup(ni);
895	if (ni->ni_wpa_ie != NULL)
896		FREE(ni->ni_wpa_ie, M_DEVBUF);
897	if (ni->ni_wme_ie != NULL)
898		FREE(ni->ni_wme_ie, M_DEVBUF);
899	IEEE80211_NODE_SAVEQ_DESTROY(ni);
900	FREE(ni, M_80211_NODE);
901}
902
903static u_int8_t
904node_getrssi(const struct ieee80211_node *ni)
905{
906	return ni->ni_rssi;
907}
908
909static void
910ieee80211_setup_node(struct ieee80211_node_table *nt,
911	struct ieee80211_node *ni, const u_int8_t *macaddr)
912{
913	struct ieee80211com *ic = nt->nt_ic;
914	int hash;
915
916	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
917		"%s %p<%s> in %s table\n", __func__, ni,
918		ether_sprintf(macaddr), nt->nt_name);
919
920	IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
921	hash = IEEE80211_NODE_HASH(macaddr);
922	ieee80211_node_initref(ni);		/* mark referenced */
923	ni->ni_chan = IEEE80211_CHAN_ANYC;
924	ni->ni_authmode = IEEE80211_AUTH_OPEN;
925	ni->ni_txpower = ic->ic_txpowlimit;	/* max power */
926	ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey, IEEE80211_KEYIX_NONE);
927	ni->ni_inact_reload = nt->nt_inact_init;
928	ni->ni_inact = ni->ni_inact_reload;
929	IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
930
931	IEEE80211_NODE_LOCK(nt);
932	TAILQ_INSERT_TAIL(&nt->nt_node, ni, ni_list);
933	LIST_INSERT_HEAD(&nt->nt_hash[hash], ni, ni_hash);
934	ni->ni_table = nt;
935	ni->ni_ic = ic;
936	IEEE80211_NODE_UNLOCK(nt);
937}
938
939struct ieee80211_node *
940ieee80211_alloc_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
941{
942	struct ieee80211com *ic = nt->nt_ic;
943	struct ieee80211_node *ni;
944
945	ni = ic->ic_node_alloc(nt);
946	if (ni != NULL)
947		ieee80211_setup_node(nt, ni, macaddr);
948	else
949		ic->ic_stats.is_rx_nodealloc++;
950	return ni;
951}
952
953/*
954 * Craft a temporary node suitable for sending a management frame
955 * to the specified station.  We craft only as much state as we
956 * need to do the work since the node will be immediately reclaimed
957 * once the send completes.
958 */
959struct ieee80211_node *
960ieee80211_tmp_node(struct ieee80211com *ic, const u_int8_t *macaddr)
961{
962	struct ieee80211_node *ni;
963
964	ni = ic->ic_node_alloc(&ic->ic_sta);
965	if (ni != NULL) {
966		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
967			"%s %p<%s>\n", __func__, ni, ether_sprintf(macaddr));
968
969		IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
970		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
971		ieee80211_node_initref(ni);		/* mark referenced */
972		ni->ni_txpower = ic->ic_bss->ni_txpower;
973		/* NB: required by ieee80211_fix_rate */
974		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
975		ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey,
976			IEEE80211_KEYIX_NONE);
977		/* XXX optimize away */
978		IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
979
980		ni->ni_table = NULL;		/* NB: pedantic */
981		ni->ni_ic = ic;
982	} else {
983		/* XXX msg */
984		ic->ic_stats.is_rx_nodealloc++;
985	}
986	return ni;
987}
988
989struct ieee80211_node *
990ieee80211_dup_bss(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
991{
992	struct ieee80211com *ic = nt->nt_ic;
993	struct ieee80211_node *ni;
994
995	ni = ic->ic_node_alloc(nt);
996	if (ni != NULL) {
997		ieee80211_setup_node(nt, ni, macaddr);
998		/*
999		 * Inherit from ic_bss.
1000		 */
1001		ni->ni_authmode = ic->ic_bss->ni_authmode;
1002		ni->ni_txpower = ic->ic_bss->ni_txpower;
1003		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
1004		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
1005		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
1006		ni->ni_rsn = ic->ic_bss->ni_rsn;
1007	} else
1008		ic->ic_stats.is_rx_nodealloc++;
1009	return ni;
1010}
1011
1012static struct ieee80211_node *
1013#ifdef IEEE80211_DEBUG_REFCNT
1014_ieee80211_find_node_debug(struct ieee80211_node_table *nt,
1015	const u_int8_t *macaddr, const char *func, int line)
1016#else
1017_ieee80211_find_node(struct ieee80211_node_table *nt,
1018	const u_int8_t *macaddr)
1019#endif
1020{
1021	struct ieee80211_node *ni;
1022	int hash;
1023
1024	IEEE80211_NODE_LOCK_ASSERT(nt);
1025
1026	hash = IEEE80211_NODE_HASH(macaddr);
1027	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1028		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
1029			ieee80211_ref_node(ni);	/* mark referenced */
1030#ifdef IEEE80211_DEBUG_REFCNT
1031			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1032			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1033			    func, line,
1034			    ni, ether_sprintf(ni->ni_macaddr),
1035			    ieee80211_node_refcnt(ni));
1036#endif
1037			return ni;
1038		}
1039	}
1040	return NULL;
1041}
1042#ifdef IEEE80211_DEBUG_REFCNT
1043#define	_ieee80211_find_node(nt, mac) \
1044	_ieee80211_find_node_debug(nt, mac, func, line)
1045#endif
1046
1047struct ieee80211_node *
1048#ifdef IEEE80211_DEBUG_REFCNT
1049ieee80211_find_node_debug(struct ieee80211_node_table *nt,
1050	const u_int8_t *macaddr, const char *func, int line)
1051#else
1052ieee80211_find_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
1053#endif
1054{
1055	struct ieee80211_node *ni;
1056
1057	IEEE80211_NODE_LOCK(nt);
1058	ni = _ieee80211_find_node(nt, macaddr);
1059	IEEE80211_NODE_UNLOCK(nt);
1060	return ni;
1061}
1062
1063/*
1064 * Fake up a node; this handles node discovery in adhoc mode.
1065 * Note that for the driver's benefit we we treat this like
1066 * an association so the driver has an opportunity to setup
1067 * it's private state.
1068 */
1069struct ieee80211_node *
1070ieee80211_fakeup_adhoc_node(struct ieee80211_node_table *nt,
1071	const u_int8_t macaddr[IEEE80211_ADDR_LEN])
1072{
1073	struct ieee80211com *ic = nt->nt_ic;
1074	struct ieee80211_node *ni;
1075
1076	ni = ieee80211_dup_bss(nt, macaddr);
1077	if (ni != NULL) {
1078		/* XXX no rate negotiation; just dup */
1079		ni->ni_rates = ic->ic_bss->ni_rates;
1080		if (ic->ic_newassoc != NULL)
1081			ic->ic_newassoc(ni, 1);
1082		/* XXX not right for 802.1x/WPA */
1083		ieee80211_node_authorize(ni);
1084	}
1085	return ni;
1086}
1087
1088#define	IS_CTL(wh) \
1089	((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_CTL)
1090#define	IS_PSPOLL(wh) \
1091	((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_PS_POLL)
1092/*
1093 * Locate the node for sender, track state, and then pass the
1094 * (referenced) node up to the 802.11 layer for its use.  We
1095 * are required to pass some node so we fall back to ic_bss
1096 * when this frame is from an unknown sender.  The 802.11 layer
1097 * knows this means the sender wasn't in the node table and
1098 * acts accordingly.
1099 */
1100struct ieee80211_node *
1101#ifdef IEEE80211_DEBUG_REFCNT
1102ieee80211_find_rxnode_debug(struct ieee80211com *ic,
1103	const struct ieee80211_frame_min *wh, const char *func, int line)
1104#else
1105ieee80211_find_rxnode(struct ieee80211com *ic,
1106	const struct ieee80211_frame_min *wh)
1107#endif
1108{
1109	struct ieee80211_node_table *nt;
1110	struct ieee80211_node *ni;
1111
1112	/* XXX may want scanned nodes in the neighbor table for adhoc */
1113	if (ic->ic_opmode == IEEE80211_M_STA ||
1114	    ic->ic_opmode == IEEE80211_M_MONITOR ||
1115	    (ic->ic_flags & IEEE80211_F_SCAN))
1116		nt = &ic->ic_scan;
1117	else
1118		nt = &ic->ic_sta;
1119	/* XXX check ic_bss first in station mode */
1120	/* XXX 4-address frames? */
1121	IEEE80211_NODE_LOCK(nt);
1122	if (IS_CTL(wh) && !IS_PSPOLL(wh) /*&& !IS_RTS(ah)*/)
1123		ni = _ieee80211_find_node(nt, wh->i_addr1);
1124	else
1125		ni = _ieee80211_find_node(nt, wh->i_addr2);
1126	if (ni == NULL)
1127		ni = ieee80211_ref_node(ic->ic_bss);
1128	IEEE80211_NODE_UNLOCK(nt);
1129
1130	return ni;
1131}
1132
1133/*
1134 * Like ieee80211_find_rxnode but use the supplied h/w
1135 * key index as a hint to locate the node in the key
1136 * mapping table.  If an entry is present at the key
1137 * index we return it; otherwise do a normal lookup and
1138 * update the mapping table if the station has a unicast
1139 * key assigned to it.
1140 */
1141struct ieee80211_node *
1142#ifdef IEEE80211_DEBUG_REFCNT
1143ieee80211_find_rxnode_withkey_debug(struct ieee80211com *ic,
1144	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix,
1145	const char *func, int line)
1146#else
1147ieee80211_find_rxnode_withkey(struct ieee80211com *ic,
1148	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix)
1149#endif
1150{
1151	struct ieee80211_node_table *nt;
1152	struct ieee80211_node *ni;
1153
1154	if (ic->ic_opmode == IEEE80211_M_STA ||
1155	    ic->ic_opmode == IEEE80211_M_MONITOR ||
1156	    (ic->ic_flags & IEEE80211_F_SCAN))
1157		nt = &ic->ic_scan;
1158	else
1159		nt = &ic->ic_sta;
1160	IEEE80211_NODE_LOCK(nt);
1161	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax)
1162		ni = nt->nt_keyixmap[keyix];
1163	else
1164		ni = NULL;
1165	if (ni == NULL) {
1166		if (IS_CTL(wh) && !IS_PSPOLL(wh) /*&& !IS_RTS(ah)*/)
1167			ni = _ieee80211_find_node(nt, wh->i_addr1);
1168		else
1169			ni = _ieee80211_find_node(nt, wh->i_addr2);
1170		if (ni == NULL)
1171			ni = ieee80211_ref_node(ic->ic_bss);
1172		if (nt->nt_keyixmap != NULL) {
1173			/*
1174			 * If the station has a unicast key cache slot
1175			 * assigned update the key->node mapping table.
1176			 */
1177			keyix = ni->ni_ucastkey.wk_rxkeyix;
1178			/* XXX can keyixmap[keyix] != NULL? */
1179			if (keyix < nt->nt_keyixmax &&
1180			    nt->nt_keyixmap[keyix] == NULL) {
1181				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1182				    "%s: add key map entry %p<%s> refcnt %d\n",
1183				    __func__, ni, ether_sprintf(ni->ni_macaddr),
1184				    ieee80211_node_refcnt(ni)+1);
1185				nt->nt_keyixmap[keyix] = ieee80211_ref_node(ni);
1186			}
1187		}
1188	} else {
1189		ieee80211_ref_node(ni);
1190	}
1191	IEEE80211_NODE_UNLOCK(nt);
1192
1193	return ni;
1194}
1195#undef IS_PSPOLL
1196#undef IS_CTL
1197
1198/*
1199 * Return a reference to the appropriate node for sending
1200 * a data frame.  This handles node discovery in adhoc networks.
1201 */
1202struct ieee80211_node *
1203#ifdef IEEE80211_DEBUG_REFCNT
1204ieee80211_find_txnode_debug(struct ieee80211com *ic, const u_int8_t *macaddr,
1205	const char *func, int line)
1206#else
1207ieee80211_find_txnode(struct ieee80211com *ic, const u_int8_t *macaddr)
1208#endif
1209{
1210	struct ieee80211_node_table *nt = &ic->ic_sta;
1211	struct ieee80211_node *ni;
1212
1213	/*
1214	 * The destination address should be in the node table
1215	 * unless this is a multicast/broadcast frame.  We can
1216	 * also optimize station mode operation, all frames go
1217	 * to the bss node.
1218	 */
1219	/* XXX can't hold lock across dup_bss 'cuz of recursive locking */
1220	IEEE80211_NODE_LOCK(nt);
1221	if (ic->ic_opmode == IEEE80211_M_STA || IEEE80211_IS_MULTICAST(macaddr))
1222		ni = ieee80211_ref_node(ic->ic_bss);
1223	else
1224		ni = _ieee80211_find_node(nt, macaddr);
1225	IEEE80211_NODE_UNLOCK(nt);
1226
1227	if (ni == NULL) {
1228		if (ic->ic_opmode == IEEE80211_M_IBSS ||
1229		    ic->ic_opmode == IEEE80211_M_AHDEMO) {
1230			/*
1231			 * In adhoc mode cons up a node for the destination.
1232			 * Note that we need an additional reference for the
1233			 * caller to be consistent with _ieee80211_find_node.
1234			 */
1235			ni = ieee80211_fakeup_adhoc_node(nt, macaddr);
1236			if (ni != NULL)
1237				(void) ieee80211_ref_node(ni);
1238		} else {
1239			IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
1240				"[%s] no node, discard frame (%s)\n",
1241				ether_sprintf(macaddr), __func__);
1242			ic->ic_stats.is_tx_nonode++;
1243		}
1244	}
1245	return ni;
1246}
1247
1248/*
1249 * Like find but search based on the channel too.
1250 */
1251struct ieee80211_node *
1252#ifdef IEEE80211_DEBUG_REFCNT
1253ieee80211_find_node_with_channel_debug(struct ieee80211_node_table *nt,
1254	const u_int8_t *macaddr, struct ieee80211_channel *chan,
1255	const char *func, int line)
1256#else
1257ieee80211_find_node_with_channel(struct ieee80211_node_table *nt,
1258	const u_int8_t *macaddr, struct ieee80211_channel *chan)
1259#endif
1260{
1261	struct ieee80211_node *ni;
1262	int hash;
1263
1264	hash = IEEE80211_NODE_HASH(macaddr);
1265	IEEE80211_NODE_LOCK(nt);
1266	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1267		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1268		    ni->ni_chan == chan) {
1269			ieee80211_ref_node(ni);		/* mark referenced */
1270			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1271#ifdef IEEE80211_DEBUG_REFCNT
1272			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1273			    func, line,
1274#else
1275			    "%s %p<%s> refcnt %d\n", __func__,
1276#endif
1277			    ni, ether_sprintf(ni->ni_macaddr),
1278			    ieee80211_node_refcnt(ni));
1279			break;
1280		}
1281	}
1282	IEEE80211_NODE_UNLOCK(nt);
1283	return ni;
1284}
1285
1286/*
1287 * Like find but search based on the ssid too.
1288 */
1289struct ieee80211_node *
1290#ifdef IEEE80211_DEBUG_REFCNT
1291ieee80211_find_node_with_ssid_debug(struct ieee80211_node_table *nt,
1292	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid,
1293	const char *func, int line)
1294#else
1295ieee80211_find_node_with_ssid(struct ieee80211_node_table *nt,
1296	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid)
1297#endif
1298{
1299#define	MATCH_SSID(ni, ssid, ssidlen) \
1300	(ni->ni_esslen == ssidlen && memcmp(ni->ni_essid, ssid, ssidlen) == 0)
1301	static const u_int8_t zeromac[IEEE80211_ADDR_LEN];
1302	struct ieee80211com *ic = nt->nt_ic;
1303	struct ieee80211_node *ni;
1304	int hash;
1305
1306	IEEE80211_NODE_LOCK(nt);
1307	/*
1308	 * A mac address that is all zero means match only the ssid;
1309	 * otherwise we must match both.
1310	 */
1311	if (IEEE80211_ADDR_EQ(macaddr, zeromac)) {
1312		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1313			if (MATCH_SSID(ni, ssid, ssidlen))
1314				break;
1315		}
1316	} else {
1317		hash = IEEE80211_NODE_HASH(macaddr);
1318		LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1319			if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1320			    MATCH_SSID(ni, ssid, ssidlen))
1321				break;
1322		}
1323	}
1324	if (ni != NULL) {
1325		ieee80211_ref_node(ni);	/* mark referenced */
1326		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1327#ifdef IEEE80211_DEBUG_REFCNT
1328		    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1329		    func, line,
1330#else
1331		    "%s %p<%s> refcnt %d\n", __func__,
1332#endif
1333		     ni, ether_sprintf(ni->ni_macaddr),
1334		     ieee80211_node_refcnt(ni));
1335	}
1336	IEEE80211_NODE_UNLOCK(nt);
1337	return ni;
1338#undef MATCH_SSID
1339}
1340
1341static void
1342_ieee80211_free_node(struct ieee80211_node *ni)
1343{
1344	struct ieee80211com *ic = ni->ni_ic;
1345	struct ieee80211_node_table *nt = ni->ni_table;
1346
1347	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1348		"%s %p<%s> in %s table\n", __func__, ni,
1349		ether_sprintf(ni->ni_macaddr),
1350		nt != NULL ? nt->nt_name : "<gone>");
1351
1352	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1353	if (nt != NULL) {
1354		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1355		LIST_REMOVE(ni, ni_hash);
1356	}
1357	ic->ic_node_free(ni);
1358}
1359
1360void
1361#ifdef IEEE80211_DEBUG_REFCNT
1362ieee80211_free_node_debug(struct ieee80211_node *ni, const char *func, int line)
1363#else
1364ieee80211_free_node(struct ieee80211_node *ni)
1365#endif
1366{
1367	struct ieee80211_node_table *nt = ni->ni_table;
1368
1369#ifdef IEEE80211_DEBUG_REFCNT
1370	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1371		"%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line, ni,
1372		 ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)-1);
1373#endif
1374	if (nt != NULL) {
1375		IEEE80211_NODE_LOCK(nt);
1376		if (ieee80211_node_dectestref(ni)) {
1377			/*
1378			 * Last reference, reclaim state.
1379			 */
1380			_ieee80211_free_node(ni);
1381		} else if (ieee80211_node_refcnt(ni) == 1 &&
1382		    nt->nt_keyixmap != NULL) {
1383			ieee80211_keyix keyix;
1384			/*
1385			 * Check for a last reference in the key mapping table.
1386			 */
1387			keyix = ni->ni_ucastkey.wk_rxkeyix;
1388			if (keyix < nt->nt_keyixmax &&
1389			    nt->nt_keyixmap[keyix] == ni) {
1390				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1391				    "%s: %p<%s> clear key map entry", __func__,
1392				    ni, ether_sprintf(ni->ni_macaddr));
1393				nt->nt_keyixmap[keyix] = NULL;
1394				ieee80211_node_decref(ni); /* XXX needed? */
1395				_ieee80211_free_node(ni);
1396			}
1397		}
1398		IEEE80211_NODE_UNLOCK(nt);
1399	} else {
1400		if (ieee80211_node_dectestref(ni))
1401			_ieee80211_free_node(ni);
1402	}
1403}
1404
1405/*
1406 * Reclaim a unicast key and clear any key cache state.
1407 */
1408int
1409ieee80211_node_delucastkey(struct ieee80211_node *ni)
1410{
1411	struct ieee80211com *ic = ni->ni_ic;
1412	struct ieee80211_node_table *nt = &ic->ic_sta;
1413	struct ieee80211_node *nikey;
1414	ieee80211_keyix keyix;
1415	int isowned, status;
1416
1417	/*
1418	 * NB: We must beware of LOR here; deleting the key
1419	 * can cause the crypto layer to block traffic updates
1420	 * which can generate a LOR against the node table lock;
1421	 * grab it here and stash the key index for our use below.
1422	 *
1423	 * Must also beware of recursion on the node table lock.
1424	 * When called from node_cleanup we may already have
1425	 * the node table lock held.  Unfortunately there's no
1426	 * way to separate out this path so we must do this
1427	 * conditionally.
1428	 */
1429	isowned = IEEE80211_NODE_IS_LOCKED(nt);
1430	if (!isowned)
1431		IEEE80211_NODE_LOCK(nt);
1432	keyix = ni->ni_ucastkey.wk_rxkeyix;
1433	status = ieee80211_crypto_delkey(ic, &ni->ni_ucastkey);
1434	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax) {
1435		nikey = nt->nt_keyixmap[keyix];
1436		nt->nt_keyixmap[keyix] = NULL;;
1437	} else
1438		nikey = NULL;
1439	if (!isowned)
1440		IEEE80211_NODE_UNLOCK(&ic->ic_sta);
1441
1442	if (nikey != NULL) {
1443		KASSERT(nikey == ni,
1444			("key map out of sync, ni %p nikey %p", ni, nikey));
1445		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1446			"%s: delete key map entry %p<%s> refcnt %d\n",
1447			__func__, ni, ether_sprintf(ni->ni_macaddr),
1448			ieee80211_node_refcnt(ni)-1);
1449		ieee80211_free_node(ni);
1450	}
1451	return status;
1452}
1453
1454/*
1455 * Reclaim a node.  If this is the last reference count then
1456 * do the normal free work.  Otherwise remove it from the node
1457 * table and mark it gone by clearing the back-reference.
1458 */
1459static void
1460node_reclaim(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1461{
1462	ieee80211_keyix keyix;
1463
1464	IEEE80211_NODE_LOCK_ASSERT(nt);
1465
1466	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1467		"%s: remove %p<%s> from %s table, refcnt %d\n",
1468		__func__, ni, ether_sprintf(ni->ni_macaddr),
1469		nt->nt_name, ieee80211_node_refcnt(ni)-1);
1470	/*
1471	 * Clear any entry in the unicast key mapping table.
1472	 * We need to do it here so rx lookups don't find it
1473	 * in the mapping table even if it's not in the hash
1474	 * table.  We cannot depend on the mapping table entry
1475	 * being cleared because the node may not be free'd.
1476	 */
1477	keyix = ni->ni_ucastkey.wk_rxkeyix;
1478	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax &&
1479	    nt->nt_keyixmap[keyix] == ni) {
1480		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1481			"%s: %p<%s> clear key map entry\n",
1482			__func__, ni, ether_sprintf(ni->ni_macaddr));
1483		nt->nt_keyixmap[keyix] = NULL;
1484		ieee80211_node_decref(ni);	/* NB: don't need free */
1485	}
1486	if (!ieee80211_node_dectestref(ni)) {
1487		/*
1488		 * Other references are present, just remove the
1489		 * node from the table so it cannot be found.  When
1490		 * the references are dropped storage will be
1491		 * reclaimed.
1492		 */
1493		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1494		LIST_REMOVE(ni, ni_hash);
1495		ni->ni_table = NULL;		/* clear reference */
1496	} else
1497		_ieee80211_free_node(ni);
1498}
1499
1500static void
1501ieee80211_free_allnodes_locked(struct ieee80211_node_table *nt)
1502{
1503	struct ieee80211com *ic = nt->nt_ic;
1504	struct ieee80211_node *ni;
1505
1506	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1507		"%s: free all nodes in %s table\n", __func__, nt->nt_name);
1508
1509	while ((ni = TAILQ_FIRST(&nt->nt_node)) != NULL) {
1510		if (ni->ni_associd != 0) {
1511			if (ic->ic_auth->ia_node_leave != NULL)
1512				ic->ic_auth->ia_node_leave(ic, ni);
1513			IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1514		}
1515		node_reclaim(nt, ni);
1516	}
1517	ieee80211_reset_erp(ic);
1518}
1519
1520static void
1521ieee80211_free_allnodes(struct ieee80211_node_table *nt)
1522{
1523
1524	IEEE80211_NODE_LOCK(nt);
1525	ieee80211_free_allnodes_locked(nt);
1526	IEEE80211_NODE_UNLOCK(nt);
1527}
1528
1529/*
1530 * Timeout entries in the scan cache.
1531 */
1532static void
1533ieee80211_timeout_scan_candidates(struct ieee80211_node_table *nt)
1534{
1535	struct ieee80211com *ic = nt->nt_ic;
1536	struct ieee80211_node *ni, *tni;
1537
1538	IEEE80211_NODE_LOCK(nt);
1539	ni = ic->ic_bss;
1540	/* XXX belongs elsewhere */
1541	if (ni->ni_rxfrag[0] != NULL && ticks > ni->ni_rxfragstamp + hz) {
1542		m_freem(ni->ni_rxfrag[0]);
1543		ni->ni_rxfrag[0] = NULL;
1544	}
1545	TAILQ_FOREACH_SAFE(ni, &nt->nt_node, ni_list, tni) {
1546		if (ni->ni_inact && --ni->ni_inact == 0) {
1547			IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1548			    "[%s] scan candidate purged from cache "
1549			    "(refcnt %u)\n", ether_sprintf(ni->ni_macaddr),
1550			    ieee80211_node_refcnt(ni));
1551			node_reclaim(nt, ni);
1552		}
1553	}
1554	IEEE80211_NODE_UNLOCK(nt);
1555
1556	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
1557}
1558
1559/*
1560 * Timeout inactive stations and do related housekeeping.
1561 * Note that we cannot hold the node lock while sending a
1562 * frame as this would lead to a LOR.  Instead we use a
1563 * generation number to mark nodes that we've scanned and
1564 * drop the lock and restart a scan if we have to time out
1565 * a node.  Since we are single-threaded by virtue of
1566 * controlling the inactivity timer we can be sure this will
1567 * process each node only once.
1568 */
1569static void
1570ieee80211_timeout_stations(struct ieee80211_node_table *nt)
1571{
1572	struct ieee80211com *ic = nt->nt_ic;
1573	struct ieee80211_node *ni;
1574	u_int gen;
1575	int isadhoc;
1576
1577	isadhoc = (ic->ic_opmode == IEEE80211_M_IBSS ||
1578		   ic->ic_opmode == IEEE80211_M_AHDEMO);
1579	IEEE80211_SCAN_LOCK(nt);
1580	gen = nt->nt_scangen++;
1581	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1582		"%s: %s scangen %u\n", __func__, nt->nt_name, gen);
1583restart:
1584	IEEE80211_NODE_LOCK(nt);
1585	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1586		if (ni->ni_scangen == gen)	/* previously handled */
1587			continue;
1588		ni->ni_scangen = gen;
1589		/*
1590		 * Ignore entries for which have yet to receive an
1591		 * authentication frame.  These are transient and
1592		 * will be reclaimed when the last reference to them
1593		 * goes away (when frame xmits complete).
1594		 */
1595		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
1596		    (ni->ni_flags & IEEE80211_NODE_AREF) == 0)
1597			continue;
1598		/*
1599		 * Free fragment if not needed anymore
1600		 * (last fragment older than 1s).
1601		 * XXX doesn't belong here
1602		 */
1603		if (ni->ni_rxfrag[0] != NULL &&
1604		    ticks > ni->ni_rxfragstamp + hz) {
1605			m_freem(ni->ni_rxfrag[0]);
1606			ni->ni_rxfrag[0] = NULL;
1607		}
1608		/*
1609		 * Special case ourself; we may be idle for extended periods
1610		 * of time and regardless reclaiming our state is wrong.
1611		 */
1612		if (ni == ic->ic_bss)
1613			continue;
1614		ni->ni_inact--;
1615		if (ni->ni_associd != 0 || isadhoc) {
1616			/*
1617			 * Age frames on the power save queue. The
1618			 * aging interval is 4 times the listen
1619			 * interval specified by the station.  This
1620			 * number is factored into the age calculations
1621			 * when the frame is placed on the queue.  We
1622			 * store ages as time differences we can check
1623			 * and/or adjust only the head of the list.
1624			 */
1625			if (IEEE80211_NODE_SAVEQ_QLEN(ni) != 0) {
1626				struct mbuf *m;
1627				int discard = 0;
1628
1629				IEEE80211_NODE_SAVEQ_LOCK(ni);
1630				while (IF_POLL(&ni->ni_savedq, m) != NULL &&
1631				     M_AGE_GET(m) < IEEE80211_INACT_WAIT) {
1632IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER, "[%s] discard frame, age %u\n", ether_sprintf(ni->ni_macaddr), M_AGE_GET(m));/*XXX*/
1633					_IEEE80211_NODE_SAVEQ_DEQUEUE_HEAD(ni, m);
1634					m_freem(m);
1635					discard++;
1636				}
1637				if (m != NULL)
1638					M_AGE_SUB(m, IEEE80211_INACT_WAIT);
1639				IEEE80211_NODE_SAVEQ_UNLOCK(ni);
1640
1641				if (discard != 0) {
1642					IEEE80211_DPRINTF(ic,
1643					    IEEE80211_MSG_POWER,
1644					    "[%s] discard %u frames for age\n",
1645					    ether_sprintf(ni->ni_macaddr),
1646					    discard);
1647					IEEE80211_NODE_STAT_ADD(ni,
1648						ps_discard, discard);
1649					if (IEEE80211_NODE_SAVEQ_QLEN(ni) == 0)
1650						ic->ic_set_tim(ni, 0);
1651				}
1652			}
1653			/*
1654			 * Probe the station before time it out.  We
1655			 * send a null data frame which may not be
1656			 * universally supported by drivers (need it
1657			 * for ps-poll support so it should be...).
1658			 */
1659			if (0 < ni->ni_inact &&
1660			    ni->ni_inact <= ic->ic_inact_probe) {
1661				IEEE80211_NOTE(ic,
1662				    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE,
1663				    ni, "%s",
1664				    "probe station due to inactivity");
1665				/*
1666				 * Grab a reference before unlocking the table
1667				 * so the node cannot be reclaimed before we
1668				 * send the frame. ieee80211_send_nulldata
1669				 * understands we've done this and reclaims the
1670				 * ref for us as needed.
1671				 */
1672				ieee80211_ref_node(ni);
1673				IEEE80211_NODE_UNLOCK(nt);
1674				ieee80211_send_nulldata(ni);
1675				/* XXX stat? */
1676				goto restart;
1677			}
1678		}
1679		if (ni->ni_inact <= 0) {
1680			IEEE80211_NOTE(ic,
1681			    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE, ni,
1682			    "station timed out due to inactivity "
1683			    "(refcnt %u)", ieee80211_node_refcnt(ni));
1684			/*
1685			 * Send a deauthenticate frame and drop the station.
1686			 * This is somewhat complicated due to reference counts
1687			 * and locking.  At this point a station will typically
1688			 * have a reference count of 1.  ieee80211_node_leave
1689			 * will do a "free" of the node which will drop the
1690			 * reference count.  But in the meantime a reference
1691			 * wil be held by the deauth frame.  The actual reclaim
1692			 * of the node will happen either after the tx is
1693			 * completed or by ieee80211_node_leave.
1694			 *
1695			 * Separately we must drop the node lock before sending
1696			 * in case the driver takes a lock, as this will result
1697			 * in  LOR between the node lock and the driver lock.
1698			 */
1699			IEEE80211_NODE_UNLOCK(nt);
1700			if (ni->ni_associd != 0) {
1701				IEEE80211_SEND_MGMT(ic, ni,
1702				    IEEE80211_FC0_SUBTYPE_DEAUTH,
1703				    IEEE80211_REASON_AUTH_EXPIRE);
1704			}
1705			ieee80211_node_leave(ic, ni);
1706			ic->ic_stats.is_node_timeout++;
1707			goto restart;
1708		}
1709	}
1710	IEEE80211_NODE_UNLOCK(nt);
1711
1712	IEEE80211_SCAN_UNLOCK(nt);
1713
1714	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
1715}
1716
1717void
1718ieee80211_iterate_nodes(struct ieee80211_node_table *nt, ieee80211_iter_func *f, void *arg)
1719{
1720	struct ieee80211_node *ni;
1721	u_int gen;
1722
1723	IEEE80211_SCAN_LOCK(nt);
1724	gen = nt->nt_scangen++;
1725restart:
1726	IEEE80211_NODE_LOCK(nt);
1727	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1728		if (ni->ni_scangen != gen) {
1729			ni->ni_scangen = gen;
1730			(void) ieee80211_ref_node(ni);
1731			IEEE80211_NODE_UNLOCK(nt);
1732			(*f)(arg, ni);
1733			ieee80211_free_node(ni);
1734			goto restart;
1735		}
1736	}
1737	IEEE80211_NODE_UNLOCK(nt);
1738
1739	IEEE80211_SCAN_UNLOCK(nt);
1740}
1741
1742void
1743ieee80211_dump_node(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1744{
1745	printf("0x%p: mac %s refcnt %d\n", ni,
1746		ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni));
1747	printf("\tscangen %u authmode %u flags 0x%x\n",
1748		ni->ni_scangen, ni->ni_authmode, ni->ni_flags);
1749	printf("\tassocid 0x%x txpower %u vlan %u\n",
1750		ni->ni_associd, ni->ni_txpower, ni->ni_vlan);
1751	printf("\ttxseq %u rxseq %u fragno %u rxfragstamp %u\n",
1752		ni->ni_txseqs[0],
1753		ni->ni_rxseqs[0] >> IEEE80211_SEQ_SEQ_SHIFT,
1754		ni->ni_rxseqs[0] & IEEE80211_SEQ_FRAG_MASK,
1755		ni->ni_rxfragstamp);
1756	printf("\trstamp %u rssi %u intval %u capinfo 0x%x\n",
1757		ni->ni_rstamp, ni->ni_rssi, ni->ni_intval, ni->ni_capinfo);
1758	printf("\tbssid %s essid \"%.*s\" channel %u:0x%x\n",
1759		ether_sprintf(ni->ni_bssid),
1760		ni->ni_esslen, ni->ni_essid,
1761		ni->ni_chan->ic_freq, ni->ni_chan->ic_flags);
1762	printf("\tfails %u inact %u txrate %u\n",
1763		ni->ni_fails, ni->ni_inact, ni->ni_txrate);
1764}
1765
1766void
1767ieee80211_dump_nodes(struct ieee80211_node_table *nt)
1768{
1769	ieee80211_iterate_nodes(nt,
1770		(ieee80211_iter_func *) ieee80211_dump_node, nt);
1771}
1772
1773/*
1774 * Handle a station joining an 11g network.
1775 */
1776static void
1777ieee80211_node_join_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
1778{
1779
1780	/*
1781	 * Station isn't capable of short slot time.  Bump
1782	 * the count of long slot time stations and disable
1783	 * use of short slot time.  Note that the actual switch
1784	 * over to long slot time use may not occur until the
1785	 * next beacon transmission (per sec. 7.3.1.4 of 11g).
1786	 */
1787	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
1788		ic->ic_longslotsta++;
1789		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1790		    "[%s] station needs long slot time, count %d\n",
1791		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
1792		/* XXX vap's w/ conflicting needs won't work */
1793		ieee80211_set_shortslottime(ic, 0);
1794	}
1795	/*
1796	 * If the new station is not an ERP station
1797	 * then bump the counter and enable protection
1798	 * if configured.
1799	 */
1800	if (!ieee80211_iserp_rateset(ic, &ni->ni_rates)) {
1801		ic->ic_nonerpsta++;
1802		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1803		    "[%s] station is !ERP, %d non-ERP stations associated\n",
1804		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
1805		/*
1806		 * If protection is configured, enable it.
1807		 */
1808		if (ic->ic_protmode != IEEE80211_PROT_NONE) {
1809			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1810			    "%s: enable use of protection\n", __func__);
1811			ic->ic_flags |= IEEE80211_F_USEPROT;
1812		}
1813		/*
1814		 * If station does not support short preamble
1815		 * then we must enable use of Barker preamble.
1816		 */
1817		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE) == 0) {
1818			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1819			    "[%s] station needs long preamble\n",
1820			    ether_sprintf(ni->ni_macaddr));
1821			ic->ic_flags |= IEEE80211_F_USEBARKER;
1822			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
1823		}
1824	} else
1825		ni->ni_flags |= IEEE80211_NODE_ERP;
1826}
1827
1828void
1829ieee80211_node_join(struct ieee80211com *ic, struct ieee80211_node *ni, int resp)
1830{
1831	int newassoc;
1832
1833	if (ni->ni_associd == 0) {
1834		u_int16_t aid;
1835
1836		/*
1837		 * It would be good to search the bitmap
1838		 * more efficiently, but this will do for now.
1839		 */
1840		for (aid = 1; aid < ic->ic_max_aid; aid++) {
1841			if (!IEEE80211_AID_ISSET(aid,
1842			    ic->ic_aid_bitmap))
1843				break;
1844		}
1845		if (aid >= ic->ic_max_aid) {
1846			IEEE80211_SEND_MGMT(ic, ni, resp,
1847			    IEEE80211_REASON_ASSOC_TOOMANY);
1848			ieee80211_node_leave(ic, ni);
1849			return;
1850		}
1851		ni->ni_associd = aid | 0xc000;
1852		IEEE80211_AID_SET(ni->ni_associd, ic->ic_aid_bitmap);
1853		ic->ic_sta_assoc++;
1854		newassoc = 1;
1855		if (ic->ic_curmode == IEEE80211_MODE_11G ||
1856		    ic->ic_curmode == IEEE80211_MODE_TURBO_G)
1857			ieee80211_node_join_11g(ic, ni);
1858	} else
1859		newassoc = 0;
1860
1861	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
1862	    "[%s] station %sassociated at aid %d: %s preamble, %s slot time%s%s\n",
1863	    ether_sprintf(ni->ni_macaddr), newassoc ? "" : "re",
1864	    IEEE80211_NODE_AID(ni),
1865	    ic->ic_flags & IEEE80211_F_SHPREAMBLE ? "short" : "long",
1866	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long",
1867	    ic->ic_flags & IEEE80211_F_USEPROT ? ", protection" : "",
1868	    ni->ni_flags & IEEE80211_NODE_QOS ? ", QoS" : ""
1869	);
1870
1871	/* give driver a chance to setup state like ni_txrate */
1872	if (ic->ic_newassoc != NULL)
1873		ic->ic_newassoc(ni, newassoc);
1874	ni->ni_inact_reload = ic->ic_inact_auth;
1875	ni->ni_inact = ni->ni_inact_reload;
1876	IEEE80211_SEND_MGMT(ic, ni, resp, IEEE80211_STATUS_SUCCESS);
1877	/* tell the authenticator about new station */
1878	if (ic->ic_auth->ia_node_join != NULL)
1879		ic->ic_auth->ia_node_join(ic, ni);
1880	ieee80211_notify_node_join(ic, ni, newassoc);
1881}
1882
1883/*
1884 * Handle a station leaving an 11g network.
1885 */
1886static void
1887ieee80211_node_leave_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
1888{
1889
1890	KASSERT(ic->ic_curmode == IEEE80211_MODE_11G ||
1891		ic->ic_curmode == IEEE80211_MODE_TURBO_G,
1892		("not in 11g, curmode %x", ic->ic_curmode));
1893
1894	/*
1895	 * If a long slot station do the slot time bookkeeping.
1896	 */
1897	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
1898		KASSERT(ic->ic_longslotsta > 0,
1899		    ("bogus long slot station count %d", ic->ic_longslotsta));
1900		ic->ic_longslotsta--;
1901		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1902		    "[%s] long slot time station leaves, count now %d\n",
1903		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
1904		if (ic->ic_longslotsta == 0) {
1905			/*
1906			 * Re-enable use of short slot time if supported
1907			 * and not operating in IBSS mode (per spec).
1908			 */
1909			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
1910			    ic->ic_opmode != IEEE80211_M_IBSS) {
1911				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1912				    "%s: re-enable use of short slot time\n",
1913				    __func__);
1914				ieee80211_set_shortslottime(ic, 1);
1915			}
1916		}
1917	}
1918	/*
1919	 * If a non-ERP station do the protection-related bookkeeping.
1920	 */
1921	if ((ni->ni_flags & IEEE80211_NODE_ERP) == 0) {
1922		KASSERT(ic->ic_nonerpsta > 0,
1923		    ("bogus non-ERP station count %d", ic->ic_nonerpsta));
1924		ic->ic_nonerpsta--;
1925		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1926		    "[%s] non-ERP station leaves, count now %d\n",
1927		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
1928		if (ic->ic_nonerpsta == 0) {
1929			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1930				"%s: disable use of protection\n", __func__);
1931			ic->ic_flags &= ~IEEE80211_F_USEPROT;
1932			/* XXX verify mode? */
1933			if (ic->ic_caps & IEEE80211_C_SHPREAMBLE) {
1934				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1935				    "%s: re-enable use of short preamble\n",
1936				    __func__);
1937				ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
1938				ic->ic_flags &= ~IEEE80211_F_USEBARKER;
1939			}
1940		}
1941	}
1942}
1943
1944/*
1945 * Handle bookkeeping for station deauthentication/disassociation
1946 * when operating as an ap.
1947 */
1948void
1949ieee80211_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
1950{
1951	struct ieee80211_node_table *nt = ni->ni_table;
1952
1953	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
1954	    "[%s] station with aid %d leaves\n",
1955	    ether_sprintf(ni->ni_macaddr), IEEE80211_NODE_AID(ni));
1956
1957	KASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
1958		ic->ic_opmode == IEEE80211_M_IBSS ||
1959		ic->ic_opmode == IEEE80211_M_AHDEMO,
1960		("unexpected operating mode %u", ic->ic_opmode));
1961	/*
1962	 * If node wasn't previously associated all
1963	 * we need to do is reclaim the reference.
1964	 */
1965	/* XXX ibss mode bypasses 11g and notification */
1966	if (ni->ni_associd == 0)
1967		goto done;
1968	/*
1969	 * Tell the authenticator the station is leaving.
1970	 * Note that we must do this before yanking the
1971	 * association id as the authenticator uses the
1972	 * associd to locate it's state block.
1973	 */
1974	if (ic->ic_auth->ia_node_leave != NULL)
1975		ic->ic_auth->ia_node_leave(ic, ni);
1976	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1977	ni->ni_associd = 0;
1978	ic->ic_sta_assoc--;
1979
1980	if (ic->ic_curmode == IEEE80211_MODE_11G ||
1981	    ic->ic_curmode == IEEE80211_MODE_TURBO_G)
1982		ieee80211_node_leave_11g(ic, ni);
1983	/*
1984	 * Cleanup station state.  In particular clear various
1985	 * state that might otherwise be reused if the node
1986	 * is reused before the reference count goes to zero
1987	 * (and memory is reclaimed).
1988	 */
1989	ieee80211_sta_leave(ic, ni);
1990done:
1991	/*
1992	 * Remove the node from any table it's recorded in and
1993	 * drop the caller's reference.  Removal from the table
1994	 * is important to insure the node is not reprocessed
1995	 * for inactivity.
1996	 */
1997	if (nt != NULL) {
1998		IEEE80211_NODE_LOCK(nt);
1999		node_reclaim(nt, ni);
2000		IEEE80211_NODE_UNLOCK(nt);
2001	} else
2002		ieee80211_free_node(ni);
2003}
2004
2005u_int8_t
2006ieee80211_getrssi(struct ieee80211com *ic)
2007{
2008#define	NZ(x)	((x) == 0 ? 1 : (x))
2009	struct ieee80211_node_table *nt = &ic->ic_sta;
2010	u_int32_t rssi_samples, rssi_total;
2011	struct ieee80211_node *ni;
2012
2013	rssi_total = 0;
2014	rssi_samples = 0;
2015	switch (ic->ic_opmode) {
2016	case IEEE80211_M_IBSS:		/* average of all ibss neighbors */
2017		/* XXX locking */
2018		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
2019			if (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) {
2020				rssi_samples++;
2021				rssi_total += ic->ic_node_getrssi(ni);
2022			}
2023		break;
2024	case IEEE80211_M_AHDEMO:	/* average of all neighbors */
2025		/* XXX locking */
2026		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
2027			rssi_samples++;
2028			rssi_total += ic->ic_node_getrssi(ni);
2029		}
2030		break;
2031	case IEEE80211_M_HOSTAP:	/* average of all associated stations */
2032		/* XXX locking */
2033		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
2034			if (IEEE80211_AID(ni->ni_associd) != 0) {
2035				rssi_samples++;
2036				rssi_total += ic->ic_node_getrssi(ni);
2037			}
2038		break;
2039	case IEEE80211_M_MONITOR:	/* XXX */
2040	case IEEE80211_M_STA:		/* use stats from associated ap */
2041	default:
2042		if (ic->ic_bss != NULL)
2043			rssi_total = ic->ic_node_getrssi(ic->ic_bss);
2044		rssi_samples = 1;
2045		break;
2046	}
2047	return rssi_total / NZ(rssi_samples);
2048#undef NZ
2049}
2050
2051/*
2052 * Indicate whether there are frames queued for a station in power-save mode.
2053 */
2054static void
2055ieee80211_set_tim(struct ieee80211_node *ni, int set)
2056{
2057	struct ieee80211com *ic = ni->ni_ic;
2058	u_int16_t aid;
2059
2060	KASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
2061		ic->ic_opmode == IEEE80211_M_IBSS,
2062		("operating mode %u", ic->ic_opmode));
2063
2064	aid = IEEE80211_AID(ni->ni_associd);
2065	KASSERT(aid < ic->ic_max_aid,
2066		("bogus aid %u, max %u", aid, ic->ic_max_aid));
2067
2068	IEEE80211_BEACON_LOCK(ic);
2069	if (set != (isset(ic->ic_tim_bitmap, aid) != 0)) {
2070		if (set) {
2071			setbit(ic->ic_tim_bitmap, aid);
2072			ic->ic_ps_pending++;
2073		} else {
2074			clrbit(ic->ic_tim_bitmap, aid);
2075			ic->ic_ps_pending--;
2076		}
2077		ic->ic_flags |= IEEE80211_F_TIMUPDATE;
2078	}
2079	IEEE80211_BEACON_UNLOCK(ic);
2080}
2081
2082/*
2083 * Node table support.
2084 */
2085
2086static void
2087ieee80211_node_table_init(struct ieee80211com *ic,
2088	struct ieee80211_node_table *nt,
2089	const char *name, int inact, int keyixmax,
2090	void (*timeout)(struct ieee80211_node_table *))
2091{
2092
2093	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
2094		"%s %s table, inact %u\n", __func__, name, inact);
2095
2096	nt->nt_ic = ic;
2097	/* XXX need unit */
2098	IEEE80211_NODE_LOCK_INIT(nt, ic->ic_ifp->if_xname);
2099	IEEE80211_SCAN_LOCK_INIT(nt, ic->ic_ifp->if_xname);
2100	TAILQ_INIT(&nt->nt_node);
2101	nt->nt_name = name;
2102	nt->nt_scangen = 1;
2103	nt->nt_inact_init = inact;
2104	nt->nt_timeout = timeout;
2105	nt->nt_keyixmax = keyixmax;
2106	if (nt->nt_keyixmax > 0) {
2107		MALLOC(nt->nt_keyixmap, struct ieee80211_node **,
2108			keyixmax * sizeof(struct ieee80211_node *),
2109			M_80211_NODE, M_NOWAIT | M_ZERO);
2110		if (nt->nt_keyixmap == NULL)
2111			if_printf(ic->ic_ifp,
2112			    "Cannot allocate key index map with %u entries\n",
2113			    keyixmax);
2114	} else
2115		nt->nt_keyixmap = NULL;
2116}
2117
2118void
2119ieee80211_node_table_reset(struct ieee80211_node_table *nt)
2120{
2121
2122	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
2123		"%s %s table\n", __func__, nt->nt_name);
2124
2125	IEEE80211_NODE_LOCK(nt);
2126	nt->nt_inact_timer = 0;
2127	ieee80211_free_allnodes_locked(nt);
2128	IEEE80211_NODE_UNLOCK(nt);
2129}
2130
2131static void
2132ieee80211_node_table_cleanup(struct ieee80211_node_table *nt)
2133{
2134
2135	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
2136		"%s %s table\n", __func__, nt->nt_name);
2137
2138	IEEE80211_NODE_LOCK(nt);
2139	ieee80211_free_allnodes_locked(nt);
2140	if (nt->nt_keyixmap != NULL) {
2141		/* XXX verify all entries are NULL */
2142		int i;
2143		for (i = 0; i < nt->nt_keyixmax; i++)
2144			if (nt->nt_keyixmap[i] != NULL)
2145				printf("%s: %s[%u] still active\n", __func__,
2146					nt->nt_name, i);
2147		FREE(nt->nt_keyixmap, M_80211_NODE);
2148		nt->nt_keyixmap = NULL;
2149	}
2150	IEEE80211_SCAN_LOCK_DESTROY(nt);
2151	IEEE80211_NODE_LOCK_DESTROY(nt);
2152}
2153