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