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