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