ieee80211_node.c revision 158121
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 158121 2006-04-28 19:06:15Z 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 void
221ieee80211_set_chan(struct ieee80211com *ic,
222	struct ieee80211_node *ni, struct ieee80211_channel *chan)
223{
224	if (chan == IEEE80211_CHAN_ANYC)	/* XXX while scanning */
225		chan = ic->ic_curchan;
226	ni->ni_chan = chan;
227	ni->ni_rates = ic->ic_sup_rates[ieee80211_chan2mode(ic, chan)];
228}
229
230/*
231 * AP scanning support.
232 */
233
234#ifdef IEEE80211_DEBUG
235static void
236dump_chanlist(const u_char chans[])
237{
238	const char *sep;
239	int i;
240
241	sep = " ";
242	for (i = 0; i < IEEE80211_CHAN_MAX; i++)
243		if (isset(chans, i)) {
244			printf("%s%u", sep, i);
245			sep = ", ";
246		}
247}
248#endif /* IEEE80211_DEBUG */
249
250/*
251 * Initialize the channel set to scan based on the
252 * of available channels and the current PHY mode.
253 */
254static void
255ieee80211_reset_scan(struct ieee80211com *ic)
256{
257
258	/* XXX ic_des_chan should be handled with ic_chan_active */
259	if (ic->ic_des_chan != IEEE80211_CHAN_ANYC) {
260		memset(ic->ic_chan_scan, 0, sizeof(ic->ic_chan_scan));
261		setbit(ic->ic_chan_scan,
262			ieee80211_chan2ieee(ic, ic->ic_des_chan));
263	} else
264		memcpy(ic->ic_chan_scan, ic->ic_chan_active,
265			sizeof(ic->ic_chan_active));
266#ifdef IEEE80211_DEBUG
267	if (ieee80211_msg_scan(ic)) {
268		printf("%s: scan set:", __func__);
269		dump_chanlist(ic->ic_chan_scan);
270		printf(" start chan %u\n",
271			ieee80211_chan2ieee(ic, ic->ic_curchan));
272	}
273#endif /* IEEE80211_DEBUG */
274}
275
276/*
277 * Begin an active scan.
278 */
279void
280ieee80211_begin_scan(struct ieee80211com *ic, int reset)
281{
282
283	ic->ic_scan.nt_scangen++;
284	/*
285	 * In all but hostap mode scanning starts off in
286	 * an active mode before switching to passive.
287	 */
288	if (ic->ic_opmode != IEEE80211_M_HOSTAP) {
289		ic->ic_flags |= IEEE80211_F_ASCAN;
290		ic->ic_stats.is_scan_active++;
291	} else
292		ic->ic_stats.is_scan_passive++;
293	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
294		"begin %s scan in %s mode, scangen %u\n",
295		(ic->ic_flags & IEEE80211_F_ASCAN) ?  "active" : "passive",
296		ieee80211_phymode_name[ic->ic_curmode], ic->ic_scan.nt_scangen);
297	/*
298	 * Clear scan state and flush any previously seen AP's.
299	 */
300	ieee80211_reset_scan(ic);
301	if (reset)
302		ieee80211_free_allnodes(&ic->ic_scan);
303
304	ic->ic_flags |= IEEE80211_F_SCAN;
305
306	/* Scan the next channel. */
307	ieee80211_next_scan(ic);
308}
309
310/*
311 * Switch to the next channel marked for scanning.
312 */
313int
314ieee80211_next_scan(struct ieee80211com *ic)
315{
316	struct ieee80211_channel *chan;
317
318	/*
319	 * Insure any previous mgt frame timeouts don't fire.
320	 * This assumes the driver does the right thing in
321	 * flushing anything queued in the driver and below.
322	 */
323	ic->ic_mgt_timer = 0;
324	ic->ic_flags_ext &= ~IEEE80211_FEXT_PROBECHAN;
325
326	chan = ic->ic_curchan;
327	do {
328		if (++chan > &ic->ic_channels[IEEE80211_CHAN_MAX])
329			chan = &ic->ic_channels[0];
330		if (isset(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan))) {
331			clrbit(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan));
332			IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
333			    "%s: chan %d->%d\n", __func__,
334			    ieee80211_chan2ieee(ic, ic->ic_curchan),
335			    ieee80211_chan2ieee(ic, chan));
336			ic->ic_curchan = chan;
337			/*
338			 * XXX drivers should do this as needed,
339			 * XXX for now maintain compatibility
340			 */
341			ic->ic_bss->ni_rates =
342				ic->ic_sup_rates[ieee80211_chan2mode(ic, chan)];
343			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
344			return 1;
345		}
346	} while (chan != ic->ic_curchan);
347	ieee80211_end_scan(ic);
348	return 0;
349}
350
351/*
352 * Probe the curent channel, if allowed, while scanning.
353 * If the channel is not marked passive-only then send
354 * a probe request immediately.  Otherwise mark state and
355 * listen for beacons on the channel; if we receive something
356 * then we'll transmit a probe request.
357 */
358void
359ieee80211_probe_curchan(struct ieee80211com *ic, int force)
360{
361	struct ifnet *ifp = ic->ic_ifp;
362
363	if ((ic->ic_curchan->ic_flags & IEEE80211_CHAN_PASSIVE) == 0 || force) {
364		/*
365		 * XXX send both broadcast+directed probe request
366		 */
367		ieee80211_send_probereq(ic->ic_bss,
368			ic->ic_myaddr, ifp->if_broadcastaddr,
369			ifp->if_broadcastaddr,
370			ic->ic_des_essid, ic->ic_des_esslen,
371			ic->ic_opt_ie, ic->ic_opt_ie_len);
372	} else
373		ic->ic_flags_ext |= IEEE80211_FEXT_PROBECHAN;
374}
375
376static __inline void
377copy_bss(struct ieee80211_node *nbss, const struct ieee80211_node *obss)
378{
379	/* propagate useful state */
380	nbss->ni_authmode = obss->ni_authmode;
381	nbss->ni_txpower = obss->ni_txpower;
382	nbss->ni_vlan = obss->ni_vlan;
383	nbss->ni_rsn = obss->ni_rsn;
384	/* XXX statistics? */
385}
386
387void
388ieee80211_create_ibss(struct ieee80211com* ic, struct ieee80211_channel *chan)
389{
390	struct ieee80211_node_table *nt;
391	struct ieee80211_node *ni;
392
393	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
394		"%s: creating ibss\n", __func__);
395
396	/*
397	 * Create the station/neighbor table.  Note that for adhoc
398	 * mode we make the initial inactivity timer longer since
399	 * we create nodes only through discovery and they typically
400	 * are long-lived associations.
401	 */
402	nt = &ic->ic_sta;
403	IEEE80211_NODE_LOCK(nt);
404	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
405		nt->nt_name = "station";
406		nt->nt_inact_init = ic->ic_inact_init;
407	} else {
408		nt->nt_name = "neighbor";
409		nt->nt_inact_init = ic->ic_inact_run;
410	}
411	IEEE80211_NODE_UNLOCK(nt);
412
413	ni = ieee80211_alloc_node(&ic->ic_sta, ic->ic_myaddr);
414	if (ni == NULL) {
415		/* XXX recovery? */
416		return;
417	}
418	IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_myaddr);
419	ni->ni_esslen = ic->ic_des_esslen;
420	memcpy(ni->ni_essid, ic->ic_des_essid, ni->ni_esslen);
421	copy_bss(ni, ic->ic_bss);
422	ni->ni_intval = ic->ic_bintval;
423	if (ic->ic_flags & IEEE80211_F_PRIVACY)
424		ni->ni_capinfo |= IEEE80211_CAPINFO_PRIVACY;
425	if (ic->ic_phytype == IEEE80211_T_FH) {
426		ni->ni_fhdwell = 200;	/* XXX */
427		ni->ni_fhindex = 1;
428	}
429	if (ic->ic_opmode == IEEE80211_M_IBSS) {
430		ic->ic_flags |= IEEE80211_F_SIBSS;
431		ni->ni_capinfo |= IEEE80211_CAPINFO_IBSS;	/* XXX */
432		if (ic->ic_flags & IEEE80211_F_DESBSSID)
433			IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_des_bssid);
434		else
435			ni->ni_bssid[0] |= 0x02;	/* local bit for IBSS */
436	} else if (ic->ic_opmode == IEEE80211_M_AHDEMO) {
437		if (ic->ic_flags & IEEE80211_F_DESBSSID)
438			IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_des_bssid);
439		else
440			memset(ni->ni_bssid, 0, IEEE80211_ADDR_LEN);
441	}
442	/*
443	 * Fix the channel and related attributes.
444	 */
445	ieee80211_set_chan(ic, ni, chan);
446	ic->ic_curchan = chan;
447	ic->ic_curmode = ieee80211_chan2mode(ic, chan);
448	/*
449	 * Do mode-specific rate setup.
450	 */
451	if (ic->ic_curmode == IEEE80211_MODE_11G) {
452		/*
453		 * Use a mixed 11b/11g rate set.
454		 */
455		ieee80211_set11gbasicrates(&ni->ni_rates, IEEE80211_MODE_11G);
456	} else if (ic->ic_curmode == IEEE80211_MODE_11B) {
457		/*
458		 * Force pure 11b rate set.
459		 */
460		ieee80211_set11gbasicrates(&ni->ni_rates, IEEE80211_MODE_11B);
461	}
462
463	(void) ieee80211_sta_join(ic, ieee80211_ref_node(ni));
464}
465
466void
467ieee80211_reset_bss(struct ieee80211com *ic)
468{
469	struct ieee80211_node *ni, *obss;
470
471	ieee80211_node_table_reset(&ic->ic_scan);
472	ieee80211_node_table_reset(&ic->ic_sta);
473
474	ni = ieee80211_alloc_node(&ic->ic_scan, ic->ic_myaddr);
475	KASSERT(ni != NULL, ("unable to setup inital BSS node"));
476	obss = ic->ic_bss;
477	ic->ic_bss = ieee80211_ref_node(ni);
478	if (obss != NULL) {
479		copy_bss(ni, obss);
480		ni->ni_intval = ic->ic_bintval;
481		ieee80211_free_node(obss);
482	}
483}
484
485/* XXX tunable */
486#define	STA_FAILS_MAX	2		/* assoc failures before ignored */
487
488static int
489ieee80211_match_bss(struct ieee80211com *ic, struct ieee80211_node *ni)
490{
491        u_int8_t rate;
492        int fail;
493
494	fail = 0;
495	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
496		fail |= 0x01;
497	if (ic->ic_des_chan != IEEE80211_CHAN_ANYC &&
498	    ni->ni_chan != ic->ic_des_chan)
499		fail |= 0x01;
500	if (ic->ic_opmode == IEEE80211_M_IBSS) {
501		if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
502			fail |= 0x02;
503	} else {
504		if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
505			fail |= 0x02;
506	}
507	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
508		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
509			fail |= 0x04;
510	} else {
511		/* XXX does this mean privacy is supported or required? */
512		if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
513			fail |= 0x04;
514	}
515	rate = ieee80211_fix_rate(ni, IEEE80211_F_DONEGO | IEEE80211_F_DOFRATE);
516	if (rate & IEEE80211_RATE_BASIC)
517		fail |= 0x08;
518	if (ic->ic_des_esslen != 0 &&
519	    (ni->ni_esslen != ic->ic_des_esslen ||
520	     memcmp(ni->ni_essid, ic->ic_des_essid, ic->ic_des_esslen) != 0))
521		fail |= 0x10;
522	if ((ic->ic_flags & IEEE80211_F_DESBSSID) &&
523	    !IEEE80211_ADDR_EQ(ic->ic_des_bssid, ni->ni_bssid))
524		fail |= 0x20;
525	if (ni->ni_fails >= STA_FAILS_MAX)
526		fail |= 0x40;
527#ifdef IEEE80211_DEBUG
528	if (ieee80211_msg_scan(ic)) {
529		printf(" %c %s",
530		    fail & 0x40 ? '=' : fail & 0x80 ? '^' : fail ? '-' : '+',
531		    ether_sprintf(ni->ni_macaddr));
532		printf(" %s%c", ether_sprintf(ni->ni_bssid),
533		    fail & 0x20 ? '!' : ' ');
534		printf(" %3d%c", ieee80211_chan2ieee(ic, ni->ni_chan),
535			fail & 0x01 ? '!' : ' ');
536		printf(" %+4d", ni->ni_rssi);
537		printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
538		    fail & 0x08 ? '!' : ' ');
539		printf(" %4s%c",
540		    (ni->ni_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
541		    (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
542		    "????",
543		    fail & 0x02 ? '!' : ' ');
544		printf(" %3s%c ",
545		    (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) ?
546		    "wep" : "no",
547		    fail & 0x04 ? '!' : ' ');
548		ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
549		printf("%s\n", fail & 0x10 ? "!" : "");
550	}
551#endif
552	return fail;
553}
554
555static __inline u_int8_t
556maxrate(const struct ieee80211_node *ni)
557{
558	const struct ieee80211_rateset *rs = &ni->ni_rates;
559	/* NB: assumes rate set is sorted (happens on frame receive) */
560	return rs->rs_rates[rs->rs_nrates-1] & IEEE80211_RATE_VAL;
561}
562
563/*
564 * Compare the capabilities of two nodes and decide which is
565 * more desirable (return >0 if a is considered better).  Note
566 * that we assume compatibility/usability has already been checked
567 * so we don't need to (e.g. validate whether privacy is supported).
568 * Used to select the best scan candidate for association in a BSS.
569 */
570static int
571ieee80211_node_compare(struct ieee80211com *ic,
572		       const struct ieee80211_node *a,
573		       const struct ieee80211_node *b)
574{
575	u_int8_t maxa, maxb;
576	u_int8_t rssia, rssib;
577	int weight;
578
579	/* privacy support preferred */
580	if ((a->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) &&
581	    (b->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
582		return 1;
583	if ((a->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0 &&
584	    (b->ni_capinfo & IEEE80211_CAPINFO_PRIVACY))
585		return -1;
586
587	/* compare count of previous failures */
588	weight = b->ni_fails - a->ni_fails;
589	if (abs(weight) > 1)
590		return weight;
591
592	rssia = ic->ic_node_getrssi(a);
593	rssib = ic->ic_node_getrssi(b);
594	if (abs(rssib - rssia) < 5) {
595		/* best/max rate preferred if signal level close enough XXX */
596		maxa = maxrate(a);
597		maxb = maxrate(b);
598		if (maxa != maxb)
599			return maxa - maxb;
600		/* XXX use freq for channel preference */
601		/* for now just prefer 5Ghz band to all other bands */
602		if (IEEE80211_IS_CHAN_5GHZ(a->ni_chan) &&
603		   !IEEE80211_IS_CHAN_5GHZ(b->ni_chan))
604			return 1;
605		if (!IEEE80211_IS_CHAN_5GHZ(a->ni_chan) &&
606		     IEEE80211_IS_CHAN_5GHZ(b->ni_chan))
607			return -1;
608	}
609	/* all things being equal, use signal level */
610	return rssia - rssib;
611}
612
613/*
614 * Mark an ongoing scan stopped.
615 */
616void
617ieee80211_cancel_scan(struct ieee80211com *ic)
618{
619
620	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN, "%s: end %s scan\n",
621		__func__,
622		(ic->ic_flags & IEEE80211_F_ASCAN) ?  "active" : "passive");
623
624	ic->ic_flags &= ~(IEEE80211_F_SCAN | IEEE80211_F_ASCAN);
625	ic->ic_flags_ext &= ~IEEE80211_FEXT_PROBECHAN;
626}
627
628/*
629 * Complete a scan of potential channels.
630 */
631void
632ieee80211_end_scan(struct ieee80211com *ic)
633{
634	struct ieee80211_node_table *nt = &ic->ic_scan;
635	struct ieee80211_node *ni, *selbs;
636
637	ieee80211_cancel_scan(ic);
638	ieee80211_notify_scan_done(ic);
639
640	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
641		u_int8_t maxrssi[IEEE80211_CHAN_MAX];	/* XXX off stack? */
642		int i, bestchan;
643		u_int8_t rssi;
644
645		/*
646		 * The passive scan to look for existing AP's completed,
647		 * select a channel to camp on.  Identify the channels
648		 * that already have one or more AP's and try to locate
649		 * an unoccupied one.  If that fails, pick a channel that
650		 * looks to be quietest.
651		 */
652		memset(maxrssi, 0, sizeof(maxrssi));
653		IEEE80211_NODE_LOCK(nt);
654		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
655			rssi = ic->ic_node_getrssi(ni);
656			i = ieee80211_chan2ieee(ic, ni->ni_chan);
657			if (rssi > maxrssi[i])
658				maxrssi[i] = rssi;
659		}
660		IEEE80211_NODE_UNLOCK(nt);
661		/* XXX select channel more intelligently */
662		bestchan = -1;
663		for (i = 0; i < IEEE80211_CHAN_MAX; i++)
664			if (isset(ic->ic_chan_active, i)) {
665				/*
666				 * If the channel is unoccupied the max rssi
667				 * should be zero; just take it.  Otherwise
668				 * track the channel with the lowest rssi and
669				 * use that when all channels appear occupied.
670				 */
671				if (maxrssi[i] == 0) {
672					bestchan = i;
673					break;
674				}
675				if (bestchan == -1 ||
676				    maxrssi[i] < maxrssi[bestchan])
677					bestchan = i;
678			}
679		if (bestchan != -1) {
680			ieee80211_create_ibss(ic, &ic->ic_channels[bestchan]);
681			return;
682		}
683		/* no suitable channel, should not happen */
684	}
685
686	/*
687	 * When manually sequencing the state machine; scan just once
688	 * regardless of whether we have a candidate or not.  The
689	 * controlling application is expected to setup state and
690	 * initiate an association.
691	 */
692	if (ic->ic_roaming == IEEE80211_ROAMING_MANUAL)
693		return;
694	/*
695	 * Automatic sequencing; look for a candidate and
696	 * if found join the network.
697	 */
698	/* NB: unlocked read should be ok */
699	if (TAILQ_FIRST(&nt->nt_node) == NULL) {
700		IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
701			"%s: no scan candidate\n", __func__);
702  notfound:
703		if (ic->ic_opmode == IEEE80211_M_IBSS &&
704		    (ic->ic_flags & IEEE80211_F_IBSSON) &&
705		    ic->ic_des_esslen != 0) {
706			ieee80211_create_ibss(ic, ic->ic_ibss_chan);
707			return;
708		}
709		/*
710		 * Decrement the failure counts so entries will be
711		 * reconsidered the next time around.  We really want
712		 * to do this only for sta's where we've previously
713		 * had some success.
714		 */
715		IEEE80211_NODE_LOCK(nt);
716		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
717			if (ni->ni_fails)
718				ni->ni_fails--;
719		IEEE80211_NODE_UNLOCK(nt);
720		/*
721		 * Reset the list of channels to scan and start again.
722		 */
723		ieee80211_reset_scan(ic);
724		ic->ic_flags |= IEEE80211_F_SCAN;
725		ieee80211_next_scan(ic);
726		return;
727	}
728	selbs = NULL;
729	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN, "\t%s\n",
730	    "macaddr          bssid         chan  rssi rate flag  wep  essid");
731	IEEE80211_NODE_LOCK(nt);
732	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
733		if (ieee80211_match_bss(ic, ni) == 0) {
734			if (selbs == NULL)
735				selbs = ni;
736			else if (ieee80211_node_compare(ic, ni, selbs) > 0)
737				selbs = ni;
738		}
739	}
740	if (selbs != NULL)		/* NB: grab ref while dropping lock */
741		(void) ieee80211_ref_node(selbs);
742	IEEE80211_NODE_UNLOCK(nt);
743	if (selbs == NULL)
744		goto notfound;
745	if (!ieee80211_sta_join(ic, selbs)) {
746		ieee80211_free_node(selbs);
747		goto notfound;
748	}
749}
750
751/*
752 * Handle 802.11 ad hoc network merge.  The
753 * convention, set by the Wireless Ethernet Compatibility Alliance
754 * (WECA), is that an 802.11 station will change its BSSID to match
755 * the "oldest" 802.11 ad hoc network, on the same channel, that
756 * has the station's desired SSID.  The "oldest" 802.11 network
757 * sends beacons with the greatest TSF timestamp.
758 *
759 * The caller is assumed to validate TSF's before attempting a merge.
760 *
761 * Return !0 if the BSSID changed, 0 otherwise.
762 */
763int
764ieee80211_ibss_merge(struct ieee80211_node *ni)
765{
766	struct ieee80211com *ic = ni->ni_ic;
767
768	if (ni == ic->ic_bss ||
769	    IEEE80211_ADDR_EQ(ni->ni_bssid, ic->ic_bss->ni_bssid)) {
770		/* unchanged, nothing to do */
771		return 0;
772	}
773	if (ieee80211_match_bss(ic, ni) != 0) {	/* capabilities mismatch */
774		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
775		    "%s: merge failed, capabilities mismatch\n", __func__);
776		ic->ic_stats.is_ibss_capmismatch++;
777		return 0;
778	}
779	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
780		"%s: new bssid %s: %s preamble, %s slot time%s\n", __func__,
781		ether_sprintf(ni->ni_bssid),
782		ic->ic_flags&IEEE80211_F_SHPREAMBLE ? "short" : "long",
783		ic->ic_flags&IEEE80211_F_SHSLOT ? "short" : "long",
784		ic->ic_flags&IEEE80211_F_USEPROT ? ", protection" : ""
785	);
786	return ieee80211_sta_join(ic, ieee80211_ref_node(ni));
787}
788
789/*
790 * Join the specified IBSS/BSS network.  The node is assumed to
791 * be passed in with a held reference.
792 */
793int
794ieee80211_sta_join(struct ieee80211com *ic, struct ieee80211_node *selbs)
795{
796	struct ieee80211_node *obss;
797
798	if (ic->ic_opmode == IEEE80211_M_IBSS) {
799		struct ieee80211_node_table *nt;
800		/*
801		 * Delete unusable rates; we've already checked
802		 * that the negotiated rate set is acceptable.
803		 */
804		ieee80211_fix_rate(selbs, IEEE80211_F_DODEL);
805		/*
806		 * Fillin the neighbor table; it will already
807		 * exist if we are simply switching mastership.
808		 * XXX ic_sta always setup so this is unnecessary?
809		 */
810		nt = &ic->ic_sta;
811		IEEE80211_NODE_LOCK(nt);
812		nt->nt_name = "neighbor";
813		nt->nt_inact_init = ic->ic_inact_run;
814		IEEE80211_NODE_UNLOCK(nt);
815	}
816
817	/*
818	 * Committed to selbs, setup state.
819	 */
820	obss = ic->ic_bss;
821	ic->ic_bss = selbs;		/* NB: caller assumed to bump refcnt */
822	if (obss != NULL) {
823		copy_bss(selbs, obss);
824		ieee80211_free_node(obss);
825	}
826	/*
827	 * Set the erp state (mostly the slot time) to deal with
828	 * the auto-select case; this should be redundant if the
829	 * mode is locked.
830	 */
831	ic->ic_curmode = ieee80211_chan2mode(ic, selbs->ni_chan);
832	ic->ic_curchan = selbs->ni_chan;
833	ieee80211_reset_erp(ic);
834	ieee80211_wme_initparams(ic);
835
836	if (ic->ic_opmode == IEEE80211_M_STA)
837		ieee80211_new_state(ic, IEEE80211_S_AUTH, -1);
838	else
839		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
840	return 1;
841}
842
843/*
844 * Leave the specified IBSS/BSS network.  The node is assumed to
845 * be passed in with a held reference.
846 */
847void
848ieee80211_sta_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
849{
850	ic->ic_node_cleanup(ni);
851	ieee80211_notify_node_leave(ic, ni);
852}
853
854static struct ieee80211_node *
855node_alloc(struct ieee80211_node_table *nt)
856{
857	struct ieee80211_node *ni;
858
859	MALLOC(ni, struct ieee80211_node *, sizeof(struct ieee80211_node),
860		M_80211_NODE, M_NOWAIT | M_ZERO);
861	return ni;
862}
863
864/*
865 * Reclaim any resources in a node and reset any critical
866 * state.  Typically nodes are free'd immediately after,
867 * but in some cases the storage may be reused so we need
868 * to insure consistent state (should probably fix that).
869 */
870static void
871node_cleanup(struct ieee80211_node *ni)
872{
873#define	N(a)	(sizeof(a)/sizeof(a[0]))
874	struct ieee80211com *ic = ni->ni_ic;
875	int i, qlen;
876
877	/* NB: preserve ni_table */
878	if (ni->ni_flags & IEEE80211_NODE_PWR_MGT) {
879		ic->ic_ps_sta--;
880		ni->ni_flags &= ~IEEE80211_NODE_PWR_MGT;
881		IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
882		    "[%s] power save mode off, %u sta's in ps mode\n",
883		    ether_sprintf(ni->ni_macaddr), ic->ic_ps_sta);
884	}
885	/*
886	 * Clear AREF flag that marks the authorization refcnt bump
887	 * has happened.  This is probably not needed as the node
888	 * should always be removed from the table so not found but
889	 * do it just in case.
890	 */
891	ni->ni_flags &= ~IEEE80211_NODE_AREF;
892
893	/*
894	 * Drain power save queue and, if needed, clear TIM.
895	 */
896	IEEE80211_NODE_SAVEQ_DRAIN(ni, qlen);
897	if (qlen != 0 && ic->ic_set_tim != NULL)
898		ic->ic_set_tim(ni, 0);
899
900	ni->ni_associd = 0;
901	if (ni->ni_challenge != NULL) {
902		FREE(ni->ni_challenge, M_DEVBUF);
903		ni->ni_challenge = NULL;
904	}
905	/*
906	 * Preserve SSID, WPA, and WME ie's so the bss node is
907	 * reusable during a re-auth/re-assoc state transition.
908	 * If we remove these data they will not be recreated
909	 * because they come from a probe-response or beacon frame
910	 * which cannot be expected prior to the association-response.
911	 * This should not be an issue when operating in other modes
912	 * as stations leaving always go through a full state transition
913	 * which will rebuild this state.
914	 *
915	 * XXX does this leave us open to inheriting old state?
916	 */
917	for (i = 0; i < N(ni->ni_rxfrag); i++)
918		if (ni->ni_rxfrag[i] != NULL) {
919			m_freem(ni->ni_rxfrag[i]);
920			ni->ni_rxfrag[i] = NULL;
921		}
922	/*
923	 * Must be careful here to remove any key map entry w/o a LOR.
924	 */
925	ieee80211_node_delucastkey(ni);
926#undef N
927}
928
929static void
930node_free(struct ieee80211_node *ni)
931{
932	struct ieee80211com *ic = ni->ni_ic;
933
934	ic->ic_node_cleanup(ni);
935	if (ni->ni_wpa_ie != NULL)
936		FREE(ni->ni_wpa_ie, M_DEVBUF);
937	if (ni->ni_wme_ie != NULL)
938		FREE(ni->ni_wme_ie, M_DEVBUF);
939	IEEE80211_NODE_SAVEQ_DESTROY(ni);
940	FREE(ni, M_80211_NODE);
941}
942
943static u_int8_t
944node_getrssi(const struct ieee80211_node *ni)
945{
946	return ni->ni_rssi;
947}
948
949static void
950ieee80211_setup_node(struct ieee80211_node_table *nt,
951	struct ieee80211_node *ni, const u_int8_t *macaddr)
952{
953	struct ieee80211com *ic = nt->nt_ic;
954	int hash;
955
956	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
957		"%s %p<%s> in %s table\n", __func__, ni,
958		ether_sprintf(macaddr), nt->nt_name);
959
960	IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
961	hash = IEEE80211_NODE_HASH(macaddr);
962	ieee80211_node_initref(ni);		/* mark referenced */
963	ni->ni_chan = IEEE80211_CHAN_ANYC;
964	ni->ni_authmode = IEEE80211_AUTH_OPEN;
965	ni->ni_txpower = ic->ic_txpowlimit;	/* max power */
966	ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey, IEEE80211_KEYIX_NONE);
967	ni->ni_inact_reload = nt->nt_inact_init;
968	ni->ni_inact = ni->ni_inact_reload;
969	IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
970
971	IEEE80211_NODE_LOCK(nt);
972	TAILQ_INSERT_TAIL(&nt->nt_node, ni, ni_list);
973	LIST_INSERT_HEAD(&nt->nt_hash[hash], ni, ni_hash);
974	ni->ni_table = nt;
975	ni->ni_ic = ic;
976	IEEE80211_NODE_UNLOCK(nt);
977}
978
979struct ieee80211_node *
980ieee80211_alloc_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
981{
982	struct ieee80211com *ic = nt->nt_ic;
983	struct ieee80211_node *ni;
984
985	ni = ic->ic_node_alloc(nt);
986	if (ni != NULL)
987		ieee80211_setup_node(nt, ni, macaddr);
988	else
989		ic->ic_stats.is_rx_nodealloc++;
990	return ni;
991}
992
993/*
994 * Craft a temporary node suitable for sending a management frame
995 * to the specified station.  We craft only as much state as we
996 * need to do the work since the node will be immediately reclaimed
997 * once the send completes.
998 */
999struct ieee80211_node *
1000ieee80211_tmp_node(struct ieee80211com *ic, const u_int8_t *macaddr)
1001{
1002	struct ieee80211_node *ni;
1003
1004	ni = ic->ic_node_alloc(&ic->ic_sta);
1005	if (ni != NULL) {
1006		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1007			"%s %p<%s>\n", __func__, ni, ether_sprintf(macaddr));
1008
1009		IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
1010		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
1011		ieee80211_node_initref(ni);		/* mark referenced */
1012		ni->ni_txpower = ic->ic_bss->ni_txpower;
1013		/* NB: required by ieee80211_fix_rate */
1014		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
1015		ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey,
1016			IEEE80211_KEYIX_NONE);
1017		/* XXX optimize away */
1018		IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
1019
1020		ni->ni_table = NULL;		/* NB: pedantic */
1021		ni->ni_ic = ic;
1022	} else {
1023		/* XXX msg */
1024		ic->ic_stats.is_rx_nodealloc++;
1025	}
1026	return ni;
1027}
1028
1029struct ieee80211_node *
1030ieee80211_dup_bss(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
1031{
1032	struct ieee80211com *ic = nt->nt_ic;
1033	struct ieee80211_node *ni;
1034
1035	ni = ic->ic_node_alloc(nt);
1036	if (ni != NULL) {
1037		ieee80211_setup_node(nt, ni, macaddr);
1038		/*
1039		 * Inherit from ic_bss.
1040		 */
1041		ni->ni_authmode = ic->ic_bss->ni_authmode;
1042		ni->ni_txpower = ic->ic_bss->ni_txpower;
1043		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
1044		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
1045		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
1046		ni->ni_rsn = ic->ic_bss->ni_rsn;
1047	} else
1048		ic->ic_stats.is_rx_nodealloc++;
1049	return ni;
1050}
1051
1052static struct ieee80211_node *
1053#ifdef IEEE80211_DEBUG_REFCNT
1054_ieee80211_find_node_debug(struct ieee80211_node_table *nt,
1055	const u_int8_t *macaddr, const char *func, int line)
1056#else
1057_ieee80211_find_node(struct ieee80211_node_table *nt,
1058	const u_int8_t *macaddr)
1059#endif
1060{
1061	struct ieee80211_node *ni;
1062	int hash;
1063
1064	IEEE80211_NODE_LOCK_ASSERT(nt);
1065
1066	hash = IEEE80211_NODE_HASH(macaddr);
1067	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1068		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
1069			ieee80211_ref_node(ni);	/* mark referenced */
1070#ifdef IEEE80211_DEBUG_REFCNT
1071			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1072			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1073			    func, line,
1074			    ni, ether_sprintf(ni->ni_macaddr),
1075			    ieee80211_node_refcnt(ni));
1076#endif
1077			return ni;
1078		}
1079	}
1080	return NULL;
1081}
1082#ifdef IEEE80211_DEBUG_REFCNT
1083#define	_ieee80211_find_node(nt, mac) \
1084	_ieee80211_find_node_debug(nt, mac, func, line)
1085#endif
1086
1087struct ieee80211_node *
1088#ifdef IEEE80211_DEBUG_REFCNT
1089ieee80211_find_node_debug(struct ieee80211_node_table *nt,
1090	const u_int8_t *macaddr, const char *func, int line)
1091#else
1092ieee80211_find_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
1093#endif
1094{
1095	struct ieee80211_node *ni;
1096
1097	IEEE80211_NODE_LOCK(nt);
1098	ni = _ieee80211_find_node(nt, macaddr);
1099	IEEE80211_NODE_UNLOCK(nt);
1100	return ni;
1101}
1102
1103/*
1104 * Fake up a node; this handles node discovery in adhoc mode.
1105 * Note that for the driver's benefit we we treat this like
1106 * an association so the driver has an opportunity to setup
1107 * it's private state.
1108 */
1109struct ieee80211_node *
1110ieee80211_fakeup_adhoc_node(struct ieee80211_node_table *nt,
1111	const u_int8_t macaddr[IEEE80211_ADDR_LEN])
1112{
1113	struct ieee80211com *ic = nt->nt_ic;
1114	struct ieee80211_node *ni;
1115
1116	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1117	    "%s: mac<%s>\n", __func__, ether_sprintf(macaddr));
1118	ni = ieee80211_dup_bss(nt, macaddr);
1119	if (ni != NULL) {
1120		/* XXX no rate negotiation; just dup */
1121		ni->ni_rates = ic->ic_bss->ni_rates;
1122		if (ic->ic_newassoc != NULL)
1123			ic->ic_newassoc(ni, 1);
1124		/* XXX not right for 802.1x/WPA */
1125		ieee80211_node_authorize(ni);
1126		if (ic->ic_opmode == IEEE80211_M_AHDEMO) {
1127			/*
1128			 * Blindly propagate capabilities based on the
1129			 * local configuration.  In particular this permits
1130			 * us to use QoS to disable ACK's.
1131			 */
1132			if (ic->ic_flags & IEEE80211_F_WME)
1133				ni->ni_flags |= IEEE80211_NODE_QOS;
1134		}
1135	}
1136	return ni;
1137}
1138
1139#ifdef IEEE80211_DEBUG
1140static void
1141dump_probe_beacon(u_int8_t subtype, int isnew,
1142	const u_int8_t mac[IEEE80211_ADDR_LEN],
1143	const struct ieee80211_scanparams *sp)
1144{
1145
1146	printf("[%s] %s%s on chan %u (bss chan %u) ",
1147	    ether_sprintf(mac), isnew ? "new " : "",
1148	    ieee80211_mgt_subtype_name[subtype >> IEEE80211_FC0_SUBTYPE_SHIFT],
1149	    sp->chan, sp->bchan);
1150	ieee80211_print_essid(sp->ssid + 2, sp->ssid[1]);
1151	printf("\n");
1152
1153	if (isnew) {
1154		printf("[%s] caps 0x%x bintval %u erp 0x%x",
1155			ether_sprintf(mac), sp->capinfo, sp->bintval, sp->erp);
1156		if (sp->country != NULL) {
1157#ifdef __FreeBSD__
1158			printf(" country info %*D",
1159				sp->country[1], sp->country+2, " ");
1160#else
1161			int i;
1162			printf(" country info");
1163			for (i = 0; i < sp->country[1]; i++)
1164				printf(" %02x", sp->country[i+2]);
1165#endif
1166		}
1167		printf("\n");
1168	}
1169}
1170#endif /* IEEE80211_DEBUG */
1171
1172static void
1173saveie(u_int8_t **iep, const u_int8_t *ie)
1174{
1175
1176	if (ie == NULL)
1177		*iep = NULL;
1178	else
1179		ieee80211_saveie(iep, ie);
1180}
1181
1182/*
1183 * Process a beacon or probe response frame.
1184 */
1185void
1186ieee80211_add_scan(struct ieee80211com *ic,
1187	const struct ieee80211_scanparams *sp,
1188	const struct ieee80211_frame *wh,
1189	int subtype, int rssi, int rstamp)
1190{
1191#define	ISPROBE(_st)	((_st) == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1192	struct ieee80211_node_table *nt = &ic->ic_scan;
1193	struct ieee80211_node *ni;
1194	int newnode = 0;
1195
1196	ni = ieee80211_find_node(nt, wh->i_addr2);
1197	if (ni == NULL) {
1198		/*
1199		 * Create a new entry.
1200		 */
1201		ni = ic->ic_node_alloc(nt);
1202		if (ni == NULL) {
1203			ic->ic_stats.is_rx_nodealloc++;
1204			return;
1205		}
1206		ieee80211_setup_node(nt, ni, wh->i_addr2);
1207		/*
1208		 * XXX inherit from ic_bss.
1209		 */
1210		ni->ni_authmode = ic->ic_bss->ni_authmode;
1211		ni->ni_txpower = ic->ic_bss->ni_txpower;
1212		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
1213		ieee80211_set_chan(ic, ni, ic->ic_curchan);
1214		ni->ni_rsn = ic->ic_bss->ni_rsn;
1215		newnode = 1;
1216	}
1217#ifdef IEEE80211_DEBUG
1218	if (ieee80211_msg_scan(ic) && (ic->ic_flags & IEEE80211_F_SCAN))
1219		dump_probe_beacon(subtype, newnode, wh->i_addr2, sp);
1220#endif
1221	/* XXX ap beaconing multiple ssid w/ same bssid */
1222	if (sp->ssid[1] != 0 &&
1223	    (ISPROBE(subtype) || ni->ni_esslen == 0)) {
1224		ni->ni_esslen = sp->ssid[1];
1225		memset(ni->ni_essid, 0, sizeof(ni->ni_essid));
1226		memcpy(ni->ni_essid, sp->ssid + 2, sp->ssid[1]);
1227	}
1228	ni->ni_scangen = ic->ic_scan.nt_scangen;
1229	IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
1230	ni->ni_rssi = rssi;
1231	ni->ni_rstamp = rstamp;
1232	memcpy(ni->ni_tstamp.data, sp->tstamp, sizeof(ni->ni_tstamp));
1233	ni->ni_intval = sp->bintval;
1234	ni->ni_capinfo = sp->capinfo;
1235	ni->ni_chan = &ic->ic_channels[sp->chan];
1236	ni->ni_fhdwell = sp->fhdwell;
1237	ni->ni_fhindex = sp->fhindex;
1238	ni->ni_erp = sp->erp;
1239	if (sp->tim != NULL) {
1240		struct ieee80211_tim_ie *ie =
1241		    (struct ieee80211_tim_ie *) sp->tim;
1242
1243		ni->ni_dtim_count = ie->tim_count;
1244		ni->ni_dtim_period = ie->tim_period;
1245	}
1246	/*
1247	 * Record the byte offset from the mac header to
1248	 * the start of the TIM information element for
1249	 * use by hardware and/or to speedup software
1250	 * processing of beacon frames.
1251	 */
1252	ni->ni_timoff = sp->timoff;
1253	/*
1254	 * Record optional information elements that might be
1255	 * used by applications or drivers.
1256	 */
1257	saveie(&ni->ni_wme_ie, sp->wme);
1258	saveie(&ni->ni_wpa_ie, sp->wpa);
1259
1260	/* NB: must be after ni_chan is setup */
1261	ieee80211_setup_rates(ni, sp->rates, sp->xrates, IEEE80211_F_DOSORT);
1262
1263	if (!newnode)
1264		ieee80211_free_node(ni);
1265#undef ISPROBE
1266}
1267
1268void
1269ieee80211_init_neighbor(struct ieee80211_node *ni,
1270	const struct ieee80211_frame *wh,
1271	const struct ieee80211_scanparams *sp)
1272{
1273
1274	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1275	    "%s: %p<%s>\n", __func__, ni, ether_sprintf(ni->ni_macaddr));
1276	ni->ni_esslen = sp->ssid[1];
1277	memcpy(ni->ni_essid, sp->ssid + 2, sp->ssid[1]);
1278	IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
1279	memcpy(ni->ni_tstamp.data, sp->tstamp, sizeof(ni->ni_tstamp));
1280	ni->ni_intval = sp->bintval;
1281	ni->ni_capinfo = sp->capinfo;
1282	ni->ni_chan = ni->ni_ic->ic_curchan;
1283	ni->ni_fhdwell = sp->fhdwell;
1284	ni->ni_fhindex = sp->fhindex;
1285	ni->ni_erp = sp->erp;
1286	ni->ni_timoff = sp->timoff;
1287	if (sp->wme != NULL)
1288		ieee80211_saveie(&ni->ni_wme_ie, sp->wme);
1289	if (sp->wpa != NULL)
1290		ieee80211_saveie(&ni->ni_wpa_ie, sp->wpa);
1291
1292	/* NB: must be after ni_chan is setup */
1293	ieee80211_setup_rates(ni, sp->rates, sp->xrates, IEEE80211_F_DOSORT);
1294}
1295
1296/*
1297 * Do node discovery in adhoc mode on receipt of a beacon
1298 * or probe response frame.  Note that for the driver's
1299 * benefit we we treat this like an association so the
1300 * driver has an opportunity to setup it's private state.
1301 */
1302struct ieee80211_node *
1303ieee80211_add_neighbor(struct ieee80211com *ic,
1304	const struct ieee80211_frame *wh,
1305	const struct ieee80211_scanparams *sp)
1306{
1307	struct ieee80211_node *ni;
1308
1309	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1310	    "%s: mac<%s>\n", __func__, ether_sprintf(wh->i_addr2));
1311	ni = ieee80211_dup_bss(&ic->ic_sta, wh->i_addr2);/* XXX alloc_node? */
1312	if (ni != NULL) {
1313		ieee80211_init_neighbor(ni, wh, sp);
1314		if (ic->ic_newassoc != NULL)
1315			ic->ic_newassoc(ni, 1);
1316		/* XXX not right for 802.1x/WPA */
1317		ieee80211_node_authorize(ni);
1318	}
1319	return ni;
1320}
1321
1322#define	IS_CTL(wh) \
1323	((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_CTL)
1324#define	IS_PSPOLL(wh) \
1325	((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_PS_POLL)
1326/*
1327 * Locate the node for sender, track state, and then pass the
1328 * (referenced) node up to the 802.11 layer for its use.  We
1329 * are required to pass some node so we fall back to ic_bss
1330 * when this frame is from an unknown sender.  The 802.11 layer
1331 * knows this means the sender wasn't in the node table and
1332 * acts accordingly.
1333 */
1334struct ieee80211_node *
1335#ifdef IEEE80211_DEBUG_REFCNT
1336ieee80211_find_rxnode_debug(struct ieee80211com *ic,
1337	const struct ieee80211_frame_min *wh, const char *func, int line)
1338#else
1339ieee80211_find_rxnode(struct ieee80211com *ic,
1340	const struct ieee80211_frame_min *wh)
1341#endif
1342{
1343	struct ieee80211_node_table *nt;
1344	struct ieee80211_node *ni;
1345
1346	/* XXX may want scanned nodes in the neighbor table for adhoc */
1347	if (ic->ic_opmode == IEEE80211_M_STA ||
1348	    ic->ic_opmode == IEEE80211_M_MONITOR ||
1349	    (ic->ic_flags & IEEE80211_F_SCAN))
1350		nt = &ic->ic_scan;
1351	else
1352		nt = &ic->ic_sta;
1353	/* XXX check ic_bss first in station mode */
1354	/* XXX 4-address frames? */
1355	IEEE80211_NODE_LOCK(nt);
1356	if (IS_CTL(wh) && !IS_PSPOLL(wh) /*&& !IS_RTS(ah)*/)
1357		ni = _ieee80211_find_node(nt, wh->i_addr1);
1358	else
1359		ni = _ieee80211_find_node(nt, wh->i_addr2);
1360	if (ni == NULL)
1361		ni = ieee80211_ref_node(ic->ic_bss);
1362	IEEE80211_NODE_UNLOCK(nt);
1363
1364	return ni;
1365}
1366
1367/*
1368 * Like ieee80211_find_rxnode but use the supplied h/w
1369 * key index as a hint to locate the node in the key
1370 * mapping table.  If an entry is present at the key
1371 * index we return it; otherwise do a normal lookup and
1372 * update the mapping table if the station has a unicast
1373 * key assigned to it.
1374 */
1375struct ieee80211_node *
1376#ifdef IEEE80211_DEBUG_REFCNT
1377ieee80211_find_rxnode_withkey_debug(struct ieee80211com *ic,
1378	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix,
1379	const char *func, int line)
1380#else
1381ieee80211_find_rxnode_withkey(struct ieee80211com *ic,
1382	const struct ieee80211_frame_min *wh, ieee80211_keyix keyix)
1383#endif
1384{
1385	struct ieee80211_node_table *nt;
1386	struct ieee80211_node *ni;
1387
1388	if (ic->ic_opmode == IEEE80211_M_STA ||
1389	    ic->ic_opmode == IEEE80211_M_MONITOR ||
1390	    (ic->ic_flags & IEEE80211_F_SCAN))
1391		nt = &ic->ic_scan;
1392	else
1393		nt = &ic->ic_sta;
1394	IEEE80211_NODE_LOCK(nt);
1395	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax)
1396		ni = nt->nt_keyixmap[keyix];
1397	else
1398		ni = NULL;
1399	if (ni == NULL) {
1400		if (IS_CTL(wh) && !IS_PSPOLL(wh) /*&& !IS_RTS(ah)*/)
1401			ni = _ieee80211_find_node(nt, wh->i_addr1);
1402		else
1403			ni = _ieee80211_find_node(nt, wh->i_addr2);
1404		if (ni == NULL)
1405			ni = ieee80211_ref_node(ic->ic_bss);
1406		if (nt->nt_keyixmap != NULL) {
1407			/*
1408			 * If the station has a unicast key cache slot
1409			 * assigned update the key->node mapping table.
1410			 */
1411			keyix = ni->ni_ucastkey.wk_rxkeyix;
1412			/* XXX can keyixmap[keyix] != NULL? */
1413			if (keyix < nt->nt_keyixmax &&
1414			    nt->nt_keyixmap[keyix] == NULL) {
1415				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1416				    "%s: add key map entry %p<%s> refcnt %d\n",
1417				    __func__, ni, ether_sprintf(ni->ni_macaddr),
1418				    ieee80211_node_refcnt(ni)+1);
1419				nt->nt_keyixmap[keyix] = ieee80211_ref_node(ni);
1420			}
1421		}
1422	} else {
1423		ieee80211_ref_node(ni);
1424	}
1425	IEEE80211_NODE_UNLOCK(nt);
1426
1427	return ni;
1428}
1429#undef IS_PSPOLL
1430#undef IS_CTL
1431
1432/*
1433 * Return a reference to the appropriate node for sending
1434 * a data frame.  This handles node discovery in adhoc networks.
1435 */
1436struct ieee80211_node *
1437#ifdef IEEE80211_DEBUG_REFCNT
1438ieee80211_find_txnode_debug(struct ieee80211com *ic, const u_int8_t *macaddr,
1439	const char *func, int line)
1440#else
1441ieee80211_find_txnode(struct ieee80211com *ic, const u_int8_t *macaddr)
1442#endif
1443{
1444	struct ieee80211_node_table *nt = &ic->ic_sta;
1445	struct ieee80211_node *ni;
1446
1447	/*
1448	 * The destination address should be in the node table
1449	 * unless this is a multicast/broadcast frame.  We can
1450	 * also optimize station mode operation, all frames go
1451	 * to the bss node.
1452	 */
1453	/* XXX can't hold lock across dup_bss 'cuz of recursive locking */
1454	IEEE80211_NODE_LOCK(nt);
1455	if (ic->ic_opmode == IEEE80211_M_STA || IEEE80211_IS_MULTICAST(macaddr))
1456		ni = ieee80211_ref_node(ic->ic_bss);
1457	else {
1458		ni = _ieee80211_find_node(nt, macaddr);
1459		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
1460		    (ni != NULL && ni->ni_associd == 0)) {
1461			/*
1462			 * Station is not associated; don't permit the
1463			 * data frame to be sent by returning NULL.  This
1464			 * is kinda a kludge but the least intrusive way
1465			 * to add this check into all drivers.
1466			 */
1467			ieee80211_unref_node(&ni);	/* NB: null's ni */
1468		}
1469	}
1470	IEEE80211_NODE_UNLOCK(nt);
1471
1472	if (ni == NULL) {
1473		if (ic->ic_opmode == IEEE80211_M_IBSS ||
1474		    ic->ic_opmode == IEEE80211_M_AHDEMO) {
1475			/*
1476			 * In adhoc mode cons up a node for the destination.
1477			 * Note that we need an additional reference for the
1478			 * caller to be consistent with _ieee80211_find_node.
1479			 */
1480			ni = ieee80211_fakeup_adhoc_node(nt, macaddr);
1481			if (ni != NULL)
1482				(void) ieee80211_ref_node(ni);
1483		} else {
1484			IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
1485				"[%s] no node, discard frame (%s)\n",
1486				ether_sprintf(macaddr), __func__);
1487			ic->ic_stats.is_tx_nonode++;
1488		}
1489	}
1490	return ni;
1491}
1492
1493/*
1494 * Like find but search based on the channel too.
1495 */
1496struct ieee80211_node *
1497#ifdef IEEE80211_DEBUG_REFCNT
1498ieee80211_find_node_with_channel_debug(struct ieee80211_node_table *nt,
1499	const u_int8_t *macaddr, struct ieee80211_channel *chan,
1500	const char *func, int line)
1501#else
1502ieee80211_find_node_with_channel(struct ieee80211_node_table *nt,
1503	const u_int8_t *macaddr, struct ieee80211_channel *chan)
1504#endif
1505{
1506	struct ieee80211_node *ni;
1507	int hash;
1508
1509	hash = IEEE80211_NODE_HASH(macaddr);
1510	IEEE80211_NODE_LOCK(nt);
1511	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1512		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1513		    ni->ni_chan == chan) {
1514			ieee80211_ref_node(ni);		/* mark referenced */
1515			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1516#ifdef IEEE80211_DEBUG_REFCNT
1517			    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1518			    func, line,
1519#else
1520			    "%s %p<%s> refcnt %d\n", __func__,
1521#endif
1522			    ni, ether_sprintf(ni->ni_macaddr),
1523			    ieee80211_node_refcnt(ni));
1524			break;
1525		}
1526	}
1527	IEEE80211_NODE_UNLOCK(nt);
1528	return ni;
1529}
1530
1531/*
1532 * Like find but search based on the ssid too.
1533 */
1534struct ieee80211_node *
1535#ifdef IEEE80211_DEBUG_REFCNT
1536ieee80211_find_node_with_ssid_debug(struct ieee80211_node_table *nt,
1537	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid,
1538	const char *func, int line)
1539#else
1540ieee80211_find_node_with_ssid(struct ieee80211_node_table *nt,
1541	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid)
1542#endif
1543{
1544#define	MATCH_SSID(ni, ssid, ssidlen) \
1545	(ni->ni_esslen == ssidlen && memcmp(ni->ni_essid, ssid, ssidlen) == 0)
1546	static const u_int8_t zeromac[IEEE80211_ADDR_LEN];
1547	struct ieee80211com *ic = nt->nt_ic;
1548	struct ieee80211_node *ni;
1549	int hash;
1550
1551	IEEE80211_NODE_LOCK(nt);
1552	/*
1553	 * A mac address that is all zero means match only the ssid;
1554	 * otherwise we must match both.
1555	 */
1556	if (IEEE80211_ADDR_EQ(macaddr, zeromac)) {
1557		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1558			if (MATCH_SSID(ni, ssid, ssidlen))
1559				break;
1560		}
1561	} else {
1562		hash = IEEE80211_NODE_HASH(macaddr);
1563		LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1564			if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1565			    MATCH_SSID(ni, ssid, ssidlen))
1566				break;
1567		}
1568	}
1569	if (ni != NULL) {
1570		ieee80211_ref_node(ni);	/* mark referenced */
1571		IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1572#ifdef IEEE80211_DEBUG_REFCNT
1573		    "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
1574		    func, line,
1575#else
1576		    "%s %p<%s> refcnt %d\n", __func__,
1577#endif
1578		     ni, ether_sprintf(ni->ni_macaddr),
1579		     ieee80211_node_refcnt(ni));
1580	}
1581	IEEE80211_NODE_UNLOCK(nt);
1582	return ni;
1583#undef MATCH_SSID
1584}
1585
1586static void
1587_ieee80211_free_node(struct ieee80211_node *ni)
1588{
1589	struct ieee80211com *ic = ni->ni_ic;
1590	struct ieee80211_node_table *nt = ni->ni_table;
1591
1592	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1593		"%s %p<%s> in %s table\n", __func__, ni,
1594		ether_sprintf(ni->ni_macaddr),
1595		nt != NULL ? nt->nt_name : "<gone>");
1596
1597	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1598	if (nt != NULL) {
1599		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1600		LIST_REMOVE(ni, ni_hash);
1601	}
1602	ic->ic_node_free(ni);
1603}
1604
1605void
1606#ifdef IEEE80211_DEBUG_REFCNT
1607ieee80211_free_node_debug(struct ieee80211_node *ni, const char *func, int line)
1608#else
1609ieee80211_free_node(struct ieee80211_node *ni)
1610#endif
1611{
1612	struct ieee80211_node_table *nt = ni->ni_table;
1613
1614#ifdef IEEE80211_DEBUG_REFCNT
1615	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1616		"%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line, ni,
1617		 ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)-1);
1618#endif
1619	if (nt != NULL) {
1620		IEEE80211_NODE_LOCK(nt);
1621		if (ieee80211_node_dectestref(ni)) {
1622			/*
1623			 * Last reference, reclaim state.
1624			 */
1625			_ieee80211_free_node(ni);
1626		} else if (ieee80211_node_refcnt(ni) == 1 &&
1627		    nt->nt_keyixmap != NULL) {
1628			ieee80211_keyix keyix;
1629			/*
1630			 * Check for a last reference in the key mapping table.
1631			 */
1632			keyix = ni->ni_ucastkey.wk_rxkeyix;
1633			if (keyix < nt->nt_keyixmax &&
1634			    nt->nt_keyixmap[keyix] == ni) {
1635				IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1636				    "%s: %p<%s> clear key map entry", __func__,
1637				    ni, ether_sprintf(ni->ni_macaddr));
1638				nt->nt_keyixmap[keyix] = NULL;
1639				ieee80211_node_decref(ni); /* XXX needed? */
1640				_ieee80211_free_node(ni);
1641			}
1642		}
1643		IEEE80211_NODE_UNLOCK(nt);
1644	} else {
1645		if (ieee80211_node_dectestref(ni))
1646			_ieee80211_free_node(ni);
1647	}
1648}
1649
1650/*
1651 * Reclaim a unicast key and clear any key cache state.
1652 */
1653int
1654ieee80211_node_delucastkey(struct ieee80211_node *ni)
1655{
1656	struct ieee80211com *ic = ni->ni_ic;
1657	struct ieee80211_node_table *nt = &ic->ic_sta;
1658	struct ieee80211_node *nikey;
1659	ieee80211_keyix keyix;
1660	int isowned, status;
1661
1662	/*
1663	 * NB: We must beware of LOR here; deleting the key
1664	 * can cause the crypto layer to block traffic updates
1665	 * which can generate a LOR against the node table lock;
1666	 * grab it here and stash the key index for our use below.
1667	 *
1668	 * Must also beware of recursion on the node table lock.
1669	 * When called from node_cleanup we may already have
1670	 * the node table lock held.  Unfortunately there's no
1671	 * way to separate out this path so we must do this
1672	 * conditionally.
1673	 */
1674	isowned = IEEE80211_NODE_IS_LOCKED(nt);
1675	if (!isowned)
1676		IEEE80211_NODE_LOCK(nt);
1677	keyix = ni->ni_ucastkey.wk_rxkeyix;
1678	status = ieee80211_crypto_delkey(ic, &ni->ni_ucastkey);
1679	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax) {
1680		nikey = nt->nt_keyixmap[keyix];
1681		nt->nt_keyixmap[keyix] = NULL;;
1682	} else
1683		nikey = NULL;
1684	if (!isowned)
1685		IEEE80211_NODE_UNLOCK(&ic->ic_sta);
1686
1687	if (nikey != NULL) {
1688		KASSERT(nikey == ni,
1689			("key map out of sync, ni %p nikey %p", ni, nikey));
1690		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1691			"%s: delete key map entry %p<%s> refcnt %d\n",
1692			__func__, ni, ether_sprintf(ni->ni_macaddr),
1693			ieee80211_node_refcnt(ni)-1);
1694		ieee80211_free_node(ni);
1695	}
1696	return status;
1697}
1698
1699/*
1700 * Reclaim a node.  If this is the last reference count then
1701 * do the normal free work.  Otherwise remove it from the node
1702 * table and mark it gone by clearing the back-reference.
1703 */
1704static void
1705node_reclaim(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1706{
1707	ieee80211_keyix keyix;
1708
1709	IEEE80211_NODE_LOCK_ASSERT(nt);
1710
1711	IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1712		"%s: remove %p<%s> from %s table, refcnt %d\n",
1713		__func__, ni, ether_sprintf(ni->ni_macaddr),
1714		nt->nt_name, ieee80211_node_refcnt(ni)-1);
1715	/*
1716	 * Clear any entry in the unicast key mapping table.
1717	 * We need to do it here so rx lookups don't find it
1718	 * in the mapping table even if it's not in the hash
1719	 * table.  We cannot depend on the mapping table entry
1720	 * being cleared because the node may not be free'd.
1721	 */
1722	keyix = ni->ni_ucastkey.wk_rxkeyix;
1723	if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax &&
1724	    nt->nt_keyixmap[keyix] == ni) {
1725		IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1726			"%s: %p<%s> clear key map entry\n",
1727			__func__, ni, ether_sprintf(ni->ni_macaddr));
1728		nt->nt_keyixmap[keyix] = NULL;
1729		ieee80211_node_decref(ni);	/* NB: don't need free */
1730	}
1731	if (!ieee80211_node_dectestref(ni)) {
1732		/*
1733		 * Other references are present, just remove the
1734		 * node from the table so it cannot be found.  When
1735		 * the references are dropped storage will be
1736		 * reclaimed.
1737		 */
1738		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1739		LIST_REMOVE(ni, ni_hash);
1740		ni->ni_table = NULL;		/* clear reference */
1741	} else
1742		_ieee80211_free_node(ni);
1743}
1744
1745static void
1746ieee80211_free_allnodes_locked(struct ieee80211_node_table *nt)
1747{
1748	struct ieee80211com *ic = nt->nt_ic;
1749	struct ieee80211_node *ni;
1750
1751	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1752		"%s: free all nodes in %s table\n", __func__, nt->nt_name);
1753
1754	while ((ni = TAILQ_FIRST(&nt->nt_node)) != NULL) {
1755		if (ni->ni_associd != 0) {
1756			if (ic->ic_auth->ia_node_leave != NULL)
1757				ic->ic_auth->ia_node_leave(ic, ni);
1758			IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1759		}
1760		node_reclaim(nt, ni);
1761	}
1762	ieee80211_reset_erp(ic);
1763}
1764
1765static void
1766ieee80211_free_allnodes(struct ieee80211_node_table *nt)
1767{
1768
1769	IEEE80211_NODE_LOCK(nt);
1770	ieee80211_free_allnodes_locked(nt);
1771	IEEE80211_NODE_UNLOCK(nt);
1772}
1773
1774/*
1775 * Timeout entries in the scan cache.
1776 */
1777static void
1778ieee80211_timeout_scan_candidates(struct ieee80211_node_table *nt)
1779{
1780	struct ieee80211com *ic = nt->nt_ic;
1781	struct ieee80211_node *ni, *tni;
1782
1783	IEEE80211_NODE_LOCK(nt);
1784	ni = ic->ic_bss;
1785	/* XXX belongs elsewhere */
1786	if (ni->ni_rxfrag[0] != NULL && ticks > ni->ni_rxfragstamp + hz) {
1787		m_freem(ni->ni_rxfrag[0]);
1788		ni->ni_rxfrag[0] = NULL;
1789	}
1790	TAILQ_FOREACH_SAFE(ni, &nt->nt_node, ni_list, tni) {
1791		if (ni->ni_inact && --ni->ni_inact == 0) {
1792			IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1793			    "[%s] scan candidate purged from cache "
1794			    "(refcnt %u)\n", ether_sprintf(ni->ni_macaddr),
1795			    ieee80211_node_refcnt(ni));
1796			node_reclaim(nt, ni);
1797		}
1798	}
1799	IEEE80211_NODE_UNLOCK(nt);
1800
1801	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
1802}
1803
1804/*
1805 * Timeout inactive stations and do related housekeeping.
1806 * Note that we cannot hold the node lock while sending a
1807 * frame as this would lead to a LOR.  Instead we use a
1808 * generation number to mark nodes that we've scanned and
1809 * drop the lock and restart a scan if we have to time out
1810 * a node.  Since we are single-threaded by virtue of
1811 * controlling the inactivity timer we can be sure this will
1812 * process each node only once.
1813 */
1814static void
1815ieee80211_timeout_stations(struct ieee80211_node_table *nt)
1816{
1817	struct ieee80211com *ic = nt->nt_ic;
1818	struct ieee80211_node *ni;
1819	u_int gen;
1820	int isadhoc;
1821
1822	isadhoc = (ic->ic_opmode == IEEE80211_M_IBSS ||
1823		   ic->ic_opmode == IEEE80211_M_AHDEMO);
1824	IEEE80211_SCAN_LOCK(nt);
1825	gen = ++nt->nt_scangen;
1826	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1827		"%s: %s scangen %u\n", __func__, nt->nt_name, gen);
1828restart:
1829	IEEE80211_NODE_LOCK(nt);
1830	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1831		if (ni->ni_scangen == gen)	/* previously handled */
1832			continue;
1833		ni->ni_scangen = gen;
1834		/*
1835		 * Ignore entries for which have yet to receive an
1836		 * authentication frame.  These are transient and
1837		 * will be reclaimed when the last reference to them
1838		 * goes away (when frame xmits complete).
1839		 */
1840		if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
1841		    (ni->ni_flags & IEEE80211_NODE_AREF) == 0)
1842			continue;
1843		/*
1844		 * Free fragment if not needed anymore
1845		 * (last fragment older than 1s).
1846		 * XXX doesn't belong here
1847		 */
1848		if (ni->ni_rxfrag[0] != NULL &&
1849		    ticks > ni->ni_rxfragstamp + hz) {
1850			m_freem(ni->ni_rxfrag[0]);
1851			ni->ni_rxfrag[0] = NULL;
1852		}
1853		/*
1854		 * Special case ourself; we may be idle for extended periods
1855		 * of time and regardless reclaiming our state is wrong.
1856		 */
1857		if (ni == ic->ic_bss)
1858			continue;
1859		ni->ni_inact--;
1860		if (ni->ni_associd != 0 || isadhoc) {
1861			/*
1862			 * Age frames on the power save queue. The
1863			 * aging interval is 4 times the listen
1864			 * interval specified by the station.  This
1865			 * number is factored into the age calculations
1866			 * when the frame is placed on the queue.  We
1867			 * store ages as time differences we can check
1868			 * and/or adjust only the head of the list.
1869			 */
1870			if (IEEE80211_NODE_SAVEQ_QLEN(ni) != 0) {
1871				struct mbuf *m;
1872				int discard = 0;
1873
1874				IEEE80211_NODE_SAVEQ_LOCK(ni);
1875				while (IF_POLL(&ni->ni_savedq, m) != NULL &&
1876				     M_AGE_GET(m) < IEEE80211_INACT_WAIT) {
1877IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER, "[%s] discard frame, age %u\n", ether_sprintf(ni->ni_macaddr), M_AGE_GET(m));/*XXX*/
1878					_IEEE80211_NODE_SAVEQ_DEQUEUE_HEAD(ni, m);
1879					m_freem(m);
1880					discard++;
1881				}
1882				if (m != NULL)
1883					M_AGE_SUB(m, IEEE80211_INACT_WAIT);
1884				IEEE80211_NODE_SAVEQ_UNLOCK(ni);
1885
1886				if (discard != 0) {
1887					IEEE80211_DPRINTF(ic,
1888					    IEEE80211_MSG_POWER,
1889					    "[%s] discard %u frames for age\n",
1890					    ether_sprintf(ni->ni_macaddr),
1891					    discard);
1892					IEEE80211_NODE_STAT_ADD(ni,
1893						ps_discard, discard);
1894					if (IEEE80211_NODE_SAVEQ_QLEN(ni) == 0)
1895						ic->ic_set_tim(ni, 0);
1896				}
1897			}
1898			/*
1899			 * Probe the station before time it out.  We
1900			 * send a null data frame which may not be
1901			 * universally supported by drivers (need it
1902			 * for ps-poll support so it should be...).
1903			 */
1904			if (0 < ni->ni_inact &&
1905			    ni->ni_inact <= ic->ic_inact_probe) {
1906				IEEE80211_NOTE(ic,
1907				    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE,
1908				    ni, "%s",
1909				    "probe station due to inactivity");
1910				/*
1911				 * Grab a reference before unlocking the table
1912				 * so the node cannot be reclaimed before we
1913				 * send the frame. ieee80211_send_nulldata
1914				 * understands we've done this and reclaims the
1915				 * ref for us as needed.
1916				 */
1917				ieee80211_ref_node(ni);
1918				IEEE80211_NODE_UNLOCK(nt);
1919				ieee80211_send_nulldata(ni);
1920				/* XXX stat? */
1921				goto restart;
1922			}
1923		}
1924		if (ni->ni_inact <= 0) {
1925			IEEE80211_NOTE(ic,
1926			    IEEE80211_MSG_INACT | IEEE80211_MSG_NODE, ni,
1927			    "station timed out due to inactivity "
1928			    "(refcnt %u)", ieee80211_node_refcnt(ni));
1929			/*
1930			 * Send a deauthenticate frame and drop the station.
1931			 * This is somewhat complicated due to reference counts
1932			 * and locking.  At this point a station will typically
1933			 * have a reference count of 1.  ieee80211_node_leave
1934			 * will do a "free" of the node which will drop the
1935			 * reference count.  But in the meantime a reference
1936			 * wil be held by the deauth frame.  The actual reclaim
1937			 * of the node will happen either after the tx is
1938			 * completed or by ieee80211_node_leave.
1939			 *
1940			 * Separately we must drop the node lock before sending
1941			 * in case the driver takes a lock, as this will result
1942			 * in  LOR between the node lock and the driver lock.
1943			 */
1944			IEEE80211_NODE_UNLOCK(nt);
1945			if (ni->ni_associd != 0) {
1946				IEEE80211_SEND_MGMT(ic, ni,
1947				    IEEE80211_FC0_SUBTYPE_DEAUTH,
1948				    IEEE80211_REASON_AUTH_EXPIRE);
1949			}
1950			ieee80211_node_leave(ic, ni);
1951			ic->ic_stats.is_node_timeout++;
1952			goto restart;
1953		}
1954	}
1955	IEEE80211_NODE_UNLOCK(nt);
1956
1957	IEEE80211_SCAN_UNLOCK(nt);
1958
1959	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
1960}
1961
1962void
1963ieee80211_iterate_nodes(struct ieee80211_node_table *nt, ieee80211_iter_func *f, void *arg)
1964{
1965	struct ieee80211_node *ni;
1966	u_int gen;
1967
1968	IEEE80211_SCAN_LOCK(nt);
1969	gen = ++nt->nt_scangen;
1970restart:
1971	IEEE80211_NODE_LOCK(nt);
1972	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1973		if (ni->ni_scangen != gen) {
1974			ni->ni_scangen = gen;
1975			(void) ieee80211_ref_node(ni);
1976			IEEE80211_NODE_UNLOCK(nt);
1977			(*f)(arg, ni);
1978			ieee80211_free_node(ni);
1979			goto restart;
1980		}
1981	}
1982	IEEE80211_NODE_UNLOCK(nt);
1983
1984	IEEE80211_SCAN_UNLOCK(nt);
1985}
1986
1987void
1988ieee80211_dump_node(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1989{
1990	printf("0x%p: mac %s refcnt %d\n", ni,
1991		ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni));
1992	printf("\tscangen %u authmode %u flags 0x%x\n",
1993		ni->ni_scangen, ni->ni_authmode, ni->ni_flags);
1994	printf("\tassocid 0x%x txpower %u vlan %u\n",
1995		ni->ni_associd, ni->ni_txpower, ni->ni_vlan);
1996	printf("\ttxseq %u rxseq %u fragno %u rxfragstamp %u\n",
1997		ni->ni_txseqs[0],
1998		ni->ni_rxseqs[0] >> IEEE80211_SEQ_SEQ_SHIFT,
1999		ni->ni_rxseqs[0] & IEEE80211_SEQ_FRAG_MASK,
2000		ni->ni_rxfragstamp);
2001	printf("\trstamp %u rssi %u intval %u capinfo 0x%x\n",
2002		ni->ni_rstamp, ni->ni_rssi, ni->ni_intval, ni->ni_capinfo);
2003	printf("\tbssid %s essid \"%.*s\" channel %u:0x%x\n",
2004		ether_sprintf(ni->ni_bssid),
2005		ni->ni_esslen, ni->ni_essid,
2006		ni->ni_chan->ic_freq, ni->ni_chan->ic_flags);
2007	printf("\tfails %u inact %u txrate %u\n",
2008		ni->ni_fails, ni->ni_inact, ni->ni_txrate);
2009}
2010
2011void
2012ieee80211_dump_nodes(struct ieee80211_node_table *nt)
2013{
2014	ieee80211_iterate_nodes(nt,
2015		(ieee80211_iter_func *) ieee80211_dump_node, nt);
2016}
2017
2018/*
2019 * Handle a station joining an 11g network.
2020 */
2021static void
2022ieee80211_node_join_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
2023{
2024
2025	/*
2026	 * Station isn't capable of short slot time.  Bump
2027	 * the count of long slot time stations and disable
2028	 * use of short slot time.  Note that the actual switch
2029	 * over to long slot time use may not occur until the
2030	 * next beacon transmission (per sec. 7.3.1.4 of 11g).
2031	 */
2032	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
2033		ic->ic_longslotsta++;
2034		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2035		    "[%s] station needs long slot time, count %d\n",
2036		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
2037		/* XXX vap's w/ conflicting needs won't work */
2038		ieee80211_set_shortslottime(ic, 0);
2039	}
2040	/*
2041	 * If the new station is not an ERP station
2042	 * then bump the counter and enable protection
2043	 * if configured.
2044	 */
2045	if (!ieee80211_iserp_rateset(ic, &ni->ni_rates)) {
2046		ic->ic_nonerpsta++;
2047		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2048		    "[%s] station is !ERP, %d non-ERP stations associated\n",
2049		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
2050		/*
2051		 * If protection is configured, enable it.
2052		 */
2053		if (ic->ic_protmode != IEEE80211_PROT_NONE) {
2054			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2055			    "%s: enable use of protection\n", __func__);
2056			ic->ic_flags |= IEEE80211_F_USEPROT;
2057		}
2058		/*
2059		 * If station does not support short preamble
2060		 * then we must enable use of Barker preamble.
2061		 */
2062		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE) == 0) {
2063			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2064			    "[%s] station needs long preamble\n",
2065			    ether_sprintf(ni->ni_macaddr));
2066			ic->ic_flags |= IEEE80211_F_USEBARKER;
2067			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
2068		}
2069		if (ic->ic_nonerpsta == 1)
2070			ic->ic_flags_ext |= IEEE80211_FEXT_ERPUPDATE;
2071	} else
2072		ni->ni_flags |= IEEE80211_NODE_ERP;
2073}
2074
2075void
2076ieee80211_node_join(struct ieee80211com *ic, struct ieee80211_node *ni, int resp)
2077{
2078	int newassoc;
2079
2080	if (ni->ni_associd == 0) {
2081		u_int16_t aid;
2082
2083		/*
2084		 * It would be good to search the bitmap
2085		 * more efficiently, but this will do for now.
2086		 */
2087		for (aid = 1; aid < ic->ic_max_aid; aid++) {
2088			if (!IEEE80211_AID_ISSET(aid,
2089			    ic->ic_aid_bitmap))
2090				break;
2091		}
2092		if (aid >= ic->ic_max_aid) {
2093			IEEE80211_SEND_MGMT(ic, ni, resp,
2094			    IEEE80211_REASON_ASSOC_TOOMANY);
2095			ieee80211_node_leave(ic, ni);
2096			return;
2097		}
2098		ni->ni_associd = aid | 0xc000;
2099		IEEE80211_AID_SET(ni->ni_associd, ic->ic_aid_bitmap);
2100		ic->ic_sta_assoc++;
2101		newassoc = 1;
2102		if (ic->ic_curmode == IEEE80211_MODE_11G)
2103			ieee80211_node_join_11g(ic, ni);
2104	} else
2105		newassoc = 0;
2106
2107	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
2108	    "[%s] station %sassociated at aid %d: %s preamble, %s slot time%s%s\n",
2109	    ether_sprintf(ni->ni_macaddr), newassoc ? "" : "re",
2110	    IEEE80211_NODE_AID(ni),
2111	    ic->ic_flags & IEEE80211_F_SHPREAMBLE ? "short" : "long",
2112	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long",
2113	    ic->ic_flags & IEEE80211_F_USEPROT ? ", protection" : "",
2114	    ni->ni_flags & IEEE80211_NODE_QOS ? ", QoS" : ""
2115	);
2116
2117	/* give driver a chance to setup state like ni_txrate */
2118	if (ic->ic_newassoc != NULL)
2119		ic->ic_newassoc(ni, newassoc);
2120	ni->ni_inact_reload = ic->ic_inact_auth;
2121	ni->ni_inact = ni->ni_inact_reload;
2122	IEEE80211_SEND_MGMT(ic, ni, resp, IEEE80211_STATUS_SUCCESS);
2123	/* tell the authenticator about new station */
2124	if (ic->ic_auth->ia_node_join != NULL)
2125		ic->ic_auth->ia_node_join(ic, ni);
2126	ieee80211_notify_node_join(ic, ni, newassoc);
2127}
2128
2129/*
2130 * Handle a station leaving an 11g network.
2131 */
2132static void
2133ieee80211_node_leave_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
2134{
2135
2136	KASSERT(ic->ic_curmode == IEEE80211_MODE_11G,
2137	     ("not in 11g, bss %u:0x%x, curmode %u", ni->ni_chan->ic_freq,
2138	      ni->ni_chan->ic_flags, ic->ic_curmode));
2139
2140	/*
2141	 * If a long slot station do the slot time bookkeeping.
2142	 */
2143	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
2144		KASSERT(ic->ic_longslotsta > 0,
2145		    ("bogus long slot station count %d", ic->ic_longslotsta));
2146		ic->ic_longslotsta--;
2147		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2148		    "[%s] long slot time station leaves, count now %d\n",
2149		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
2150		if (ic->ic_longslotsta == 0) {
2151			/*
2152			 * Re-enable use of short slot time if supported
2153			 * and not operating in IBSS mode (per spec).
2154			 */
2155			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
2156			    ic->ic_opmode != IEEE80211_M_IBSS) {
2157				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2158				    "%s: re-enable use of short slot time\n",
2159				    __func__);
2160				ieee80211_set_shortslottime(ic, 1);
2161			}
2162		}
2163	}
2164	/*
2165	 * If a non-ERP station do the protection-related bookkeeping.
2166	 */
2167	if ((ni->ni_flags & IEEE80211_NODE_ERP) == 0) {
2168		KASSERT(ic->ic_nonerpsta > 0,
2169		    ("bogus non-ERP station count %d", ic->ic_nonerpsta));
2170		ic->ic_nonerpsta--;
2171		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2172		    "[%s] non-ERP station leaves, count now %d\n",
2173		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
2174		if (ic->ic_nonerpsta == 0) {
2175			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2176				"%s: disable use of protection\n", __func__);
2177			ic->ic_flags &= ~IEEE80211_F_USEPROT;
2178			/* XXX verify mode? */
2179			if (ic->ic_caps & IEEE80211_C_SHPREAMBLE) {
2180				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
2181				    "%s: re-enable use of short preamble\n",
2182				    __func__);
2183				ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
2184				ic->ic_flags &= ~IEEE80211_F_USEBARKER;
2185			}
2186			ic->ic_flags_ext |= IEEE80211_FEXT_ERPUPDATE;
2187		}
2188	}
2189}
2190
2191/*
2192 * Handle bookkeeping for station deauthentication/disassociation
2193 * when operating as an ap.
2194 */
2195void
2196ieee80211_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
2197{
2198	struct ieee80211_node_table *nt = ni->ni_table;
2199
2200	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
2201	    "[%s] station with aid %d leaves\n",
2202	    ether_sprintf(ni->ni_macaddr), IEEE80211_NODE_AID(ni));
2203
2204	KASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
2205		ic->ic_opmode == IEEE80211_M_IBSS ||
2206		ic->ic_opmode == IEEE80211_M_AHDEMO,
2207		("unexpected operating mode %u", ic->ic_opmode));
2208	/*
2209	 * If node wasn't previously associated all
2210	 * we need to do is reclaim the reference.
2211	 */
2212	/* XXX ibss mode bypasses 11g and notification */
2213	if (ni->ni_associd == 0)
2214		goto done;
2215	/*
2216	 * Tell the authenticator the station is leaving.
2217	 * Note that we must do this before yanking the
2218	 * association id as the authenticator uses the
2219	 * associd to locate it's state block.
2220	 */
2221	if (ic->ic_auth->ia_node_leave != NULL)
2222		ic->ic_auth->ia_node_leave(ic, ni);
2223	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
2224	ni->ni_associd = 0;
2225	ic->ic_sta_assoc--;
2226
2227	if (ic->ic_curmode == IEEE80211_MODE_11G)
2228		ieee80211_node_leave_11g(ic, ni);
2229	/*
2230	 * Cleanup station state.  In particular clear various
2231	 * state that might otherwise be reused if the node
2232	 * is reused before the reference count goes to zero
2233	 * (and memory is reclaimed).
2234	 */
2235	ieee80211_sta_leave(ic, ni);
2236done:
2237	/*
2238	 * Remove the node from any table it's recorded in and
2239	 * drop the caller's reference.  Removal from the table
2240	 * is important to insure the node is not reprocessed
2241	 * for inactivity.
2242	 */
2243	if (nt != NULL) {
2244		IEEE80211_NODE_LOCK(nt);
2245		node_reclaim(nt, ni);
2246		IEEE80211_NODE_UNLOCK(nt);
2247	} else
2248		ieee80211_free_node(ni);
2249}
2250
2251u_int8_t
2252ieee80211_getrssi(struct ieee80211com *ic)
2253{
2254#define	NZ(x)	((x) == 0 ? 1 : (x))
2255	struct ieee80211_node_table *nt = &ic->ic_sta;
2256	u_int32_t rssi_samples, rssi_total;
2257	struct ieee80211_node *ni;
2258
2259	rssi_total = 0;
2260	rssi_samples = 0;
2261	switch (ic->ic_opmode) {
2262	case IEEE80211_M_IBSS:		/* average of all ibss neighbors */
2263		/* XXX locking */
2264		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
2265			if (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) {
2266				rssi_samples++;
2267				rssi_total += ic->ic_node_getrssi(ni);
2268			}
2269		break;
2270	case IEEE80211_M_AHDEMO:	/* average of all neighbors */
2271		/* XXX locking */
2272		TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
2273			rssi_samples++;
2274			rssi_total += ic->ic_node_getrssi(ni);
2275		}
2276		break;
2277	case IEEE80211_M_HOSTAP:	/* average of all associated stations */
2278		/* XXX locking */
2279		TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
2280			if (IEEE80211_AID(ni->ni_associd) != 0) {
2281				rssi_samples++;
2282				rssi_total += ic->ic_node_getrssi(ni);
2283			}
2284		break;
2285	case IEEE80211_M_MONITOR:	/* XXX */
2286	case IEEE80211_M_STA:		/* use stats from associated ap */
2287	default:
2288		if (ic->ic_bss != NULL)
2289			rssi_total = ic->ic_node_getrssi(ic->ic_bss);
2290		rssi_samples = 1;
2291		break;
2292	}
2293	return rssi_total / NZ(rssi_samples);
2294#undef NZ
2295}
2296
2297/*
2298 * Indicate whether there are frames queued for a station in power-save mode.
2299 */
2300static void
2301ieee80211_set_tim(struct ieee80211_node *ni, int set)
2302{
2303	struct ieee80211com *ic = ni->ni_ic;
2304	u_int16_t aid;
2305
2306	KASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
2307		ic->ic_opmode == IEEE80211_M_IBSS,
2308		("operating mode %u", ic->ic_opmode));
2309
2310	aid = IEEE80211_AID(ni->ni_associd);
2311	KASSERT(aid < ic->ic_max_aid,
2312		("bogus aid %u, max %u", aid, ic->ic_max_aid));
2313
2314	IEEE80211_BEACON_LOCK(ic);
2315	if (set != (isset(ic->ic_tim_bitmap, aid) != 0)) {
2316		if (set) {
2317			setbit(ic->ic_tim_bitmap, aid);
2318			ic->ic_ps_pending++;
2319		} else {
2320			clrbit(ic->ic_tim_bitmap, aid);
2321			ic->ic_ps_pending--;
2322		}
2323		ic->ic_flags |= IEEE80211_F_TIMUPDATE;
2324	}
2325	IEEE80211_BEACON_UNLOCK(ic);
2326}
2327
2328/*
2329 * Node table support.
2330 */
2331
2332static void
2333ieee80211_node_table_init(struct ieee80211com *ic,
2334	struct ieee80211_node_table *nt,
2335	const char *name, int inact, int keyixmax,
2336	void (*timeout)(struct ieee80211_node_table *))
2337{
2338
2339	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
2340		"%s %s table, inact %u\n", __func__, name, inact);
2341
2342	nt->nt_ic = ic;
2343	/* XXX need unit */
2344	IEEE80211_NODE_LOCK_INIT(nt, ic->ic_ifp->if_xname);
2345	IEEE80211_SCAN_LOCK_INIT(nt, ic->ic_ifp->if_xname);
2346	TAILQ_INIT(&nt->nt_node);
2347	nt->nt_name = name;
2348	nt->nt_scangen = 1;
2349	nt->nt_inact_init = inact;
2350	nt->nt_timeout = timeout;
2351	nt->nt_keyixmax = keyixmax;
2352	if (nt->nt_keyixmax > 0) {
2353		MALLOC(nt->nt_keyixmap, struct ieee80211_node **,
2354			keyixmax * sizeof(struct ieee80211_node *),
2355			M_80211_NODE, M_NOWAIT | M_ZERO);
2356		if (nt->nt_keyixmap == NULL)
2357			if_printf(ic->ic_ifp,
2358			    "Cannot allocate key index map with %u entries\n",
2359			    keyixmax);
2360	} else
2361		nt->nt_keyixmap = NULL;
2362}
2363
2364void
2365ieee80211_node_table_reset(struct ieee80211_node_table *nt)
2366{
2367
2368	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
2369		"%s %s table\n", __func__, nt->nt_name);
2370
2371	IEEE80211_NODE_LOCK(nt);
2372	nt->nt_inact_timer = 0;
2373	ieee80211_free_allnodes_locked(nt);
2374	IEEE80211_NODE_UNLOCK(nt);
2375}
2376
2377static void
2378ieee80211_node_table_cleanup(struct ieee80211_node_table *nt)
2379{
2380
2381	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
2382		"%s %s table\n", __func__, nt->nt_name);
2383
2384	IEEE80211_NODE_LOCK(nt);
2385	ieee80211_free_allnodes_locked(nt);
2386	if (nt->nt_keyixmap != NULL) {
2387		/* XXX verify all entries are NULL */
2388		int i;
2389		for (i = 0; i < nt->nt_keyixmax; i++)
2390			if (nt->nt_keyixmap[i] != NULL)
2391				printf("%s: %s[%u] still active\n", __func__,
2392					nt->nt_name, i);
2393		FREE(nt->nt_keyixmap, M_80211_NODE);
2394		nt->nt_keyixmap = NULL;
2395	}
2396	IEEE80211_SCAN_LOCK_DESTROY(nt);
2397	IEEE80211_NODE_LOCK_DESTROY(nt);
2398}
2399