ieee80211_scan_sta.c revision 186904
1170530Ssam/*-
2186904Ssam * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
3170530Ssam * All rights reserved.
4170530Ssam *
5170530Ssam * Redistribution and use in source and binary forms, with or without
6170530Ssam * modification, are permitted provided that the following conditions
7170530Ssam * are met:
8170530Ssam * 1. Redistributions of source code must retain the above copyright
9170530Ssam *    notice, this list of conditions and the following disclaimer.
10170530Ssam * 2. Redistributions in binary form must reproduce the above copyright
11170530Ssam *    notice, this list of conditions and the following disclaimer in the
12170530Ssam *    documentation and/or other materials provided with the distribution.
13170530Ssam *
14170530Ssam * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15170530Ssam * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16170530Ssam * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17170530Ssam * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18170530Ssam * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19170530Ssam * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20170530Ssam * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21170530Ssam * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22170530Ssam * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23170530Ssam * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24170530Ssam */
25170530Ssam
26170530Ssam#include <sys/cdefs.h>
27170530Ssam__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_scan_sta.c 186904 2009-01-08 17:12:47Z sam $");
28170530Ssam
29170530Ssam/*
30170530Ssam * IEEE 802.11 station scanning support.
31170530Ssam */
32178354Ssam#include "opt_wlan.h"
33178354Ssam
34170530Ssam#include <sys/param.h>
35170530Ssam#include <sys/systm.h>
36170530Ssam#include <sys/kernel.h>
37170530Ssam#include <sys/module.h>
38170530Ssam
39170530Ssam#include <sys/socket.h>
40170530Ssam
41170530Ssam#include <net/if.h>
42170530Ssam#include <net/if_media.h>
43170530Ssam#include <net/ethernet.h>
44170530Ssam
45170530Ssam#include <net80211/ieee80211_var.h>
46178354Ssam#include <net80211/ieee80211_input.h>
47178354Ssam#include <net80211/ieee80211_regdomain.h>
48186904Ssam#ifdef IEEE80211_SUPPORT_TDMA
49186904Ssam#include <net80211/ieee80211_tdma.h>
50186904Ssam#endif
51170530Ssam
52170530Ssam#include <net/bpf.h>
53170530Ssam
54170530Ssam/*
55170530Ssam * Parameters for managing cache entries:
56170530Ssam *
57170530Ssam * o a station with STA_FAILS_MAX failures is not considered
58170530Ssam *   when picking a candidate
59170530Ssam * o a station that hasn't had an update in STA_PURGE_SCANS
60170530Ssam *   (background) scans is discarded
61170530Ssam * o after STA_FAILS_AGE seconds we clear the failure count
62170530Ssam */
63170530Ssam#define	STA_FAILS_MAX	2		/* assoc failures before ignored */
64170530Ssam#define	STA_FAILS_AGE	(2*60)		/* time before clearing fails (secs) */
65170530Ssam#define	STA_PURGE_SCANS	2		/* age for purging entries (scans) */
66170530Ssam
67170530Ssam/* XXX tunable */
68170530Ssam#define	STA_RSSI_MIN	8		/* min acceptable rssi */
69170530Ssam#define	STA_RSSI_MAX	40		/* max rssi for comparison */
70170530Ssam
71170530Ssamstruct sta_entry {
72170530Ssam	struct ieee80211_scan_entry base;
73170530Ssam	TAILQ_ENTRY(sta_entry) se_list;
74170530Ssam	LIST_ENTRY(sta_entry) se_hash;
75170530Ssam	uint8_t		se_fails;		/* failure to associate count */
76170530Ssam	uint8_t		se_seen;		/* seen during current scan */
77170530Ssam	uint8_t		se_notseen;		/* not seen in previous scans */
78170530Ssam	uint8_t		se_flags;
79184302Ssam#define	STA_DEMOTE11B	0x01			/* match w/ demoted 11b chan */
80170530Ssam	uint32_t	se_avgrssi;		/* LPF rssi state */
81170530Ssam	unsigned long	se_lastupdate;		/* time of last update */
82170530Ssam	unsigned long	se_lastfail;		/* time of last failure */
83170530Ssam	unsigned long	se_lastassoc;		/* time of last association */
84170530Ssam	u_int		se_scangen;		/* iterator scan gen# */
85178354Ssam	u_int		se_countrygen;		/* gen# of last cc notify */
86170530Ssam};
87170530Ssam
88170530Ssam#define	STA_HASHSIZE	32
89170530Ssam/* simple hash is enough for variation of macaddr */
90170530Ssam#define	STA_HASH(addr)	\
91170530Ssam	(((const uint8_t *)(addr))[IEEE80211_ADDR_LEN - 1] % STA_HASHSIZE)
92170530Ssam
93186107Ssam#define	MAX_IEEE_CHAN	256			/* max acceptable IEEE chan # */
94186107SsamCTASSERT(MAX_IEEE_CHAN >= 256);
95186107Ssam
96170530Ssamstruct sta_table {
97170530Ssam	struct mtx	st_lock;		/* on scan table */
98170530Ssam	TAILQ_HEAD(, sta_entry) st_entry;	/* all entries */
99170530Ssam	LIST_HEAD(, sta_entry) st_hash[STA_HASHSIZE];
100178354Ssam	struct mtx	st_scanlock;		/* on st_scaniter */
101178354Ssam	u_int		st_scaniter;		/* gen# for iterator */
102178354Ssam	u_int		st_scangen;		/* scan generation # */
103170530Ssam	int		st_newscan;
104178354Ssam	/* ap-related state */
105186107Ssam	int		st_maxrssi[MAX_IEEE_CHAN];
106170530Ssam};
107170530Ssam
108170530Ssamstatic void sta_flush_table(struct sta_table *);
109171409Ssam/*
110171409Ssam * match_bss returns a bitmask describing if an entry is suitable
111171409Ssam * for use.  If non-zero the entry was deemed not suitable and it's
112171409Ssam * contents explains why.  The following flags are or'd to to this
113171409Ssam * mask and can be used to figure out why the entry was rejected.
114171409Ssam */
115184302Ssam#define	MATCH_CHANNEL		0x0001	/* channel mismatch */
116184302Ssam#define	MATCH_CAPINFO		0x0002	/* capabilities mismatch, e.g. no ess */
117184302Ssam#define	MATCH_PRIVACY		0x0004	/* privacy mismatch */
118184302Ssam#define	MATCH_RATE		0x0008	/* rate set mismatch */
119184302Ssam#define	MATCH_SSID		0x0010	/* ssid mismatch */
120184302Ssam#define	MATCH_BSSID		0x0020	/* bssid mismatch */
121184302Ssam#define	MATCH_FAILS		0x0040	/* too many failed auth attempts */
122184302Ssam#define	MATCH_NOTSEEN		0x0080	/* not seen in recent scans */
123184302Ssam#define	MATCH_RSSI		0x0100	/* rssi deemed too low to use */
124184302Ssam#define	MATCH_CC		0x0200	/* country code mismatch */
125186904Ssam#define	MATCH_TDMA_NOIE		0x0400	/* no TDMA ie */
126186904Ssam#define	MATCH_TDMA_NOTMASTER	0x0800	/* not TDMA master */
127186904Ssam#define	MATCH_TDMA_NOSLOT	0x1000	/* all TDMA slots occupied */
128186904Ssam#define	MATCH_TDMA_LOCAL	0x2000	/* local address */
129178354Ssamstatic int match_bss(struct ieee80211vap *,
130170530Ssam	const struct ieee80211_scan_state *, struct sta_entry *, int);
131178354Ssamstatic void adhoc_age(struct ieee80211_scan_state *);
132170530Ssam
133178354Ssamstatic __inline int
134178354Ssamisocmp(const uint8_t cc1[], const uint8_t cc2[])
135178354Ssam{
136178354Ssam     return (cc1[0] == cc2[0] && cc1[1] == cc2[1]);
137178354Ssam}
138178354Ssam
139170530Ssam/* number of references from net80211 layer */
140170530Ssamstatic	int nrefs = 0;
141170530Ssam
142170530Ssam/*
143170530Ssam * Attach prior to any scanning work.
144170530Ssam */
145170530Ssamstatic int
146170530Ssamsta_attach(struct ieee80211_scan_state *ss)
147170530Ssam{
148170530Ssam	struct sta_table *st;
149170530Ssam
150186302Ssam	st = (struct sta_table *) malloc(sizeof(struct sta_table),
151170530Ssam		M_80211_SCAN, M_NOWAIT | M_ZERO);
152170530Ssam	if (st == NULL)
153170530Ssam		return 0;
154170530Ssam	mtx_init(&st->st_lock, "scantable", "802.11 scan table", MTX_DEF);
155170530Ssam	mtx_init(&st->st_scanlock, "scangen", "802.11 scangen", MTX_DEF);
156170530Ssam	TAILQ_INIT(&st->st_entry);
157170530Ssam	ss->ss_priv = st;
158170530Ssam	nrefs++;			/* NB: we assume caller locking */
159170530Ssam	return 1;
160170530Ssam}
161170530Ssam
162170530Ssam/*
163170530Ssam * Cleanup any private state.
164170530Ssam */
165170530Ssamstatic int
166170530Ssamsta_detach(struct ieee80211_scan_state *ss)
167170530Ssam{
168170530Ssam	struct sta_table *st = ss->ss_priv;
169170530Ssam
170170530Ssam	if (st != NULL) {
171170530Ssam		sta_flush_table(st);
172170530Ssam		mtx_destroy(&st->st_lock);
173170530Ssam		mtx_destroy(&st->st_scanlock);
174186302Ssam		free(st, M_80211_SCAN);
175170530Ssam		KASSERT(nrefs > 0, ("imbalanced attach/detach"));
176170530Ssam		nrefs--;		/* NB: we assume caller locking */
177170530Ssam	}
178170530Ssam	return 1;
179170530Ssam}
180170530Ssam
181170530Ssam/*
182170530Ssam * Flush all per-scan state.
183170530Ssam */
184170530Ssamstatic int
185170530Ssamsta_flush(struct ieee80211_scan_state *ss)
186170530Ssam{
187170530Ssam	struct sta_table *st = ss->ss_priv;
188170530Ssam
189170530Ssam	mtx_lock(&st->st_lock);
190170530Ssam	sta_flush_table(st);
191170530Ssam	mtx_unlock(&st->st_lock);
192170530Ssam	ss->ss_last = 0;
193170530Ssam	return 0;
194170530Ssam}
195170530Ssam
196170530Ssam/*
197170530Ssam * Flush all entries in the scan cache.
198170530Ssam */
199170530Ssamstatic void
200170530Ssamsta_flush_table(struct sta_table *st)
201170530Ssam{
202170530Ssam	struct sta_entry *se, *next;
203170530Ssam
204170530Ssam	TAILQ_FOREACH_SAFE(se, &st->st_entry, se_list, next) {
205170530Ssam		TAILQ_REMOVE(&st->st_entry, se, se_list);
206170530Ssam		LIST_REMOVE(se, se_hash);
207178354Ssam		ieee80211_ies_cleanup(&se->base.se_ies);
208186302Ssam		free(se, M_80211_SCAN);
209170530Ssam	}
210178354Ssam	memset(st->st_maxrssi, 0, sizeof(st->st_maxrssi));
211170530Ssam}
212170530Ssam
213170530Ssam/*
214170530Ssam * Process a beacon or probe response frame; create an
215170530Ssam * entry in the scan cache or update any previous entry.
216170530Ssam */
217170530Ssamstatic int
218170530Ssamsta_add(struct ieee80211_scan_state *ss,
219170530Ssam	const struct ieee80211_scanparams *sp,
220170530Ssam	const struct ieee80211_frame *wh,
221170530Ssam	int subtype, int rssi, int noise, int rstamp)
222170530Ssam{
223170530Ssam#define	ISPROBE(_st)	((_st) == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
224170530Ssam#define	PICK1ST(_ss) \
225170530Ssam	((ss->ss_flags & (IEEE80211_SCAN_PICK1ST | IEEE80211_SCAN_GOTPICK)) == \
226170530Ssam	IEEE80211_SCAN_PICK1ST)
227170530Ssam	struct sta_table *st = ss->ss_priv;
228170530Ssam	const uint8_t *macaddr = wh->i_addr2;
229178354Ssam	struct ieee80211vap *vap = ss->ss_vap;
230178354Ssam	struct ieee80211com *ic = vap->iv_ic;
231170530Ssam	struct sta_entry *se;
232170530Ssam	struct ieee80211_scan_entry *ise;
233178354Ssam	int hash;
234170530Ssam
235170530Ssam	hash = STA_HASH(macaddr);
236170530Ssam
237170530Ssam	mtx_lock(&st->st_lock);
238170530Ssam	LIST_FOREACH(se, &st->st_hash[hash], se_hash)
239170530Ssam		if (IEEE80211_ADDR_EQ(se->base.se_macaddr, macaddr))
240170530Ssam			goto found;
241186302Ssam	se = (struct sta_entry *) malloc(sizeof(struct sta_entry),
242170530Ssam		M_80211_SCAN, M_NOWAIT | M_ZERO);
243170530Ssam	if (se == NULL) {
244170530Ssam		mtx_unlock(&st->st_lock);
245170530Ssam		return 0;
246170530Ssam	}
247178354Ssam	se->se_scangen = st->st_scaniter-1;
248178354Ssam	se->se_avgrssi = IEEE80211_RSSI_DUMMY_MARKER;
249170530Ssam	IEEE80211_ADDR_COPY(se->base.se_macaddr, macaddr);
250170530Ssam	TAILQ_INSERT_TAIL(&st->st_entry, se, se_list);
251170530Ssam	LIST_INSERT_HEAD(&st->st_hash[hash], se, se_hash);
252170530Ssamfound:
253170530Ssam	ise = &se->base;
254170530Ssam	/* XXX ap beaconing multiple ssid w/ same bssid */
255170530Ssam	if (sp->ssid[1] != 0 &&
256170530Ssam	    (ISPROBE(subtype) || ise->se_ssid[1] == 0))
257170530Ssam		memcpy(ise->se_ssid, sp->ssid, 2+sp->ssid[1]);
258170530Ssam	KASSERT(sp->rates[1] <= IEEE80211_RATE_MAXSIZE,
259170530Ssam		("rate set too large: %u", sp->rates[1]));
260170530Ssam	memcpy(ise->se_rates, sp->rates, 2+sp->rates[1]);
261170530Ssam	if (sp->xrates != NULL) {
262170530Ssam		/* XXX validate xrates[1] */
263178354Ssam		KASSERT(sp->xrates[1] <= IEEE80211_RATE_MAXSIZE,
264170530Ssam			("xrate set too large: %u", sp->xrates[1]));
265170530Ssam		memcpy(ise->se_xrates, sp->xrates, 2+sp->xrates[1]);
266170530Ssam	} else
267170530Ssam		ise->se_xrates[1] = 0;
268170530Ssam	IEEE80211_ADDR_COPY(ise->se_bssid, wh->i_addr3);
269178354Ssam	if ((sp->status & IEEE80211_BPARSE_OFFCHAN) == 0) {
270173368Ssam		/*
271173368Ssam		 * Record rssi data using extended precision LPF filter.
272173368Ssam		 *
273173368Ssam		 * NB: use only on-channel data to insure we get a good
274173368Ssam		 *     estimate of the signal we'll see when associated.
275173368Ssam		 */
276178354Ssam		IEEE80211_RSSI_LPF(se->se_avgrssi, rssi);
277178354Ssam		ise->se_rssi = IEEE80211_RSSI_GET(se->se_avgrssi);
278173368Ssam		ise->se_noise = noise;
279173368Ssam	}
280170530Ssam	ise->se_rstamp = rstamp;
281170530Ssam	memcpy(ise->se_tstamp.data, sp->tstamp, sizeof(ise->se_tstamp));
282170530Ssam	ise->se_intval = sp->bintval;
283170530Ssam	ise->se_capinfo = sp->capinfo;
284173368Ssam	/*
285173368Ssam	 * Beware of overriding se_chan for frames seen
286173368Ssam	 * off-channel; this can cause us to attempt an
287178354Ssam	 * association on the wrong channel.
288173368Ssam	 */
289178354Ssam	if (sp->status & IEEE80211_BPARSE_OFFCHAN) {
290173862Ssam		struct ieee80211_channel *c;
291173368Ssam		/*
292173862Ssam		 * Off-channel, locate the home/bss channel for the sta
293178354Ssam		 * using the value broadcast in the DSPARMS ie.  We know
294178354Ssam		 * sp->chan has this value because it's used to calculate
295178354Ssam		 * IEEE80211_BPARSE_OFFCHAN.
296173368Ssam		 */
297178354Ssam		c = ieee80211_find_channel_byieee(ic, sp->chan,
298178354Ssam		    ic->ic_curchan->ic_flags);
299173956Ssam		if (c != NULL) {
300173956Ssam			ise->se_chan = c;
301173956Ssam		} else if (ise->se_chan == NULL) {
302173862Ssam			/* should not happen, pick something */
303178354Ssam			ise->se_chan = ic->ic_curchan;
304173862Ssam		}
305173862Ssam	} else
306178354Ssam		ise->se_chan = ic->ic_curchan;
307170530Ssam	ise->se_fhdwell = sp->fhdwell;
308170530Ssam	ise->se_fhindex = sp->fhindex;
309170530Ssam	ise->se_erp = sp->erp;
310170530Ssam	ise->se_timoff = sp->timoff;
311170530Ssam	if (sp->tim != NULL) {
312170530Ssam		const struct ieee80211_tim_ie *tim =
313170530Ssam		    (const struct ieee80211_tim_ie *) sp->tim;
314170530Ssam		ise->se_dtimperiod = tim->tim_period;
315170530Ssam	}
316178354Ssam	if (sp->country != NULL) {
317178354Ssam		const struct ieee80211_country_ie *cie =
318178354Ssam		    (const struct ieee80211_country_ie *) sp->country;
319178354Ssam		/*
320178354Ssam		 * If 11d is enabled and we're attempting to join a bss
321178354Ssam		 * that advertises it's country code then compare our
322178354Ssam		 * current settings to what we fetched from the country ie.
323178354Ssam		 * If our country code is unspecified or different then
324178354Ssam		 * dispatch an event to user space that identifies the
325178354Ssam		 * country code so our regdomain config can be changed.
326178354Ssam		 */
327178354Ssam		/* XXX only for STA mode? */
328178354Ssam		if ((IEEE80211_IS_CHAN_11D(ise->se_chan) ||
329178354Ssam		    (vap->iv_flags_ext & IEEE80211_FEXT_DOTD)) &&
330178354Ssam		    (ic->ic_regdomain.country == CTRY_DEFAULT ||
331178354Ssam		     !isocmp(cie->cc, ic->ic_regdomain.isocc))) {
332178354Ssam			/* only issue one notify event per scan */
333178354Ssam			if (se->se_countrygen != st->st_scangen) {
334178354Ssam				ieee80211_notify_country(vap, ise->se_bssid,
335178354Ssam				    cie->cc);
336178354Ssam				se->se_countrygen = st->st_scangen;
337178354Ssam			}
338178354Ssam		}
339178354Ssam		ise->se_cc[0] = cie->cc[0];
340178354Ssam		ise->se_cc[1] = cie->cc[1];
341178354Ssam	}
342178354Ssam	/* NB: no need to setup ie ptrs; they are not (currently) used */
343178354Ssam	(void) ieee80211_ies_init(&ise->se_ies, sp->ies, sp->ies_len);
344170530Ssam
345170530Ssam	/* clear failure count after STA_FAIL_AGE passes */
346170530Ssam	if (se->se_fails && (ticks - se->se_lastfail) > STA_FAILS_AGE*hz) {
347170530Ssam		se->se_fails = 0;
348178354Ssam		IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_SCAN, macaddr,
349170530Ssam		    "%s: fails %u", __func__, se->se_fails);
350170530Ssam	}
351170530Ssam
352170530Ssam	se->se_lastupdate = ticks;		/* update time */
353170530Ssam	se->se_seen = 1;
354170530Ssam	se->se_notseen = 0;
355170530Ssam
356186107Ssam	KASSERT(sizeof(sp->bchan) == 1, ("bchan size"));
357178354Ssam	if (rssi > st->st_maxrssi[sp->bchan])
358178354Ssam		st->st_maxrssi[sp->bchan] = rssi;
359178354Ssam
360170530Ssam	mtx_unlock(&st->st_lock);
361170530Ssam
362170530Ssam	/*
363170530Ssam	 * If looking for a quick choice and nothing's
364170530Ssam	 * been found check here.
365170530Ssam	 */
366178354Ssam	if (PICK1ST(ss) && match_bss(vap, ss, se, IEEE80211_MSG_SCAN) == 0)
367170530Ssam		ss->ss_flags |= IEEE80211_SCAN_GOTPICK;
368170530Ssam
369170530Ssam	return 1;
370170530Ssam#undef PICK1ST
371170530Ssam#undef ISPROBE
372170530Ssam}
373170530Ssam
374170530Ssam/*
375170530Ssam * Check if a channel is excluded by user request.
376170530Ssam */
377170530Ssamstatic int
378178354Ssamisexcluded(struct ieee80211vap *vap, const struct ieee80211_channel *c)
379170530Ssam{
380178354Ssam	return (isclr(vap->iv_ic->ic_chan_active, c->ic_ieee) ||
381178354Ssam	    (vap->iv_des_chan != IEEE80211_CHAN_ANYC &&
382178354Ssam	     c->ic_freq != vap->iv_des_chan->ic_freq));
383170530Ssam}
384170530Ssam
385170530Ssamstatic struct ieee80211_channel *
386170530Ssamfind11gchannel(struct ieee80211com *ic, int i, int freq)
387170530Ssam{
388170530Ssam	struct ieee80211_channel *c;
389170530Ssam	int j;
390170530Ssam
391170530Ssam	/*
392170530Ssam	 * The normal ordering in the channel list is b channel
393170530Ssam	 * immediately followed by g so optimize the search for
394170530Ssam	 * this.  We'll still do a full search just in case.
395170530Ssam	 */
396170530Ssam	for (j = i+1; j < ic->ic_nchans; j++) {
397170530Ssam		c = &ic->ic_channels[j];
398170530Ssam		if (c->ic_freq == freq && IEEE80211_IS_CHAN_ANYG(c))
399170530Ssam			return c;
400170530Ssam	}
401170530Ssam	for (j = 0; j < i; j++) {
402170530Ssam		c = &ic->ic_channels[j];
403170530Ssam		if (c->ic_freq == freq && IEEE80211_IS_CHAN_ANYG(c))
404170530Ssam			return c;
405170530Ssam	}
406170530Ssam	return NULL;
407170530Ssam}
408170530Ssamstatic const u_int chanflags[IEEE80211_MODE_MAX] = {
409170530Ssam	IEEE80211_CHAN_B,	/* IEEE80211_MODE_AUTO */
410170530Ssam	IEEE80211_CHAN_A,	/* IEEE80211_MODE_11A */
411170530Ssam	IEEE80211_CHAN_B,	/* IEEE80211_MODE_11B */
412170530Ssam	IEEE80211_CHAN_G,	/* IEEE80211_MODE_11G */
413170530Ssam	IEEE80211_CHAN_FHSS,	/* IEEE80211_MODE_FH */
414170530Ssam	IEEE80211_CHAN_A,	/* IEEE80211_MODE_TURBO_A (check base channel)*/
415170530Ssam	IEEE80211_CHAN_G,	/* IEEE80211_MODE_TURBO_G */
416170530Ssam	IEEE80211_CHAN_ST,	/* IEEE80211_MODE_STURBO_A */
417170530Ssam	IEEE80211_CHAN_A,	/* IEEE80211_MODE_11NA (check legacy) */
418170530Ssam	IEEE80211_CHAN_G,	/* IEEE80211_MODE_11NG (check legacy) */
419170530Ssam};
420170530Ssam
421170530Ssamstatic void
422178354Ssamadd_channels(struct ieee80211vap *vap,
423170530Ssam	struct ieee80211_scan_state *ss,
424170530Ssam	enum ieee80211_phymode mode, const uint16_t freq[], int nfreq)
425170530Ssam{
426170530Ssam#define	N(a)	(sizeof(a) / sizeof(a[0]))
427178354Ssam	struct ieee80211com *ic = vap->iv_ic;
428170530Ssam	struct ieee80211_channel *c, *cg;
429170530Ssam	u_int modeflags;
430170530Ssam	int i;
431170530Ssam
432170530Ssam	KASSERT(mode < N(chanflags), ("Unexpected mode %u", mode));
433170530Ssam	modeflags = chanflags[mode];
434170530Ssam	for (i = 0; i < nfreq; i++) {
435170530Ssam		if (ss->ss_last >= IEEE80211_SCAN_MAX)
436170530Ssam			break;
437170530Ssam
438170530Ssam		c = ieee80211_find_channel(ic, freq[i], modeflags);
439178354Ssam		if (c == NULL || isexcluded(vap, c))
440170530Ssam			continue;
441170530Ssam		if (mode == IEEE80211_MODE_AUTO) {
442170530Ssam			/*
443170530Ssam			 * XXX special-case 11b/g channels so we select
444178354Ssam			 *     the g channel if both are present.
445170530Ssam			 */
446178354Ssam			if (IEEE80211_IS_CHAN_B(c) &&
447178354Ssam			    (cg = find11gchannel(ic, i, c->ic_freq)) != NULL)
448178354Ssam				c = cg;
449170530Ssam		}
450170530Ssam		ss->ss_chans[ss->ss_last++] = c;
451170530Ssam	}
452170530Ssam#undef N
453170530Ssam}
454170530Ssam
455170530Ssamstruct scanlist {
456170530Ssam	uint16_t	mode;
457170530Ssam	uint16_t	count;
458170530Ssam	const uint16_t	*list;
459170530Ssam};
460170530Ssam
461170530Ssamstatic int
462170530Ssamchecktable(const struct scanlist *scan, const struct ieee80211_channel *c)
463170530Ssam{
464170530Ssam	int i;
465170530Ssam
466170530Ssam	for (; scan->list != NULL; scan++) {
467170530Ssam		for (i = 0; i < scan->count; i++)
468170530Ssam			if (scan->list[i] == c->ic_freq)
469170530Ssam				return 1;
470170530Ssam	}
471170530Ssam	return 0;
472170530Ssam}
473170530Ssam
474176653Ssamstatic void
475178354Ssamsweepchannels(struct ieee80211_scan_state *ss, struct ieee80211vap *vap,
476176653Ssam	const struct scanlist table[])
477176653Ssam{
478178354Ssam	struct ieee80211com *ic = vap->iv_ic;
479176653Ssam	struct ieee80211_channel *c;
480176653Ssam	int i;
481176653Ssam
482176653Ssam	for (i = 0; i < ic->ic_nchans; i++) {
483176653Ssam		if (ss->ss_last >= IEEE80211_SCAN_MAX)
484176653Ssam			break;
485176653Ssam
486176653Ssam		c = &ic->ic_channels[i];
487176653Ssam		/*
488176653Ssam		 * Ignore dynamic turbo channels; we scan them
489176653Ssam		 * in normal mode (i.e. not boosted).  Likewise
490176653Ssam		 * for HT channels, they get scanned using
491176653Ssam		 * legacy rates.
492176653Ssam		 */
493176653Ssam		if (IEEE80211_IS_CHAN_DTURBO(c) || IEEE80211_IS_CHAN_HT(c))
494176653Ssam			continue;
495176653Ssam
496176653Ssam		/*
497176653Ssam		 * If a desired mode was specified, scan only
498176653Ssam		 * channels that satisfy that constraint.
499176653Ssam		 */
500178354Ssam		if (vap->iv_des_mode != IEEE80211_MODE_AUTO &&
501178354Ssam		    vap->iv_des_mode != ieee80211_chan2mode(c))
502176653Ssam			continue;
503176653Ssam
504176653Ssam		/*
505176653Ssam		 * Skip channels excluded by user request.
506176653Ssam		 */
507178354Ssam		if (isexcluded(vap, c))
508176653Ssam			continue;
509176653Ssam
510176653Ssam		/*
511176653Ssam		 * Add the channel unless it is listed in the
512176653Ssam		 * fixed scan order tables.  This insures we
513176653Ssam		 * don't sweep back in channels we filtered out
514176653Ssam		 * above.
515176653Ssam		 */
516176653Ssam		if (checktable(table, c))
517176653Ssam			continue;
518176653Ssam
519176653Ssam		/* Add channel to scanning list. */
520176653Ssam		ss->ss_chans[ss->ss_last++] = c;
521176653Ssam	}
522176653Ssam}
523176653Ssam
524178354Ssamstatic void
525178354Ssammakescanlist(struct ieee80211_scan_state *ss, struct ieee80211vap *vap,
526178354Ssam	const struct scanlist table[])
527170530Ssam{
528170530Ssam	const struct scanlist *scan;
529170530Ssam	enum ieee80211_phymode mode;
530170530Ssam
531170530Ssam	ss->ss_last = 0;
532170530Ssam	/*
533170530Ssam	 * Use the table of ordered channels to construct the list
534170530Ssam	 * of channels for scanning.  Any channels in the ordered
535170530Ssam	 * list not in the master list will be discarded.
536170530Ssam	 */
537178354Ssam	for (scan = table; scan->list != NULL; scan++) {
538170530Ssam		mode = scan->mode;
539178354Ssam		if (vap->iv_des_mode != IEEE80211_MODE_AUTO) {
540170530Ssam			/*
541170530Ssam			 * If a desired mode was specified, scan only
542170530Ssam			 * channels that satisfy that constraint.
543170530Ssam			 */
544178354Ssam			if (vap->iv_des_mode != mode) {
545170530Ssam				/*
546170530Ssam				 * The scan table marks 2.4Ghz channels as b
547170530Ssam				 * so if the desired mode is 11g, then use
548170530Ssam				 * the 11b channel list but upgrade the mode.
549170530Ssam				 */
550178354Ssam				if (vap->iv_des_mode != IEEE80211_MODE_11G ||
551170530Ssam				    mode != IEEE80211_MODE_11B)
552170530Ssam					continue;
553170530Ssam				mode = IEEE80211_MODE_11G;	/* upgrade */
554170530Ssam			}
555170530Ssam		} else {
556170530Ssam			/*
557170530Ssam			 * This lets add_channels upgrade an 11b channel
558170530Ssam			 * to 11g if available.
559170530Ssam			 */
560170530Ssam			if (mode == IEEE80211_MODE_11B)
561170530Ssam				mode = IEEE80211_MODE_AUTO;
562170530Ssam		}
563170530Ssam#ifdef IEEE80211_F_XR
564170530Ssam		/* XR does not operate on turbo channels */
565178354Ssam		if ((vap->iv_flags & IEEE80211_F_XR) &&
566170530Ssam		    (mode == IEEE80211_MODE_TURBO_A ||
567170530Ssam		     mode == IEEE80211_MODE_TURBO_G ||
568170530Ssam		     mode == IEEE80211_MODE_STURBO_A))
569170530Ssam			continue;
570170530Ssam#endif
571170530Ssam		/*
572170530Ssam		 * Add the list of the channels; any that are not
573170530Ssam		 * in the master channel list will be discarded.
574170530Ssam		 */
575178354Ssam		add_channels(vap, ss, mode, scan->list, scan->count);
576170530Ssam	}
577170530Ssam
578170530Ssam	/*
579178354Ssam	 * Add the channels from the ic that are not present
580178354Ssam	 * in the table.
581170530Ssam	 */
582178354Ssam	sweepchannels(ss, vap, table);
583178354Ssam}
584170530Ssam
585178354Ssamstatic const uint16_t rcl1[] =		/* 8 FCC channel: 52, 56, 60, 64, 36, 40, 44, 48 */
586178354Ssam{ 5260, 5280, 5300, 5320, 5180, 5200, 5220, 5240 };
587178354Ssamstatic const uint16_t rcl2[] =		/* 4 MKK channels: 34, 38, 42, 46 */
588178354Ssam{ 5170, 5190, 5210, 5230 };
589178354Ssamstatic const uint16_t rcl3[] =		/* 2.4Ghz ch: 1,6,11,7,13 */
590178354Ssam{ 2412, 2437, 2462, 2442, 2472 };
591178354Ssamstatic const uint16_t rcl4[] =		/* 5 FCC channel: 149, 153, 161, 165 */
592178354Ssam{ 5745, 5765, 5785, 5805, 5825 };
593178354Ssamstatic const uint16_t rcl7[] =		/* 11 ETSI channel: 100,104,108,112,116,120,124,128,132,136,140 */
594178354Ssam{ 5500, 5520, 5540, 5560, 5580, 5600, 5620, 5640, 5660, 5680, 5700 };
595178354Ssamstatic const uint16_t rcl8[] =		/* 2.4Ghz ch: 2,3,4,5,8,9,10,12 */
596178354Ssam{ 2417, 2422, 2427, 2432, 2447, 2452, 2457, 2467 };
597178354Ssamstatic const uint16_t rcl9[] =		/* 2.4Ghz ch: 14 */
598178354Ssam{ 2484 };
599178354Ssamstatic const uint16_t rcl10[] =	/* Added Korean channels 2312-2372 */
600178354Ssam{ 2312, 2317, 2322, 2327, 2332, 2337, 2342, 2347, 2352, 2357, 2362, 2367, 2372 };
601178354Ssamstatic const uint16_t rcl11[] =	/* Added Japan channels in 4.9/5.0 spectrum */
602178354Ssam{ 5040, 5060, 5080, 4920, 4940, 4960, 4980 };
603178354Ssam#ifdef ATH_TURBO_SCAN
604178354Ssamstatic const uint16_t rcl5[] =		/* 3 static turbo channels */
605178354Ssam{ 5210, 5250, 5290 };
606178354Ssamstatic const uint16_t rcl6[] =		/* 2 static turbo channels */
607178354Ssam{ 5760, 5800 };
608178354Ssamstatic const uint16_t rcl6x[] =	/* 4 FCC3 turbo channels */
609178354Ssam{ 5540, 5580, 5620, 5660 };
610178354Ssamstatic const uint16_t rcl12[] =	/* 2.4Ghz Turbo channel 6 */
611178354Ssam{ 2437 };
612178354Ssamstatic const uint16_t rcl13[] =	/* dynamic Turbo channels */
613178354Ssam{ 5200, 5240, 5280, 5765, 5805 };
614178354Ssam#endif /* ATH_TURBO_SCAN */
615170530Ssam
616178354Ssam#define	X(a)	.count = sizeof(a)/sizeof(a[0]), .list = a
617170530Ssam
618178354Ssamstatic const struct scanlist staScanTable[] = {
619178354Ssam	{ IEEE80211_MODE_11B,   	X(rcl3) },
620178354Ssam	{ IEEE80211_MODE_11A,   	X(rcl1) },
621178354Ssam	{ IEEE80211_MODE_11A,   	X(rcl2) },
622178354Ssam	{ IEEE80211_MODE_11B,   	X(rcl8) },
623178354Ssam	{ IEEE80211_MODE_11B,   	X(rcl9) },
624178354Ssam	{ IEEE80211_MODE_11A,   	X(rcl4) },
625178354Ssam#ifdef ATH_TURBO_SCAN
626178354Ssam	{ IEEE80211_MODE_STURBO_A,	X(rcl5) },
627178354Ssam	{ IEEE80211_MODE_STURBO_A,	X(rcl6) },
628178354Ssam	{ IEEE80211_MODE_TURBO_A,	X(rcl6x) },
629178354Ssam	{ IEEE80211_MODE_TURBO_A,	X(rcl13) },
630178354Ssam#endif /* ATH_TURBO_SCAN */
631178354Ssam	{ IEEE80211_MODE_11A,		X(rcl7) },
632178354Ssam	{ IEEE80211_MODE_11B,		X(rcl10) },
633178354Ssam	{ IEEE80211_MODE_11A,		X(rcl11) },
634178354Ssam#ifdef ATH_TURBO_SCAN
635178354Ssam	{ IEEE80211_MODE_TURBO_G,	X(rcl12) },
636178354Ssam#endif /* ATH_TURBO_SCAN */
637178354Ssam	{ .list = NULL }
638178354Ssam};
639178354Ssam
640178354Ssam/*
641178354Ssam * Start a station-mode scan by populating the channel list.
642178354Ssam */
643178354Ssamstatic int
644178354Ssamsta_start(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
645178354Ssam{
646178354Ssam	struct sta_table *st = ss->ss_priv;
647178354Ssam
648178354Ssam	makescanlist(ss, vap, staScanTable);
649178354Ssam
650178354Ssam	if (ss->ss_mindwell == 0)
651178354Ssam		ss->ss_mindwell = msecs_to_ticks(20);	/* 20ms */
652178354Ssam	if (ss->ss_maxdwell == 0)
653178354Ssam		ss->ss_maxdwell = msecs_to_ticks(200);	/* 200ms */
654178354Ssam
655178354Ssam	st->st_scangen++;
656170530Ssam	st->st_newscan = 1;
657170530Ssam
658170530Ssam	return 0;
659170530Ssam}
660170530Ssam
661170530Ssam/*
662178354Ssam * Restart a scan, typically a bg scan but can
663178354Ssam * also be a fg scan that came up empty.
664170530Ssam */
665170530Ssamstatic int
666178354Ssamsta_restart(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
667170530Ssam{
668170530Ssam	struct sta_table *st = ss->ss_priv;
669170530Ssam
670170530Ssam	st->st_newscan = 1;
671170530Ssam	return 0;
672170530Ssam}
673170530Ssam
674170530Ssam/*
675170530Ssam * Cancel an ongoing scan.
676170530Ssam */
677170530Ssamstatic int
678178354Ssamsta_cancel(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
679170530Ssam{
680170530Ssam	return 0;
681170530Ssam}
682170530Ssam
683178354Ssam/* unalligned little endian access */
684178354Ssam#define LE_READ_2(p)					\
685178354Ssam	((uint16_t)					\
686178354Ssam	 ((((const uint8_t *)(p))[0]      ) |		\
687178354Ssam	  (((const uint8_t *)(p))[1] <<  8)))
688184302Ssam
689184302Ssam/*
690184302Ssam * Demote any supplied 11g channel to 11b.  There should
691184302Ssam * always be an 11b channel but we check anyway...
692184302Ssam */
693184302Ssamstatic struct ieee80211_channel *
694184302Ssamdemote11b(struct ieee80211vap *vap, struct ieee80211_channel *chan)
695184302Ssam{
696184302Ssam	struct ieee80211_channel *c;
697178354Ssam
698184302Ssam	if (IEEE80211_IS_CHAN_ANYG(chan) &&
699184302Ssam	    vap->iv_des_mode == IEEE80211_MODE_AUTO) {
700184302Ssam		c = ieee80211_find_channel(vap->iv_ic, chan->ic_freq,
701184302Ssam		    (chan->ic_flags &~ (IEEE80211_CHAN_PUREG | IEEE80211_CHAN_G)) |
702184302Ssam		    IEEE80211_CHAN_B);
703184302Ssam		if (c != NULL)
704184302Ssam			chan = c;
705184302Ssam	}
706184302Ssam	return chan;
707184302Ssam}
708184302Ssam
709178354Ssamstatic int
710170530Ssammaxrate(const struct ieee80211_scan_entry *se)
711170530Ssam{
712178354Ssam	const struct ieee80211_ie_htcap *htcap =
713178354Ssam	    (const struct ieee80211_ie_htcap *) se->se_ies.htcap_ie;
714178354Ssam	int rmax, r, i;
715178354Ssam	uint16_t caps;
716170530Ssam
717170530Ssam	rmax = 0;
718178354Ssam	if (htcap != NULL) {
719178354Ssam		/*
720178354Ssam		 * HT station; inspect supported MCS and then adjust
721178354Ssam		 * rate by channel width.  Could also include short GI
722178354Ssam		 * in this if we want to be extra accurate.
723178354Ssam		 */
724178354Ssam		/* XXX assumes MCS15 is max */
725178354Ssam		for (i = 15; i >= 0 && isclr(htcap->hc_mcsset, i); i--)
726178354Ssam			;
727178354Ssam		if (i >= 0) {
728178354Ssam			caps = LE_READ_2(&htcap->hc_cap);
729178354Ssam			/* XXX short/long GI */
730178354Ssam			if (caps & IEEE80211_HTCAP_CHWIDTH40)
731178354Ssam				rmax = ieee80211_htrates[i].ht40_rate_400ns;
732178354Ssam			else
733178354Ssam				rmax = ieee80211_htrates[i].ht40_rate_800ns;
734178354Ssam		}
735178354Ssam	}
736170530Ssam	for (i = 0; i < se->se_rates[1]; i++) {
737170530Ssam		r = se->se_rates[2+i] & IEEE80211_RATE_VAL;
738170530Ssam		if (r > rmax)
739170530Ssam			rmax = r;
740170530Ssam	}
741170530Ssam	for (i = 0; i < se->se_xrates[1]; i++) {
742170530Ssam		r = se->se_xrates[2+i] & IEEE80211_RATE_VAL;
743170530Ssam		if (r > rmax)
744170530Ssam			rmax = r;
745170530Ssam	}
746170530Ssam	return rmax;
747170530Ssam}
748170530Ssam
749170530Ssam/*
750170530Ssam * Compare the capabilities of two entries and decide which is
751170530Ssam * more desirable (return >0 if a is considered better).  Note
752170530Ssam * that we assume compatibility/usability has already been checked
753170530Ssam * so we don't need to (e.g. validate whether privacy is supported).
754170530Ssam * Used to select the best scan candidate for association in a BSS.
755170530Ssam */
756170530Ssamstatic int
757170530Ssamsta_compare(const struct sta_entry *a, const struct sta_entry *b)
758170530Ssam{
759170530Ssam#define	PREFER(_a,_b,_what) do {			\
760170530Ssam	if (((_a) ^ (_b)) & (_what))			\
761170530Ssam		return ((_a) & (_what)) ? 1 : -1;	\
762170530Ssam} while (0)
763178354Ssam	int maxa, maxb;
764170530Ssam	int8_t rssia, rssib;
765170530Ssam	int weight;
766170530Ssam
767170530Ssam	/* privacy support */
768170530Ssam	PREFER(a->base.se_capinfo, b->base.se_capinfo,
769170530Ssam		IEEE80211_CAPINFO_PRIVACY);
770170530Ssam
771170530Ssam	/* compare count of previous failures */
772170530Ssam	weight = b->se_fails - a->se_fails;
773170530Ssam	if (abs(weight) > 1)
774170530Ssam		return weight;
775170530Ssam
776170530Ssam	/*
777170530Ssam	 * Compare rssi.  If the two are considered equivalent
778170530Ssam	 * then fallback to other criteria.  We threshold the
779170530Ssam	 * comparisons to avoid selecting an ap purely by rssi
780170530Ssam	 * when both values may be good but one ap is otherwise
781170530Ssam	 * more desirable (e.g. an 11b-only ap with stronger
782170530Ssam	 * signal than an 11g ap).
783170530Ssam	 */
784170530Ssam	rssia = MIN(a->base.se_rssi, STA_RSSI_MAX);
785170530Ssam	rssib = MIN(b->base.se_rssi, STA_RSSI_MAX);
786170530Ssam	if (abs(rssib - rssia) < 5) {
787170530Ssam		/* best/max rate preferred if signal level close enough XXX */
788170530Ssam		maxa = maxrate(&a->base);
789170530Ssam		maxb = maxrate(&b->base);
790170530Ssam		if (maxa != maxb)
791170530Ssam			return maxa - maxb;
792170530Ssam		/* XXX use freq for channel preference */
793170530Ssam		/* for now just prefer 5Ghz band to all other bands */
794178354Ssam		PREFER(IEEE80211_IS_CHAN_5GHZ(a->base.se_chan),
795178354Ssam		       IEEE80211_IS_CHAN_5GHZ(b->base.se_chan), 1);
796170530Ssam	}
797170530Ssam	/* all things being equal, use signal level */
798170530Ssam	return a->base.se_rssi - b->base.se_rssi;
799170530Ssam#undef PREFER
800170530Ssam}
801170530Ssam
802170530Ssam/*
803170530Ssam * Check rate set suitability and return the best supported rate.
804178354Ssam * XXX inspect MCS for HT
805170530Ssam */
806170530Ssamstatic int
807184302Ssamcheck_rate(struct ieee80211vap *vap, const struct ieee80211_channel *chan,
808184302Ssam    const struct ieee80211_scan_entry *se)
809170530Ssam{
810170530Ssam#define	RV(v)	((v) & IEEE80211_RATE_VAL)
811170530Ssam	const struct ieee80211_rateset *srs;
812178354Ssam	int i, j, nrs, r, okrate, badrate, fixedrate, ucastrate;
813170530Ssam	const uint8_t *rs;
814170530Ssam
815178354Ssam	okrate = badrate = 0;
816170530Ssam
817184302Ssam	srs = ieee80211_get_suprates(vap->iv_ic, chan);
818170530Ssam	nrs = se->se_rates[1];
819170530Ssam	rs = se->se_rates+2;
820178354Ssam	/* XXX MCS */
821184302Ssam	ucastrate = vap->iv_txparms[ieee80211_chan2mode(chan)].ucastrate;
822170530Ssam	fixedrate = IEEE80211_FIXED_RATE_NONE;
823170530Ssamagain:
824170530Ssam	for (i = 0; i < nrs; i++) {
825170530Ssam		r = RV(rs[i]);
826170530Ssam		badrate = r;
827170530Ssam		/*
828170530Ssam		 * Check any fixed rate is included.
829170530Ssam		 */
830178354Ssam		if (r == ucastrate)
831170530Ssam			fixedrate = r;
832170530Ssam		/*
833170530Ssam		 * Check against our supported rates.
834170530Ssam		 */
835170530Ssam		for (j = 0; j < srs->rs_nrates; j++)
836170530Ssam			if (r == RV(srs->rs_rates[j])) {
837170530Ssam				if (r > okrate)		/* NB: track max */
838170530Ssam					okrate = r;
839170530Ssam				break;
840170530Ssam			}
841170530Ssam
842170530Ssam		if (j == srs->rs_nrates && (rs[i] & IEEE80211_RATE_BASIC)) {
843170530Ssam			/*
844170530Ssam			 * Don't try joining a BSS, if we don't support
845170530Ssam			 * one of its basic rates.
846170530Ssam			 */
847170530Ssam			okrate = 0;
848170530Ssam			goto back;
849170530Ssam		}
850170530Ssam	}
851170530Ssam	if (rs == se->se_rates+2) {
852170530Ssam		/* scan xrates too; sort of an algol68-style for loop */
853170530Ssam		nrs = se->se_xrates[1];
854170530Ssam		rs = se->se_xrates+2;
855170530Ssam		goto again;
856170530Ssam	}
857170530Ssam
858170530Ssamback:
859178354Ssam	if (okrate == 0 || ucastrate != fixedrate)
860170530Ssam		return badrate | IEEE80211_RATE_BASIC;
861170530Ssam	else
862170530Ssam		return RV(okrate);
863170530Ssam#undef RV
864170530Ssam}
865170530Ssam
866170530Ssamstatic int
867170530Ssammatch_ssid(const uint8_t *ie,
868170530Ssam	int nssid, const struct ieee80211_scan_ssid ssids[])
869170530Ssam{
870170530Ssam	int i;
871170530Ssam
872170530Ssam	for (i = 0; i < nssid; i++) {
873170530Ssam		if (ie[1] == ssids[i].len &&
874170530Ssam		     memcmp(ie+2, ssids[i].ssid, ie[1]) == 0)
875170530Ssam			return 1;
876170530Ssam	}
877170530Ssam	return 0;
878170530Ssam}
879170530Ssam
880186904Ssam#ifdef IEEE80211_SUPPORT_TDMA
881186904Ssamstatic int
882186904Ssamtdma_isfull(const struct ieee80211_tdma_param *tdma)
883186904Ssam{
884186904Ssam	int slot, slotcnt;
885186904Ssam
886186904Ssam	slotcnt = tdma->tdma_slotcnt;
887186904Ssam	for (slot = slotcnt-1; slot >= 0; slot--)
888186904Ssam		if (isclr(tdma->tdma_inuse, slot))
889186904Ssam			return 0;
890186904Ssam	return 1;
891186904Ssam}
892186904Ssam#endif /* IEEE80211_SUPPORT_TDMA */
893186904Ssam
894170530Ssam/*
895170530Ssam * Test a scan candidate for suitability/compatibility.
896170530Ssam */
897170530Ssamstatic int
898178354Ssammatch_bss(struct ieee80211vap *vap,
899170530Ssam	const struct ieee80211_scan_state *ss, struct sta_entry *se0,
900170530Ssam	int debug)
901170530Ssam{
902178354Ssam	struct ieee80211com *ic = vap->iv_ic;
903170530Ssam	struct ieee80211_scan_entry *se = &se0->base;
904178354Ssam        uint8_t rate;
905178354Ssam        int fail;
906170530Ssam
907170530Ssam	fail = 0;
908170530Ssam	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, se->se_chan)))
909171409Ssam		fail |= MATCH_CHANNEL;
910170530Ssam	/*
911170530Ssam	 * NB: normally the desired mode is used to construct
912170530Ssam	 * the channel list, but it's possible for the scan
913170530Ssam	 * cache to include entries for stations outside this
914170530Ssam	 * list so we check the desired mode here to weed them
915170530Ssam	 * out.
916170530Ssam	 */
917178354Ssam	if (vap->iv_des_mode != IEEE80211_MODE_AUTO &&
918170530Ssam	    (se->se_chan->ic_flags & IEEE80211_CHAN_ALLTURBO) !=
919178354Ssam	    chanflags[vap->iv_des_mode])
920171409Ssam		fail |= MATCH_CHANNEL;
921178354Ssam	if (vap->iv_opmode == IEEE80211_M_IBSS) {
922170530Ssam		if ((se->se_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
923171409Ssam			fail |= MATCH_CAPINFO;
924186904Ssam#ifdef IEEE80211_SUPPORT_TDMA
925186904Ssam	} else if (vap->iv_opmode == IEEE80211_M_AHDEMO) {
926186904Ssam		/*
927186904Ssam		 * Adhoc demo network setup shouldn't really be scanning
928186904Ssam		 * but just in case skip stations operating in IBSS or
929186904Ssam		 * BSS mode.
930186904Ssam		 */
931186904Ssam		if (se->se_capinfo & (IEEE80211_CAPINFO_IBSS|IEEE80211_CAPINFO_ESS))
932186904Ssam			fail |= MATCH_CAPINFO;
933186904Ssam		/*
934186904Ssam		 * TDMA operation cannot coexist with a normal 802.11 network;
935186904Ssam		 * skip if IBSS or ESS capabilities are marked and require
936186904Ssam		 * the beacon have a TDMA ie present.
937186904Ssam		 */
938186904Ssam		if (vap->iv_caps & IEEE80211_C_TDMA) {
939186904Ssam			const struct ieee80211_tdma_param *tdma =
940186904Ssam			    (const struct ieee80211_tdma_param *)se->se_ies.tdma_ie;
941186904Ssam
942186904Ssam			if (tdma == NULL)
943186904Ssam				fail |= MATCH_TDMA_NOIE;
944186904Ssam			else if (tdma->tdma_slot != 0)
945186904Ssam				fail |= MATCH_TDMA_NOTMASTER;
946186904Ssam			else if (tdma_isfull(tdma))
947186904Ssam				fail |= MATCH_TDMA_NOSLOT;
948186904Ssam#if 0
949186904Ssam			else if (ieee80211_local_address(se->se_macaddr))
950186904Ssam				fail |= MATCH_TDMA_LOCAL;
951186904Ssam#endif
952186904Ssam		}
953186904Ssam#endif /* IEEE80211_SUPPORT_TDMA */
954170530Ssam	} else {
955170530Ssam		if ((se->se_capinfo & IEEE80211_CAPINFO_ESS) == 0)
956171409Ssam			fail |= MATCH_CAPINFO;
957178354Ssam		/*
958178354Ssam		 * If 11d is enabled and we're attempting to join a bss
959178354Ssam		 * that advertises it's country code then compare our
960178354Ssam		 * current settings to what we fetched from the country ie.
961178354Ssam		 * If our country code is unspecified or different then do
962178354Ssam		 * not attempt to join the bss.  We should have already
963178354Ssam		 * dispatched an event to user space that identifies the
964178354Ssam		 * new country code so our regdomain config should match.
965178354Ssam		 */
966178354Ssam		if ((IEEE80211_IS_CHAN_11D(se->se_chan) ||
967178354Ssam		    (vap->iv_flags_ext & IEEE80211_FEXT_DOTD)) &&
968178354Ssam		    se->se_cc[0] != 0 &&
969178354Ssam		    (ic->ic_regdomain.country == CTRY_DEFAULT ||
970178354Ssam		     !isocmp(se->se_cc, ic->ic_regdomain.isocc)))
971178354Ssam			fail |= MATCH_CC;
972170530Ssam	}
973178354Ssam	if (vap->iv_flags & IEEE80211_F_PRIVACY) {
974170530Ssam		if ((se->se_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
975171409Ssam			fail |= MATCH_PRIVACY;
976170530Ssam	} else {
977170530Ssam		/* XXX does this mean privacy is supported or required? */
978170530Ssam		if (se->se_capinfo & IEEE80211_CAPINFO_PRIVACY)
979171409Ssam			fail |= MATCH_PRIVACY;
980170530Ssam	}
981184302Ssam	se0->se_flags &= ~STA_DEMOTE11B;
982184302Ssam	rate = check_rate(vap, se->se_chan, se);
983184302Ssam	if (rate & IEEE80211_RATE_BASIC) {
984171409Ssam		fail |= MATCH_RATE;
985184302Ssam		/*
986184302Ssam		 * An 11b-only ap will give a rate mismatch if there is an
987184302Ssam		 * OFDM fixed tx rate for 11g.  Try downgrading the channel
988184302Ssam		 * in the scan list to 11b and retry the rate check.
989184302Ssam		 */
990184302Ssam		if (IEEE80211_IS_CHAN_ANYG(se->se_chan)) {
991184302Ssam			rate = check_rate(vap, demote11b(vap, se->se_chan), se);
992184302Ssam			if ((rate & IEEE80211_RATE_BASIC) == 0) {
993184302Ssam				fail &= ~MATCH_RATE;
994184302Ssam				se0->se_flags |= STA_DEMOTE11B;
995184302Ssam			}
996184302Ssam		}
997184302Ssam	} else if (rate < 2*24) {
998184302Ssam		/*
999184302Ssam		 * This is an 11b-only ap.  Check the desired mode in
1000184302Ssam		 * case that needs to be honored (mode 11g filters out
1001184302Ssam		 * 11b-only ap's).  Otherwise force any 11g channel used
1002184302Ssam		 * in scanning to be demoted.
1003184302Ssam		 *
1004184302Ssam		 * NB: we cheat a bit here by looking at the max rate;
1005184302Ssam		 *     we could/should check the rates.
1006184302Ssam		 */
1007184302Ssam		if (!(vap->iv_des_mode == IEEE80211_MODE_AUTO ||
1008184302Ssam		      vap->iv_des_mode == IEEE80211_MODE_11B))
1009184302Ssam			fail |= MATCH_RATE;
1010184302Ssam		else
1011184302Ssam			se0->se_flags |= STA_DEMOTE11B;
1012184302Ssam	}
1013170530Ssam	if (ss->ss_nssid != 0 &&
1014171409Ssam	    !match_ssid(se->se_ssid, ss->ss_nssid, ss->ss_ssid))
1015171409Ssam		fail |= MATCH_SSID;
1016178354Ssam	if ((vap->iv_flags & IEEE80211_F_DESBSSID) &&
1017178354Ssam	    !IEEE80211_ADDR_EQ(vap->iv_des_bssid, se->se_bssid))
1018178354Ssam		fail |= MATCH_BSSID;
1019170530Ssam	if (se0->se_fails >= STA_FAILS_MAX)
1020171409Ssam		fail |= MATCH_FAILS;
1021170530Ssam	if (se0->se_notseen >= STA_PURGE_SCANS)
1022171409Ssam		fail |= MATCH_NOTSEEN;
1023170530Ssam	if (se->se_rssi < STA_RSSI_MIN)
1024171409Ssam		fail |= MATCH_RSSI;
1025170530Ssam#ifdef IEEE80211_DEBUG
1026178354Ssam	if (ieee80211_msg(vap, debug)) {
1027170530Ssam		printf(" %c %s",
1028171409Ssam		    fail & MATCH_FAILS ? '=' :
1029171409Ssam		    fail & MATCH_NOTSEEN ? '^' :
1030178354Ssam		    fail & MATCH_CC ? '$' :
1031186904Ssam#ifdef IEEE80211_SUPPORT_TDMA
1032186904Ssam		    fail & MATCH_TDMA_NOIE ? '&' :
1033186904Ssam		    fail & MATCH_TDMA_NOTMASTER ? ':' :
1034186904Ssam		    fail & MATCH_TDMA_NOSLOT ? '@' :
1035186904Ssam		    fail & MATCH_TDMA_LOCAL ? '#' :
1036186904Ssam#endif
1037171409Ssam		    fail ? '-' : '+', ether_sprintf(se->se_macaddr));
1038170530Ssam		printf(" %s%c", ether_sprintf(se->se_bssid),
1039171409Ssam		    fail & MATCH_BSSID ? '!' : ' ');
1040170530Ssam		printf(" %3d%c", ieee80211_chan2ieee(ic, se->se_chan),
1041171409Ssam			fail & MATCH_CHANNEL ? '!' : ' ');
1042171409Ssam		printf(" %+4d%c", se->se_rssi, fail & MATCH_RSSI ? '!' : ' ');
1043170530Ssam		printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
1044171409Ssam		    fail & MATCH_RATE ? '!' : ' ');
1045170530Ssam		printf(" %4s%c",
1046170530Ssam		    (se->se_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
1047170530Ssam		    (se->se_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
1048170530Ssam		    "????",
1049171409Ssam		    fail & MATCH_CAPINFO ? '!' : ' ');
1050170530Ssam		printf(" %3s%c ",
1051170530Ssam		    (se->se_capinfo & IEEE80211_CAPINFO_PRIVACY) ?
1052170530Ssam		    "wep" : "no",
1053171409Ssam		    fail & MATCH_PRIVACY ? '!' : ' ');
1054170530Ssam		ieee80211_print_essid(se->se_ssid+2, se->se_ssid[1]);
1055171409Ssam		printf("%s\n", fail & MATCH_SSID ? "!" : "");
1056170530Ssam	}
1057170530Ssam#endif
1058170530Ssam	return fail;
1059170530Ssam}
1060170530Ssam
1061170530Ssamstatic void
1062170530Ssamsta_update_notseen(struct sta_table *st)
1063170530Ssam{
1064170530Ssam	struct sta_entry *se;
1065170530Ssam
1066170530Ssam	mtx_lock(&st->st_lock);
1067170530Ssam	TAILQ_FOREACH(se, &st->st_entry, se_list) {
1068170530Ssam		/*
1069170530Ssam		 * If seen the reset and don't bump the count;
1070170530Ssam		 * otherwise bump the ``not seen'' count.  Note
1071170530Ssam		 * that this insures that stations for which we
1072170530Ssam		 * see frames while not scanning but not during
1073170530Ssam		 * this scan will not be penalized.
1074170530Ssam		 */
1075170530Ssam		if (se->se_seen)
1076170530Ssam			se->se_seen = 0;
1077170530Ssam		else
1078170530Ssam			se->se_notseen++;
1079170530Ssam	}
1080170530Ssam	mtx_unlock(&st->st_lock);
1081170530Ssam}
1082170530Ssam
1083170530Ssamstatic void
1084170530Ssamsta_dec_fails(struct sta_table *st)
1085170530Ssam{
1086170530Ssam	struct sta_entry *se;
1087170530Ssam
1088170530Ssam	mtx_lock(&st->st_lock);
1089170530Ssam	TAILQ_FOREACH(se, &st->st_entry, se_list)
1090170530Ssam		if (se->se_fails)
1091170530Ssam			se->se_fails--;
1092170530Ssam	mtx_unlock(&st->st_lock);
1093170530Ssam}
1094170530Ssam
1095170530Ssamstatic struct sta_entry *
1096178354Ssamselect_bss(struct ieee80211_scan_state *ss, struct ieee80211vap *vap, int debug)
1097170530Ssam{
1098170530Ssam	struct sta_table *st = ss->ss_priv;
1099170530Ssam	struct sta_entry *se, *selbs = NULL;
1100170530Ssam
1101178354Ssam	IEEE80211_DPRINTF(vap, debug, " %s\n",
1102170530Ssam	    "macaddr          bssid         chan  rssi  rate flag  wep  essid");
1103170530Ssam	mtx_lock(&st->st_lock);
1104170530Ssam	TAILQ_FOREACH(se, &st->st_entry, se_list) {
1105184275Ssam		ieee80211_ies_expand(&se->base.se_ies);
1106178354Ssam		if (match_bss(vap, ss, se, debug) == 0) {
1107170530Ssam			if (selbs == NULL)
1108170530Ssam				selbs = se;
1109170530Ssam			else if (sta_compare(se, selbs) > 0)
1110170530Ssam				selbs = se;
1111170530Ssam		}
1112170530Ssam	}
1113170530Ssam	mtx_unlock(&st->st_lock);
1114170530Ssam
1115170530Ssam	return selbs;
1116170530Ssam}
1117170530Ssam
1118170530Ssam/*
1119170530Ssam * Pick an ap or ibss network to join or find a channel
1120170530Ssam * to use to start an ibss network.
1121170530Ssam */
1122170530Ssamstatic int
1123178354Ssamsta_pick_bss(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1124170530Ssam{
1125170530Ssam	struct sta_table *st = ss->ss_priv;
1126170530Ssam	struct sta_entry *selbs;
1127184274Ssam	struct ieee80211_channel *chan;
1128170530Ssam
1129178354Ssam	KASSERT(vap->iv_opmode == IEEE80211_M_STA,
1130178354Ssam		("wrong mode %u", vap->iv_opmode));
1131170530Ssam
1132170530Ssam	if (st->st_newscan) {
1133170530Ssam		sta_update_notseen(st);
1134170530Ssam		st->st_newscan = 0;
1135170530Ssam	}
1136170530Ssam	if (ss->ss_flags & IEEE80211_SCAN_NOPICK) {
1137170530Ssam		/*
1138170530Ssam		 * Manual/background scan, don't select+join the
1139170530Ssam		 * bss, just return.  The scanning framework will
1140170530Ssam		 * handle notification that this has completed.
1141170530Ssam		 */
1142170530Ssam		ss->ss_flags &= ~IEEE80211_SCAN_NOPICK;
1143170530Ssam		return 1;
1144170530Ssam	}
1145170530Ssam	/*
1146170530Ssam	 * Automatic sequencing; look for a candidate and
1147170530Ssam	 * if found join the network.
1148170530Ssam	 */
1149170530Ssam	/* NB: unlocked read should be ok */
1150170530Ssam	if (TAILQ_FIRST(&st->st_entry) == NULL) {
1151178354Ssam		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
1152170530Ssam			"%s: no scan candidate\n", __func__);
1153178354Ssam		if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1154178354Ssam			return 0;
1155170530Ssamnotfound:
1156170530Ssam		/*
1157170530Ssam		 * If nothing suitable was found decrement
1158170530Ssam		 * the failure counts so entries will be
1159170530Ssam		 * reconsidered the next time around.  We
1160170530Ssam		 * really want to do this only for sta's
1161170530Ssam		 * where we've previously had some success.
1162170530Ssam		 */
1163170530Ssam		sta_dec_fails(st);
1164170530Ssam		st->st_newscan = 1;
1165170530Ssam		return 0;			/* restart scan */
1166170530Ssam	}
1167178354Ssam	selbs = select_bss(ss, vap, IEEE80211_MSG_SCAN);
1168178354Ssam	if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1169178354Ssam		return (selbs != NULL);
1170184274Ssam	if (selbs == NULL)
1171170530Ssam		goto notfound;
1172184274Ssam	chan = selbs->base.se_chan;
1173184302Ssam	if (selbs->se_flags & STA_DEMOTE11B)
1174184302Ssam		chan = demote11b(vap, chan);
1175184274Ssam	if (!ieee80211_sta_join(vap, chan, &selbs->base))
1176184274Ssam		goto notfound;
1177170530Ssam	return 1;				/* terminate scan */
1178170530Ssam}
1179170530Ssam
1180170530Ssam/*
1181170530Ssam * Lookup an entry in the scan cache.  We assume we're
1182170530Ssam * called from the bottom half or such that we don't need
1183170530Ssam * to block the bottom half so that it's safe to return
1184170530Ssam * a reference to an entry w/o holding the lock on the table.
1185170530Ssam */
1186170530Ssamstatic struct sta_entry *
1187170530Ssamsta_lookup(struct sta_table *st, const uint8_t macaddr[IEEE80211_ADDR_LEN])
1188170530Ssam{
1189170530Ssam	struct sta_entry *se;
1190170530Ssam	int hash = STA_HASH(macaddr);
1191170530Ssam
1192170530Ssam	mtx_lock(&st->st_lock);
1193170530Ssam	LIST_FOREACH(se, &st->st_hash[hash], se_hash)
1194170530Ssam		if (IEEE80211_ADDR_EQ(se->base.se_macaddr, macaddr))
1195170530Ssam			break;
1196170530Ssam	mtx_unlock(&st->st_lock);
1197170530Ssam
1198170530Ssam	return se;		/* NB: unlocked */
1199170530Ssam}
1200170530Ssam
1201170530Ssamstatic void
1202178354Ssamsta_roam_check(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1203170530Ssam{
1204178354Ssam	struct ieee80211com *ic = vap->iv_ic;
1205178354Ssam	struct ieee80211_node *ni = vap->iv_bss;
1206170530Ssam	struct sta_table *st = ss->ss_priv;
1207178354Ssam	enum ieee80211_phymode mode;
1208170530Ssam	struct sta_entry *se, *selbs;
1209178354Ssam	uint8_t roamRate, curRate, ucastRate;
1210170530Ssam	int8_t roamRssi, curRssi;
1211170530Ssam
1212170530Ssam	se = sta_lookup(st, ni->ni_macaddr);
1213170530Ssam	if (se == NULL) {
1214170530Ssam		/* XXX something is wrong */
1215170530Ssam		return;
1216170530Ssam	}
1217170530Ssam
1218178354Ssam	mode = ieee80211_chan2mode(ic->ic_bsschan);
1219178354Ssam	roamRate = vap->iv_roamparms[mode].rate;
1220178354Ssam	roamRssi = vap->iv_roamparms[mode].rssi;
1221178354Ssam	ucastRate = vap->iv_txparms[mode].ucastrate;
1222170530Ssam	/* NB: the most up to date rssi is in the node, not the scan cache */
1223170530Ssam	curRssi = ic->ic_node_getrssi(ni);
1224178354Ssam	if (ucastRate == IEEE80211_FIXED_RATE_NONE) {
1225178354Ssam		curRate = ni->ni_txrate;
1226178354Ssam		roamRate &= IEEE80211_RATE_VAL;
1227178354Ssam		IEEE80211_DPRINTF(vap, IEEE80211_MSG_ROAM,
1228170530Ssam		    "%s: currssi %d currate %u roamrssi %d roamrate %u\n",
1229170530Ssam		    __func__, curRssi, curRate, roamRssi, roamRate);
1230170530Ssam	} else {
1231170530Ssam		curRate = roamRate;	/* NB: insure compare below fails */
1232178354Ssam		IEEE80211_DPRINTF(vap, IEEE80211_MSG_ROAM,
1233170530Ssam		    "%s: currssi %d roamrssi %d\n", __func__, curRssi, roamRssi);
1234170530Ssam	}
1235170530Ssam	/*
1236170530Ssam	 * Check if a new ap should be used and switch.
1237170530Ssam	 * XXX deauth current ap
1238170530Ssam	 */
1239170530Ssam	if (curRate < roamRate || curRssi < roamRssi) {
1240178354Ssam		if (time_after(ticks, ic->ic_lastscan + vap->iv_scanvalid)) {
1241170530Ssam			/*
1242170530Ssam			 * Scan cache contents are too old; force a scan now
1243170530Ssam			 * if possible so we have current state to make a
1244170530Ssam			 * decision with.  We don't kick off a bg scan if
1245170530Ssam			 * we're using dynamic turbo and boosted or if the
1246170530Ssam			 * channel is busy.
1247170530Ssam			 * XXX force immediate switch on scan complete
1248170530Ssam			 */
1249170530Ssam			if (!IEEE80211_IS_CHAN_DTURBO(ic->ic_curchan) &&
1250178354Ssam			    time_after(ticks, ic->ic_lastdata + vap->iv_bgscanidle))
1251178354Ssam				ieee80211_bg_scan(vap, 0);
1252170530Ssam			return;
1253170530Ssam		}
1254170530Ssam		se->base.se_rssi = curRssi;
1255178354Ssam		selbs = select_bss(ss, vap, IEEE80211_MSG_ROAM);
1256170530Ssam		if (selbs != NULL && selbs != se) {
1257184274Ssam			struct ieee80211_channel *chan;
1258184274Ssam
1259178354Ssam			IEEE80211_DPRINTF(vap,
1260170530Ssam			    IEEE80211_MSG_ROAM | IEEE80211_MSG_DEBUG,
1261170530Ssam			    "%s: ROAM: curRate %u, roamRate %u, "
1262170530Ssam			    "curRssi %d, roamRssi %d\n", __func__,
1263170530Ssam			    curRate, roamRate, curRssi, roamRssi);
1264184274Ssam
1265184274Ssam			chan = selbs->base.se_chan;
1266184302Ssam			if (selbs->se_flags & STA_DEMOTE11B)
1267184302Ssam				chan = demote11b(vap, chan);
1268184274Ssam			(void) ieee80211_sta_join(vap, chan, &selbs->base);
1269170530Ssam		}
1270170530Ssam	}
1271170530Ssam}
1272170530Ssam
1273170530Ssam/*
1274170530Ssam * Age entries in the scan cache.
1275170530Ssam * XXX also do roaming since it's convenient
1276170530Ssam */
1277170530Ssamstatic void
1278170530Ssamsta_age(struct ieee80211_scan_state *ss)
1279170530Ssam{
1280178354Ssam	struct ieee80211vap *vap = ss->ss_vap;
1281170530Ssam
1282178354Ssam	adhoc_age(ss);
1283170530Ssam	/*
1284170530Ssam	 * If rate control is enabled check periodically to see if
1285170530Ssam	 * we should roam from our current connection to one that
1286170530Ssam	 * might be better.  This only applies when we're operating
1287170530Ssam	 * in sta mode and automatic roaming is set.
1288170530Ssam	 * XXX defer if busy
1289170530Ssam	 * XXX repeater station
1290170530Ssam	 * XXX do when !bgscan?
1291170530Ssam	 */
1292178354Ssam	KASSERT(vap->iv_opmode == IEEE80211_M_STA,
1293178354Ssam		("wrong mode %u", vap->iv_opmode));
1294178354Ssam	if (vap->iv_roaming == IEEE80211_ROAMING_AUTO &&
1295178354Ssam	    (vap->iv_ic->ic_flags & IEEE80211_F_BGSCAN) &&
1296178354Ssam	    vap->iv_state >= IEEE80211_S_RUN)
1297170530Ssam		/* XXX vap is implicit */
1298178354Ssam		sta_roam_check(ss, vap);
1299170530Ssam}
1300170530Ssam
1301170530Ssam/*
1302170530Ssam * Iterate over the entries in the scan cache, invoking
1303170530Ssam * the callback function on each one.
1304170530Ssam */
1305170530Ssamstatic void
1306170530Ssamsta_iterate(struct ieee80211_scan_state *ss,
1307170530Ssam	ieee80211_scan_iter_func *f, void *arg)
1308170530Ssam{
1309170530Ssam	struct sta_table *st = ss->ss_priv;
1310170530Ssam	struct sta_entry *se;
1311170530Ssam	u_int gen;
1312170530Ssam
1313170530Ssam	mtx_lock(&st->st_scanlock);
1314178354Ssam	gen = st->st_scaniter++;
1315170530Ssamrestart:
1316170530Ssam	mtx_lock(&st->st_lock);
1317170530Ssam	TAILQ_FOREACH(se, &st->st_entry, se_list) {
1318170530Ssam		if (se->se_scangen != gen) {
1319170530Ssam			se->se_scangen = gen;
1320170530Ssam			/* update public state */
1321170530Ssam			se->base.se_age = ticks - se->se_lastupdate;
1322170530Ssam			mtx_unlock(&st->st_lock);
1323170530Ssam			(*f)(arg, &se->base);
1324170530Ssam			goto restart;
1325170530Ssam		}
1326170530Ssam	}
1327170530Ssam	mtx_unlock(&st->st_lock);
1328170530Ssam
1329170530Ssam	mtx_unlock(&st->st_scanlock);
1330170530Ssam}
1331170530Ssam
1332170530Ssamstatic void
1333170530Ssamsta_assoc_fail(struct ieee80211_scan_state *ss,
1334170530Ssam	const uint8_t macaddr[IEEE80211_ADDR_LEN], int reason)
1335170530Ssam{
1336170530Ssam	struct sta_table *st = ss->ss_priv;
1337170530Ssam	struct sta_entry *se;
1338170530Ssam
1339170530Ssam	se = sta_lookup(st, macaddr);
1340170530Ssam	if (se != NULL) {
1341170530Ssam		se->se_fails++;
1342170530Ssam		se->se_lastfail = ticks;
1343178354Ssam		IEEE80211_NOTE_MAC(ss->ss_vap, IEEE80211_MSG_SCAN,
1344170530Ssam		    macaddr, "%s: reason %u fails %u",
1345170530Ssam		    __func__, reason, se->se_fails);
1346170530Ssam	}
1347170530Ssam}
1348170530Ssam
1349170530Ssamstatic void
1350170530Ssamsta_assoc_success(struct ieee80211_scan_state *ss,
1351170530Ssam	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1352170530Ssam{
1353170530Ssam	struct sta_table *st = ss->ss_priv;
1354170530Ssam	struct sta_entry *se;
1355170530Ssam
1356170530Ssam	se = sta_lookup(st, macaddr);
1357170530Ssam	if (se != NULL) {
1358170530Ssam#if 0
1359170530Ssam		se->se_fails = 0;
1360178354Ssam		IEEE80211_NOTE_MAC(ss->ss_vap, IEEE80211_MSG_SCAN,
1361170530Ssam		    macaddr, "%s: fails %u",
1362170530Ssam		    __func__, se->se_fails);
1363170530Ssam#endif
1364170530Ssam		se->se_lastassoc = ticks;
1365170530Ssam	}
1366170530Ssam}
1367170530Ssam
1368170530Ssamstatic const struct ieee80211_scanner sta_default = {
1369170530Ssam	.scan_name		= "default",
1370170530Ssam	.scan_attach		= sta_attach,
1371170530Ssam	.scan_detach		= sta_detach,
1372170530Ssam	.scan_start		= sta_start,
1373170530Ssam	.scan_restart		= sta_restart,
1374170530Ssam	.scan_cancel		= sta_cancel,
1375170530Ssam	.scan_end		= sta_pick_bss,
1376170530Ssam	.scan_flush		= sta_flush,
1377170530Ssam	.scan_add		= sta_add,
1378170530Ssam	.scan_age		= sta_age,
1379170530Ssam	.scan_iterate		= sta_iterate,
1380170530Ssam	.scan_assoc_fail	= sta_assoc_fail,
1381170530Ssam	.scan_assoc_success	= sta_assoc_success,
1382170530Ssam};
1383170530Ssam
1384170530Ssam/*
1385170530Ssam * Adhoc mode-specific support.
1386170530Ssam */
1387170530Ssam
1388170530Ssamstatic const uint16_t adhocWorld[] =		/* 36, 40, 44, 48 */
1389170530Ssam{ 5180, 5200, 5220, 5240 };
1390170530Ssamstatic const uint16_t adhocFcc3[] =		/* 36, 40, 44, 48 145, 149, 153, 157, 161, 165 */
1391170530Ssam{ 5180, 5200, 5220, 5240, 5725, 5745, 5765, 5785, 5805, 5825 };
1392170530Ssamstatic const uint16_t adhocMkk[] =		/* 34, 38, 42, 46 */
1393170530Ssam{ 5170, 5190, 5210, 5230 };
1394170530Ssamstatic const uint16_t adhoc11b[] =		/* 10, 11 */
1395170530Ssam{ 2457, 2462 };
1396170530Ssam
1397170530Ssamstatic const struct scanlist adhocScanTable[] = {
1398170530Ssam	{ IEEE80211_MODE_11B,   	X(adhoc11b) },
1399170530Ssam	{ IEEE80211_MODE_11A,   	X(adhocWorld) },
1400170530Ssam	{ IEEE80211_MODE_11A,   	X(adhocFcc3) },
1401170530Ssam	{ IEEE80211_MODE_11B,   	X(adhocMkk) },
1402170530Ssam	{ .list = NULL }
1403170530Ssam};
1404170530Ssam#undef X
1405170530Ssam
1406170530Ssam/*
1407170530Ssam * Start an adhoc-mode scan by populating the channel list.
1408170530Ssam */
1409170530Ssamstatic int
1410178354Ssamadhoc_start(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1411170530Ssam{
1412170530Ssam	struct sta_table *st = ss->ss_priv;
1413170530Ssam
1414178354Ssam	makescanlist(ss, vap, adhocScanTable);
1415176653Ssam
1416178354Ssam	if (ss->ss_mindwell == 0)
1417178354Ssam		ss->ss_mindwell = msecs_to_ticks(200);	/* 200ms */
1418178354Ssam	if (ss->ss_maxdwell == 0)
1419178354Ssam		ss->ss_maxdwell = msecs_to_ticks(200);	/* 200ms */
1420176653Ssam
1421178354Ssam	st->st_scangen++;
1422170530Ssam	st->st_newscan = 1;
1423170530Ssam
1424170530Ssam	return 0;
1425170530Ssam}
1426170530Ssam
1427170530Ssam/*
1428170530Ssam * Select a channel to start an adhoc network on.
1429170530Ssam * The channel list was populated with appropriate
1430170530Ssam * channels so select one that looks least occupied.
1431170530Ssam */
1432170530Ssamstatic struct ieee80211_channel *
1433178354Ssamadhoc_pick_channel(struct ieee80211_scan_state *ss, int flags)
1434170530Ssam{
1435170530Ssam	struct sta_table *st = ss->ss_priv;
1436170530Ssam	struct sta_entry *se;
1437170530Ssam	struct ieee80211_channel *c, *bestchan;
1438170530Ssam	int i, bestrssi, maxrssi;
1439170530Ssam
1440170530Ssam	bestchan = NULL;
1441170530Ssam	bestrssi = -1;
1442170530Ssam
1443170530Ssam	mtx_lock(&st->st_lock);
1444170530Ssam	for (i = 0; i < ss->ss_last; i++) {
1445170530Ssam		c = ss->ss_chans[i];
1446178354Ssam		/* never consider a channel with radar */
1447178354Ssam		if (IEEE80211_IS_CHAN_RADAR(c))
1448176653Ssam			continue;
1449178354Ssam		/* skip channels disallowed by regulatory settings */
1450178354Ssam		if (IEEE80211_IS_CHAN_NOADHOC(c))
1451178354Ssam			continue;
1452178354Ssam		/* check channel attributes for band compatibility */
1453178354Ssam		if (flags != 0 && (c->ic_flags & flags) != flags)
1454178354Ssam			continue;
1455170530Ssam		maxrssi = 0;
1456170530Ssam		TAILQ_FOREACH(se, &st->st_entry, se_list) {
1457170530Ssam			if (se->base.se_chan != c)
1458170530Ssam				continue;
1459170530Ssam			if (se->base.se_rssi > maxrssi)
1460170530Ssam				maxrssi = se->base.se_rssi;
1461170530Ssam		}
1462170530Ssam		if (bestchan == NULL || maxrssi < bestrssi)
1463170530Ssam			bestchan = c;
1464170530Ssam	}
1465170530Ssam	mtx_unlock(&st->st_lock);
1466170530Ssam
1467170530Ssam	return bestchan;
1468170530Ssam}
1469170530Ssam
1470170530Ssam/*
1471170530Ssam * Pick an ibss network to join or find a channel
1472170530Ssam * to use to start an ibss network.
1473170530Ssam */
1474170530Ssamstatic int
1475178354Ssamadhoc_pick_bss(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1476170530Ssam{
1477170530Ssam	struct sta_table *st = ss->ss_priv;
1478170530Ssam	struct sta_entry *selbs;
1479170530Ssam	struct ieee80211_channel *chan;
1480170530Ssam
1481178354Ssam	KASSERT(vap->iv_opmode == IEEE80211_M_IBSS ||
1482178354Ssam		vap->iv_opmode == IEEE80211_M_AHDEMO,
1483178354Ssam		("wrong opmode %u", vap->iv_opmode));
1484170530Ssam
1485170530Ssam	if (st->st_newscan) {
1486170530Ssam		sta_update_notseen(st);
1487170530Ssam		st->st_newscan = 0;
1488170530Ssam	}
1489170530Ssam	if (ss->ss_flags & IEEE80211_SCAN_NOPICK) {
1490170530Ssam		/*
1491170530Ssam		 * Manual/background scan, don't select+join the
1492170530Ssam		 * bss, just return.  The scanning framework will
1493170530Ssam		 * handle notification that this has completed.
1494170530Ssam		 */
1495170530Ssam		ss->ss_flags &= ~IEEE80211_SCAN_NOPICK;
1496170530Ssam		return 1;
1497170530Ssam	}
1498170530Ssam	/*
1499170530Ssam	 * Automatic sequencing; look for a candidate and
1500170530Ssam	 * if found join the network.
1501170530Ssam	 */
1502170530Ssam	/* NB: unlocked read should be ok */
1503170530Ssam	if (TAILQ_FIRST(&st->st_entry) == NULL) {
1504178354Ssam		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
1505170530Ssam			"%s: no scan candidate\n", __func__);
1506178354Ssam		if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1507178354Ssam			return 0;
1508170530Ssamnotfound:
1509186904Ssam		/* NB: never auto-start a tdma network for slot !0 */
1510186904Ssam#ifdef IEEE80211_SUPPORT_TDMA
1511186904Ssam		if (vap->iv_des_nssid &&
1512186904Ssam		    ((vap->iv_caps & IEEE80211_C_TDMA) == 0 ||
1513186904Ssam		     ieee80211_tdma_getslot(vap) == 0)) {
1514186904Ssam#else
1515178354Ssam		if (vap->iv_des_nssid) {
1516186904Ssam#endif
1517170530Ssam			/*
1518170530Ssam			 * No existing adhoc network to join and we have
1519170530Ssam			 * an ssid; start one up.  If no channel was
1520170530Ssam			 * specified, try to select a channel.
1521170530Ssam			 */
1522178354Ssam			if (vap->iv_des_chan == IEEE80211_CHAN_ANYC ||
1523178354Ssam			    IEEE80211_IS_CHAN_RADAR(vap->iv_des_chan)) {
1524183421Ssam				struct ieee80211com *ic = vap->iv_ic;
1525183421Ssam
1526183421Ssam				chan = adhoc_pick_channel(ss, 0);
1527183421Ssam				if (chan != NULL)
1528183421Ssam					chan = ieee80211_ht_adjust_channel(ic,
1529183421Ssam					    chan, vap->iv_flags_ext);
1530178354Ssam			} else
1531178354Ssam				chan = vap->iv_des_chan;
1532170530Ssam			if (chan != NULL) {
1533178354Ssam				ieee80211_create_ibss(vap, chan);
1534170530Ssam				return 1;
1535170530Ssam			}
1536170530Ssam		}
1537170530Ssam		/*
1538170530Ssam		 * If nothing suitable was found decrement
1539170530Ssam		 * the failure counts so entries will be
1540170530Ssam		 * reconsidered the next time around.  We
1541170530Ssam		 * really want to do this only for sta's
1542170530Ssam		 * where we've previously had some success.
1543170530Ssam		 */
1544170530Ssam		sta_dec_fails(st);
1545170530Ssam		st->st_newscan = 1;
1546170530Ssam		return 0;			/* restart scan */
1547170530Ssam	}
1548178354Ssam	selbs = select_bss(ss, vap, IEEE80211_MSG_SCAN);
1549178354Ssam	if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1550178354Ssam		return (selbs != NULL);
1551184274Ssam	if (selbs == NULL)
1552170530Ssam		goto notfound;
1553184274Ssam	chan = selbs->base.se_chan;
1554184302Ssam	if (selbs->se_flags & STA_DEMOTE11B)
1555184302Ssam		chan = demote11b(vap, chan);
1556184274Ssam	if (!ieee80211_sta_join(vap, chan, &selbs->base))
1557184274Ssam		goto notfound;
1558170530Ssam	return 1;				/* terminate scan */
1559170530Ssam}
1560170530Ssam
1561170530Ssam/*
1562170530Ssam * Age entries in the scan cache.
1563170530Ssam */
1564170530Ssamstatic void
1565170530Ssamadhoc_age(struct ieee80211_scan_state *ss)
1566170530Ssam{
1567170530Ssam	struct sta_table *st = ss->ss_priv;
1568170530Ssam	struct sta_entry *se, *next;
1569170530Ssam
1570170530Ssam	mtx_lock(&st->st_lock);
1571170530Ssam	TAILQ_FOREACH_SAFE(se, &st->st_entry, se_list, next) {
1572170530Ssam		if (se->se_notseen > STA_PURGE_SCANS) {
1573170530Ssam			TAILQ_REMOVE(&st->st_entry, se, se_list);
1574170530Ssam			LIST_REMOVE(se, se_hash);
1575178354Ssam			ieee80211_ies_cleanup(&se->base.se_ies);
1576186302Ssam			free(se, M_80211_SCAN);
1577170530Ssam		}
1578170530Ssam	}
1579170530Ssam	mtx_unlock(&st->st_lock);
1580170530Ssam}
1581170530Ssam
1582170530Ssamstatic const struct ieee80211_scanner adhoc_default = {
1583170530Ssam	.scan_name		= "default",
1584170530Ssam	.scan_attach		= sta_attach,
1585170530Ssam	.scan_detach		= sta_detach,
1586170530Ssam	.scan_start		= adhoc_start,
1587170530Ssam	.scan_restart		= sta_restart,
1588170530Ssam	.scan_cancel		= sta_cancel,
1589170530Ssam	.scan_end		= adhoc_pick_bss,
1590170530Ssam	.scan_flush		= sta_flush,
1591178354Ssam	.scan_pickchan		= adhoc_pick_channel,
1592170530Ssam	.scan_add		= sta_add,
1593170530Ssam	.scan_age		= adhoc_age,
1594170530Ssam	.scan_iterate		= sta_iterate,
1595170530Ssam	.scan_assoc_fail	= sta_assoc_fail,
1596170530Ssam	.scan_assoc_success	= sta_assoc_success,
1597170530Ssam};
1598170530Ssam
1599178354Ssamstatic void
1600178354Ssamap_force_promisc(struct ieee80211com *ic)
1601178354Ssam{
1602178354Ssam	struct ifnet *ifp = ic->ic_ifp;
1603178354Ssam
1604178354Ssam	IEEE80211_LOCK(ic);
1605178354Ssam	/* set interface into promiscuous mode */
1606178354Ssam	ifp->if_flags |= IFF_PROMISC;
1607178354Ssam	ic->ic_update_promisc(ifp);
1608178354Ssam	IEEE80211_UNLOCK(ic);
1609178354Ssam}
1610178354Ssam
1611178354Ssamstatic void
1612178354Ssamap_reset_promisc(struct ieee80211com *ic)
1613178354Ssam{
1614178354Ssam	IEEE80211_LOCK(ic);
1615178354Ssam	ieee80211_syncifflag_locked(ic, IFF_PROMISC);
1616178354Ssam	IEEE80211_UNLOCK(ic);
1617178354Ssam}
1618178354Ssam
1619178354Ssamstatic int
1620178354Ssamap_start(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1621178354Ssam{
1622178354Ssam	struct sta_table *st = ss->ss_priv;
1623178354Ssam
1624178354Ssam	makescanlist(ss, vap, staScanTable);
1625178354Ssam
1626178354Ssam	if (ss->ss_mindwell == 0)
1627178354Ssam		ss->ss_mindwell = msecs_to_ticks(200);	/* 200ms */
1628178354Ssam	if (ss->ss_maxdwell == 0)
1629178354Ssam		ss->ss_maxdwell = msecs_to_ticks(200);	/* 200ms */
1630178354Ssam
1631178354Ssam	st->st_scangen++;
1632178354Ssam	st->st_newscan = 1;
1633178354Ssam
1634178354Ssam	ap_force_promisc(vap->iv_ic);
1635178354Ssam	return 0;
1636178354Ssam}
1637178354Ssam
1638170530Ssam/*
1639178354Ssam * Cancel an ongoing scan.
1640170530Ssam */
1641170530Ssamstatic int
1642178354Ssamap_cancel(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1643170530Ssam{
1644178354Ssam	ap_reset_promisc(vap->iv_ic);
1645178354Ssam	return 0;
1646178354Ssam}
1647178354Ssam
1648178354Ssam/*
1649178354Ssam * Pick a quiet channel to use for ap operation.
1650178354Ssam */
1651178354Ssamstatic struct ieee80211_channel *
1652178354Ssamap_pick_channel(struct ieee80211_scan_state *ss, int flags)
1653178354Ssam{
1654178354Ssam	struct sta_table *st = ss->ss_priv;
1655178354Ssam	struct ieee80211_channel *bestchan = NULL;
1656178354Ssam	int i;
1657178354Ssam
1658178354Ssam	/* XXX select channel more intelligently, e.g. channel spread, power */
1659178354Ssam	/* NB: use scan list order to preserve channel preference */
1660178354Ssam	for (i = 0; i < ss->ss_last; i++) {
1661178354Ssam		struct ieee80211_channel *chan = ss->ss_chans[i];
1662178354Ssam		/*
1663178354Ssam		 * If the channel is unoccupied the max rssi
1664178354Ssam		 * should be zero; just take it.  Otherwise
1665178354Ssam		 * track the channel with the lowest rssi and
1666178354Ssam		 * use that when all channels appear occupied.
1667178354Ssam		 */
1668178354Ssam		if (IEEE80211_IS_CHAN_RADAR(chan))
1669178354Ssam			continue;
1670178354Ssam		if (IEEE80211_IS_CHAN_NOHOSTAP(chan))
1671178354Ssam			continue;
1672178354Ssam		/* check channel attributes for band compatibility */
1673178354Ssam		if (flags != 0 && (chan->ic_flags & flags) != flags)
1674178354Ssam			continue;
1675186107Ssam		KASSERT(sizeof(chan->ic_ieee) == 1, ("ic_chan size"));
1676178354Ssam		/* XXX channel have interference */
1677178354Ssam		if (st->st_maxrssi[chan->ic_ieee] == 0) {
1678178354Ssam			/* XXX use other considerations */
1679178354Ssam			return chan;
1680170530Ssam		}
1681178354Ssam		if (bestchan == NULL ||
1682178354Ssam		    st->st_maxrssi[chan->ic_ieee] < st->st_maxrssi[bestchan->ic_ieee])
1683178354Ssam			bestchan = chan;
1684178354Ssam	}
1685178354Ssam	return bestchan;
1686178354Ssam}
1687178354Ssam
1688178354Ssam/*
1689178354Ssam * Pick a quiet channel to use for ap operation.
1690178354Ssam */
1691178354Ssamstatic int
1692178354Ssamap_end(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1693178354Ssam{
1694178354Ssam	struct ieee80211com *ic = vap->iv_ic;
1695178354Ssam	struct ieee80211_channel *bestchan;
1696178354Ssam
1697178354Ssam	KASSERT(vap->iv_opmode == IEEE80211_M_HOSTAP,
1698178354Ssam		("wrong opmode %u", vap->iv_opmode));
1699178354Ssam	bestchan = ap_pick_channel(ss, 0);
1700178354Ssam	if (bestchan == NULL) {
1701178354Ssam		/* no suitable channel, should not happen */
1702178354Ssam		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
1703178354Ssam		    "%s: no suitable channel! (should not happen)\n", __func__);
1704178354Ssam		/* XXX print something? */
1705178354Ssam		return 0;			/* restart scan */
1706178354Ssam	}
1707178354Ssam	/*
1708178354Ssam	 * If this is a dynamic turbo channel, start with the unboosted one.
1709178354Ssam	 */
1710178354Ssam	if (IEEE80211_IS_CHAN_TURBO(bestchan)) {
1711178354Ssam		bestchan = ieee80211_find_channel(ic, bestchan->ic_freq,
1712178354Ssam			bestchan->ic_flags & ~IEEE80211_CHAN_TURBO);
1713178354Ssam		if (bestchan == NULL) {
1714178354Ssam			/* should never happen ?? */
1715178354Ssam			return 0;
1716170530Ssam		}
1717170530Ssam	}
1718178354Ssam	ap_reset_promisc(ic);
1719178354Ssam	if (ss->ss_flags & (IEEE80211_SCAN_NOPICK | IEEE80211_SCAN_NOJOIN)) {
1720178354Ssam		/*
1721178354Ssam		 * Manual/background scan, don't select+join the
1722178354Ssam		 * bss, just return.  The scanning framework will
1723178354Ssam		 * handle notification that this has completed.
1724178354Ssam		 */
1725178354Ssam		ss->ss_flags &= ~IEEE80211_SCAN_NOPICK;
1726178354Ssam		return 1;
1727178354Ssam	}
1728178354Ssam	ieee80211_create_ibss(vap,
1729178354Ssam	    ieee80211_ht_adjust_channel(ic, bestchan, vap->iv_flags_ext));
1730178354Ssam	return 1;
1731170530Ssam}
1732170530Ssam
1733178354Ssamstatic const struct ieee80211_scanner ap_default = {
1734178354Ssam	.scan_name		= "default",
1735178354Ssam	.scan_attach		= sta_attach,
1736178354Ssam	.scan_detach		= sta_detach,
1737178354Ssam	.scan_start		= ap_start,
1738178354Ssam	.scan_restart		= sta_restart,
1739178354Ssam	.scan_cancel		= ap_cancel,
1740178354Ssam	.scan_end		= ap_end,
1741178354Ssam	.scan_flush		= sta_flush,
1742178354Ssam	.scan_pickchan		= ap_pick_channel,
1743178354Ssam	.scan_add		= sta_add,
1744178354Ssam	.scan_age		= adhoc_age,
1745178354Ssam	.scan_iterate		= sta_iterate,
1746178354Ssam	.scan_assoc_success	= sta_assoc_success,
1747178354Ssam	.scan_assoc_fail	= sta_assoc_fail,
1748170530Ssam};
1749178354Ssam
1750178354Ssam/*
1751178354Ssam * Module glue.
1752178354Ssam */
1753178354SsamIEEE80211_SCANNER_MODULE(sta, 1);
1754178354SsamIEEE80211_SCANNER_ALG(sta, IEEE80211_M_STA, sta_default);
1755178354SsamIEEE80211_SCANNER_ALG(ibss, IEEE80211_M_IBSS, adhoc_default);
1756178354SsamIEEE80211_SCANNER_ALG(ahdemo, IEEE80211_M_AHDEMO, adhoc_default);
1757178354SsamIEEE80211_SCANNER_ALG(ap, IEEE80211_M_HOSTAP, ap_default);
1758