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