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