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