ieee80211_scan_sta.c revision 298359
1/*-
2 * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#include <sys/cdefs.h>
27__FBSDID("$FreeBSD: head/sys/net80211/ieee80211_scan_sta.c 298359 2016-04-20 18:29:30Z avos $");
28
29/*
30 * IEEE 802.11 station scanning support.
31 */
32#include "opt_wlan.h"
33
34#include <sys/param.h>
35#include <sys/systm.h>
36#include <sys/kernel.h>
37#include <sys/endian.h>
38#include <sys/malloc.h>
39#include <sys/module.h>
40
41#include <sys/socket.h>
42
43#include <net/if.h>
44#include <net/if_var.h>
45#include <net/if_media.h>
46#include <net/ethernet.h>
47
48#include <net80211/ieee80211_var.h>
49#include <net80211/ieee80211_input.h>
50#include <net80211/ieee80211_regdomain.h>
51#ifdef IEEE80211_SUPPORT_TDMA
52#include <net80211/ieee80211_tdma.h>
53#endif
54#ifdef IEEE80211_SUPPORT_MESH
55#include <net80211/ieee80211_mesh.h>
56#endif
57#include <net80211/ieee80211_ratectl.h>
58
59#include <net/bpf.h>
60
61/*
62 * Parameters for managing cache entries:
63 *
64 * o a station with STA_FAILS_MAX failures is not considered
65 *   when picking a candidate
66 * o a station that hasn't had an update in STA_PURGE_SCANS
67 *   (background) scans is discarded
68 * o after STA_FAILS_AGE seconds we clear the failure count
69 */
70#define	STA_FAILS_MAX	2		/* assoc failures before ignored */
71#define	STA_FAILS_AGE	(2*60)		/* time before clearing fails (secs) */
72#define	STA_PURGE_SCANS	2		/* age for purging entries (scans) */
73
74/* XXX tunable */
75#define	STA_RSSI_MIN	8		/* min acceptable rssi */
76#define	STA_RSSI_MAX	40		/* max rssi for comparison */
77
78struct sta_entry {
79	struct ieee80211_scan_entry base;
80	TAILQ_ENTRY(sta_entry) se_list;
81	LIST_ENTRY(sta_entry) se_hash;
82	uint8_t		se_fails;		/* failure to associate count */
83	uint8_t		se_seen;		/* seen during current scan */
84	uint8_t		se_notseen;		/* not seen in previous scans */
85	uint8_t		se_flags;
86#define	STA_DEMOTE11B	0x01			/* match w/ demoted 11b chan */
87	uint32_t	se_avgrssi;		/* LPF rssi state */
88	unsigned long	se_lastupdate;		/* time of last update */
89	unsigned long	se_lastfail;		/* time of last failure */
90	unsigned long	se_lastassoc;		/* time of last association */
91	u_int		se_scangen;		/* iterator scan gen# */
92	u_int		se_countrygen;		/* gen# of last cc notify */
93};
94
95#define	STA_HASHSIZE	32
96/* simple hash is enough for variation of macaddr */
97#define	STA_HASH(addr)	\
98	(((const uint8_t *)(addr))[IEEE80211_ADDR_LEN - 1] % STA_HASHSIZE)
99
100#define	MAX_IEEE_CHAN	256			/* max acceptable IEEE chan # */
101CTASSERT(MAX_IEEE_CHAN >= 256);
102
103struct sta_table {
104	ieee80211_scan_table_lock_t st_lock;	/* on scan table */
105	TAILQ_HEAD(, sta_entry) st_entry;	/* all entries */
106	LIST_HEAD(, sta_entry) st_hash[STA_HASHSIZE];
107	ieee80211_scan_iter_lock_t st_scanlock;		/* on st_scaniter */
108	u_int		st_scaniter;		/* gen# for iterator */
109	u_int		st_scangen;		/* scan generation # */
110	int		st_newscan;
111	/* ap-related state */
112	int		st_maxrssi[MAX_IEEE_CHAN];
113};
114
115static void sta_flush_table(struct sta_table *);
116/*
117 * match_bss returns a bitmask describing if an entry is suitable
118 * for use.  If non-zero the entry was deemed not suitable and it's
119 * contents explains why.  The following flags are or'd to to this
120 * mask and can be used to figure out why the entry was rejected.
121 */
122#define	MATCH_CHANNEL		0x00001	/* channel mismatch */
123#define	MATCH_CAPINFO		0x00002	/* capabilities mismatch, e.g. no ess */
124#define	MATCH_PRIVACY		0x00004	/* privacy mismatch */
125#define	MATCH_RATE		0x00008	/* rate set mismatch */
126#define	MATCH_SSID		0x00010	/* ssid mismatch */
127#define	MATCH_BSSID		0x00020	/* bssid mismatch */
128#define	MATCH_FAILS		0x00040	/* too many failed auth attempts */
129#define	MATCH_NOTSEEN		0x00080	/* not seen in recent scans */
130#define	MATCH_RSSI		0x00100	/* rssi deemed too low to use */
131#define	MATCH_CC		0x00200	/* country code mismatch */
132#define	MATCH_TDMA_NOIE		0x00400	/* no TDMA ie */
133#define	MATCH_TDMA_NOTMASTER	0x00800	/* not TDMA master */
134#define	MATCH_TDMA_NOSLOT	0x01000	/* all TDMA slots occupied */
135#define	MATCH_TDMA_LOCAL	0x02000	/* local address */
136#define	MATCH_TDMA_VERSION	0x04000	/* protocol version mismatch */
137#define	MATCH_MESH_NOID		0x10000	/* no MESHID ie */
138#define	MATCH_MESHID		0x20000	/* meshid mismatch */
139static int match_bss(struct ieee80211vap *,
140	const struct ieee80211_scan_state *, struct sta_entry *, int);
141static void adhoc_age(struct ieee80211_scan_state *);
142
143static __inline int
144isocmp(const uint8_t cc1[], const uint8_t cc2[])
145{
146     return (cc1[0] == cc2[0] && cc1[1] == cc2[1]);
147}
148
149/* number of references from net80211 layer */
150static	int nrefs = 0;
151/*
152 * Module glue.
153 */
154IEEE80211_SCANNER_MODULE(sta, 1);
155
156/*
157 * Attach prior to any scanning work.
158 */
159static int
160sta_attach(struct ieee80211_scan_state *ss)
161{
162	struct sta_table *st;
163
164	st = (struct sta_table *) IEEE80211_MALLOC(sizeof(struct sta_table),
165		M_80211_SCAN,
166		IEEE80211_M_NOWAIT | IEEE80211_M_ZERO);
167	if (st == NULL)
168		return 0;
169	IEEE80211_SCAN_TABLE_LOCK_INIT(st, "scantable");
170	IEEE80211_SCAN_ITER_LOCK_INIT(st, "scangen");
171	TAILQ_INIT(&st->st_entry);
172	ss->ss_priv = st;
173	nrefs++;			/* NB: we assume caller locking */
174	return 1;
175}
176
177/*
178 * Cleanup any private state.
179 */
180static int
181sta_detach(struct ieee80211_scan_state *ss)
182{
183	struct sta_table *st = ss->ss_priv;
184
185	if (st != NULL) {
186		sta_flush_table(st);
187		IEEE80211_SCAN_TABLE_LOCK_DESTROY(st);
188		IEEE80211_SCAN_ITER_LOCK_DESTROY(st);
189		IEEE80211_FREE(st, M_80211_SCAN);
190		KASSERT(nrefs > 0, ("imbalanced attach/detach"));
191		nrefs--;		/* NB: we assume caller locking */
192	}
193	return 1;
194}
195
196/*
197 * Flush all per-scan state.
198 */
199static int
200sta_flush(struct ieee80211_scan_state *ss)
201{
202	struct sta_table *st = ss->ss_priv;
203
204	IEEE80211_SCAN_TABLE_LOCK(st);
205	sta_flush_table(st);
206	IEEE80211_SCAN_TABLE_UNLOCK(st);
207	ss->ss_last = 0;
208	return 0;
209}
210
211/*
212 * Flush all entries in the scan cache.
213 */
214static void
215sta_flush_table(struct sta_table *st)
216{
217	struct sta_entry *se, *next;
218
219	TAILQ_FOREACH_SAFE(se, &st->st_entry, se_list, next) {
220		TAILQ_REMOVE(&st->st_entry, se, se_list);
221		LIST_REMOVE(se, se_hash);
222		ieee80211_ies_cleanup(&se->base.se_ies);
223		IEEE80211_FREE(se, M_80211_SCAN);
224	}
225	memset(st->st_maxrssi, 0, sizeof(st->st_maxrssi));
226}
227
228/*
229 * Process a beacon or probe response frame; create an
230 * entry in the scan cache or update any previous entry.
231 */
232static int
233sta_add(struct ieee80211_scan_state *ss,
234	struct ieee80211_channel *curchan,
235	const struct ieee80211_scanparams *sp,
236	const struct ieee80211_frame *wh,
237	int subtype, int rssi, int noise)
238{
239#define	ISPROBE(_st)	((_st) == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
240#define	PICK1ST(_ss) \
241	((ss->ss_flags & (IEEE80211_SCAN_PICK1ST | IEEE80211_SCAN_GOTPICK)) == \
242	IEEE80211_SCAN_PICK1ST)
243	struct sta_table *st = ss->ss_priv;
244	const uint8_t *macaddr = wh->i_addr2;
245	struct ieee80211vap *vap = ss->ss_vap;
246	struct ieee80211com *ic = vap->iv_ic;
247	struct ieee80211_channel *c;
248	struct sta_entry *se;
249	struct ieee80211_scan_entry *ise;
250	int hash;
251
252	hash = STA_HASH(macaddr);
253
254	IEEE80211_SCAN_TABLE_LOCK(st);
255	LIST_FOREACH(se, &st->st_hash[hash], se_hash)
256		if (IEEE80211_ADDR_EQ(se->base.se_macaddr, macaddr))
257			goto found;
258	se = (struct sta_entry *) IEEE80211_MALLOC(sizeof(struct sta_entry),
259		M_80211_SCAN, IEEE80211_M_NOWAIT | IEEE80211_M_ZERO);
260	if (se == NULL) {
261		IEEE80211_SCAN_TABLE_UNLOCK(st);
262		return 0;
263	}
264	se->se_scangen = st->st_scaniter-1;
265	se->se_avgrssi = IEEE80211_RSSI_DUMMY_MARKER;
266	IEEE80211_ADDR_COPY(se->base.se_macaddr, macaddr);
267	TAILQ_INSERT_TAIL(&st->st_entry, se, se_list);
268	LIST_INSERT_HEAD(&st->st_hash[hash], se, se_hash);
269found:
270	ise = &se->base;
271	/* XXX ap beaconing multiple ssid w/ same bssid */
272	if (sp->ssid[1] != 0 &&
273	    (ISPROBE(subtype) || ise->se_ssid[1] == 0))
274		memcpy(ise->se_ssid, sp->ssid, 2+sp->ssid[1]);
275	KASSERT(sp->rates[1] <= IEEE80211_RATE_MAXSIZE,
276		("rate set too large: %u", sp->rates[1]));
277	memcpy(ise->se_rates, sp->rates, 2+sp->rates[1]);
278	if (sp->xrates != NULL) {
279		/* XXX validate xrates[1] */
280		KASSERT(sp->xrates[1] <= IEEE80211_RATE_MAXSIZE,
281			("xrate set too large: %u", sp->xrates[1]));
282		memcpy(ise->se_xrates, sp->xrates, 2+sp->xrates[1]);
283	} else
284		ise->se_xrates[1] = 0;
285	IEEE80211_ADDR_COPY(ise->se_bssid, wh->i_addr3);
286	if ((sp->status & IEEE80211_BPARSE_OFFCHAN) == 0) {
287		/*
288		 * Record rssi data using extended precision LPF filter.
289		 *
290		 * NB: use only on-channel data to insure we get a good
291		 *     estimate of the signal we'll see when associated.
292		 */
293		IEEE80211_RSSI_LPF(se->se_avgrssi, rssi);
294		ise->se_rssi = IEEE80211_RSSI_GET(se->se_avgrssi);
295		ise->se_noise = noise;
296	}
297	memcpy(ise->se_tstamp.data, sp->tstamp, sizeof(ise->se_tstamp));
298	ise->se_intval = sp->bintval;
299	ise->se_capinfo = sp->capinfo;
300#ifdef IEEE80211_SUPPORT_MESH
301	if (sp->meshid != NULL && sp->meshid[1] != 0)
302		memcpy(ise->se_meshid, sp->meshid, 2+sp->meshid[1]);
303#endif
304	/*
305	 * Beware of overriding se_chan for frames seen
306	 * off-channel; this can cause us to attempt an
307	 * association on the wrong channel.
308	 */
309	if (sp->status & IEEE80211_BPARSE_OFFCHAN) {
310		/*
311		 * Off-channel, locate the home/bss channel for the sta
312		 * using the value broadcast in the DSPARMS ie.  We know
313		 * sp->chan has this value because it's used to calculate
314		 * IEEE80211_BPARSE_OFFCHAN.
315		 */
316		c = ieee80211_find_channel_byieee(ic, sp->chan,
317		    curchan->ic_flags);
318		if (c != NULL) {
319			ise->se_chan = c;
320		} else if (ise->se_chan == NULL) {
321			/* should not happen, pick something */
322			ise->se_chan = curchan;
323		}
324	} else
325		ise->se_chan = curchan;
326	if (IEEE80211_IS_CHAN_HT(ise->se_chan) && sp->htcap == NULL) {
327		/* Demote legacy networks to a non-HT channel. */
328		c = ieee80211_find_channel(ic, ise->se_chan->ic_freq,
329		    ise->se_chan->ic_flags & ~IEEE80211_CHAN_HT);
330		KASSERT(c != NULL,
331		    ("no legacy channel %u", ise->se_chan->ic_ieee));
332		ise->se_chan = c;
333	}
334	ise->se_fhdwell = sp->fhdwell;
335	ise->se_fhindex = sp->fhindex;
336	ise->se_erp = sp->erp;
337	ise->se_timoff = sp->timoff;
338	if (sp->tim != NULL) {
339		const struct ieee80211_tim_ie *tim =
340		    (const struct ieee80211_tim_ie *) sp->tim;
341		ise->se_dtimperiod = tim->tim_period;
342	}
343	if (sp->country != NULL) {
344		const struct ieee80211_country_ie *cie =
345		    (const struct ieee80211_country_ie *) sp->country;
346		/*
347		 * If 11d is enabled and we're attempting to join a bss
348		 * that advertises it's country code then compare our
349		 * current settings to what we fetched from the country ie.
350		 * If our country code is unspecified or different then
351		 * dispatch an event to user space that identifies the
352		 * country code so our regdomain config can be changed.
353		 */
354		/* XXX only for STA mode? */
355		if ((IEEE80211_IS_CHAN_11D(ise->se_chan) ||
356		    (vap->iv_flags_ext & IEEE80211_FEXT_DOTD)) &&
357		    (ic->ic_regdomain.country == CTRY_DEFAULT ||
358		     !isocmp(cie->cc, ic->ic_regdomain.isocc))) {
359			/* only issue one notify event per scan */
360			if (se->se_countrygen != st->st_scangen) {
361				ieee80211_notify_country(vap, ise->se_bssid,
362				    cie->cc);
363				se->se_countrygen = st->st_scangen;
364			}
365		}
366		ise->se_cc[0] = cie->cc[0];
367		ise->se_cc[1] = cie->cc[1];
368	}
369	/* NB: no need to setup ie ptrs; they are not (currently) used */
370	(void) ieee80211_ies_init(&ise->se_ies, sp->ies, sp->ies_len);
371
372	/* clear failure count after STA_FAIL_AGE passes */
373	if (se->se_fails && (ticks - se->se_lastfail) > STA_FAILS_AGE*hz) {
374		se->se_fails = 0;
375		IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_SCAN, macaddr,
376		    "%s: fails %u", __func__, se->se_fails);
377	}
378
379	se->se_lastupdate = ticks;		/* update time */
380	se->se_seen = 1;
381	se->se_notseen = 0;
382
383	KASSERT(sizeof(sp->bchan) == 1, ("bchan size"));
384	if (rssi > st->st_maxrssi[sp->bchan])
385		st->st_maxrssi[sp->bchan] = rssi;
386
387	IEEE80211_SCAN_TABLE_UNLOCK(st);
388
389	/*
390	 * If looking for a quick choice and nothing's
391	 * been found check here.
392	 */
393	if (PICK1ST(ss) && match_bss(vap, ss, se, IEEE80211_MSG_SCAN) == 0)
394		ss->ss_flags |= IEEE80211_SCAN_GOTPICK;
395
396	return 1;
397#undef PICK1ST
398#undef ISPROBE
399}
400
401/*
402 * Check if a channel is excluded by user request.
403 */
404static int
405isexcluded(struct ieee80211vap *vap, const struct ieee80211_channel *c)
406{
407	return (isclr(vap->iv_ic->ic_chan_active, c->ic_ieee) ||
408	    (vap->iv_des_chan != IEEE80211_CHAN_ANYC &&
409	     c->ic_freq != vap->iv_des_chan->ic_freq));
410}
411
412static struct ieee80211_channel *
413find11gchannel(struct ieee80211com *ic, int i, int freq)
414{
415	struct ieee80211_channel *c;
416	int j;
417
418	/*
419	 * The normal ordering in the channel list is b channel
420	 * immediately followed by g so optimize the search for
421	 * this.  We'll still do a full search just in case.
422	 */
423	for (j = i+1; j < ic->ic_nchans; j++) {
424		c = &ic->ic_channels[j];
425		if (c->ic_freq == freq && IEEE80211_IS_CHAN_G(c))
426			return c;
427	}
428	for (j = 0; j < i; j++) {
429		c = &ic->ic_channels[j];
430		if (c->ic_freq == freq && IEEE80211_IS_CHAN_G(c))
431			return c;
432	}
433	return NULL;
434}
435
436static const u_int chanflags[IEEE80211_MODE_MAX] = {
437	[IEEE80211_MODE_AUTO]	  = IEEE80211_CHAN_B,
438	[IEEE80211_MODE_11A]	  = IEEE80211_CHAN_A,
439	[IEEE80211_MODE_11B]	  = IEEE80211_CHAN_B,
440	[IEEE80211_MODE_11G]	  = IEEE80211_CHAN_G,
441	[IEEE80211_MODE_FH]	  = IEEE80211_CHAN_FHSS,
442	/* check base channel */
443	[IEEE80211_MODE_TURBO_A]  = IEEE80211_CHAN_A,
444	[IEEE80211_MODE_TURBO_G]  = IEEE80211_CHAN_G,
445	[IEEE80211_MODE_STURBO_A] = IEEE80211_CHAN_ST,
446	[IEEE80211_MODE_HALF]	  = IEEE80211_CHAN_HALF,
447	[IEEE80211_MODE_QUARTER]  = IEEE80211_CHAN_QUARTER,
448	/* check legacy */
449	[IEEE80211_MODE_11NA]	  = IEEE80211_CHAN_A,
450	[IEEE80211_MODE_11NG]	  = IEEE80211_CHAN_G,
451};
452
453static void
454add_channels(struct ieee80211vap *vap,
455	struct ieee80211_scan_state *ss,
456	enum ieee80211_phymode mode, const uint16_t freq[], int nfreq)
457{
458	struct ieee80211com *ic = vap->iv_ic;
459	struct ieee80211_channel *c, *cg;
460	u_int modeflags;
461	int i;
462
463	KASSERT(mode < nitems(chanflags), ("Unexpected mode %u", mode));
464	modeflags = chanflags[mode];
465	for (i = 0; i < nfreq; i++) {
466		if (ss->ss_last >= IEEE80211_SCAN_MAX)
467			break;
468
469		c = ieee80211_find_channel(ic, freq[i], modeflags);
470		if (c == NULL || isexcluded(vap, c))
471			continue;
472		if (mode == IEEE80211_MODE_AUTO) {
473			/*
474			 * XXX special-case 11b/g channels so we select
475			 *     the g channel if both are present.
476			 */
477			if (IEEE80211_IS_CHAN_B(c) &&
478			    (cg = find11gchannel(ic, i, c->ic_freq)) != NULL)
479				c = cg;
480		}
481		ss->ss_chans[ss->ss_last++] = c;
482	}
483}
484
485struct scanlist {
486	uint16_t	mode;
487	uint16_t	count;
488	const uint16_t	*list;
489};
490
491static int
492checktable(const struct scanlist *scan, const struct ieee80211_channel *c)
493{
494	int i;
495
496	for (; scan->list != NULL; scan++) {
497		for (i = 0; i < scan->count; i++)
498			if (scan->list[i] == c->ic_freq)
499				return 1;
500	}
501	return 0;
502}
503
504static int
505onscanlist(const struct ieee80211_scan_state *ss,
506	const struct ieee80211_channel *c)
507{
508	int i;
509
510	for (i = 0; i < ss->ss_last; i++)
511		if (ss->ss_chans[i] == c)
512			return 1;
513	return 0;
514}
515
516static void
517sweepchannels(struct ieee80211_scan_state *ss, struct ieee80211vap *vap,
518	const struct scanlist table[])
519{
520	struct ieee80211com *ic = vap->iv_ic;
521	struct ieee80211_channel *c;
522	int i;
523
524	for (i = 0; i < ic->ic_nchans; i++) {
525		if (ss->ss_last >= IEEE80211_SCAN_MAX)
526			break;
527
528		c = &ic->ic_channels[i];
529		/*
530		 * Ignore dynamic turbo channels; we scan them
531		 * in normal mode (i.e. not boosted).  Likewise
532		 * for HT channels, they get scanned using
533		 * legacy rates.
534		 */
535		if (IEEE80211_IS_CHAN_DTURBO(c) || IEEE80211_IS_CHAN_HT(c))
536			continue;
537
538		/*
539		 * If a desired mode was specified, scan only
540		 * channels that satisfy that constraint.
541		 */
542		if (vap->iv_des_mode != IEEE80211_MODE_AUTO &&
543		    vap->iv_des_mode != ieee80211_chan2mode(c))
544			continue;
545
546		/*
547		 * Skip channels excluded by user request.
548		 */
549		if (isexcluded(vap, c))
550			continue;
551
552		/*
553		 * Add the channel unless it is listed in the
554		 * fixed scan order tables.  This insures we
555		 * don't sweep back in channels we filtered out
556		 * above.
557		 */
558		if (checktable(table, c))
559			continue;
560
561		/* Add channel to scanning list. */
562		ss->ss_chans[ss->ss_last++] = c;
563	}
564	/*
565	 * Explicitly add any desired channel if:
566	 * - not already on the scan list
567	 * - allowed by any desired mode constraint
568	 * - there is space in the scan list
569	 * This allows the channel to be used when the filtering
570	 * mechanisms would otherwise elide it (e.g HT, turbo).
571	 */
572	c = vap->iv_des_chan;
573	if (c != IEEE80211_CHAN_ANYC &&
574	    !onscanlist(ss, c) &&
575	    (vap->iv_des_mode == IEEE80211_MODE_AUTO ||
576	     vap->iv_des_mode == ieee80211_chan2mode(c)) &&
577	    ss->ss_last < IEEE80211_SCAN_MAX)
578		ss->ss_chans[ss->ss_last++] = c;
579}
580
581static void
582makescanlist(struct ieee80211_scan_state *ss, struct ieee80211vap *vap,
583	const struct scanlist table[])
584{
585	const struct scanlist *scan;
586	enum ieee80211_phymode mode;
587
588	ss->ss_last = 0;
589	/*
590	 * Use the table of ordered channels to construct the list
591	 * of channels for scanning.  Any channels in the ordered
592	 * list not in the master list will be discarded.
593	 */
594	for (scan = table; scan->list != NULL; scan++) {
595		mode = scan->mode;
596		if (vap->iv_des_mode != IEEE80211_MODE_AUTO) {
597			/*
598			 * If a desired mode was specified, scan only
599			 * channels that satisfy that constraint.
600			 */
601			if (vap->iv_des_mode != mode) {
602				/*
603				 * The scan table marks 2.4Ghz channels as b
604				 * so if the desired mode is 11g, then use
605				 * the 11b channel list but upgrade the mode.
606				 */
607				if (vap->iv_des_mode == IEEE80211_MODE_11G) {
608					if (mode == IEEE80211_MODE_11G) /* Skip the G check */
609						continue;
610					else if (mode == IEEE80211_MODE_11B)
611						mode = IEEE80211_MODE_11G;	/* upgrade */
612				}
613			}
614		} else {
615			/*
616			 * This lets add_channels upgrade an 11b channel
617			 * to 11g if available.
618			 */
619			if (mode == IEEE80211_MODE_11B)
620				mode = IEEE80211_MODE_AUTO;
621		}
622#ifdef IEEE80211_F_XR
623		/* XR does not operate on turbo channels */
624		if ((vap->iv_flags & IEEE80211_F_XR) &&
625		    (mode == IEEE80211_MODE_TURBO_A ||
626		     mode == IEEE80211_MODE_TURBO_G ||
627		     mode == IEEE80211_MODE_STURBO_A))
628			continue;
629#endif
630		/*
631		 * Add the list of the channels; any that are not
632		 * in the master channel list will be discarded.
633		 */
634		add_channels(vap, ss, mode, scan->list, scan->count);
635	}
636
637	/*
638	 * Add the channels from the ic that are not present
639	 * in the table.
640	 */
641	sweepchannels(ss, vap, table);
642}
643
644static const uint16_t rcl1[] =		/* 8 FCC channel: 52, 56, 60, 64, 36, 40, 44, 48 */
645{ 5260, 5280, 5300, 5320, 5180, 5200, 5220, 5240 };
646static const uint16_t rcl2[] =		/* 4 MKK channels: 34, 38, 42, 46 */
647{ 5170, 5190, 5210, 5230 };
648static const uint16_t rcl3[] =		/* 2.4Ghz ch: 1,6,11,7,13 */
649{ 2412, 2437, 2462, 2442, 2472 };
650static const uint16_t rcl4[] =		/* 5 FCC channel: 149, 153, 161, 165 */
651{ 5745, 5765, 5785, 5805, 5825 };
652static const uint16_t rcl7[] =		/* 11 ETSI channel: 100,104,108,112,116,120,124,128,132,136,140 */
653{ 5500, 5520, 5540, 5560, 5580, 5600, 5620, 5640, 5660, 5680, 5700 };
654static const uint16_t rcl8[] =		/* 2.4Ghz ch: 2,3,4,5,8,9,10,12 */
655{ 2417, 2422, 2427, 2432, 2447, 2452, 2457, 2467 };
656static const uint16_t rcl9[] =		/* 2.4Ghz ch: 14 */
657{ 2484 };
658static const uint16_t rcl10[] =	/* Added Korean channels 2312-2372 */
659{ 2312, 2317, 2322, 2327, 2332, 2337, 2342, 2347, 2352, 2357, 2362, 2367, 2372 };
660static const uint16_t rcl11[] =	/* Added Japan channels in 4.9/5.0 spectrum */
661{ 5040, 5060, 5080, 4920, 4940, 4960, 4980 };
662#ifdef ATH_TURBO_SCAN
663static const uint16_t rcl5[] =		/* 3 static turbo channels */
664{ 5210, 5250, 5290 };
665static const uint16_t rcl6[] =		/* 2 static turbo channels */
666{ 5760, 5800 };
667static const uint16_t rcl6x[] =	/* 4 FCC3 turbo channels */
668{ 5540, 5580, 5620, 5660 };
669static const uint16_t rcl12[] =	/* 2.4Ghz Turbo channel 6 */
670{ 2437 };
671static const uint16_t rcl13[] =	/* dynamic Turbo channels */
672{ 5200, 5240, 5280, 5765, 5805 };
673#endif /* ATH_TURBO_SCAN */
674
675#define	X(a)	.count = sizeof(a)/sizeof(a[0]), .list = a
676
677static const struct scanlist staScanTable[] = {
678	{ IEEE80211_MODE_11B,   	X(rcl3) },
679	{ IEEE80211_MODE_11A,   	X(rcl1) },
680	{ IEEE80211_MODE_11A,   	X(rcl2) },
681	{ IEEE80211_MODE_11B,   	X(rcl8) },
682	{ IEEE80211_MODE_11B,   	X(rcl9) },
683	{ IEEE80211_MODE_11A,   	X(rcl4) },
684#ifdef ATH_TURBO_SCAN
685	{ IEEE80211_MODE_STURBO_A,	X(rcl5) },
686	{ IEEE80211_MODE_STURBO_A,	X(rcl6) },
687	{ IEEE80211_MODE_TURBO_A,	X(rcl6x) },
688	{ IEEE80211_MODE_TURBO_A,	X(rcl13) },
689#endif /* ATH_TURBO_SCAN */
690	{ IEEE80211_MODE_11A,		X(rcl7) },
691	{ IEEE80211_MODE_11B,		X(rcl10) },
692	{ IEEE80211_MODE_11A,		X(rcl11) },
693#ifdef ATH_TURBO_SCAN
694	{ IEEE80211_MODE_TURBO_G,	X(rcl12) },
695#endif /* ATH_TURBO_SCAN */
696	{ .list = NULL }
697};
698
699/*
700 * Start a station-mode scan by populating the channel list.
701 */
702static int
703sta_start(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
704{
705	struct sta_table *st = ss->ss_priv;
706
707	makescanlist(ss, vap, staScanTable);
708
709	if (ss->ss_mindwell == 0)
710		ss->ss_mindwell = msecs_to_ticks(20);	/* 20ms */
711	if (ss->ss_maxdwell == 0)
712		ss->ss_maxdwell = msecs_to_ticks(200);	/* 200ms */
713
714	st->st_scangen++;
715	st->st_newscan = 1;
716
717	return 0;
718}
719
720/*
721 * Restart a scan, typically a bg scan but can
722 * also be a fg scan that came up empty.
723 */
724static int
725sta_restart(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
726{
727	struct sta_table *st = ss->ss_priv;
728
729	st->st_newscan = 1;
730	return 0;
731}
732
733/*
734 * Cancel an ongoing scan.
735 */
736static int
737sta_cancel(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
738{
739	return 0;
740}
741
742/*
743 * Demote any supplied 11g channel to 11b.  There should
744 * always be an 11b channel but we check anyway...
745 */
746static struct ieee80211_channel *
747demote11b(struct ieee80211vap *vap, struct ieee80211_channel *chan)
748{
749	struct ieee80211_channel *c;
750
751	if (IEEE80211_IS_CHAN_ANYG(chan) &&
752	    vap->iv_des_mode == IEEE80211_MODE_AUTO) {
753		c = ieee80211_find_channel(vap->iv_ic, chan->ic_freq,
754		    (chan->ic_flags &~ (IEEE80211_CHAN_PUREG | IEEE80211_CHAN_G)) |
755		    IEEE80211_CHAN_B);
756		if (c != NULL)
757			chan = c;
758	}
759	return chan;
760}
761
762static int
763maxrate(const struct ieee80211_scan_entry *se)
764{
765	const struct ieee80211_ie_htcap *htcap =
766	    (const struct ieee80211_ie_htcap *) se->se_ies.htcap_ie;
767	int rmax, r, i, txstream;
768	uint16_t caps;
769	uint8_t txparams;
770
771	rmax = 0;
772	if (htcap != NULL) {
773		/*
774		 * HT station; inspect supported MCS and then adjust
775		 * rate by channel width.
776		 */
777		txparams = htcap->hc_mcsset[12];
778		if (txparams & 0x3) {
779			/*
780			 * TX MCS parameters defined and not equal to RX,
781			 * extract the number of spartial streams and
782			 * map it to the highest MCS rate.
783			 */
784			txstream = ((txparams & 0xc) >> 2) + 1;
785			i = txstream * 8 - 1;
786		} else
787			for (i = 31; i >= 0 && isclr(htcap->hc_mcsset, i); i--);
788		if (i >= 0) {
789			caps = le16dec(&htcap->hc_cap);
790			if ((caps & IEEE80211_HTCAP_CHWIDTH40) &&
791			    (caps & IEEE80211_HTCAP_SHORTGI40))
792				rmax = ieee80211_htrates[i].ht40_rate_400ns;
793			else if (caps & IEEE80211_HTCAP_CHWIDTH40)
794				rmax = ieee80211_htrates[i].ht40_rate_800ns;
795			else if (caps & IEEE80211_HTCAP_SHORTGI20)
796				rmax = ieee80211_htrates[i].ht20_rate_400ns;
797			else
798				rmax = ieee80211_htrates[i].ht20_rate_800ns;
799		}
800	}
801	for (i = 0; i < se->se_rates[1]; i++) {
802		r = se->se_rates[2+i] & IEEE80211_RATE_VAL;
803		if (r > rmax)
804			rmax = r;
805	}
806	for (i = 0; i < se->se_xrates[1]; i++) {
807		r = se->se_xrates[2+i] & IEEE80211_RATE_VAL;
808		if (r > rmax)
809			rmax = r;
810	}
811	return rmax;
812}
813
814/*
815 * Compare the capabilities of two entries and decide which is
816 * more desirable (return >0 if a is considered better).  Note
817 * that we assume compatibility/usability has already been checked
818 * so we don't need to (e.g. validate whether privacy is supported).
819 * Used to select the best scan candidate for association in a BSS.
820 */
821static int
822sta_compare(const struct sta_entry *a, const struct sta_entry *b)
823{
824#define	PREFER(_a,_b,_what) do {			\
825	if (((_a) ^ (_b)) & (_what))			\
826		return ((_a) & (_what)) ? 1 : -1;	\
827} while (0)
828	int maxa, maxb;
829	int8_t rssia, rssib;
830	int weight;
831
832	/* privacy support */
833	PREFER(a->base.se_capinfo, b->base.se_capinfo,
834		IEEE80211_CAPINFO_PRIVACY);
835
836	/* compare count of previous failures */
837	weight = b->se_fails - a->se_fails;
838	if (abs(weight) > 1)
839		return weight;
840
841	/*
842	 * Compare rssi.  If the two are considered equivalent
843	 * then fallback to other criteria.  We threshold the
844	 * comparisons to avoid selecting an ap purely by rssi
845	 * when both values may be good but one ap is otherwise
846	 * more desirable (e.g. an 11b-only ap with stronger
847	 * signal than an 11g ap).
848	 */
849	rssia = MIN(a->base.se_rssi, STA_RSSI_MAX);
850	rssib = MIN(b->base.se_rssi, STA_RSSI_MAX);
851	if (abs(rssib - rssia) < 5) {
852		/* best/max rate preferred if signal level close enough XXX */
853		maxa = maxrate(&a->base);
854		maxb = maxrate(&b->base);
855		if (maxa != maxb)
856			return maxa - maxb;
857		/* XXX use freq for channel preference */
858		/* for now just prefer 5Ghz band to all other bands */
859		PREFER(IEEE80211_IS_CHAN_5GHZ(a->base.se_chan),
860		       IEEE80211_IS_CHAN_5GHZ(b->base.se_chan), 1);
861	}
862	/* all things being equal, use signal level */
863	return a->base.se_rssi - b->base.se_rssi;
864#undef PREFER
865}
866
867/*
868 * Check rate set suitability and return the best supported rate.
869 * XXX inspect MCS for HT
870 */
871static int
872check_rate(struct ieee80211vap *vap, const struct ieee80211_channel *chan,
873    const struct ieee80211_scan_entry *se)
874{
875	const struct ieee80211_rateset *srs;
876	int i, j, nrs, r, okrate, badrate, fixedrate, ucastrate;
877	const uint8_t *rs;
878
879	okrate = badrate = 0;
880
881	srs = ieee80211_get_suprates(vap->iv_ic, chan);
882	nrs = se->se_rates[1];
883	rs = se->se_rates+2;
884	/* XXX MCS */
885	ucastrate = vap->iv_txparms[ieee80211_chan2mode(chan)].ucastrate;
886	fixedrate = IEEE80211_FIXED_RATE_NONE;
887again:
888	for (i = 0; i < nrs; i++) {
889		r = IEEE80211_RV(rs[i]);
890		badrate = r;
891		/*
892		 * Check any fixed rate is included.
893		 */
894		if (r == ucastrate)
895			fixedrate = r;
896		/*
897		 * Check against our supported rates.
898		 */
899		for (j = 0; j < srs->rs_nrates; j++)
900			if (r == IEEE80211_RV(srs->rs_rates[j])) {
901				if (r > okrate)		/* NB: track max */
902					okrate = r;
903				break;
904			}
905
906		if (j == srs->rs_nrates && (rs[i] & IEEE80211_RATE_BASIC)) {
907			/*
908			 * Don't try joining a BSS, if we don't support
909			 * one of its basic rates.
910			 */
911			okrate = 0;
912			goto back;
913		}
914	}
915	if (rs == se->se_rates+2) {
916		/* scan xrates too; sort of an algol68-style for loop */
917		nrs = se->se_xrates[1];
918		rs = se->se_xrates+2;
919		goto again;
920	}
921
922back:
923	if (okrate == 0 || ucastrate != fixedrate)
924		return badrate | IEEE80211_RATE_BASIC;
925	else
926		return IEEE80211_RV(okrate);
927}
928
929static __inline int
930match_id(const uint8_t *ie, const uint8_t *val, int len)
931{
932	return (ie[1] == len && memcmp(ie+2, val, len) == 0);
933}
934
935static int
936match_ssid(const uint8_t *ie,
937	int nssid, const struct ieee80211_scan_ssid ssids[])
938{
939	int i;
940
941	for (i = 0; i < nssid; i++) {
942		if (match_id(ie, ssids[i].ssid, ssids[i].len))
943			return 1;
944	}
945	return 0;
946}
947
948#ifdef IEEE80211_SUPPORT_TDMA
949static int
950tdma_isfull(const struct ieee80211_tdma_param *tdma)
951{
952	int slot, slotcnt;
953
954	slotcnt = tdma->tdma_slotcnt;
955	for (slot = slotcnt-1; slot >= 0; slot--)
956		if (isclr(tdma->tdma_inuse, slot))
957			return 0;
958	return 1;
959}
960#endif /* IEEE80211_SUPPORT_TDMA */
961
962/*
963 * Test a scan candidate for suitability/compatibility.
964 */
965static int
966match_bss(struct ieee80211vap *vap,
967	const struct ieee80211_scan_state *ss, struct sta_entry *se0,
968	int debug)
969{
970	struct ieee80211com *ic = vap->iv_ic;
971	struct ieee80211_scan_entry *se = &se0->base;
972        uint8_t rate;
973        int fail;
974
975	fail = 0;
976	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, se->se_chan)))
977		fail |= MATCH_CHANNEL;
978	/*
979	 * NB: normally the desired mode is used to construct
980	 * the channel list, but it's possible for the scan
981	 * cache to include entries for stations outside this
982	 * list so we check the desired mode here to weed them
983	 * out.
984	 */
985	if (vap->iv_des_mode != IEEE80211_MODE_AUTO &&
986	    (se->se_chan->ic_flags & IEEE80211_CHAN_ALLTURBO) !=
987	    chanflags[vap->iv_des_mode])
988		fail |= MATCH_CHANNEL;
989	if (vap->iv_opmode == IEEE80211_M_IBSS) {
990		if ((se->se_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
991			fail |= MATCH_CAPINFO;
992#ifdef IEEE80211_SUPPORT_TDMA
993	} else if (vap->iv_opmode == IEEE80211_M_AHDEMO) {
994		/*
995		 * Adhoc demo network setup shouldn't really be scanning
996		 * but just in case skip stations operating in IBSS or
997		 * BSS mode.
998		 */
999		if (se->se_capinfo & (IEEE80211_CAPINFO_IBSS|IEEE80211_CAPINFO_ESS))
1000			fail |= MATCH_CAPINFO;
1001		/*
1002		 * TDMA operation cannot coexist with a normal 802.11 network;
1003		 * skip if IBSS or ESS capabilities are marked and require
1004		 * the beacon have a TDMA ie present.
1005		 */
1006		if (vap->iv_caps & IEEE80211_C_TDMA) {
1007			const struct ieee80211_tdma_param *tdma =
1008			    (const struct ieee80211_tdma_param *)se->se_ies.tdma_ie;
1009			const struct ieee80211_tdma_state *ts = vap->iv_tdma;
1010
1011			if (tdma == NULL)
1012				fail |= MATCH_TDMA_NOIE;
1013			else if (tdma->tdma_version != ts->tdma_version)
1014				fail |= MATCH_TDMA_VERSION;
1015			else if (tdma->tdma_slot != 0)
1016				fail |= MATCH_TDMA_NOTMASTER;
1017			else if (tdma_isfull(tdma))
1018				fail |= MATCH_TDMA_NOSLOT;
1019#if 0
1020			else if (ieee80211_local_address(se->se_macaddr))
1021				fail |= MATCH_TDMA_LOCAL;
1022#endif
1023		}
1024#endif /* IEEE80211_SUPPORT_TDMA */
1025#ifdef IEEE80211_SUPPORT_MESH
1026	} else if (vap->iv_opmode == IEEE80211_M_MBSS) {
1027		const struct ieee80211_mesh_state *ms = vap->iv_mesh;
1028		/*
1029		 * Mesh nodes have IBSS & ESS bits in capinfo turned off
1030		 * and two special ie's that must be present.
1031		 */
1032		if (se->se_capinfo & (IEEE80211_CAPINFO_IBSS|IEEE80211_CAPINFO_ESS))
1033			fail |= MATCH_CAPINFO;
1034		else if (se->se_meshid[0] != IEEE80211_ELEMID_MESHID)
1035			fail |= MATCH_MESH_NOID;
1036		else if (ms->ms_idlen != 0 &&
1037		    match_id(se->se_meshid, ms->ms_id, ms->ms_idlen))
1038			fail |= MATCH_MESHID;
1039#endif
1040	} else {
1041		if ((se->se_capinfo & IEEE80211_CAPINFO_ESS) == 0)
1042			fail |= MATCH_CAPINFO;
1043		/*
1044		 * If 11d is enabled and we're attempting to join a bss
1045		 * that advertises it's country code then compare our
1046		 * current settings to what we fetched from the country ie.
1047		 * If our country code is unspecified or different then do
1048		 * not attempt to join the bss.  We should have already
1049		 * dispatched an event to user space that identifies the
1050		 * new country code so our regdomain config should match.
1051		 */
1052		if ((IEEE80211_IS_CHAN_11D(se->se_chan) ||
1053		    (vap->iv_flags_ext & IEEE80211_FEXT_DOTD)) &&
1054		    se->se_cc[0] != 0 &&
1055		    (ic->ic_regdomain.country == CTRY_DEFAULT ||
1056		     !isocmp(se->se_cc, ic->ic_regdomain.isocc)))
1057			fail |= MATCH_CC;
1058	}
1059	if (vap->iv_flags & IEEE80211_F_PRIVACY) {
1060		if ((se->se_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
1061			fail |= MATCH_PRIVACY;
1062	} else {
1063		/* XXX does this mean privacy is supported or required? */
1064		if (se->se_capinfo & IEEE80211_CAPINFO_PRIVACY)
1065			fail |= MATCH_PRIVACY;
1066	}
1067	se0->se_flags &= ~STA_DEMOTE11B;
1068	rate = check_rate(vap, se->se_chan, se);
1069	if (rate & IEEE80211_RATE_BASIC) {
1070		fail |= MATCH_RATE;
1071		/*
1072		 * An 11b-only ap will give a rate mismatch if there is an
1073		 * OFDM fixed tx rate for 11g.  Try downgrading the channel
1074		 * in the scan list to 11b and retry the rate check.
1075		 */
1076		if (IEEE80211_IS_CHAN_ANYG(se->se_chan)) {
1077			rate = check_rate(vap, demote11b(vap, se->se_chan), se);
1078			if ((rate & IEEE80211_RATE_BASIC) == 0) {
1079				fail &= ~MATCH_RATE;
1080				se0->se_flags |= STA_DEMOTE11B;
1081			}
1082		}
1083	} else if (rate < 2*24) {
1084		/*
1085		 * This is an 11b-only ap.  Check the desired mode in
1086		 * case that needs to be honored (mode 11g filters out
1087		 * 11b-only ap's).  Otherwise force any 11g channel used
1088		 * in scanning to be demoted.
1089		 *
1090		 * NB: we cheat a bit here by looking at the max rate;
1091		 *     we could/should check the rates.
1092		 */
1093		if (!(vap->iv_des_mode == IEEE80211_MODE_AUTO ||
1094		      vap->iv_des_mode == IEEE80211_MODE_11B))
1095			fail |= MATCH_RATE;
1096		else
1097			se0->se_flags |= STA_DEMOTE11B;
1098	}
1099	if (ss->ss_nssid != 0 &&
1100	    !match_ssid(se->se_ssid, ss->ss_nssid, ss->ss_ssid))
1101		fail |= MATCH_SSID;
1102	if ((vap->iv_flags & IEEE80211_F_DESBSSID) &&
1103	    !IEEE80211_ADDR_EQ(vap->iv_des_bssid, se->se_bssid))
1104		fail |= MATCH_BSSID;
1105	if (se0->se_fails >= STA_FAILS_MAX)
1106		fail |= MATCH_FAILS;
1107	if (se0->se_notseen >= STA_PURGE_SCANS)
1108		fail |= MATCH_NOTSEEN;
1109	if (se->se_rssi < STA_RSSI_MIN)
1110		fail |= MATCH_RSSI;
1111#ifdef IEEE80211_DEBUG
1112	if (ieee80211_msg(vap, debug)) {
1113		printf(" %c %s",
1114		    fail & MATCH_FAILS ? '=' :
1115		    fail & MATCH_NOTSEEN ? '^' :
1116		    fail & MATCH_CC ? '$' :
1117#ifdef IEEE80211_SUPPORT_TDMA
1118		    fail & MATCH_TDMA_NOIE ? '&' :
1119		    fail & MATCH_TDMA_VERSION ? 'v' :
1120		    fail & MATCH_TDMA_NOTMASTER ? 's' :
1121		    fail & MATCH_TDMA_NOSLOT ? 'f' :
1122		    fail & MATCH_TDMA_LOCAL ? 'l' :
1123#endif
1124		    fail & MATCH_MESH_NOID ? 'm' :
1125		    fail ? '-' : '+', ether_sprintf(se->se_macaddr));
1126		printf(" %s%c", ether_sprintf(se->se_bssid),
1127		    fail & MATCH_BSSID ? '!' : ' ');
1128		printf(" %3d%c", ieee80211_chan2ieee(ic, se->se_chan),
1129			fail & MATCH_CHANNEL ? '!' : ' ');
1130		printf(" %+4d%c", se->se_rssi, fail & MATCH_RSSI ? '!' : ' ');
1131		printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
1132		    fail & MATCH_RATE ? '!' : ' ');
1133		printf(" %4s%c",
1134		    (se->se_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
1135		    (se->se_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" : "",
1136		    fail & MATCH_CAPINFO ? '!' : ' ');
1137		printf(" %3s%c ",
1138		    (se->se_capinfo & IEEE80211_CAPINFO_PRIVACY) ?
1139		    "wep" : "no",
1140		    fail & MATCH_PRIVACY ? '!' : ' ');
1141		ieee80211_print_essid(se->se_ssid+2, se->se_ssid[1]);
1142		printf("%s\n", fail & (MATCH_SSID | MATCH_MESHID) ? "!" : "");
1143	}
1144#endif
1145	return fail;
1146}
1147
1148static void
1149sta_update_notseen(struct sta_table *st)
1150{
1151	struct sta_entry *se;
1152
1153	IEEE80211_SCAN_TABLE_LOCK(st);
1154	TAILQ_FOREACH(se, &st->st_entry, se_list) {
1155		/*
1156		 * If seen the reset and don't bump the count;
1157		 * otherwise bump the ``not seen'' count.  Note
1158		 * that this insures that stations for which we
1159		 * see frames while not scanning but not during
1160		 * this scan will not be penalized.
1161		 */
1162		if (se->se_seen)
1163			se->se_seen = 0;
1164		else
1165			se->se_notseen++;
1166	}
1167	IEEE80211_SCAN_TABLE_UNLOCK(st);
1168}
1169
1170static void
1171sta_dec_fails(struct sta_table *st)
1172{
1173	struct sta_entry *se;
1174
1175	IEEE80211_SCAN_TABLE_LOCK(st);
1176	TAILQ_FOREACH(se, &st->st_entry, se_list)
1177		if (se->se_fails)
1178			se->se_fails--;
1179	IEEE80211_SCAN_TABLE_UNLOCK(st);
1180}
1181
1182static struct sta_entry *
1183select_bss(struct ieee80211_scan_state *ss, struct ieee80211vap *vap, int debug)
1184{
1185	struct sta_table *st = ss->ss_priv;
1186	struct sta_entry *se, *selbs = NULL;
1187
1188	IEEE80211_DPRINTF(vap, debug, " %s\n",
1189	    "macaddr          bssid         chan  rssi  rate flag  wep  essid");
1190	IEEE80211_SCAN_TABLE_LOCK(st);
1191	TAILQ_FOREACH(se, &st->st_entry, se_list) {
1192		ieee80211_ies_expand(&se->base.se_ies);
1193		if (match_bss(vap, ss, se, debug) == 0) {
1194			if (selbs == NULL)
1195				selbs = se;
1196			else if (sta_compare(se, selbs) > 0)
1197				selbs = se;
1198		}
1199	}
1200	IEEE80211_SCAN_TABLE_UNLOCK(st);
1201
1202	return selbs;
1203}
1204
1205/*
1206 * Pick an ap or ibss network to join or find a channel
1207 * to use to start an ibss network.
1208 */
1209static int
1210sta_pick_bss(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1211{
1212	struct sta_table *st = ss->ss_priv;
1213	struct sta_entry *selbs;
1214	struct ieee80211_channel *chan;
1215
1216	KASSERT(vap->iv_opmode == IEEE80211_M_STA,
1217		("wrong mode %u", vap->iv_opmode));
1218
1219	if (st->st_newscan) {
1220		sta_update_notseen(st);
1221		st->st_newscan = 0;
1222	}
1223	if (ss->ss_flags & IEEE80211_SCAN_NOPICK) {
1224		/*
1225		 * Manual/background scan, don't select+join the
1226		 * bss, just return.  The scanning framework will
1227		 * handle notification that this has completed.
1228		 */
1229		ss->ss_flags &= ~IEEE80211_SCAN_NOPICK;
1230		return 1;
1231	}
1232	/*
1233	 * Automatic sequencing; look for a candidate and
1234	 * if found join the network.
1235	 */
1236	/* NB: unlocked read should be ok */
1237	if (TAILQ_FIRST(&st->st_entry) == NULL) {
1238		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
1239			"%s: no scan candidate\n", __func__);
1240		if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1241			return 0;
1242notfound:
1243		/*
1244		 * If nothing suitable was found decrement
1245		 * the failure counts so entries will be
1246		 * reconsidered the next time around.  We
1247		 * really want to do this only for sta's
1248		 * where we've previously had some success.
1249		 */
1250		sta_dec_fails(st);
1251		st->st_newscan = 1;
1252		return 0;			/* restart scan */
1253	}
1254	selbs = select_bss(ss, vap, IEEE80211_MSG_SCAN);
1255	if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1256		return (selbs != NULL);
1257	if (selbs == NULL)
1258		goto notfound;
1259	chan = selbs->base.se_chan;
1260	if (selbs->se_flags & STA_DEMOTE11B)
1261		chan = demote11b(vap, chan);
1262	if (!ieee80211_sta_join(vap, chan, &selbs->base))
1263		goto notfound;
1264	return 1;				/* terminate scan */
1265}
1266
1267/*
1268 * Lookup an entry in the scan cache.  We assume we're
1269 * called from the bottom half or such that we don't need
1270 * to block the bottom half so that it's safe to return
1271 * a reference to an entry w/o holding the lock on the table.
1272 */
1273static struct sta_entry *
1274sta_lookup(struct sta_table *st, const uint8_t macaddr[IEEE80211_ADDR_LEN])
1275{
1276	struct sta_entry *se;
1277	int hash = STA_HASH(macaddr);
1278
1279	IEEE80211_SCAN_TABLE_LOCK(st);
1280	LIST_FOREACH(se, &st->st_hash[hash], se_hash)
1281		if (IEEE80211_ADDR_EQ(se->base.se_macaddr, macaddr))
1282			break;
1283	IEEE80211_SCAN_TABLE_UNLOCK(st);
1284
1285	return se;		/* NB: unlocked */
1286}
1287
1288static void
1289sta_roam_check(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1290{
1291	struct ieee80211com *ic = vap->iv_ic;
1292	struct ieee80211_node *ni = vap->iv_bss;
1293	struct sta_table *st = ss->ss_priv;
1294	enum ieee80211_phymode mode;
1295	struct sta_entry *se, *selbs;
1296	uint8_t roamRate, curRate, ucastRate;
1297	int8_t roamRssi, curRssi;
1298
1299	se = sta_lookup(st, ni->ni_macaddr);
1300	if (se == NULL) {
1301		/* XXX something is wrong */
1302		return;
1303	}
1304
1305	mode = ieee80211_chan2mode(ic->ic_bsschan);
1306	roamRate = vap->iv_roamparms[mode].rate;
1307	roamRssi = vap->iv_roamparms[mode].rssi;
1308	ucastRate = vap->iv_txparms[mode].ucastrate;
1309	/* NB: the most up to date rssi is in the node, not the scan cache */
1310	curRssi = ic->ic_node_getrssi(ni);
1311	if (ucastRate == IEEE80211_FIXED_RATE_NONE) {
1312		curRate = ni->ni_txrate;
1313		roamRate &= IEEE80211_RATE_VAL;
1314		IEEE80211_DPRINTF(vap, IEEE80211_MSG_ROAM,
1315		    "%s: currssi %d currate %u roamrssi %d roamrate %u\n",
1316		    __func__, curRssi, curRate, roamRssi, roamRate);
1317	} else {
1318		curRate = roamRate;	/* NB: insure compare below fails */
1319		IEEE80211_DPRINTF(vap, IEEE80211_MSG_ROAM,
1320		    "%s: currssi %d roamrssi %d\n", __func__, curRssi, roamRssi);
1321	}
1322	/*
1323	 * Check if a new ap should be used and switch.
1324	 * XXX deauth current ap
1325	 */
1326	if (curRate < roamRate || curRssi < roamRssi) {
1327		if (ieee80211_time_after(ticks, ic->ic_lastscan + vap->iv_scanvalid)) {
1328			/*
1329			 * Scan cache contents are too old; force a scan now
1330			 * if possible so we have current state to make a
1331			 * decision with.  We don't kick off a bg scan if
1332			 * we're using dynamic turbo and boosted or if the
1333			 * channel is busy.
1334			 * XXX force immediate switch on scan complete
1335			 */
1336			if (!IEEE80211_IS_CHAN_DTURBO(ic->ic_curchan) &&
1337			    ieee80211_time_after(ticks, ic->ic_lastdata + vap->iv_bgscanidle))
1338				ieee80211_bg_scan(vap, 0);
1339			return;
1340		}
1341		se->base.se_rssi = curRssi;
1342		selbs = select_bss(ss, vap, IEEE80211_MSG_ROAM);
1343		if (selbs != NULL && selbs != se) {
1344			struct ieee80211_channel *chan;
1345
1346			IEEE80211_DPRINTF(vap,
1347			    IEEE80211_MSG_ROAM | IEEE80211_MSG_DEBUG,
1348			    "%s: ROAM: curRate %u, roamRate %u, "
1349			    "curRssi %d, roamRssi %d\n", __func__,
1350			    curRate, roamRate, curRssi, roamRssi);
1351
1352			chan = selbs->base.se_chan;
1353			if (selbs->se_flags & STA_DEMOTE11B)
1354				chan = demote11b(vap, chan);
1355			(void) ieee80211_sta_join(vap, chan, &selbs->base);
1356		}
1357	}
1358}
1359
1360/*
1361 * Age entries in the scan cache.
1362 * XXX also do roaming since it's convenient
1363 */
1364static void
1365sta_age(struct ieee80211_scan_state *ss)
1366{
1367	struct ieee80211vap *vap = ss->ss_vap;
1368
1369	adhoc_age(ss);
1370	/*
1371	 * If rate control is enabled check periodically to see if
1372	 * we should roam from our current connection to one that
1373	 * might be better.  This only applies when we're operating
1374	 * in sta mode and automatic roaming is set.
1375	 * XXX defer if busy
1376	 * XXX repeater station
1377	 * XXX do when !bgscan?
1378	 */
1379	KASSERT(vap->iv_opmode == IEEE80211_M_STA,
1380		("wrong mode %u", vap->iv_opmode));
1381	if (vap->iv_roaming == IEEE80211_ROAMING_AUTO &&
1382	    (vap->iv_flags & IEEE80211_F_BGSCAN) &&
1383	    vap->iv_state >= IEEE80211_S_RUN)
1384		/* XXX vap is implicit */
1385		sta_roam_check(ss, vap);
1386}
1387
1388/*
1389 * Iterate over the entries in the scan cache, invoking
1390 * the callback function on each one.
1391 */
1392static void
1393sta_iterate(struct ieee80211_scan_state *ss,
1394	ieee80211_scan_iter_func *f, void *arg)
1395{
1396	struct sta_table *st = ss->ss_priv;
1397	struct sta_entry *se;
1398	u_int gen;
1399
1400	IEEE80211_SCAN_ITER_LOCK(st);
1401	gen = st->st_scaniter++;
1402restart:
1403	IEEE80211_SCAN_TABLE_LOCK(st);
1404	TAILQ_FOREACH(se, &st->st_entry, se_list) {
1405		if (se->se_scangen != gen) {
1406			se->se_scangen = gen;
1407			/* update public state */
1408			se->base.se_age = ticks - se->se_lastupdate;
1409			IEEE80211_SCAN_TABLE_UNLOCK(st);
1410			(*f)(arg, &se->base);
1411			goto restart;
1412		}
1413	}
1414	IEEE80211_SCAN_TABLE_UNLOCK(st);
1415
1416	IEEE80211_SCAN_ITER_UNLOCK(st);
1417}
1418
1419static void
1420sta_assoc_fail(struct ieee80211_scan_state *ss,
1421	const uint8_t macaddr[IEEE80211_ADDR_LEN], int reason)
1422{
1423	struct sta_table *st = ss->ss_priv;
1424	struct sta_entry *se;
1425
1426	se = sta_lookup(st, macaddr);
1427	if (se != NULL) {
1428		se->se_fails++;
1429		se->se_lastfail = ticks;
1430		IEEE80211_NOTE_MAC(ss->ss_vap, IEEE80211_MSG_SCAN,
1431		    macaddr, "%s: reason %u fails %u",
1432		    __func__, reason, se->se_fails);
1433	}
1434}
1435
1436static void
1437sta_assoc_success(struct ieee80211_scan_state *ss,
1438	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1439{
1440	struct sta_table *st = ss->ss_priv;
1441	struct sta_entry *se;
1442
1443	se = sta_lookup(st, macaddr);
1444	if (se != NULL) {
1445#if 0
1446		se->se_fails = 0;
1447		IEEE80211_NOTE_MAC(ss->ss_vap, IEEE80211_MSG_SCAN,
1448		    macaddr, "%s: fails %u",
1449		    __func__, se->se_fails);
1450#endif
1451		se->se_lastassoc = ticks;
1452	}
1453}
1454
1455static const struct ieee80211_scanner sta_default = {
1456	.scan_name		= "default",
1457	.scan_attach		= sta_attach,
1458	.scan_detach		= sta_detach,
1459	.scan_start		= sta_start,
1460	.scan_restart		= sta_restart,
1461	.scan_cancel		= sta_cancel,
1462	.scan_end		= sta_pick_bss,
1463	.scan_flush		= sta_flush,
1464	.scan_add		= sta_add,
1465	.scan_age		= sta_age,
1466	.scan_iterate		= sta_iterate,
1467	.scan_assoc_fail	= sta_assoc_fail,
1468	.scan_assoc_success	= sta_assoc_success,
1469};
1470IEEE80211_SCANNER_ALG(sta, IEEE80211_M_STA, sta_default);
1471
1472/*
1473 * Adhoc mode-specific support.
1474 */
1475
1476static const uint16_t adhocWorld[] =		/* 36, 40, 44, 48 */
1477{ 5180, 5200, 5220, 5240 };
1478static const uint16_t adhocFcc3[] =		/* 36, 40, 44, 48 145, 149, 153, 157, 161, 165 */
1479{ 5180, 5200, 5220, 5240, 5725, 5745, 5765, 5785, 5805, 5825 };
1480static const uint16_t adhocMkk[] =		/* 34, 38, 42, 46 */
1481{ 5170, 5190, 5210, 5230 };
1482static const uint16_t adhoc11b[] =		/* 10, 11 */
1483{ 2457, 2462 };
1484
1485static const struct scanlist adhocScanTable[] = {
1486	{ IEEE80211_MODE_11B,   	X(adhoc11b) },
1487	{ IEEE80211_MODE_11A,   	X(adhocWorld) },
1488	{ IEEE80211_MODE_11A,   	X(adhocFcc3) },
1489	{ IEEE80211_MODE_11B,   	X(adhocMkk) },
1490	{ .list = NULL }
1491};
1492#undef X
1493
1494/*
1495 * Start an adhoc-mode scan by populating the channel list.
1496 */
1497static int
1498adhoc_start(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1499{
1500	struct sta_table *st = ss->ss_priv;
1501
1502	makescanlist(ss, vap, adhocScanTable);
1503
1504	if (ss->ss_mindwell == 0)
1505		ss->ss_mindwell = msecs_to_ticks(200);	/* 200ms */
1506	if (ss->ss_maxdwell == 0)
1507		ss->ss_maxdwell = msecs_to_ticks(200);	/* 200ms */
1508
1509	st->st_scangen++;
1510	st->st_newscan = 1;
1511
1512	return 0;
1513}
1514
1515/*
1516 * Select a channel to start an adhoc network on.
1517 * The channel list was populated with appropriate
1518 * channels so select one that looks least occupied.
1519 */
1520static struct ieee80211_channel *
1521adhoc_pick_channel(struct ieee80211_scan_state *ss, int flags)
1522{
1523	struct sta_table *st = ss->ss_priv;
1524	struct sta_entry *se;
1525	struct ieee80211_channel *c, *bestchan;
1526	int i, bestrssi, maxrssi;
1527
1528	bestchan = NULL;
1529	bestrssi = -1;
1530
1531	IEEE80211_SCAN_TABLE_LOCK(st);
1532	for (i = 0; i < ss->ss_last; i++) {
1533		c = ss->ss_chans[i];
1534		/* never consider a channel with radar */
1535		if (IEEE80211_IS_CHAN_RADAR(c))
1536			continue;
1537		/* skip channels disallowed by regulatory settings */
1538		if (IEEE80211_IS_CHAN_NOADHOC(c))
1539			continue;
1540		/* check channel attributes for band compatibility */
1541		if (flags != 0 && (c->ic_flags & flags) != flags)
1542			continue;
1543		maxrssi = 0;
1544		TAILQ_FOREACH(se, &st->st_entry, se_list) {
1545			if (se->base.se_chan != c)
1546				continue;
1547			if (se->base.se_rssi > maxrssi)
1548				maxrssi = se->base.se_rssi;
1549		}
1550		if (bestchan == NULL || maxrssi < bestrssi)
1551			bestchan = c;
1552	}
1553	IEEE80211_SCAN_TABLE_UNLOCK(st);
1554
1555	return bestchan;
1556}
1557
1558/*
1559 * Pick an ibss network to join or find a channel
1560 * to use to start an ibss network.
1561 */
1562static int
1563adhoc_pick_bss(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1564{
1565	struct sta_table *st = ss->ss_priv;
1566	struct sta_entry *selbs;
1567	struct ieee80211_channel *chan;
1568	struct ieee80211com *ic = vap->iv_ic;
1569
1570	KASSERT(vap->iv_opmode == IEEE80211_M_IBSS ||
1571		vap->iv_opmode == IEEE80211_M_AHDEMO ||
1572		vap->iv_opmode == IEEE80211_M_MBSS,
1573		("wrong opmode %u", vap->iv_opmode));
1574
1575	if (st->st_newscan) {
1576		sta_update_notseen(st);
1577		st->st_newscan = 0;
1578	}
1579	if (ss->ss_flags & IEEE80211_SCAN_NOPICK) {
1580		/*
1581		 * Manual/background scan, don't select+join the
1582		 * bss, just return.  The scanning framework will
1583		 * handle notification that this has completed.
1584		 */
1585		ss->ss_flags &= ~IEEE80211_SCAN_NOPICK;
1586		return 1;
1587	}
1588	/*
1589	 * Automatic sequencing; look for a candidate and
1590	 * if found join the network.
1591	 */
1592	/* NB: unlocked read should be ok */
1593	if (TAILQ_FIRST(&st->st_entry) == NULL) {
1594		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
1595			"%s: no scan candidate\n", __func__);
1596		if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1597			return 0;
1598notfound:
1599		/* NB: never auto-start a tdma network for slot !0 */
1600#ifdef IEEE80211_SUPPORT_TDMA
1601		if (vap->iv_des_nssid &&
1602		    ((vap->iv_caps & IEEE80211_C_TDMA) == 0 ||
1603		     ieee80211_tdma_getslot(vap) == 0)) {
1604#else
1605		if (vap->iv_des_nssid) {
1606#endif
1607			/*
1608			 * No existing adhoc network to join and we have
1609			 * an ssid; start one up.  If no channel was
1610			 * specified, try to select a channel.
1611			 */
1612			if (vap->iv_des_chan == IEEE80211_CHAN_ANYC ||
1613			    IEEE80211_IS_CHAN_RADAR(vap->iv_des_chan)) {
1614				chan = adhoc_pick_channel(ss, 0);
1615			} else
1616				chan = vap->iv_des_chan;
1617			if (chan != NULL) {
1618				struct ieee80211com *ic = vap->iv_ic;
1619				/*
1620				 * Create a HT capable IBSS; the per-node
1621				 * probe request/response will result in
1622				 * "correct" rate control capabilities being
1623				 * negotiated.
1624				 */
1625				chan = ieee80211_ht_adjust_channel(ic,
1626				    chan, vap->iv_flags_ht);
1627				ieee80211_create_ibss(vap, chan);
1628				return 1;
1629			}
1630		}
1631		/*
1632		 * If nothing suitable was found decrement
1633		 * the failure counts so entries will be
1634		 * reconsidered the next time around.  We
1635		 * really want to do this only for sta's
1636		 * where we've previously had some success.
1637		 */
1638		sta_dec_fails(st);
1639		st->st_newscan = 1;
1640		return 0;			/* restart scan */
1641	}
1642	selbs = select_bss(ss, vap, IEEE80211_MSG_SCAN);
1643	if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1644		return (selbs != NULL);
1645	if (selbs == NULL)
1646		goto notfound;
1647	chan = selbs->base.se_chan;
1648	if (selbs->se_flags & STA_DEMOTE11B)
1649		chan = demote11b(vap, chan);
1650	/*
1651	 * If HT is available, make it a possibility here.
1652	 * The intent is to enable HT20/HT40 when joining a non-HT
1653	 * IBSS node; we can then advertise HT IEs and speak HT
1654	 * to any subsequent nodes that support it.
1655	 */
1656	chan = ieee80211_ht_adjust_channel(ic,
1657	    chan, vap->iv_flags_ht);
1658	if (!ieee80211_sta_join(vap, chan, &selbs->base))
1659		goto notfound;
1660	return 1;				/* terminate scan */
1661}
1662
1663/*
1664 * Age entries in the scan cache.
1665 */
1666static void
1667adhoc_age(struct ieee80211_scan_state *ss)
1668{
1669	struct sta_table *st = ss->ss_priv;
1670	struct sta_entry *se, *next;
1671
1672	IEEE80211_SCAN_TABLE_LOCK(st);
1673	TAILQ_FOREACH_SAFE(se, &st->st_entry, se_list, next) {
1674		if (se->se_notseen > STA_PURGE_SCANS) {
1675			TAILQ_REMOVE(&st->st_entry, se, se_list);
1676			LIST_REMOVE(se, se_hash);
1677			ieee80211_ies_cleanup(&se->base.se_ies);
1678			IEEE80211_FREE(se, M_80211_SCAN);
1679		}
1680	}
1681	IEEE80211_SCAN_TABLE_UNLOCK(st);
1682}
1683
1684static const struct ieee80211_scanner adhoc_default = {
1685	.scan_name		= "default",
1686	.scan_attach		= sta_attach,
1687	.scan_detach		= sta_detach,
1688	.scan_start		= adhoc_start,
1689	.scan_restart		= sta_restart,
1690	.scan_cancel		= sta_cancel,
1691	.scan_end		= adhoc_pick_bss,
1692	.scan_flush		= sta_flush,
1693	.scan_pickchan		= adhoc_pick_channel,
1694	.scan_add		= sta_add,
1695	.scan_age		= adhoc_age,
1696	.scan_iterate		= sta_iterate,
1697	.scan_assoc_fail	= sta_assoc_fail,
1698	.scan_assoc_success	= sta_assoc_success,
1699};
1700IEEE80211_SCANNER_ALG(ibss, IEEE80211_M_IBSS, adhoc_default);
1701IEEE80211_SCANNER_ALG(ahdemo, IEEE80211_M_AHDEMO, adhoc_default);
1702
1703static int
1704ap_start(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1705{
1706	struct sta_table *st = ss->ss_priv;
1707
1708	makescanlist(ss, vap, staScanTable);
1709
1710	if (ss->ss_mindwell == 0)
1711		ss->ss_mindwell = msecs_to_ticks(200);	/* 200ms */
1712	if (ss->ss_maxdwell == 0)
1713		ss->ss_maxdwell = msecs_to_ticks(200);	/* 200ms */
1714
1715	st->st_scangen++;
1716	st->st_newscan = 1;
1717
1718	return 0;
1719}
1720
1721/*
1722 * Cancel an ongoing scan.
1723 */
1724static int
1725ap_cancel(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1726{
1727	return 0;
1728}
1729
1730/*
1731 * Pick a quiet channel to use for ap operation.
1732 */
1733static struct ieee80211_channel *
1734ap_pick_channel(struct ieee80211_scan_state *ss, int flags)
1735{
1736	struct sta_table *st = ss->ss_priv;
1737	struct ieee80211_channel *bestchan = NULL;
1738	int i;
1739
1740	/* XXX select channel more intelligently, e.g. channel spread, power */
1741	/* NB: use scan list order to preserve channel preference */
1742	for (i = 0; i < ss->ss_last; i++) {
1743		struct ieee80211_channel *chan = ss->ss_chans[i];
1744		/*
1745		 * If the channel is unoccupied the max rssi
1746		 * should be zero; just take it.  Otherwise
1747		 * track the channel with the lowest rssi and
1748		 * use that when all channels appear occupied.
1749		 */
1750		if (IEEE80211_IS_CHAN_RADAR(chan))
1751			continue;
1752		if (IEEE80211_IS_CHAN_NOHOSTAP(chan))
1753			continue;
1754		/* check channel attributes for band compatibility */
1755		if (flags != 0 && (chan->ic_flags & flags) != flags)
1756			continue;
1757		KASSERT(sizeof(chan->ic_ieee) == 1, ("ic_chan size"));
1758		/* XXX channel have interference */
1759		if (st->st_maxrssi[chan->ic_ieee] == 0) {
1760			/* XXX use other considerations */
1761			return chan;
1762		}
1763		if (bestchan == NULL ||
1764		    st->st_maxrssi[chan->ic_ieee] < st->st_maxrssi[bestchan->ic_ieee])
1765			bestchan = chan;
1766	}
1767	return bestchan;
1768}
1769
1770/*
1771 * Pick a quiet channel to use for ap operation.
1772 */
1773static int
1774ap_end(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1775{
1776	struct ieee80211com *ic = vap->iv_ic;
1777	struct ieee80211_channel *bestchan;
1778
1779	KASSERT(vap->iv_opmode == IEEE80211_M_HOSTAP,
1780		("wrong opmode %u", vap->iv_opmode));
1781	bestchan = ap_pick_channel(ss, 0);
1782	if (bestchan == NULL) {
1783		/* no suitable channel, should not happen */
1784		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
1785		    "%s: no suitable channel! (should not happen)\n", __func__);
1786		/* XXX print something? */
1787		return 0;			/* restart scan */
1788	}
1789	/*
1790	 * If this is a dynamic turbo channel, start with the unboosted one.
1791	 */
1792	if (IEEE80211_IS_CHAN_TURBO(bestchan)) {
1793		bestchan = ieee80211_find_channel(ic, bestchan->ic_freq,
1794			bestchan->ic_flags & ~IEEE80211_CHAN_TURBO);
1795		if (bestchan == NULL) {
1796			/* should never happen ?? */
1797			return 0;
1798		}
1799	}
1800	if (ss->ss_flags & (IEEE80211_SCAN_NOPICK | IEEE80211_SCAN_NOJOIN)) {
1801		/*
1802		 * Manual/background scan, don't select+join the
1803		 * bss, just return.  The scanning framework will
1804		 * handle notification that this has completed.
1805		 */
1806		ss->ss_flags &= ~IEEE80211_SCAN_NOPICK;
1807		return 1;
1808	}
1809	ieee80211_create_ibss(vap,
1810	    ieee80211_ht_adjust_channel(ic, bestchan, vap->iv_flags_ht));
1811	return 1;
1812}
1813
1814static const struct ieee80211_scanner ap_default = {
1815	.scan_name		= "default",
1816	.scan_attach		= sta_attach,
1817	.scan_detach		= sta_detach,
1818	.scan_start		= ap_start,
1819	.scan_restart		= sta_restart,
1820	.scan_cancel		= ap_cancel,
1821	.scan_end		= ap_end,
1822	.scan_flush		= sta_flush,
1823	.scan_pickchan		= ap_pick_channel,
1824	.scan_add		= sta_add,
1825	.scan_age		= adhoc_age,
1826	.scan_iterate		= sta_iterate,
1827	.scan_assoc_success	= sta_assoc_success,
1828	.scan_assoc_fail	= sta_assoc_fail,
1829};
1830IEEE80211_SCANNER_ALG(ap, IEEE80211_M_HOSTAP, ap_default);
1831
1832#ifdef IEEE80211_SUPPORT_MESH
1833/*
1834 * Pick an mbss network to join or find a channel
1835 * to use to start an mbss network.
1836 */
1837static int
1838mesh_pick_bss(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1839{
1840	struct sta_table *st = ss->ss_priv;
1841	struct ieee80211_mesh_state *ms = vap->iv_mesh;
1842	struct sta_entry *selbs;
1843	struct ieee80211_channel *chan;
1844
1845	KASSERT(vap->iv_opmode == IEEE80211_M_MBSS,
1846		("wrong opmode %u", vap->iv_opmode));
1847
1848	if (st->st_newscan) {
1849		sta_update_notseen(st);
1850		st->st_newscan = 0;
1851	}
1852	if (ss->ss_flags & IEEE80211_SCAN_NOPICK) {
1853		/*
1854		 * Manual/background scan, don't select+join the
1855		 * bss, just return.  The scanning framework will
1856		 * handle notification that this has completed.
1857		 */
1858		ss->ss_flags &= ~IEEE80211_SCAN_NOPICK;
1859		return 1;
1860	}
1861	/*
1862	 * Automatic sequencing; look for a candidate and
1863	 * if found join the network.
1864	 */
1865	/* NB: unlocked read should be ok */
1866	if (TAILQ_FIRST(&st->st_entry) == NULL) {
1867		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
1868			"%s: no scan candidate\n", __func__);
1869		if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1870			return 0;
1871notfound:
1872		if (ms->ms_idlen != 0) {
1873			/*
1874			 * No existing mbss network to join and we have
1875			 * a meshid; start one up.  If no channel was
1876			 * specified, try to select a channel.
1877			 */
1878			if (vap->iv_des_chan == IEEE80211_CHAN_ANYC ||
1879			    IEEE80211_IS_CHAN_RADAR(vap->iv_des_chan)) {
1880				struct ieee80211com *ic = vap->iv_ic;
1881
1882				chan = adhoc_pick_channel(ss, 0);
1883				if (chan != NULL)
1884					chan = ieee80211_ht_adjust_channel(ic,
1885					    chan, vap->iv_flags_ht);
1886			} else
1887				chan = vap->iv_des_chan;
1888			if (chan != NULL) {
1889				ieee80211_create_ibss(vap, chan);
1890				return 1;
1891			}
1892		}
1893		/*
1894		 * If nothing suitable was found decrement
1895		 * the failure counts so entries will be
1896		 * reconsidered the next time around.  We
1897		 * really want to do this only for sta's
1898		 * where we've previously had some success.
1899		 */
1900		sta_dec_fails(st);
1901		st->st_newscan = 1;
1902		return 0;			/* restart scan */
1903	}
1904	selbs = select_bss(ss, vap, IEEE80211_MSG_SCAN);
1905	if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1906		return (selbs != NULL);
1907	if (selbs == NULL)
1908		goto notfound;
1909	chan = selbs->base.se_chan;
1910	if (selbs->se_flags & STA_DEMOTE11B)
1911		chan = demote11b(vap, chan);
1912	if (!ieee80211_sta_join(vap, chan, &selbs->base))
1913		goto notfound;
1914	return 1;				/* terminate scan */
1915}
1916
1917static const struct ieee80211_scanner mesh_default = {
1918	.scan_name		= "default",
1919	.scan_attach		= sta_attach,
1920	.scan_detach		= sta_detach,
1921	.scan_start		= adhoc_start,
1922	.scan_restart		= sta_restart,
1923	.scan_cancel		= sta_cancel,
1924	.scan_end		= mesh_pick_bss,
1925	.scan_flush		= sta_flush,
1926	.scan_pickchan		= adhoc_pick_channel,
1927	.scan_add		= sta_add,
1928	.scan_age		= adhoc_age,
1929	.scan_iterate		= sta_iterate,
1930	.scan_assoc_fail	= sta_assoc_fail,
1931	.scan_assoc_success	= sta_assoc_success,
1932};
1933IEEE80211_SCANNER_ALG(mesh, IEEE80211_M_MBSS, mesh_default);
1934#endif /* IEEE80211_SUPPORT_MESH */
1935