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