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