ieee80211_node.c revision 139520
1/*-
2 * Copyright (c) 2001 Atsushi Onoe
3 * Copyright (c) 2002-2004 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 139520 2004-12-31 21:19:59Z 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
52static struct ieee80211_node *node_alloc(struct ieee80211_node_table *);
53static void node_cleanup(struct ieee80211_node *);
54static void node_free(struct ieee80211_node *);
55static u_int8_t node_getrssi(const struct ieee80211_node *);
56
57static void ieee80211_setup_node(struct ieee80211_node_table *,
58		struct ieee80211_node *, const u_int8_t *);
59static void _ieee80211_free_node(struct ieee80211_node *);
60static void ieee80211_free_allnodes(struct ieee80211_node_table *);
61
62static void ieee80211_timeout_scan_candidates(struct ieee80211_node_table *);
63static void ieee80211_timeout_stations(struct ieee80211_node_table *);
64
65static void ieee80211_set_tim(struct ieee80211com *,
66		struct ieee80211_node *, int set);
67
68static void ieee80211_node_table_init(struct ieee80211com *ic,
69	struct ieee80211_node_table *nt, const char *name, int inact,
70	void (*timeout)(struct ieee80211_node_table *));
71static struct ieee80211_node_table *ieee80211_node_table_alloc(
72	struct ieee80211com *ic, const char *name, int inact,
73	void (*timeout)(struct ieee80211_node_table *));
74static void ieee80211_node_table_cleanup(struct ieee80211_node_table *nt);
75
76MALLOC_DEFINE(M_80211_NODE, "80211node", "802.11 node state");
77
78void
79ieee80211_node_attach(struct ieee80211com *ic)
80{
81
82	ic->ic_sta = NULL;		/* defer to when we need it */
83	ieee80211_node_table_init(ic, &ic->ic_scan, "scan",
84		IEEE80211_INACT_SCAN, ieee80211_timeout_scan_candidates);
85
86	ic->ic_node_alloc = node_alloc;
87	ic->ic_node_free = node_free;
88	ic->ic_node_cleanup = node_cleanup;
89	ic->ic_node_getrssi = node_getrssi;
90
91	/* default station inactivity timer setings */
92	ic->ic_inact_init = IEEE80211_INACT_INIT;
93	ic->ic_inact_auth = IEEE80211_INACT_AUTH;
94	ic->ic_inact_run = IEEE80211_INACT_RUN;
95	ic->ic_inact_probe = IEEE80211_INACT_PROBE;
96
97	/* XXX defer */
98	if (ic->ic_max_aid == 0)
99		ic->ic_max_aid = IEEE80211_AID_DEF;
100	else if (ic->ic_max_aid > IEEE80211_AID_MAX)
101		ic->ic_max_aid = IEEE80211_AID_MAX;
102	MALLOC(ic->ic_aid_bitmap, u_int32_t *,
103		howmany(ic->ic_max_aid, 32) * sizeof(u_int32_t),
104		M_DEVBUF, M_NOWAIT | M_ZERO);
105	if (ic->ic_aid_bitmap == NULL) {
106		/* XXX no way to recover */
107		printf("%s: no memory for AID bitmap!\n", __func__);
108		ic->ic_max_aid = 0;
109	}
110
111	/* XXX defer until using hostap/ibss mode */
112	ic->ic_tim_len = howmany(ic->ic_max_aid, 8) * sizeof(u_int8_t);
113	MALLOC(ic->ic_tim_bitmap, u_int8_t *, ic->ic_tim_len,
114		M_DEVBUF, M_NOWAIT | M_ZERO);
115	if (ic->ic_tim_bitmap == NULL) {
116		/* XXX no way to recover */
117		printf("%s: no memory for TIM bitmap!\n", __func__);
118	}
119	ic->ic_set_tim = ieee80211_set_tim;	/* NB: driver should override */
120}
121
122void
123ieee80211_node_lateattach(struct ieee80211com *ic)
124{
125	struct ieee80211_node *ni;
126	struct ieee80211_rsnparms *rsn;
127
128	ni = ieee80211_alloc_node(&ic->ic_scan, ic->ic_myaddr);
129	KASSERT(ni != NULL, ("unable to setup inital BSS node"));
130	/*
131	 * Setup "global settings" in the bss node so that
132	 * each new station automatically inherits them.
133	 */
134	rsn = &ni->ni_rsn;
135	/* WEP, TKIP, and AES-CCM are always supported */
136	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_WEP;
137	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_TKIP;
138	rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_AES_CCM;
139	if (ic->ic_caps & IEEE80211_C_AES)
140		rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_AES_OCB;
141	if (ic->ic_caps & IEEE80211_C_CKIP)
142		rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_CKIP;
143	/*
144	 * Default unicast cipher to WEP for 802.1x use.  If
145	 * WPA is enabled the management code will set these
146	 * values to reflect.
147	 */
148	rsn->rsn_ucastcipher = IEEE80211_CIPHER_WEP;
149	rsn->rsn_ucastkeylen = 104 / NBBY;
150	/*
151	 * WPA says the multicast cipher is the lowest unicast
152	 * cipher supported.  But we skip WEP which would
153	 * otherwise be used based on this criteria.
154	 */
155	rsn->rsn_mcastcipher = IEEE80211_CIPHER_TKIP;
156	rsn->rsn_mcastkeylen = 128 / NBBY;
157
158	/*
159	 * We support both WPA-PSK and 802.1x; the one used
160	 * is determined by the authentication mode and the
161	 * setting of the PSK state.
162	 */
163	rsn->rsn_keymgmtset = WPA_ASE_8021X_UNSPEC | WPA_ASE_8021X_PSK;
164	rsn->rsn_keymgmt = WPA_ASE_8021X_PSK;
165
166	ic->ic_bss = ieee80211_ref_node(ni);		/* hold reference */
167	ic->ic_auth = ieee80211_authenticator_get(ni->ni_authmode);
168}
169
170void
171ieee80211_node_detach(struct ieee80211com *ic)
172{
173
174	if (ic->ic_bss != NULL) {
175		ieee80211_free_node(ic->ic_bss);
176		ic->ic_bss = NULL;
177	}
178	ieee80211_node_table_cleanup(&ic->ic_scan);
179	if (ic->ic_sta != NULL) {
180		ieee80211_node_table_free(ic->ic_sta);
181		ic->ic_sta = NULL;
182	}
183	if (ic->ic_aid_bitmap != NULL) {
184		FREE(ic->ic_aid_bitmap, M_DEVBUF);
185		ic->ic_aid_bitmap = NULL;
186	}
187	if (ic->ic_tim_bitmap != NULL) {
188		FREE(ic->ic_tim_bitmap, M_DEVBUF);
189		ic->ic_tim_bitmap = NULL;
190	}
191}
192
193/*
194 * Port authorize/unauthorize interfaces for use by an authenticator.
195 */
196
197void
198ieee80211_node_authorize(struct ieee80211com *ic, struct ieee80211_node *ni)
199{
200	ni->ni_flags |= IEEE80211_NODE_AUTH;
201}
202
203void
204ieee80211_node_unauthorize(struct ieee80211com *ic, struct ieee80211_node *ni)
205{
206	ni->ni_flags &= ~IEEE80211_NODE_AUTH;
207}
208
209/*
210 * Set/change the channel.  The rate set is also updated as
211 * to insure a consistent view by drivers.
212 */
213static __inline void
214ieee80211_set_chan(struct ieee80211com *ic,
215	struct ieee80211_node *ni, struct ieee80211_channel *chan)
216{
217	ni->ni_chan = chan;
218	ni->ni_rates = ic->ic_sup_rates[ieee80211_chan2mode(ic, chan)];
219}
220
221/*
222 * AP scanning support.
223 */
224
225#ifdef IEEE80211_DEBUG
226static void
227dump_chanlist(const u_char chans[])
228{
229	const char *sep;
230	int i;
231
232	sep = " ";
233	for (i = 0; i < IEEE80211_CHAN_MAX; i++)
234		if (isset(chans, i)) {
235			printf("%s%u", sep, i);
236			sep = ", ";
237		}
238}
239#endif /* IEEE80211_DEBUG */
240
241/*
242 * Initialize the channel set to scan based on the
243 * of available channels and the current PHY mode.
244 */
245static void
246ieee80211_reset_scan(struct ieee80211com *ic)
247{
248
249	/* XXX ic_des_chan should be handled with ic_chan_active */
250	if (ic->ic_des_chan != IEEE80211_CHAN_ANYC) {
251		memset(ic->ic_chan_scan, 0, sizeof(ic->ic_chan_scan));
252		setbit(ic->ic_chan_scan,
253			ieee80211_chan2ieee(ic, ic->ic_des_chan));
254	} else
255		memcpy(ic->ic_chan_scan, ic->ic_chan_active,
256			sizeof(ic->ic_chan_active));
257	/* NB: hack, setup so next_scan starts with the first channel */
258	if (ic->ic_bss->ni_chan == IEEE80211_CHAN_ANYC)
259		ieee80211_set_chan(ic, ic->ic_bss,
260			&ic->ic_channels[IEEE80211_CHAN_MAX]);
261#ifdef IEEE80211_DEBUG
262	if (ieee80211_msg_scan(ic)) {
263		printf("%s: scan set:", __func__);
264		dump_chanlist(ic->ic_chan_scan);
265		printf(" start chan %u\n",
266			ieee80211_chan2ieee(ic, ic->ic_bss->ni_chan));
267	}
268#endif /* IEEE80211_DEBUG */
269}
270
271/*
272 * Begin an active scan.
273 */
274void
275ieee80211_begin_scan(struct ieee80211com *ic, int reset)
276{
277
278	ic->ic_scan.nt_scangen++;
279	/*
280	 * In all but hostap mode scanning starts off in
281	 * an active mode before switching to passive.
282	 */
283	if (ic->ic_opmode != IEEE80211_M_HOSTAP) {
284		ic->ic_flags |= IEEE80211_F_ASCAN;
285		ic->ic_stats.is_scan_active++;
286	} else
287		ic->ic_stats.is_scan_passive++;
288	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
289		"begin %s scan in %s mode, scangen %u\n",
290		(ic->ic_flags & IEEE80211_F_ASCAN) ?  "active" : "passive",
291		ieee80211_phymode_name[ic->ic_curmode], ic->ic_scan.nt_scangen);
292	/*
293	 * Clear scan state and flush any previously seen AP's.
294	 */
295	ieee80211_reset_scan(ic);
296	if (reset)
297		ieee80211_free_allnodes(&ic->ic_scan);
298
299	ic->ic_flags |= IEEE80211_F_SCAN;
300
301	/* Scan the next channel. */
302	ieee80211_next_scan(ic);
303}
304
305/*
306 * Switch to the next channel marked for scanning.
307 */
308int
309ieee80211_next_scan(struct ieee80211com *ic)
310{
311	struct ieee80211_channel *chan;
312
313	/*
314	 * Insure any previous mgt frame timeouts don't fire.
315	 * This assumes the driver does the right thing in
316	 * flushing anything queued in the driver and below.
317	 */
318	ic->ic_mgt_timer = 0;
319
320	chan = ic->ic_bss->ni_chan;
321	do {
322		if (++chan > &ic->ic_channels[IEEE80211_CHAN_MAX])
323			chan = &ic->ic_channels[0];
324		if (isset(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan))) {
325			clrbit(ic->ic_chan_scan, ieee80211_chan2ieee(ic, chan));
326			IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
327			    "%s: chan %d->%d\n", __func__,
328			    ieee80211_chan2ieee(ic, ic->ic_bss->ni_chan),
329			    ieee80211_chan2ieee(ic, chan));
330			ieee80211_set_chan(ic, ic->ic_bss, chan);
331#ifdef notyet
332			/* XXX driver state change */
333			/*
334			 * Scan next channel. If doing an active scan
335			 * and the channel is not marked passive-only
336			 * then send a probe request.  Otherwise just
337			 * listen for beacons on the channel.
338			 */
339			if ((ic->ic_flags & IEEE80211_F_ASCAN) &&
340			    (ni->ni_chan->ic_flags & IEEE80211_CHAN_PASSIVE) == 0) {
341				IEEE80211_SEND_MGMT(ic, ni,
342				    IEEE80211_FC0_SUBTYPE_PROBE_REQ, 0);
343			}
344#else
345			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
346#endif
347			return 1;
348		}
349	} while (chan != ic->ic_bss->ni_chan);
350	ieee80211_end_scan(ic);
351	return 0;
352}
353
354void
355ieee80211_create_ibss(struct ieee80211com* ic, struct ieee80211_channel *chan)
356{
357	struct ieee80211_node *ni;
358
359	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
360		"%s: creating ibss\n", __func__);
361
362	/*
363	 * Create the station/neighbor table.  Note that for adhoc
364	 * mode we make the initial inactivity timer longer since
365	 * we create nodes only through discovery and they typically
366	 * are long-lived associations.
367	 */
368	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
369		ic->ic_sta = ieee80211_node_table_alloc(ic,
370					"station", ic->ic_inact_init,
371					ieee80211_timeout_stations);
372	else
373		ic->ic_sta = ieee80211_node_table_alloc(ic,
374					"neighbor", ic->ic_inact_run,
375					ieee80211_timeout_stations);
376	if (ic->ic_sta == NULL) {
377		/*
378		 * Should remain in SCAN state and retry.
379		 */
380		/* XXX stat+msg */
381		return;
382	}
383
384	ni = ic->ic_bss;
385	IEEE80211_ADDR_COPY(ni->ni_macaddr, ic->ic_myaddr);
386	IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_myaddr);
387	ni->ni_esslen = ic->ic_des_esslen;
388	memcpy(ni->ni_essid, ic->ic_des_essid, ni->ni_esslen);
389	ni->ni_rssi = 0;
390	ni->ni_rstamp = 0;
391	ni->ni_tstamp.tsf = 0;
392	ni->ni_intval = ic->ic_lintval;
393	ni->ni_capinfo = 0;
394	ni->ni_erp = 0;
395	if (ic->ic_flags & IEEE80211_F_PRIVACY)
396		ni->ni_capinfo |= IEEE80211_CAPINFO_PRIVACY;
397	if (ic->ic_phytype == IEEE80211_T_FH) {
398		ni->ni_fhdwell = 200;	/* XXX */
399		ni->ni_fhindex = 1;
400	}
401	if (ic->ic_opmode == IEEE80211_M_IBSS) {
402		ic->ic_flags |= IEEE80211_F_SIBSS;
403		ni->ni_capinfo |= IEEE80211_CAPINFO_IBSS;	/* XXX */
404		ni->ni_bssid[0] |= 0x02;	/* local bit for IBSS */
405	}
406	/*
407	 * Fix the channel and related attributes.
408	 */
409	ieee80211_set_chan(ic, ni, chan);
410	ic->ic_curmode = ieee80211_chan2mode(ic, chan);
411	/*
412	 * Do mode-specific rate setup.
413	 */
414	if (ic->ic_curmode == IEEE80211_MODE_11G) {
415		/*
416		 * Use a mixed 11b/11g rate set.
417		 */
418		ieee80211_set11gbasicrates(&ni->ni_rates, IEEE80211_MODE_11G);
419	} else if (ic->ic_curmode == IEEE80211_MODE_11B) {
420		/*
421		 * Force pure 11b rate set.
422		 */
423		ieee80211_set11gbasicrates(&ni->ni_rates, IEEE80211_MODE_11B);
424	}
425	/*
426	 * Set the erp state (mostly the slot time) to deal with
427	 * the auto-select case; this should be redundant if the
428	 * mode is locked.
429	 */
430	ieee80211_reset_erp(ic);
431	ieee80211_wme_initparams(ic);
432
433	ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
434}
435
436void
437ieee80211_reset_bss(struct ieee80211com *ic)
438{
439	struct ieee80211_node *ni, *obss;
440
441	ieee80211_node_table_reset(&ic->ic_scan);
442	ni = ieee80211_alloc_node(&ic->ic_scan, ic->ic_myaddr);
443	KASSERT(ni != NULL, ("unable to setup inital BSS node"));
444	obss = ic->ic_bss;
445	ic->ic_bss = ieee80211_ref_node(ni);
446	if (obss != NULL)
447		ieee80211_free_node(obss);
448	if (ic->ic_sta != NULL) {
449		ieee80211_node_table_free(ic->ic_sta);
450		ic->ic_sta = NULL;
451	}
452}
453
454static int
455ieee80211_match_bss(struct ieee80211com *ic, struct ieee80211_node *ni)
456{
457        u_int8_t rate;
458        int fail;
459
460	fail = 0;
461	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
462		fail |= 0x01;
463	if (ic->ic_des_chan != IEEE80211_CHAN_ANYC &&
464	    ni->ni_chan != ic->ic_des_chan)
465		fail |= 0x01;
466	if (ic->ic_opmode == IEEE80211_M_IBSS) {
467		if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
468			fail |= 0x02;
469	} else {
470		if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
471			fail |= 0x02;
472	}
473	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
474		if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
475			fail |= 0x04;
476	} else {
477		/* XXX does this mean privacy is supported or required? */
478		if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
479			fail |= 0x04;
480	}
481	rate = ieee80211_fix_rate(ic, ni, IEEE80211_F_DONEGO);
482	if (rate & IEEE80211_RATE_BASIC)
483		fail |= 0x08;
484	if (ic->ic_des_esslen != 0 &&
485	    (ni->ni_esslen != ic->ic_des_esslen ||
486	     memcmp(ni->ni_essid, ic->ic_des_essid, ic->ic_des_esslen) != 0))
487		fail |= 0x10;
488	if ((ic->ic_flags & IEEE80211_F_DESBSSID) &&
489	    !IEEE80211_ADDR_EQ(ic->ic_des_bssid, ni->ni_bssid))
490		fail |= 0x20;
491#ifdef IEEE80211_DEBUG
492	if (ieee80211_msg_scan(ic)) {
493		printf(" %c %s", fail ? '-' : '+',
494		    ether_sprintf(ni->ni_macaddr));
495		printf(" %s%c", ether_sprintf(ni->ni_bssid),
496		    fail & 0x20 ? '!' : ' ');
497		printf(" %3d%c", ieee80211_chan2ieee(ic, ni->ni_chan),
498			fail & 0x01 ? '!' : ' ');
499		printf(" %+4d", ni->ni_rssi);
500		printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
501		    fail & 0x08 ? '!' : ' ');
502		printf(" %4s%c",
503		    (ni->ni_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
504		    (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
505		    "????",
506		    fail & 0x02 ? '!' : ' ');
507		printf(" %3s%c ",
508		    (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) ?
509		    "wep" : "no",
510		    fail & 0x04 ? '!' : ' ');
511		ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
512		printf("%s\n", fail & 0x10 ? "!" : "");
513	}
514#endif
515	return fail;
516}
517
518static __inline u_int8_t
519maxrate(const struct ieee80211_node *ni)
520{
521	const struct ieee80211_rateset *rs = &ni->ni_rates;
522	/* NB: assumes rate set is sorted (happens on frame receive) */
523	return rs->rs_rates[rs->rs_nrates-1] & IEEE80211_RATE_VAL;
524}
525
526/*
527 * Compare the capabilities of two nodes and decide which is
528 * more desirable (return >0 if a is considered better).  Note
529 * that we assume compatibility/usability has already been checked
530 * so we don't need to (e.g. validate whether privacy is supported).
531 * Used to select the best scan candidate for association in a BSS.
532 */
533static int
534ieee80211_node_compare(struct ieee80211com *ic,
535		       const struct ieee80211_node *a,
536		       const struct ieee80211_node *b)
537{
538	u_int8_t maxa, maxb;
539	u_int8_t rssia, rssib;
540
541	/* privacy support preferred */
542	if ((a->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) &&
543	    (b->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
544		return 1;
545	if ((a->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0 &&
546	    (b->ni_capinfo & IEEE80211_CAPINFO_PRIVACY))
547		return -1;
548
549	/* best/max rate preferred if signal level close enough XXX */
550	maxa = maxrate(a);
551	maxb = maxrate(b);
552	rssia = ic->ic_node_getrssi(a);
553	rssib = ic->ic_node_getrssi(b);
554	if (maxa != maxb && abs(rssib - rssia) < 5)
555		return maxa - maxb;
556
557	/* XXX use freq for channel preference */
558	/* for now just prefer 5Ghz band to all other bands */
559	if (IEEE80211_IS_CHAN_5GHZ(a->ni_chan) &&
560	   !IEEE80211_IS_CHAN_5GHZ(b->ni_chan))
561		return 1;
562	if (!IEEE80211_IS_CHAN_5GHZ(a->ni_chan) &&
563	     IEEE80211_IS_CHAN_5GHZ(b->ni_chan))
564		return -1;
565
566	/* all things being equal, use signal level */
567	return rssia - rssib;
568}
569
570/*
571 * Complete a scan of potential channels.
572 */
573void
574ieee80211_end_scan(struct ieee80211com *ic)
575{
576	struct ieee80211_node *ni, *nextbs, *selbs;
577	struct ieee80211_node_table *nt;
578
579	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN, "end %s scan\n",
580		(ic->ic_flags & IEEE80211_F_ASCAN) ?  "active" : "passive");
581
582	ic->ic_flags &= ~(IEEE80211_F_SCAN | IEEE80211_F_ASCAN);
583	nt = &ic->ic_scan;
584	ni = TAILQ_FIRST(&nt->nt_node);
585
586	ieee80211_notify_scan_done(ic);
587
588	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
589		u_int8_t maxrssi[IEEE80211_CHAN_MAX];	/* XXX off stack? */
590		int i, bestchan;
591		u_int8_t rssi;
592
593		/*
594		 * The passive scan to look for existing AP's completed,
595		 * select a channel to camp on.  Identify the channels
596		 * that already have one or more AP's and try to locate
597		 * an unnoccupied one.  If that fails, pick a channel that
598		 * looks to be quietest.
599		 */
600		memset(maxrssi, 0, sizeof(maxrssi));
601		for (; ni != NULL; ni = nextbs) {
602			ieee80211_ref_node(ni);
603			nextbs = TAILQ_NEXT(ni, ni_list);
604			rssi = ic->ic_node_getrssi(ni);
605			i = ieee80211_chan2ieee(ic, ni->ni_chan);
606			if (rssi > maxrssi[i])
607				maxrssi[i] = rssi;
608			ieee80211_unref_node(&ni);
609		}
610		/* XXX select channel more intelligently */
611		bestchan = -1;
612		for (i = 0; i < IEEE80211_CHAN_MAX; i++)
613			if (isset(ic->ic_chan_active, i)) {
614				/*
615				 * If the channel is unoccupied the max rssi
616				 * should be zero; just take it.  Otherwise
617				 * track the channel with the lowest rssi and
618				 * use that when all channels appear occupied.
619				 */
620				if (maxrssi[i] == 0) {
621					bestchan = i;
622					break;
623				}
624				if (maxrssi[i] < maxrssi[bestchan])
625					bestchan = i;
626			}
627		if (bestchan != -1) {
628			ieee80211_create_ibss(ic, &ic->ic_channels[bestchan]);
629			return;
630		}
631		/* no suitable channel, should not happen */
632	}
633
634	/*
635	 * When manually sequencing the state machine; scan just once
636	 * regardless of whether we have a candidate or not.  The
637	 * controlling application is expected to setup state and
638	 * initiate an association.
639	 */
640	if (ic->ic_roaming == IEEE80211_ROAMING_MANUAL)
641		return;
642	/*
643	 * Automatic sequencing; look for a candidate and
644	 * if found join the network.
645	 */
646	if (ni == NULL) {
647		IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
648			"%s: no scan candidate\n", __func__);
649  notfound:
650		if (ic->ic_opmode == IEEE80211_M_IBSS &&
651		    (ic->ic_flags & IEEE80211_F_IBSSON) &&
652		    ic->ic_des_esslen != 0) {
653			ieee80211_create_ibss(ic, ic->ic_ibss_chan);
654			return;
655		}
656		/*
657		 * Reset the list of channels to scan and start again.
658		 */
659		ieee80211_reset_scan(ic);
660		ic->ic_flags |= IEEE80211_F_SCAN;
661		ieee80211_next_scan(ic);
662		return;
663	}
664	selbs = NULL;
665	IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN, "\t%s\n",
666	    "macaddr          bssid         chan  rssi rate flag  wep  essid");
667	for (; ni != NULL; ni = nextbs) {
668		ieee80211_ref_node(ni);
669		nextbs = TAILQ_NEXT(ni, ni_list);
670		if (ni->ni_fails) {
671			/*
672			 * The configuration of the access points may change
673			 * during my scan.  So delete the entry for the AP
674			 * and retry to associate if there is another beacon.
675			 */
676			IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
677				"%s: skip scan candidate %s, fails %u\n",
678				__func__, ether_sprintf(ni->ni_macaddr),
679				ni->ni_fails);
680			if (ni->ni_fails++ > 2)
681				ieee80211_free_node(ni);
682			continue;
683		}
684		if (ieee80211_match_bss(ic, ni) == 0) {
685			if (selbs == NULL)
686				selbs = ni;
687			else if (ieee80211_node_compare(ic, ni, selbs) > 0) {
688				ieee80211_unref_node(&selbs);
689				selbs = ni;
690			} else
691				ieee80211_unref_node(&ni);
692		} else {
693			ieee80211_unref_node(&ni);
694		}
695	}
696	if (selbs == NULL)
697		goto notfound;
698	if (!ieee80211_sta_join(ic, selbs)) {
699		ieee80211_unref_node(&selbs);
700		goto notfound;
701	}
702}
703
704/*
705 * Handle 802.11 ad hoc network merge.  The
706 * convention, set by the Wireless Ethernet Compatibility Alliance
707 * (WECA), is that an 802.11 station will change its BSSID to match
708 * the "oldest" 802.11 ad hoc network, on the same channel, that
709 * has the station's desired SSID.  The "oldest" 802.11 network
710 * sends beacons with the greatest TSF timestamp.
711 *
712 * The caller is assumed to validate TSF's before attempting a merge.
713 *
714 * Return !0 if the BSSID changed, 0 otherwise.
715 */
716int
717ieee80211_ibss_merge(struct ieee80211com *ic, struct ieee80211_node *ni)
718{
719
720	if (IEEE80211_ADDR_EQ(ni->ni_bssid, ic->ic_bss->ni_bssid)) {
721		/* unchanged, nothing to do */
722		return 0;
723	}
724	if (ieee80211_match_bss(ic, ni) != 0) {	/* capabilities mismatch */
725		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
726		    "%s: merge failed, capabilities mismatch\n", __func__);
727		ic->ic_stats.is_ibss_capmismatch++;
728		return 0;
729	}
730	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
731		"%s: new bssid %s: %s preamble, %s slot time%s\n", __func__,
732		ether_sprintf(ni->ni_bssid),
733		ic->ic_flags&IEEE80211_F_SHPREAMBLE ? "short" : "long",
734		ic->ic_flags&IEEE80211_F_SHSLOT ? "short" : "long",
735		ic->ic_flags&IEEE80211_F_USEPROT ? ", protection" : ""
736	);
737	return ieee80211_sta_join(ic, ni);
738}
739
740/*
741 * Join the specified IBSS/BSS network.  The node is assumed to
742 * be passed in with a held reference.
743 */
744int
745ieee80211_sta_join(struct ieee80211com *ic, struct ieee80211_node *selbs)
746{
747	struct ieee80211_node *obss;
748
749	if (ic->ic_opmode == IEEE80211_M_IBSS) {
750		/*
751		 * Check rate set before committing to this node.
752		 */
753		ieee80211_fix_rate(ic, selbs, IEEE80211_F_DOFRATE |
754		    IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
755		if (selbs->ni_rates.rs_nrates == 0) {
756			selbs->ni_fails++;
757			ic->ic_stats.is_ibss_norate++;
758			return 0;
759		}
760		/*
761		 * Create the neighbor table.
762		 */
763		ic->ic_sta = ieee80211_node_table_alloc(ic,
764					"neighbor", ic->ic_inact_run,
765					ieee80211_timeout_stations);
766		if (ic->ic_sta == NULL) {
767			/*
768			 * Should remain in SCAN state and retry.
769			 */
770			/* XXX stat+msg */
771			return 0;
772		}
773	}
774
775	/*
776	 * Committed to selbs, setup state.
777	 */
778	obss = ic->ic_bss;
779	ic->ic_bss = selbs;
780	if (obss != NULL)
781		ieee80211_free_node(obss);
782	/*
783	 * Set the erp state (mostly the slot time) to deal with
784	 * the auto-select case; this should be redundant if the
785	 * mode is locked.
786	 */
787	ic->ic_curmode = ieee80211_chan2mode(ic, selbs->ni_chan);
788	ieee80211_reset_erp(ic);
789	ieee80211_wme_initparams(ic);
790	if (ic->ic_opmode == IEEE80211_M_IBSS)
791		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
792	else
793		ieee80211_new_state(ic, IEEE80211_S_AUTH, -1);
794	return 1;
795}
796
797/*
798 * Leave the specified IBSS/BSS network.  The node is assumed to
799 * be passed in with a held reference.
800 */
801void
802ieee80211_sta_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
803{
804	ic->ic_node_cleanup(ni);
805	ieee80211_notify_node_leave(ic, ni);
806}
807
808static struct ieee80211_node *
809node_alloc(struct ieee80211_node_table *nt)
810{
811	struct ieee80211_node *ni;
812
813	MALLOC(ni, struct ieee80211_node *, sizeof(struct ieee80211_node),
814		M_80211_NODE, M_NOWAIT | M_ZERO);
815	return ni;
816}
817
818/*
819 * Reclaim any resources in a node and reset any critical
820 * state.  Typically nodes are free'd immediately after,
821 * but in some cases the storage may be reused so we need
822 * to insure consistent state (should probably fix that).
823 */
824static void
825node_cleanup(struct ieee80211_node *ni)
826{
827#define	N(a)	(sizeof(a)/sizeof(a[0]))
828	struct ieee80211com *ic = ni->ni_ic;
829	int i, qlen;
830
831	/* NB: preserve ni_table */
832	if (ni->ni_flags & IEEE80211_NODE_PWR_MGT) {
833		ic->ic_ps_sta--;
834		ni->ni_flags &= ~IEEE80211_NODE_PWR_MGT;
835		IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
836		    "[%s] power save mode off, %u sta's in ps mode\n",
837		    ether_sprintf(ni->ni_macaddr), ic->ic_ps_sta);
838	}
839
840	/*
841	 * Drain power save queue and, if needed, clear TIM.
842	 */
843	IEEE80211_NODE_SAVEQ_DRAIN(ni, qlen);
844	if (qlen != 0 && ic->ic_set_tim != NULL)
845		ic->ic_set_tim(ic, ni, 0);
846
847	ni->ni_associd = 0;
848	if (ni->ni_challenge != NULL) {
849		FREE(ni->ni_challenge, M_DEVBUF);
850		ni->ni_challenge = NULL;
851	}
852	/*
853	 * Preserve SSID, WPA, and WME ie's so the bss node is
854	 * reusable during a re-auth/re-assoc state transition.
855	 * If we remove these data they will not be recreated
856	 * because they come from a probe-response or beacon frame
857	 * which cannot be expected prior to the association-response.
858	 * This should not be an issue when operating in other modes
859	 * as stations leaving always go through a full state transition
860	 * which will rebuild this state.
861	 *
862	 * XXX does this leave us open to inheriting old state?
863	 */
864	for (i = 0; i < N(ni->ni_rxfrag); i++)
865		if (ni->ni_rxfrag[i] != NULL) {
866			m_freem(ni->ni_rxfrag[i]);
867			ni->ni_rxfrag[i] = NULL;
868		}
869	ieee80211_crypto_delkey(ic, &ni->ni_ucastkey);
870#undef N
871}
872
873static void
874node_free(struct ieee80211_node *ni)
875{
876	struct ieee80211com *ic = ni->ni_ic;
877
878	ic->ic_node_cleanup(ni);
879	if (ni->ni_wpa_ie != NULL)
880		FREE(ni->ni_wpa_ie, M_DEVBUF);
881	if (ni->ni_wme_ie != NULL)
882		FREE(ni->ni_wme_ie, M_DEVBUF);
883	IEEE80211_NODE_SAVEQ_DESTROY(ni);
884	FREE(ni, M_80211_NODE);
885}
886
887static u_int8_t
888node_getrssi(const struct ieee80211_node *ni)
889{
890	return ni->ni_rssi;
891}
892
893static void
894ieee80211_setup_node(struct ieee80211_node_table *nt,
895	struct ieee80211_node *ni, const u_int8_t *macaddr)
896{
897	struct ieee80211com *ic = nt->nt_ic;
898	int hash;
899
900	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
901		"%s %s in %s table\n", __func__,
902		ether_sprintf(macaddr), nt->nt_name);
903
904	IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
905	hash = IEEE80211_NODE_HASH(macaddr);
906	ieee80211_node_initref(ni);		/* mark referenced */
907	ni->ni_chan = IEEE80211_CHAN_ANYC;
908	ni->ni_authmode = IEEE80211_AUTH_OPEN;
909	ni->ni_txpower = ic->ic_txpowlimit;	/* max power */
910	ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey, IEEE80211_KEYIX_NONE);
911	ni->ni_inact = ni->ni_inact_reload = nt->nt_inact_init;
912	IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
913
914	IEEE80211_NODE_LOCK(nt);
915	TAILQ_INSERT_TAIL(&nt->nt_node, ni, ni_list);
916	LIST_INSERT_HEAD(&nt->nt_hash[hash], ni, ni_hash);
917	ni->ni_table = nt;
918	ni->ni_ic = ic;
919	IEEE80211_NODE_UNLOCK(nt);
920}
921
922struct ieee80211_node *
923ieee80211_alloc_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
924{
925	struct ieee80211com *ic = nt->nt_ic;
926	struct ieee80211_node *ni;
927
928	ni = ic->ic_node_alloc(nt);
929	if (ni != NULL)
930		ieee80211_setup_node(nt, ni, macaddr);
931	else
932		ic->ic_stats.is_rx_nodealloc++;
933	return ni;
934}
935
936struct ieee80211_node *
937ieee80211_dup_bss(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
938{
939	struct ieee80211com *ic = nt->nt_ic;
940	struct ieee80211_node *ni;
941
942	ni = ic->ic_node_alloc(nt);
943	if (ni != NULL) {
944		ieee80211_setup_node(nt, ni, macaddr);
945		/*
946		 * Inherit from ic_bss.
947		 */
948		ni->ni_authmode = ic->ic_bss->ni_authmode;
949		ni->ni_txpower = ic->ic_bss->ni_txpower;
950		ni->ni_vlan = ic->ic_bss->ni_vlan;	/* XXX?? */
951		IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
952		ieee80211_set_chan(ic, ni, ic->ic_bss->ni_chan);
953		ni->ni_rsn = ic->ic_bss->ni_rsn;
954	} else
955		ic->ic_stats.is_rx_nodealloc++;
956	return ni;
957}
958
959static struct ieee80211_node *
960#ifdef IEEE80211_DEBUG_REFCNT
961_ieee80211_find_node_debug(struct ieee80211_node_table *nt,
962	const u_int8_t *macaddr, const char *func, int line)
963#else
964_ieee80211_find_node(struct ieee80211_node_table *nt,
965	const u_int8_t *macaddr)
966#endif
967{
968	struct ieee80211_node *ni;
969	int hash;
970
971	IEEE80211_NODE_LOCK_ASSERT(nt);
972
973	hash = IEEE80211_NODE_HASH(macaddr);
974	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
975		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
976			ieee80211_ref_node(ni);	/* mark referenced */
977#ifdef IEEE80211_DEBUG_REFCNT
978			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
979			    "%s (%s:%u) %s refcnt %d\n", __func__, func, line,
980			     ether_sprintf(ni->ni_macaddr),
981			     ieee80211_node_refcnt(ni));
982#endif
983			return ni;
984		}
985	}
986	return NULL;
987}
988#ifdef IEEE80211_DEBUG_REFCNT
989#define	_ieee80211_find_node(nt, mac) \
990	_ieee80211_find_node_debug(nt, mac, func, line)
991#endif
992
993struct ieee80211_node *
994#ifdef IEEE80211_DEBUG_REFCNT
995ieee80211_find_node_debug(struct ieee80211_node_table *nt,
996	const u_int8_t *macaddr, const char *func, int line)
997#else
998ieee80211_find_node(struct ieee80211_node_table *nt, const u_int8_t *macaddr)
999#endif
1000{
1001	struct ieee80211_node *ni;
1002
1003	IEEE80211_NODE_LOCK(nt);
1004	ni = _ieee80211_find_node(nt, macaddr);
1005	IEEE80211_NODE_UNLOCK(nt);
1006	return ni;
1007}
1008
1009/*
1010 * Fake up a node; this handles node discovery in adhoc mode.
1011 * Note that for the driver's benefit we we treat this like
1012 * an association so the driver has an opportunity to setup
1013 * it's private state.
1014 */
1015struct ieee80211_node *
1016ieee80211_fakeup_adhoc_node(struct ieee80211_node_table *nt,
1017	const u_int8_t macaddr[IEEE80211_ADDR_LEN])
1018{
1019	struct ieee80211com *ic = nt->nt_ic;
1020	struct ieee80211_node *ni;
1021
1022	ni = ieee80211_dup_bss(nt, macaddr);
1023	if (ni != NULL) {
1024		/* XXX no rate negotiation; just dup */
1025		ni->ni_rates = ic->ic_bss->ni_rates;
1026		if (ic->ic_newassoc)
1027			ic->ic_newassoc(ic, ni, 1);
1028		/* XXX not right for 802.1x/WPA */
1029		ieee80211_node_authorize(ic, ni);
1030		ieee80211_ref_node(ni);		/* hold reference */
1031	}
1032	return ni;
1033}
1034
1035/*
1036 * Locate the node for sender, track state, and then pass the
1037 * (referenced) node up to the 802.11 layer for its use.  We
1038 * are required to pass some node so we fall back to ic_bss
1039 * when this frame is from an unknown sender.  The 802.11 layer
1040 * knows this means the sender wasn't in the node table and
1041 * acts accordingly.
1042 */
1043struct ieee80211_node *
1044#ifdef IEEE80211_DEBUG_REFCNT
1045ieee80211_find_rxnode_debug(struct ieee80211com *ic,
1046	const struct ieee80211_frame_min *wh, const char *func, int line)
1047#else
1048ieee80211_find_rxnode(struct ieee80211com *ic,
1049	const struct ieee80211_frame_min *wh)
1050#endif
1051{
1052#define	IS_CTL(wh) \
1053	((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_CTL)
1054#define	IS_PSPOLL(wh) \
1055	((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_PS_POLL)
1056	struct ieee80211_node_table *nt;
1057	struct ieee80211_node *ni;
1058
1059	/* XXX may want scanned nodes in the neighbor table for adhoc */
1060	if (ic->ic_opmode == IEEE80211_M_STA ||
1061	    ic->ic_opmode == IEEE80211_M_MONITOR ||
1062	    (ic->ic_flags & IEEE80211_F_SCAN))
1063		nt = &ic->ic_scan;
1064	else
1065		nt = ic->ic_sta;
1066	/* XXX check ic_bss first in station mode */
1067	/* XXX 4-address frames? */
1068	IEEE80211_NODE_LOCK(nt);
1069	if (IS_CTL(wh) && !IS_PSPOLL(wh) /*&& !IS_RTS(ah)*/)
1070		ni = _ieee80211_find_node(nt, wh->i_addr1);
1071	else
1072		ni = _ieee80211_find_node(nt, wh->i_addr2);
1073	IEEE80211_NODE_UNLOCK(nt);
1074
1075	return (ni != NULL ? ni : ieee80211_ref_node(ic->ic_bss));
1076#undef IS_PSPOLL
1077#undef IS_CTL
1078}
1079
1080/*
1081 * Return a reference to the appropriate node for sending
1082 * a data frame.  This handles node discovery in adhoc networks.
1083 */
1084struct ieee80211_node *
1085#ifdef IEEE80211_DEBUG_REFCNT
1086ieee80211_find_txnode_debug(struct ieee80211com *ic, const u_int8_t *macaddr,
1087	const char *func, int line)
1088#else
1089ieee80211_find_txnode(struct ieee80211com *ic, const u_int8_t *macaddr)
1090#endif
1091{
1092	struct ieee80211_node_table *nt = ic->ic_sta;
1093	struct ieee80211_node *ni;
1094
1095	/*
1096	 * The destination address should be in the node table
1097	 * unless we are operating in station mode or this is a
1098	 * multicast/broadcast frame.
1099	 */
1100	if (nt == NULL || IEEE80211_IS_MULTICAST(macaddr))
1101		return ieee80211_ref_node(ic->ic_bss);
1102
1103	/* XXX can't hold lock across dup_bss 'cuz of recursive locking */
1104	IEEE80211_NODE_LOCK(nt);
1105	ni = _ieee80211_find_node(nt, macaddr);
1106	IEEE80211_NODE_UNLOCK(nt);
1107
1108	if (ni == NULL) {
1109		if (ic->ic_opmode == IEEE80211_M_IBSS ||
1110		    ic->ic_opmode == IEEE80211_M_AHDEMO)
1111			ni = ieee80211_fakeup_adhoc_node(nt, macaddr);
1112		else {
1113			IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
1114				"[%s] no node, discard frame (%s)\n",
1115				ether_sprintf(macaddr), __func__);
1116			ic->ic_stats.is_tx_nonode++;
1117		}
1118	}
1119	return ni;
1120}
1121
1122/*
1123 * Like find but search based on the channel too.
1124 */
1125struct ieee80211_node *
1126#ifdef IEEE80211_DEBUG_REFCNT
1127ieee80211_find_node_with_channel_debug(struct ieee80211_node_table *nt,
1128	const u_int8_t *macaddr, struct ieee80211_channel *chan,
1129	const char *func, int line)
1130#else
1131ieee80211_find_node_with_channel(struct ieee80211_node_table *nt,
1132	const u_int8_t *macaddr, struct ieee80211_channel *chan)
1133#endif
1134{
1135	struct ieee80211_node *ni;
1136	int hash;
1137
1138	hash = IEEE80211_NODE_HASH(macaddr);
1139	IEEE80211_NODE_LOCK(nt);
1140	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1141		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1142		    ni->ni_chan == chan) {
1143			ieee80211_ref_node(ni);		/* mark referenced */
1144			IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1145#ifdef IEEE80211_DEBUG_REFCNT
1146			    "%s (%s:%u) %s refcnt %d\n", __func__, func, line,
1147#else
1148			    "%s %s refcnt %d\n", __func__,
1149#endif
1150			     ether_sprintf(ni->ni_macaddr),
1151			     ieee80211_node_refcnt(ni));
1152			break;
1153		}
1154	}
1155	IEEE80211_NODE_UNLOCK(nt);
1156	return ni;
1157}
1158
1159/*
1160 * Like find but search based on the ssid too.
1161 */
1162struct ieee80211_node *
1163#ifdef IEEE80211_DEBUG_REFCNT
1164ieee80211_find_node_with_ssid_debug(struct ieee80211_node_table *nt,
1165	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid,
1166	const char *func, int line)
1167#else
1168ieee80211_find_node_with_ssid(struct ieee80211_node_table *nt,
1169	const u_int8_t *macaddr, u_int ssidlen, const u_int8_t *ssid)
1170#endif
1171{
1172	struct ieee80211com *ic = nt->nt_ic;
1173	struct ieee80211_node *ni;
1174	int hash;
1175
1176	hash = IEEE80211_NODE_HASH(macaddr);
1177	IEEE80211_NODE_LOCK(nt);
1178	LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1179		if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1180		    ni->ni_esslen == ic->ic_des_esslen &&
1181		    memcmp(ni->ni_essid, ic->ic_des_essid, ni->ni_esslen) == 0) {
1182			ieee80211_ref_node(ni);		/* mark referenced */
1183			IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1184#ifdef IEEE80211_DEBUG_REFCNT
1185			    "%s (%s:%u) %s refcnt %d\n", __func__, func, line,
1186#else
1187			    "%s %s refcnt %d\n", __func__,
1188#endif
1189			     ether_sprintf(ni->ni_macaddr),
1190			     ieee80211_node_refcnt(ni));
1191			break;
1192		}
1193	}
1194	IEEE80211_NODE_UNLOCK(nt);
1195	return ni;
1196}
1197
1198
1199static void
1200_ieee80211_free_node(struct ieee80211_node *ni)
1201{
1202	struct ieee80211com *ic = ni->ni_ic;
1203	struct ieee80211_node_table *nt = ni->ni_table;
1204
1205	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1206		"%s %s in %s table\n", __func__, ether_sprintf(ni->ni_macaddr),
1207		nt != NULL ? nt->nt_name : "<gone>");
1208
1209	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1210	if (nt != NULL) {
1211		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1212		LIST_REMOVE(ni, ni_hash);
1213	}
1214	ic->ic_node_free(ni);
1215}
1216
1217void
1218#ifdef IEEE80211_DEBUG_REFCNT
1219ieee80211_free_node_debug(struct ieee80211_node *ni, const char *func, int line)
1220#else
1221ieee80211_free_node(struct ieee80211_node *ni)
1222#endif
1223{
1224	struct ieee80211_node_table *nt = ni->ni_table;
1225
1226#ifdef IEEE80211_DEBUG_REFCNT
1227	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1228		"%s (%s:%u) %s refcnt %d\n", __func__, func, line,
1229		 ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)-1);
1230#endif
1231	if (ieee80211_node_dectestref(ni)) {
1232		/*
1233		 * Beware; if the node is marked gone then it's already
1234		 * been removed from the table and we cannot assume the
1235		 * table still exists.  Regardless, there's no need to lock
1236		 * the table.
1237		 */
1238		if (ni->ni_table != NULL) {
1239			IEEE80211_NODE_LOCK(nt);
1240			_ieee80211_free_node(ni);
1241			IEEE80211_NODE_UNLOCK(nt);
1242		} else
1243			_ieee80211_free_node(ni);
1244	}
1245}
1246
1247/*
1248 * Reclaim a node.  If this is the last reference count then
1249 * do the normal free work.  Otherwise remove it from the node
1250 * table and mark it gone by clearing the back-reference.
1251 */
1252static void
1253node_reclaim(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1254{
1255
1256	if (!ieee80211_node_dectestref(ni)) {
1257		/*
1258		 * Other references are present, just remove the
1259		 * node from the table so it cannot be found.  When
1260		 * the references are dropped storage will be
1261		 * reclaimed.  This normally only happens for ic_bss.
1262		 */
1263		TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1264		LIST_REMOVE(ni, ni_hash);
1265		ni->ni_table = NULL;		/* clear reference */
1266	} else
1267		_ieee80211_free_node(ni);
1268}
1269
1270static void
1271ieee80211_free_allnodes_locked(struct ieee80211_node_table *nt)
1272{
1273	struct ieee80211com *ic = nt->nt_ic;
1274	struct ieee80211_node *ni;
1275
1276	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1277		"%s: free all nodes in %s table\n", __func__, nt->nt_name);
1278
1279	while ((ni = TAILQ_FIRST(&nt->nt_node)) != NULL) {
1280		if (ni->ni_associd != 0) {
1281			if (ic->ic_auth->ia_node_leave != NULL)
1282				ic->ic_auth->ia_node_leave(ic, ni);
1283			IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1284		}
1285		node_reclaim(nt, ni);
1286	}
1287	ieee80211_reset_erp(ic);
1288}
1289
1290static void
1291ieee80211_free_allnodes(struct ieee80211_node_table *nt)
1292{
1293
1294	IEEE80211_NODE_LOCK(nt);
1295	ieee80211_free_allnodes_locked(nt);
1296	IEEE80211_NODE_UNLOCK(nt);
1297}
1298
1299/*
1300 * Timeout entries in the scan cache.
1301 */
1302static void
1303ieee80211_timeout_scan_candidates(struct ieee80211_node_table *nt)
1304{
1305	struct ieee80211com *ic = nt->nt_ic;
1306	struct ieee80211_node *ni, *tni;
1307
1308	IEEE80211_NODE_LOCK(nt);
1309	ni = ic->ic_bss;
1310	/* XXX belongs elsewhere */
1311	if (ni->ni_rxfrag[0] != NULL && ticks > ni->ni_rxfragstamp + hz) {
1312		m_freem(ni->ni_rxfrag[0]);
1313		ni->ni_rxfrag[0] = NULL;
1314	}
1315	TAILQ_FOREACH_SAFE(ni, &nt->nt_node, ni_list, tni) {
1316		if (ni->ni_inact && --ni->ni_inact == 0) {
1317			IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1318			    "[%s] scan candidate purged from cache "
1319			    "(refcnt %u)\n", ether_sprintf(ni->ni_macaddr),
1320			    ieee80211_node_refcnt(ni)-1);
1321			node_reclaim(nt, ni);
1322		}
1323	}
1324	IEEE80211_NODE_UNLOCK(nt);
1325
1326	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
1327}
1328
1329/*
1330 * Timeout inactive stations and do related housekeeping.
1331 * Note that we cannot hold the node lock while sending a
1332 * frame as this would lead to a LOR.  Instead we use a
1333 * generation number to mark nodes that we've scanned and
1334 * drop the lock and restart a scan if we have to time out
1335 * a node.  Since we are single-threaded by virtue of
1336 * controlling the inactivity timer we can be sure this will
1337 * process each node only once.
1338 */
1339static void
1340ieee80211_timeout_stations(struct ieee80211_node_table *nt)
1341{
1342	struct ieee80211com *ic = nt->nt_ic;
1343	struct ieee80211_node *ni;
1344	u_int gen;
1345
1346	IEEE80211_SCAN_LOCK(nt);
1347	gen = nt->nt_scangen++;
1348	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1349		"%s: sta scangen %u\n", __func__, gen);
1350restart:
1351	IEEE80211_NODE_LOCK(nt);
1352	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1353		if (ni->ni_scangen == gen)	/* previously handled */
1354			continue;
1355		ni->ni_scangen = gen;
1356		/*
1357		 * Free fragment if not needed anymore
1358		 * (last fragment older than 1s).
1359		 * XXX doesn't belong here
1360		 */
1361		if (ni->ni_rxfrag[0] != NULL &&
1362		    ticks > ni->ni_rxfragstamp + hz) {
1363			m_freem(ni->ni_rxfrag[0]);
1364			ni->ni_rxfrag[0] = NULL;
1365		}
1366		ni->ni_inact--;
1367		if (ni->ni_associd != 0) {
1368			/*
1369			 * Age frames on the power save queue. The
1370			 * aging interval is 4 times the listen
1371			 * interval specified by the station.  This
1372			 * number is factored into the age calculations
1373			 * when the frame is placed on the queue.  We
1374			 * store ages as time differences we can check
1375			 * and/or adjust only the head of the list.
1376			 */
1377			if (IEEE80211_NODE_SAVEQ_QLEN(ni) != 0) {
1378				struct mbuf *m;
1379				int discard = 0;
1380
1381				IEEE80211_NODE_SAVEQ_LOCK(ni);
1382				while (IF_POLL(&ni->ni_savedq, m) != NULL &&
1383				     M_AGE_GET(m) < IEEE80211_INACT_WAIT) {
1384IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER, "[%s] discard frame, age %u\n", ether_sprintf(ni->ni_macaddr), M_AGE_GET(m));/*XXX*/
1385					_IEEE80211_NODE_SAVEQ_DEQUEUE_HEAD(ni, m);
1386					m_freem(m);
1387					discard++;
1388				}
1389				if (m != NULL)
1390					M_AGE_SUB(m, IEEE80211_INACT_WAIT);
1391				IEEE80211_NODE_SAVEQ_UNLOCK(ni);
1392
1393				if (discard != 0) {
1394					IEEE80211_DPRINTF(ic,
1395					    IEEE80211_MSG_POWER,
1396					    "[%s] discard %u frames for age\n",
1397					    ether_sprintf(ni->ni_macaddr),
1398					    discard);
1399					IEEE80211_NODE_STAT_ADD(ni,
1400						ps_discard, discard);
1401					if (IEEE80211_NODE_SAVEQ_QLEN(ni) == 0)
1402						ic->ic_set_tim(ic, ni, 0);
1403				}
1404			}
1405			/*
1406			 * Probe the station before time it out.  We
1407			 * send a null data frame which may not be
1408			 * universally supported by drivers (need it
1409			 * for ps-poll support so it should be...).
1410			 */
1411			if (ni->ni_inact == ic->ic_inact_probe) {
1412				IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1413				    "[%s] probe station due to inactivity\n",
1414				    ether_sprintf(ni->ni_macaddr));
1415				IEEE80211_NODE_UNLOCK(nt);
1416				ieee80211_send_nulldata(ic, ni);
1417				/* XXX stat? */
1418				goto restart;
1419			}
1420		}
1421		if (ni->ni_inact <= 0) {
1422			IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1423			    "[%s] station timed out due to inactivity "
1424			    "(refcnt %u)\n", ether_sprintf(ni->ni_macaddr),
1425			    ieee80211_node_refcnt(ni));
1426			/*
1427			 * Send a deauthenticate frame and drop the station.
1428			 * This is somewhat complicated due to reference counts
1429			 * and locking.  At this point a station will typically
1430			 * have a reference count of 1.  ieee80211_node_leave
1431			 * will do a "free" of the node which will drop the
1432			 * reference count.  But in the meantime a reference
1433			 * wil be held by the deauth frame.  The actual reclaim
1434			 * of the node will happen either after the tx is
1435			 * completed or by ieee80211_node_leave.
1436			 *
1437			 * Separately we must drop the node lock before sending
1438			 * in case the driver takes a lock, as this will result
1439			 * in  LOR between the node lock and the driver lock.
1440			 */
1441			IEEE80211_NODE_UNLOCK(nt);
1442			if (ni->ni_associd != 0) {
1443				IEEE80211_SEND_MGMT(ic, ni,
1444				    IEEE80211_FC0_SUBTYPE_DEAUTH,
1445				    IEEE80211_REASON_AUTH_EXPIRE);
1446			}
1447			ieee80211_node_leave(ic, ni);
1448			ic->ic_stats.is_node_timeout++;
1449			goto restart;
1450		}
1451	}
1452	IEEE80211_NODE_UNLOCK(nt);
1453
1454	IEEE80211_SCAN_UNLOCK(nt);
1455
1456	nt->nt_inact_timer = IEEE80211_INACT_WAIT;
1457}
1458
1459void
1460ieee80211_iterate_nodes(struct ieee80211_node_table *nt, ieee80211_iter_func *f, void *arg)
1461{
1462	struct ieee80211_node *ni;
1463	u_int gen;
1464
1465	IEEE80211_SCAN_LOCK(nt);
1466	gen = nt->nt_scangen++;
1467
1468	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1469		"%s: sta scangen %u\n", __func__, gen);
1470restart:
1471	IEEE80211_NODE_LOCK(nt);
1472	TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1473		if (ni->ni_scangen != gen) {
1474			ni->ni_scangen = gen;
1475			(void) ieee80211_ref_node(ni);
1476			IEEE80211_NODE_UNLOCK(nt);
1477			(*f)(arg, ni);
1478			ieee80211_free_node(ni);
1479			goto restart;
1480		}
1481	}
1482	IEEE80211_NODE_UNLOCK(nt);
1483
1484	IEEE80211_SCAN_UNLOCK(nt);
1485}
1486
1487void
1488ieee80211_dump_node(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1489{
1490	printf("0x%p: mac %s refcnt %d\n", ni,
1491		ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni));
1492	printf("\tscangen %u authmode %u flags 0x%x\n",
1493		ni->ni_scangen, ni->ni_authmode, ni->ni_flags);
1494	printf("\tassocid 0x%x txpower %u vlan %u\n",
1495		ni->ni_associd, ni->ni_txpower, ni->ni_vlan);
1496	printf("\ttxseq %u rxseq %u fragno %u rxfragstamp %u\n",
1497		ni->ni_txseqs[0],
1498		ni->ni_rxseqs[0] >> IEEE80211_SEQ_SEQ_SHIFT,
1499		ni->ni_rxseqs[0] & IEEE80211_SEQ_FRAG_MASK,
1500		ni->ni_rxfragstamp);
1501	printf("\trstamp %u rssi %u intval %u capinfo 0x%x\n",
1502		ni->ni_rstamp, ni->ni_rssi, ni->ni_intval, ni->ni_capinfo);
1503	printf("\tbssid %s essid \"%.*s\" channel %u:0x%x\n",
1504		ether_sprintf(ni->ni_bssid),
1505		ni->ni_esslen, ni->ni_essid,
1506		ni->ni_chan->ic_freq, ni->ni_chan->ic_flags);
1507	printf("\tfails %u inact %u txrate %u\n",
1508		ni->ni_fails, ni->ni_inact, ni->ni_txrate);
1509}
1510
1511void
1512ieee80211_dump_nodes(struct ieee80211_node_table *nt)
1513{
1514	ieee80211_iterate_nodes(nt,
1515		(ieee80211_iter_func *) ieee80211_dump_node, nt);
1516}
1517
1518/*
1519 * Handle a station joining an 11g network.
1520 */
1521static void
1522ieee80211_node_join_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
1523{
1524
1525	/*
1526	 * Station isn't capable of short slot time.  Bump
1527	 * the count of long slot time stations and disable
1528	 * use of short slot time.  Note that the actual switch
1529	 * over to long slot time use may not occur until the
1530	 * next beacon transmission (per sec. 7.3.1.4 of 11g).
1531	 */
1532	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
1533		ic->ic_longslotsta++;
1534		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1535		    "[%s] station needs long slot time, count %d\n",
1536		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
1537		/* XXX vap's w/ conflicting needs won't work */
1538		ieee80211_set_shortslottime(ic, 0);
1539	}
1540	/*
1541	 * If the new station is not an ERP station
1542	 * then bump the counter and enable protection
1543	 * if configured.
1544	 */
1545	if (!ieee80211_iserp_rateset(ic, &ni->ni_rates)) {
1546		ic->ic_nonerpsta++;
1547		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1548		    "[%s] station is !ERP, %d non-ERP stations associated\n",
1549		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
1550		/*
1551		 * If protection is configured, enable it.
1552		 */
1553		if (ic->ic_protmode != IEEE80211_PROT_NONE) {
1554			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1555			    "%s: enable use of protection\n", __func__);
1556			ic->ic_flags |= IEEE80211_F_USEPROT;
1557		}
1558		/*
1559		 * If station does not support short preamble
1560		 * then we must enable use of Barker preamble.
1561		 */
1562		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE) == 0) {
1563			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1564			    "[%s] station needs long preamble\n",
1565			    ether_sprintf(ni->ni_macaddr));
1566			ic->ic_flags |= IEEE80211_F_USEBARKER;
1567			ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
1568		}
1569	} else
1570		ni->ni_flags |= IEEE80211_NODE_ERP;
1571}
1572
1573void
1574ieee80211_node_join(struct ieee80211com *ic, struct ieee80211_node *ni, int resp)
1575{
1576	int newassoc;
1577
1578	if (ni->ni_associd == 0) {
1579		u_int16_t aid;
1580
1581		/*
1582		 * It would be good to search the bitmap
1583		 * more efficiently, but this will do for now.
1584		 */
1585		for (aid = 1; aid < ic->ic_max_aid; aid++) {
1586			if (!IEEE80211_AID_ISSET(aid,
1587			    ic->ic_aid_bitmap))
1588				break;
1589		}
1590		if (aid >= ic->ic_max_aid) {
1591			IEEE80211_SEND_MGMT(ic, ni, resp,
1592			    IEEE80211_REASON_ASSOC_TOOMANY);
1593			ieee80211_node_leave(ic, ni);
1594			return;
1595		}
1596		ni->ni_associd = aid | 0xc000;
1597		IEEE80211_AID_SET(ni->ni_associd, ic->ic_aid_bitmap);
1598		ic->ic_sta_assoc++;
1599		newassoc = 1;
1600		if (ic->ic_curmode == IEEE80211_MODE_11G)
1601			ieee80211_node_join_11g(ic, ni);
1602	} else
1603		newassoc = 0;
1604
1605	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
1606	    "[%s] station %s associated at aid %d\n",
1607	    ether_sprintf(ni->ni_macaddr), newassoc ? "newly" : "already",
1608	    IEEE80211_NODE_AID(ni));
1609
1610	/* give driver a chance to setup state like ni_txrate */
1611	if (ic->ic_newassoc)
1612		ic->ic_newassoc(ic, ni, newassoc);
1613	ni->ni_inact_reload = ic->ic_inact_run;
1614	IEEE80211_SEND_MGMT(ic, ni, resp, IEEE80211_STATUS_SUCCESS);
1615	/* tell the authenticator about new station */
1616	if (ic->ic_auth->ia_node_join != NULL)
1617		ic->ic_auth->ia_node_join(ic, ni);
1618	ieee80211_notify_node_join(ic, ni, newassoc);
1619}
1620
1621/*
1622 * Handle a station leaving an 11g network.
1623 */
1624static void
1625ieee80211_node_leave_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
1626{
1627
1628	KASSERT(ic->ic_curmode == IEEE80211_MODE_11G,
1629		("not in 11g, curmode %x", ic->ic_curmode));
1630
1631	/*
1632	 * If a long slot station do the slot time bookkeeping.
1633	 */
1634	if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
1635		KASSERT(ic->ic_longslotsta > 0,
1636		    ("bogus long slot station count %d", ic->ic_longslotsta));
1637		ic->ic_longslotsta--;
1638		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1639		    "[%s] long slot time station leaves, count now %d\n",
1640		    ether_sprintf(ni->ni_macaddr), ic->ic_longslotsta);
1641		if (ic->ic_longslotsta == 0) {
1642			/*
1643			 * Re-enable use of short slot time if supported
1644			 * and not operating in IBSS mode (per spec).
1645			 */
1646			if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
1647			    ic->ic_opmode != IEEE80211_M_IBSS) {
1648				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1649				    "%s: re-enable use of short slot time\n",
1650				    __func__);
1651				ieee80211_set_shortslottime(ic, 1);
1652			}
1653		}
1654	}
1655	/*
1656	 * If a non-ERP station do the protection-related bookkeeping.
1657	 */
1658	if ((ni->ni_flags & IEEE80211_NODE_ERP) == 0) {
1659		KASSERT(ic->ic_nonerpsta > 0,
1660		    ("bogus non-ERP station count %d", ic->ic_nonerpsta));
1661		ic->ic_nonerpsta--;
1662		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1663		    "[%s] non-ERP station leaves, count now %d\n",
1664		    ether_sprintf(ni->ni_macaddr), ic->ic_nonerpsta);
1665		if (ic->ic_nonerpsta == 0) {
1666			IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1667				"%s: disable use of protection\n", __func__);
1668			ic->ic_flags &= ~IEEE80211_F_USEPROT;
1669			/* XXX verify mode? */
1670			if (ic->ic_caps & IEEE80211_C_SHPREAMBLE) {
1671				IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1672				    "%s: re-enable use of short preamble\n",
1673				    __func__);
1674				ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
1675				ic->ic_flags &= ~IEEE80211_F_USEBARKER;
1676			}
1677		}
1678	}
1679}
1680
1681/*
1682 * Handle bookkeeping for station deauthentication/disassociation
1683 * when operating as an ap.
1684 */
1685void
1686ieee80211_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
1687{
1688
1689	IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG,
1690	    "[%s] station with aid %d leaves\n",
1691	    ether_sprintf(ni->ni_macaddr), IEEE80211_NODE_AID(ni));
1692
1693	KASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
1694		ic->ic_opmode == IEEE80211_M_IBSS ||
1695		ic->ic_opmode == IEEE80211_M_AHDEMO,
1696		("unexpected operating mode %u", ic->ic_opmode));
1697	/*
1698	 * If node wasn't previously associated all
1699	 * we need to do is reclaim the reference.
1700	 */
1701	/* XXX ibss mode bypasses 11g and notification */
1702	if (ni->ni_associd == 0)
1703		goto done;
1704	/*
1705	 * Tell the authenticator the station is leaving.
1706	 * Note that we must do this before yanking the
1707	 * association id as the authenticator uses the
1708	 * associd to locate it's state block.
1709	 */
1710	if (ic->ic_auth->ia_node_leave != NULL)
1711		ic->ic_auth->ia_node_leave(ic, ni);
1712	IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1713	ni->ni_associd = 0;
1714	ic->ic_sta_assoc--;
1715
1716	if (ic->ic_curmode == IEEE80211_MODE_11G)
1717		ieee80211_node_leave_11g(ic, ni);
1718	/*
1719	 * Cleanup station state.  In particular clear various
1720	 * state that might otherwise be reused if the node
1721	 * is reused before the reference count goes to zero
1722	 * (and memory is reclaimed).
1723	 */
1724	ieee80211_sta_leave(ic, ni);
1725done:
1726	ni->ni_inact_reload = ic->ic_inact_init;	/* just in case */
1727	ieee80211_free_node(ni);
1728}
1729
1730u_int8_t
1731ieee80211_getrssi(struct ieee80211com *ic)
1732{
1733#define	NZ(x)	((x) == 0 ? 1 : (x))
1734	struct ieee80211_node_table *nt = ic->ic_sta;
1735	u_int32_t rssi_samples, rssi_total;
1736	struct ieee80211_node *ni;
1737
1738	rssi_total = 0;
1739	rssi_samples = 0;
1740	switch (ic->ic_opmode) {
1741	case IEEE80211_M_IBSS:		/* average of all ibss neighbors */
1742		nt = ic->ic_sta;
1743		if (nt == NULL)
1744			break;
1745		/* XXX locking */
1746		TAILQ_FOREACH(ni, &ic->ic_sta->nt_node, ni_list)
1747			if (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) {
1748				rssi_samples++;
1749				rssi_total += ic->ic_node_getrssi(ni);
1750			}
1751		break;
1752	case IEEE80211_M_AHDEMO:	/* average of all neighbors */
1753		nt = ic->ic_sta;
1754		if (nt == NULL)
1755			break;
1756		/* XXX locking */
1757		TAILQ_FOREACH(ni, &ic->ic_sta->nt_node, ni_list) {
1758			rssi_samples++;
1759			rssi_total += ic->ic_node_getrssi(ni);
1760		}
1761		break;
1762	case IEEE80211_M_HOSTAP:	/* average of all associated stations */
1763		nt = ic->ic_sta;
1764		if (nt == NULL)
1765			break;
1766		/* XXX locking */
1767		TAILQ_FOREACH(ni, &ic->ic_sta->nt_node, ni_list)
1768			if (IEEE80211_AID(ni->ni_associd) != 0) {
1769				rssi_samples++;
1770				rssi_total += ic->ic_node_getrssi(ni);
1771			}
1772		break;
1773	case IEEE80211_M_MONITOR:	/* XXX */
1774	case IEEE80211_M_STA:		/* use stats from associated ap */
1775	default:
1776		if (ic->ic_bss != NULL)
1777			rssi_total = ic->ic_node_getrssi(ic->ic_bss);
1778		rssi_samples = 1;
1779		break;
1780	}
1781	return rssi_total / NZ(rssi_samples);
1782#undef NZ
1783}
1784
1785/*
1786 * Indicate whether there are frames queued for a station in power-save mode.
1787 */
1788static void
1789ieee80211_set_tim(struct ieee80211com *ic, struct ieee80211_node *ni, int set)
1790{
1791	u_int16_t aid;
1792
1793	KASSERT(ic->ic_opmode == IEEE80211_M_HOSTAP ||
1794		ic->ic_opmode == IEEE80211_M_IBSS,
1795		("operating mode %u", ic->ic_opmode));
1796
1797	aid = IEEE80211_AID(ni->ni_associd);
1798	KASSERT(aid < ic->ic_max_aid,
1799		("bogus aid %u, max %u", aid, ic->ic_max_aid));
1800
1801	IEEE80211_BEACON_LOCK(ic);
1802	if (set != (isset(ic->ic_tim_bitmap, aid) != 0)) {
1803		if (set) {
1804			setbit(ic->ic_tim_bitmap, aid);
1805			ic->ic_ps_pending++;
1806		} else {
1807			clrbit(ic->ic_tim_bitmap, aid);
1808			ic->ic_ps_pending--;
1809		}
1810		ic->ic_flags |= IEEE80211_F_TIMUPDATE;
1811	}
1812	IEEE80211_BEACON_UNLOCK(ic);
1813}
1814
1815/*
1816 * Node table support.
1817 */
1818
1819static void
1820ieee80211_node_table_init(struct ieee80211com *ic,
1821	struct ieee80211_node_table *nt,
1822	const char *name, int inact,
1823	void (*timeout)(struct ieee80211_node_table *))
1824{
1825
1826	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1827		"%s %s table, inact %u\n", __func__, name, inact);
1828
1829	nt->nt_ic = ic;
1830	/* XXX need unit */
1831	IEEE80211_NODE_LOCK_INIT(nt, ic->ic_ifp->if_xname);
1832	IEEE80211_SCAN_LOCK_INIT(nt, ic->ic_ifp->if_xname);
1833	TAILQ_INIT(&nt->nt_node);
1834	nt->nt_name = name;
1835	nt->nt_scangen = 1;
1836	nt->nt_inact_init = inact;
1837	nt->nt_timeout = timeout;
1838}
1839
1840static struct ieee80211_node_table *
1841ieee80211_node_table_alloc(struct ieee80211com *ic,
1842	const char *name, int inact,
1843	void (*timeout)(struct ieee80211_node_table *))
1844{
1845	struct ieee80211_node_table *nt;
1846
1847	MALLOC(nt, struct ieee80211_node_table *,
1848		sizeof(struct ieee80211_node_table),
1849		M_DEVBUF, M_NOWAIT | M_ZERO);
1850	if (nt == NULL) {
1851		printf("%s: no memory node table!\n", __func__);
1852		return NULL;
1853	}
1854	ieee80211_node_table_init(ic, nt, name, inact, timeout);
1855	return nt;
1856}
1857
1858void
1859ieee80211_node_table_reset(struct ieee80211_node_table *nt)
1860{
1861
1862	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1863		"%s %s table\n", __func__, nt->nt_name);
1864
1865	IEEE80211_NODE_LOCK(nt);
1866	nt->nt_inact_timer = 0;
1867	ieee80211_free_allnodes_locked(nt);
1868	IEEE80211_NODE_UNLOCK(nt);
1869}
1870
1871static void
1872ieee80211_node_table_cleanup(struct ieee80211_node_table *nt)
1873{
1874
1875	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1876		"%s %s table\n", __func__, nt->nt_name);
1877
1878	ieee80211_free_allnodes_locked(nt);
1879	IEEE80211_SCAN_LOCK_DESTROY(nt);
1880	IEEE80211_NODE_LOCK_DESTROY(nt);
1881}
1882
1883/*
1884 * NB: public for use in ieee80211_proto.c
1885 */
1886void
1887ieee80211_node_table_free(struct ieee80211_node_table *nt)
1888{
1889
1890	IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1891		"%s %s table\n", __func__, nt->nt_name);
1892
1893	IEEE80211_NODE_LOCK(nt);
1894	nt->nt_inact_timer = 0;
1895	ieee80211_node_table_cleanup(nt);
1896	FREE(nt, M_DEVBUF);
1897}
1898