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