xref: /freebsd/sys/net80211/ieee80211_scan_sta.c (revision 1db64f89363c97858961c4df0b7d02f3223723cf)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
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 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 	[IEEE80211_MODE_VHT_5GHZ] = IEEE80211_CHAN_A,
474 	[IEEE80211_MODE_VHT_2GHZ] = IEEE80211_CHAN_G,
475 };
476 
477 static void
478 add_channels(struct ieee80211vap *vap,
479 	struct ieee80211_scan_state *ss,
480 	enum ieee80211_phymode mode, const uint16_t freq[], int nfreq)
481 {
482 	struct ieee80211com *ic = vap->iv_ic;
483 	struct ieee80211_channel *c, *cg;
484 	u_int modeflags;
485 	int i;
486 
487 	KASSERT(mode < nitems(chanflags), ("Unexpected mode %u", mode));
488 	modeflags = chanflags[mode];
489 	for (i = 0; i < nfreq; i++) {
490 		if (ss->ss_last >= IEEE80211_SCAN_MAX)
491 			break;
492 
493 		c = ieee80211_find_channel(ic, freq[i], modeflags);
494 		if (c == NULL || isexcluded(vap, c))
495 			continue;
496 		if (mode == IEEE80211_MODE_AUTO) {
497 			KASSERT(IEEE80211_IS_CHAN_B(c),
498 			    ("%s: wrong channel for 'auto' mode %u / %u\n",
499 			    __func__, c->ic_freq, c->ic_flags));
500 
501 			/*
502 			 * XXX special-case 11b/g channels so we select
503 			 *     the g channel if both are present.
504 			 */
505 			if ((cg = find11gchannel(ic, i, c->ic_freq)) != NULL)
506 				c = cg;
507 		}
508 		ss->ss_chans[ss->ss_last++] = c;
509 	}
510 }
511 
512 struct scanlist {
513 	uint16_t	mode;
514 	uint16_t	count;
515 	const uint16_t	*list;
516 };
517 
518 static int
519 checktable(const struct scanlist *scan, const struct ieee80211_channel *c)
520 {
521 	int i;
522 
523 	for (; scan->list != NULL; scan++) {
524 		for (i = 0; i < scan->count; i++)
525 			if (scan->list[i] == c->ic_freq)
526 				return 1;
527 	}
528 	return 0;
529 }
530 
531 static int
532 onscanlist(const struct ieee80211_scan_state *ss,
533 	const struct ieee80211_channel *c)
534 {
535 	int i;
536 
537 	for (i = 0; i < ss->ss_last; i++)
538 		if (ss->ss_chans[i] == c)
539 			return 1;
540 	return 0;
541 }
542 
543 static void
544 sweepchannels(struct ieee80211_scan_state *ss, struct ieee80211vap *vap,
545 	const struct scanlist table[])
546 {
547 	struct ieee80211com *ic = vap->iv_ic;
548 	struct ieee80211_channel *c;
549 	int i;
550 
551 	for (i = 0; i < ic->ic_nchans; i++) {
552 		if (ss->ss_last >= IEEE80211_SCAN_MAX)
553 			break;
554 
555 		c = &ic->ic_channels[i];
556 		/*
557 		 * Ignore dynamic turbo channels; we scan them
558 		 * in normal mode (i.e. not boosted).  Likewise
559 		 * for HT/VHT channels, they get scanned using
560 		 * legacy rates.
561 		 */
562 		if (IEEE80211_IS_CHAN_DTURBO(c) || IEEE80211_IS_CHAN_HT(c) ||
563 		    IEEE80211_IS_CHAN_VHT(c))
564 			continue;
565 
566 		/*
567 		 * If a desired mode was specified, scan only
568 		 * channels that satisfy that constraint.
569 		 */
570 		if (vap->iv_des_mode != IEEE80211_MODE_AUTO &&
571 		    vap->iv_des_mode != ieee80211_chan2mode(c))
572 			continue;
573 
574 		/*
575 		 * Skip channels excluded by user request.
576 		 */
577 		if (isexcluded(vap, c))
578 			continue;
579 
580 		/*
581 		 * Add the channel unless it is listed in the
582 		 * fixed scan order tables.  This insures we
583 		 * don't sweep back in channels we filtered out
584 		 * above.
585 		 */
586 		if (checktable(table, c))
587 			continue;
588 
589 		/* Add channel to scanning list. */
590 		ss->ss_chans[ss->ss_last++] = c;
591 	}
592 	/*
593 	 * Explicitly add any desired channel if:
594 	 * - not already on the scan list
595 	 * - allowed by any desired mode constraint
596 	 * - there is space in the scan list
597 	 * This allows the channel to be used when the filtering
598 	 * mechanisms would otherwise elide it (e.g HT, turbo).
599 	 */
600 	c = vap->iv_des_chan;
601 	if (c != IEEE80211_CHAN_ANYC &&
602 	    !onscanlist(ss, c) &&
603 	    (vap->iv_des_mode == IEEE80211_MODE_AUTO ||
604 	     vap->iv_des_mode == ieee80211_chan2mode(c)) &&
605 	    ss->ss_last < IEEE80211_SCAN_MAX)
606 		ss->ss_chans[ss->ss_last++] = c;
607 }
608 
609 static void
610 makescanlist(struct ieee80211_scan_state *ss, struct ieee80211vap *vap,
611 	const struct scanlist table[])
612 {
613 	const struct scanlist *scan;
614 	enum ieee80211_phymode mode;
615 
616 	ss->ss_last = 0;
617 	/*
618 	 * Use the table of ordered channels to construct the list
619 	 * of channels for scanning.  Any channels in the ordered
620 	 * list not in the master list will be discarded.
621 	 */
622 	for (scan = table; scan->list != NULL; scan++) {
623 		mode = scan->mode;
624 
625 		switch (mode) {
626 		case IEEE80211_MODE_11B:
627 			if (vap->iv_des_mode == IEEE80211_MODE_11B)
628 				break;
629 
630 			/*
631 			 * The scan table marks 2.4Ghz channels as b
632 			 * so if the desired mode is 11g / 11ng / 11acg,
633 			 * then use the 11b channel list but upgrade the mode.
634 			 *
635 			 * NB: 11b -> AUTO lets add_channels upgrade an
636 			 * 11b channel to 11g if available.
637 			 */
638 			if (vap->iv_des_mode == IEEE80211_MODE_AUTO ||
639 			    vap->iv_des_mode == IEEE80211_MODE_11G ||
640 			    vap->iv_des_mode == IEEE80211_MODE_11NG ||
641 			    vap->iv_des_mode == IEEE80211_MODE_VHT_2GHZ) {
642 				mode = vap->iv_des_mode;
643 				break;
644 			}
645 
646 			continue;
647 		case IEEE80211_MODE_11A:
648 			/* Use 11a channel list for 11na / 11ac modes */
649 			if (vap->iv_des_mode == IEEE80211_MODE_11NA ||
650 			    vap->iv_des_mode == IEEE80211_MODE_VHT_5GHZ) {
651 				mode = vap->iv_des_mode;
652 				break;
653 			}
654 
655 			/* FALLTHROUGH */
656 		default:
657 			/*
658 			 * If a desired mode was specified, scan only
659 			 * channels that satisfy that constraint.
660 			 */
661 			if (vap->iv_des_mode != IEEE80211_MODE_AUTO &&
662 			    vap->iv_des_mode != mode)
663 				continue;
664 		}
665 
666 #ifdef IEEE80211_F_XR
667 		/* XR does not operate on turbo channels */
668 		if ((vap->iv_flags & IEEE80211_F_XR) &&
669 		    (mode == IEEE80211_MODE_TURBO_A ||
670 		     mode == IEEE80211_MODE_TURBO_G ||
671 		     mode == IEEE80211_MODE_STURBO_A))
672 			continue;
673 #endif
674 		/*
675 		 * Add the list of the channels; any that are not
676 		 * in the master channel list will be discarded.
677 		 */
678 		add_channels(vap, ss, mode, scan->list, scan->count);
679 	}
680 
681 	/*
682 	 * Add the channels from the ic that are not present
683 	 * in the table.
684 	 */
685 	sweepchannels(ss, vap, table);
686 }
687 
688 static const uint16_t rcl1[] =		/* 8 FCC channel: 52, 56, 60, 64, 36, 40, 44, 48 */
689 { 5260, 5280, 5300, 5320, 5180, 5200, 5220, 5240 };
690 static const uint16_t rcl2[] =		/* 4 MKK channels: 34, 38, 42, 46 */
691 { 5170, 5190, 5210, 5230 };
692 static const uint16_t rcl3[] =		/* 2.4Ghz ch: 1,6,11,7,13 */
693 { 2412, 2437, 2462, 2442, 2472 };
694 static const uint16_t rcl4[] =		/* 5 FCC channel: 149, 153, 161, 165 */
695 { 5745, 5765, 5785, 5805, 5825 };
696 static const uint16_t rcl7[] =		/* 11 ETSI channel: 100,104,108,112,116,120,124,128,132,136,140 */
697 { 5500, 5520, 5540, 5560, 5580, 5600, 5620, 5640, 5660, 5680, 5700 };
698 static const uint16_t rcl8[] =		/* 2.4Ghz ch: 2,3,4,5,8,9,10,12 */
699 { 2417, 2422, 2427, 2432, 2447, 2452, 2457, 2467 };
700 static const uint16_t rcl9[] =		/* 2.4Ghz ch: 14 */
701 { 2484 };
702 static const uint16_t rcl10[] =	/* Added Korean channels 2312-2372 */
703 { 2312, 2317, 2322, 2327, 2332, 2337, 2342, 2347, 2352, 2357, 2362, 2367, 2372 };
704 static const uint16_t rcl11[] =	/* Added Japan channels in 4.9/5.0 spectrum */
705 { 5040, 5060, 5080, 4920, 4940, 4960, 4980 };
706 #ifdef ATH_TURBO_SCAN
707 static const uint16_t rcl5[] =		/* 3 static turbo channels */
708 { 5210, 5250, 5290 };
709 static const uint16_t rcl6[] =		/* 2 static turbo channels */
710 { 5760, 5800 };
711 static const uint16_t rcl6x[] =	/* 4 FCC3 turbo channels */
712 { 5540, 5580, 5620, 5660 };
713 static const uint16_t rcl12[] =	/* 2.4Ghz Turbo channel 6 */
714 { 2437 };
715 static const uint16_t rcl13[] =	/* dynamic Turbo channels */
716 { 5200, 5240, 5280, 5765, 5805 };
717 #endif /* ATH_TURBO_SCAN */
718 
719 #define	X(a)	.count = sizeof(a)/sizeof(a[0]), .list = a
720 
721 static const struct scanlist staScanTable[] = {
722 	{ IEEE80211_MODE_11B,   	X(rcl3) },
723 	{ IEEE80211_MODE_11A,   	X(rcl1) },
724 	{ IEEE80211_MODE_11A,   	X(rcl2) },
725 	{ IEEE80211_MODE_11B,   	X(rcl8) },
726 	{ IEEE80211_MODE_11B,   	X(rcl9) },
727 	{ IEEE80211_MODE_11A,   	X(rcl4) },
728 #ifdef ATH_TURBO_SCAN
729 	{ IEEE80211_MODE_STURBO_A,	X(rcl5) },
730 	{ IEEE80211_MODE_STURBO_A,	X(rcl6) },
731 	{ IEEE80211_MODE_TURBO_A,	X(rcl6x) },
732 	{ IEEE80211_MODE_TURBO_A,	X(rcl13) },
733 #endif /* ATH_TURBO_SCAN */
734 	{ IEEE80211_MODE_11A,		X(rcl7) },
735 	{ IEEE80211_MODE_11B,		X(rcl10) },
736 	{ IEEE80211_MODE_11A,		X(rcl11) },
737 #ifdef ATH_TURBO_SCAN
738 	{ IEEE80211_MODE_TURBO_G,	X(rcl12) },
739 #endif /* ATH_TURBO_SCAN */
740 	{ .list = NULL }
741 };
742 
743 /*
744  * Start a station-mode scan by populating the channel list.
745  */
746 static int
747 sta_start(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
748 {
749 	struct sta_table *st = ss->ss_priv;
750 
751 	makescanlist(ss, vap, staScanTable);
752 
753 	if (ss->ss_mindwell == 0)
754 		ss->ss_mindwell = msecs_to_ticks(20);	/* 20ms */
755 	if (ss->ss_maxdwell == 0)
756 		ss->ss_maxdwell = msecs_to_ticks(200);	/* 200ms */
757 
758 	st->st_scangen++;
759 	st->st_newscan = 1;
760 
761 	return 0;
762 }
763 
764 /*
765  * Restart a scan, typically a bg scan but can
766  * also be a fg scan that came up empty.
767  */
768 static int
769 sta_restart(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
770 {
771 	struct sta_table *st = ss->ss_priv;
772 
773 	st->st_newscan = 1;
774 	return 0;
775 }
776 
777 /*
778  * Cancel an ongoing scan.
779  */
780 static int
781 sta_cancel(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
782 {
783 	return 0;
784 }
785 
786 /*
787  * Demote any supplied 11g channel to 11b.  There should
788  * always be an 11b channel but we check anyway...
789  */
790 static struct ieee80211_channel *
791 demote11b(struct ieee80211vap *vap, struct ieee80211_channel *chan)
792 {
793 	struct ieee80211_channel *c;
794 
795 	if (IEEE80211_IS_CHAN_ANYG(chan) &&
796 	    vap->iv_des_mode == IEEE80211_MODE_AUTO) {
797 		c = ieee80211_find_channel(vap->iv_ic, chan->ic_freq,
798 		    (chan->ic_flags &~ (IEEE80211_CHAN_PUREG | IEEE80211_CHAN_G)) |
799 		    IEEE80211_CHAN_B);
800 		if (c != NULL)
801 			chan = c;
802 	}
803 	return chan;
804 }
805 
806 static int
807 maxrate(const struct ieee80211_scan_entry *se)
808 {
809 	const struct ieee80211_ie_htcap *htcap =
810 	    (const struct ieee80211_ie_htcap *) se->se_ies.htcap_ie;
811 	int rmax, r, i, txstream;
812 	uint16_t caps;
813 	uint8_t txparams;
814 
815 	rmax = 0;
816 	if (htcap != NULL) {
817 		/*
818 		 * HT station; inspect supported MCS and then adjust
819 		 * rate by channel width.
820 		 */
821 		txparams = htcap->hc_mcsset[12];
822 		if (txparams & 0x3) {
823 			/*
824 			 * TX MCS parameters defined and not equal to RX,
825 			 * extract the number of spartial streams and
826 			 * map it to the highest MCS rate.
827 			 */
828 			txstream = ((txparams & 0xc) >> 2) + 1;
829 			i = txstream * 8 - 1;
830 		} else
831 			for (i = 31; i >= 0 && isclr(htcap->hc_mcsset, i); i--);
832 		if (i >= 0) {
833 			caps = le16dec(&htcap->hc_cap);
834 			if ((caps & IEEE80211_HTCAP_CHWIDTH40) &&
835 			    (caps & IEEE80211_HTCAP_SHORTGI40))
836 				rmax = ieee80211_htrates[i].ht40_rate_400ns;
837 			else if (caps & IEEE80211_HTCAP_CHWIDTH40)
838 				rmax = ieee80211_htrates[i].ht40_rate_800ns;
839 			else if (caps & IEEE80211_HTCAP_SHORTGI20)
840 				rmax = ieee80211_htrates[i].ht20_rate_400ns;
841 			else
842 				rmax = ieee80211_htrates[i].ht20_rate_800ns;
843 		}
844 	}
845 	for (i = 0; i < se->se_rates[1]; i++) {
846 		r = se->se_rates[2+i] & IEEE80211_RATE_VAL;
847 		if (r > rmax)
848 			rmax = r;
849 	}
850 	for (i = 0; i < se->se_xrates[1]; i++) {
851 		r = se->se_xrates[2+i] & IEEE80211_RATE_VAL;
852 		if (r > rmax)
853 			rmax = r;
854 	}
855 	return rmax;
856 }
857 
858 /*
859  * Compare the capabilities of two entries and decide which is
860  * more desirable (return >0 if a is considered better).  Note
861  * that we assume compatibility/usability has already been checked
862  * so we don't need to (e.g. validate whether privacy is supported).
863  * Used to select the best scan candidate for association in a BSS.
864  *
865  * TODO: should we take 11n, 11ac into account when selecting the
866  * best?  Right now it just compares frequency band and RSSI.
867  */
868 static int
869 sta_compare(const struct sta_entry *a, const struct sta_entry *b)
870 {
871 #define	PREFER(_a,_b,_what) do {			\
872 	if (((_a) ^ (_b)) & (_what))			\
873 		return ((_a) & (_what)) ? 1 : -1;	\
874 } while (0)
875 	int maxa, maxb;
876 	int8_t rssia, rssib;
877 	int weight;
878 
879 	/* privacy support */
880 	PREFER(a->base.se_capinfo, b->base.se_capinfo,
881 		IEEE80211_CAPINFO_PRIVACY);
882 
883 	/* compare count of previous failures */
884 	weight = b->se_fails - a->se_fails;
885 	if (abs(weight) > 1)
886 		return weight;
887 
888 	/*
889 	 * Compare rssi.  If the two are considered equivalent
890 	 * then fallback to other criteria.  We threshold the
891 	 * comparisons to avoid selecting an ap purely by rssi
892 	 * when both values may be good but one ap is otherwise
893 	 * more desirable (e.g. an 11b-only ap with stronger
894 	 * signal than an 11g ap).
895 	 */
896 	rssia = MIN(a->base.se_rssi, STA_RSSI_MAX);
897 	rssib = MIN(b->base.se_rssi, STA_RSSI_MAX);
898 	if (abs(rssib - rssia) < 5) {
899 		/* best/max rate preferred if signal level close enough XXX */
900 		maxa = maxrate(&a->base);
901 		maxb = maxrate(&b->base);
902 		if (maxa != maxb)
903 			return maxa - maxb;
904 		/* XXX use freq for channel preference */
905 		/* for now just prefer 5Ghz band to all other bands */
906 		PREFER(IEEE80211_IS_CHAN_5GHZ(a->base.se_chan),
907 		       IEEE80211_IS_CHAN_5GHZ(b->base.se_chan), 1);
908 	}
909 	/* all things being equal, use signal level */
910 	return a->base.se_rssi - b->base.se_rssi;
911 #undef PREFER
912 }
913 
914 /*
915  * Check rate set suitability and return the best supported rate.
916  * XXX inspect MCS for HT
917  */
918 static int
919 check_rate(struct ieee80211vap *vap, const struct ieee80211_channel *chan,
920     const struct ieee80211_scan_entry *se)
921 {
922 	const struct ieee80211_rateset *srs;
923 	int i, j, nrs, r, okrate, badrate, fixedrate, ucastrate;
924 	const uint8_t *rs;
925 
926 	okrate = badrate = 0;
927 
928 	srs = ieee80211_get_suprates(vap->iv_ic, chan);
929 	nrs = se->se_rates[1];
930 	rs = se->se_rates+2;
931 	/* XXX MCS */
932 	ucastrate = vap->iv_txparms[ieee80211_chan2mode(chan)].ucastrate;
933 	fixedrate = IEEE80211_FIXED_RATE_NONE;
934 again:
935 	for (i = 0; i < nrs; i++) {
936 		r = IEEE80211_RV(rs[i]);
937 		badrate = r;
938 		/*
939 		 * Check any fixed rate is included.
940 		 */
941 		if (r == ucastrate)
942 			fixedrate = r;
943 		/*
944 		 * Check against our supported rates.
945 		 */
946 		for (j = 0; j < srs->rs_nrates; j++)
947 			if (r == IEEE80211_RV(srs->rs_rates[j])) {
948 				if (r > okrate)		/* NB: track max */
949 					okrate = r;
950 				break;
951 			}
952 
953 		if (j == srs->rs_nrates && (rs[i] & IEEE80211_RATE_BASIC)) {
954 			/*
955 			 * Don't try joining a BSS, if we don't support
956 			 * one of its basic rates.
957 			 */
958 			okrate = 0;
959 			goto back;
960 		}
961 	}
962 	if (rs == se->se_rates+2) {
963 		/* scan xrates too; sort of an algol68-style for loop */
964 		nrs = se->se_xrates[1];
965 		rs = se->se_xrates+2;
966 		goto again;
967 	}
968 
969 back:
970 	if (okrate == 0 || ucastrate != fixedrate)
971 		return badrate | IEEE80211_RATE_BASIC;
972 	else
973 		return IEEE80211_RV(okrate);
974 }
975 
976 static __inline int
977 match_id(const uint8_t *ie, const uint8_t *val, int len)
978 {
979 	return (ie[1] == len && memcmp(ie+2, val, len) == 0);
980 }
981 
982 static int
983 match_ssid(const uint8_t *ie,
984 	int nssid, const struct ieee80211_scan_ssid ssids[])
985 {
986 	int i;
987 
988 	for (i = 0; i < nssid; i++) {
989 		if (match_id(ie, ssids[i].ssid, ssids[i].len))
990 			return 1;
991 	}
992 	return 0;
993 }
994 
995 #ifdef IEEE80211_SUPPORT_TDMA
996 static int
997 tdma_isfull(const struct ieee80211_tdma_param *tdma)
998 {
999 	int slot, slotcnt;
1000 
1001 	slotcnt = tdma->tdma_slotcnt;
1002 	for (slot = slotcnt-1; slot >= 0; slot--)
1003 		if (isclr(tdma->tdma_inuse, slot))
1004 			return 0;
1005 	return 1;
1006 }
1007 #endif /* IEEE80211_SUPPORT_TDMA */
1008 
1009 /*
1010  * Test a scan candidate for suitability/compatibility.
1011  */
1012 static int
1013 match_bss(struct ieee80211vap *vap,
1014 	const struct ieee80211_scan_state *ss, struct sta_entry *se0,
1015 	int debug)
1016 {
1017 	struct ieee80211com *ic = vap->iv_ic;
1018 	struct ieee80211_scan_entry *se = &se0->base;
1019         uint8_t rate;
1020         int fail;
1021 
1022 	fail = 0;
1023 	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, se->se_chan)))
1024 		fail |= MATCH_CHANNEL;
1025 	/*
1026 	 * NB: normally the desired mode is used to construct
1027 	 * the channel list, but it's possible for the scan
1028 	 * cache to include entries for stations outside this
1029 	 * list so we check the desired mode here to weed them
1030 	 * out.
1031 	 */
1032 	if (vap->iv_des_mode != IEEE80211_MODE_AUTO &&
1033 	    (se->se_chan->ic_flags & IEEE80211_CHAN_ALLTURBO) !=
1034 	    chanflags[vap->iv_des_mode])
1035 		fail |= MATCH_CHANNEL;
1036 	if (vap->iv_opmode == IEEE80211_M_IBSS) {
1037 		if ((se->se_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
1038 			fail |= MATCH_CAPINFO;
1039 #ifdef IEEE80211_SUPPORT_TDMA
1040 	} else if (vap->iv_opmode == IEEE80211_M_AHDEMO) {
1041 		/*
1042 		 * Adhoc demo network setup shouldn't really be scanning
1043 		 * but just in case skip stations operating in IBSS or
1044 		 * BSS mode.
1045 		 */
1046 		if (se->se_capinfo & (IEEE80211_CAPINFO_IBSS|IEEE80211_CAPINFO_ESS))
1047 			fail |= MATCH_CAPINFO;
1048 		/*
1049 		 * TDMA operation cannot coexist with a normal 802.11 network;
1050 		 * skip if IBSS or ESS capabilities are marked and require
1051 		 * the beacon have a TDMA ie present.
1052 		 */
1053 		if (vap->iv_caps & IEEE80211_C_TDMA) {
1054 			const struct ieee80211_tdma_param *tdma =
1055 			    (const struct ieee80211_tdma_param *)se->se_ies.tdma_ie;
1056 			const struct ieee80211_tdma_state *ts = vap->iv_tdma;
1057 
1058 			if (tdma == NULL)
1059 				fail |= MATCH_TDMA_NOIE;
1060 			else if (tdma->tdma_version != ts->tdma_version)
1061 				fail |= MATCH_TDMA_VERSION;
1062 			else if (tdma->tdma_slot != 0)
1063 				fail |= MATCH_TDMA_NOTMASTER;
1064 			else if (tdma_isfull(tdma))
1065 				fail |= MATCH_TDMA_NOSLOT;
1066 #if 0
1067 			else if (ieee80211_local_address(se->se_macaddr))
1068 				fail |= MATCH_TDMA_LOCAL;
1069 #endif
1070 		}
1071 #endif /* IEEE80211_SUPPORT_TDMA */
1072 #ifdef IEEE80211_SUPPORT_MESH
1073 	} else if (vap->iv_opmode == IEEE80211_M_MBSS) {
1074 		const struct ieee80211_mesh_state *ms = vap->iv_mesh;
1075 		/*
1076 		 * Mesh nodes have IBSS & ESS bits in capinfo turned off
1077 		 * and two special ie's that must be present.
1078 		 */
1079 		if (se->se_capinfo & (IEEE80211_CAPINFO_IBSS|IEEE80211_CAPINFO_ESS))
1080 			fail |= MATCH_CAPINFO;
1081 		else if (se->se_meshid[0] != IEEE80211_ELEMID_MESHID)
1082 			fail |= MATCH_MESH_NOID;
1083 		else if (ms->ms_idlen != 0 &&
1084 		    match_id(se->se_meshid, ms->ms_id, ms->ms_idlen))
1085 			fail |= MATCH_MESHID;
1086 #endif
1087 	} else {
1088 		if ((se->se_capinfo & IEEE80211_CAPINFO_ESS) == 0)
1089 			fail |= MATCH_CAPINFO;
1090 		/*
1091 		 * If 11d is enabled and we're attempting to join a bss
1092 		 * that advertises it's country code then compare our
1093 		 * current settings to what we fetched from the country ie.
1094 		 * If our country code is unspecified or different then do
1095 		 * not attempt to join the bss.  We should have already
1096 		 * dispatched an event to user space that identifies the
1097 		 * new country code so our regdomain config should match.
1098 		 */
1099 		if ((IEEE80211_IS_CHAN_11D(se->se_chan) ||
1100 		    (vap->iv_flags_ext & IEEE80211_FEXT_DOTD)) &&
1101 		    se->se_cc[0] != 0 &&
1102 		    (ic->ic_regdomain.country == CTRY_DEFAULT ||
1103 		     !isocmp(se->se_cc, ic->ic_regdomain.isocc)))
1104 			fail |= MATCH_CC;
1105 	}
1106 	if (vap->iv_flags & IEEE80211_F_PRIVACY) {
1107 		if ((se->se_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
1108 			fail |= MATCH_PRIVACY;
1109 	} else {
1110 		/* XXX does this mean privacy is supported or required? */
1111 		if (se->se_capinfo & IEEE80211_CAPINFO_PRIVACY)
1112 			fail |= MATCH_PRIVACY;
1113 	}
1114 	se0->se_flags &= ~STA_DEMOTE11B;
1115 	rate = check_rate(vap, se->se_chan, se);
1116 	if (rate & IEEE80211_RATE_BASIC) {
1117 		fail |= MATCH_RATE;
1118 		/*
1119 		 * An 11b-only ap will give a rate mismatch if there is an
1120 		 * OFDM fixed tx rate for 11g.  Try downgrading the channel
1121 		 * in the scan list to 11b and retry the rate check.
1122 		 */
1123 		if (IEEE80211_IS_CHAN_ANYG(se->se_chan)) {
1124 			rate = check_rate(vap, demote11b(vap, se->se_chan), se);
1125 			if ((rate & IEEE80211_RATE_BASIC) == 0) {
1126 				fail &= ~MATCH_RATE;
1127 				se0->se_flags |= STA_DEMOTE11B;
1128 			}
1129 		}
1130 	} else if (rate < 2*24) {
1131 		/*
1132 		 * This is an 11b-only ap.  Check the desired mode in
1133 		 * case that needs to be honored (mode 11g filters out
1134 		 * 11b-only ap's).  Otherwise force any 11g channel used
1135 		 * in scanning to be demoted.
1136 		 *
1137 		 * NB: we cheat a bit here by looking at the max rate;
1138 		 *     we could/should check the rates.
1139 		 */
1140 		if (!(vap->iv_des_mode == IEEE80211_MODE_AUTO ||
1141 		      vap->iv_des_mode == IEEE80211_MODE_11B))
1142 			fail |= MATCH_RATE;
1143 		else
1144 			se0->se_flags |= STA_DEMOTE11B;
1145 	}
1146 	if (ss->ss_nssid != 0 &&
1147 	    !match_ssid(se->se_ssid, ss->ss_nssid, ss->ss_ssid))
1148 		fail |= MATCH_SSID;
1149 	if ((vap->iv_flags & IEEE80211_F_DESBSSID) &&
1150 	    !IEEE80211_ADDR_EQ(vap->iv_des_bssid, se->se_bssid))
1151 		fail |= MATCH_BSSID;
1152 	if (se0->se_fails >= STA_FAILS_MAX)
1153 		fail |= MATCH_FAILS;
1154 	if (se0->se_notseen >= STA_PURGE_SCANS)
1155 		fail |= MATCH_NOTSEEN;
1156 	if (se->se_rssi < STA_RSSI_MIN)
1157 		fail |= MATCH_RSSI;
1158 #ifdef IEEE80211_DEBUG
1159 	if (ieee80211_msg(vap, debug)) {
1160 		printf(" %c %s",
1161 		    fail & MATCH_FAILS ? '=' :
1162 		    fail & MATCH_NOTSEEN ? '^' :
1163 		    fail & MATCH_CC ? '$' :
1164 #ifdef IEEE80211_SUPPORT_TDMA
1165 		    fail & MATCH_TDMA_NOIE ? '&' :
1166 		    fail & MATCH_TDMA_VERSION ? 'v' :
1167 		    fail & MATCH_TDMA_NOTMASTER ? 's' :
1168 		    fail & MATCH_TDMA_NOSLOT ? 'f' :
1169 		    fail & MATCH_TDMA_LOCAL ? 'l' :
1170 #endif
1171 		    fail & MATCH_MESH_NOID ? 'm' :
1172 		    fail ? '-' : '+', ether_sprintf(se->se_macaddr));
1173 		printf(" %s%c", ether_sprintf(se->se_bssid),
1174 		    fail & MATCH_BSSID ? '!' : ' ');
1175 		printf(" %3d%c", ieee80211_chan2ieee(ic, se->se_chan),
1176 			fail & MATCH_CHANNEL ? '!' : ' ');
1177 		printf(" %+4d%c", se->se_rssi, fail & MATCH_RSSI ? '!' : ' ');
1178 		printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
1179 		    fail & MATCH_RATE ? '!' : ' ');
1180 		printf(" %4s%c",
1181 		    (se->se_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
1182 		    (se->se_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" : "",
1183 		    fail & MATCH_CAPINFO ? '!' : ' ');
1184 		printf(" %3s%c ",
1185 		    (se->se_capinfo & IEEE80211_CAPINFO_PRIVACY) ?
1186 		    "wep" : "no",
1187 		    fail & MATCH_PRIVACY ? '!' : ' ');
1188 		ieee80211_print_essid(se->se_ssid+2, se->se_ssid[1]);
1189 		printf("%s\n", fail & (MATCH_SSID | MATCH_MESHID) ? "!" : "");
1190 	}
1191 #endif
1192 	return fail;
1193 }
1194 
1195 static void
1196 sta_update_notseen(struct sta_table *st)
1197 {
1198 	struct sta_entry *se;
1199 
1200 	IEEE80211_SCAN_TABLE_LOCK(st);
1201 	TAILQ_FOREACH(se, &st->st_entry, se_list) {
1202 		/*
1203 		 * If seen the reset and don't bump the count;
1204 		 * otherwise bump the ``not seen'' count.  Note
1205 		 * that this insures that stations for which we
1206 		 * see frames while not scanning but not during
1207 		 * this scan will not be penalized.
1208 		 */
1209 		if (se->se_seen)
1210 			se->se_seen = 0;
1211 		else
1212 			se->se_notseen++;
1213 	}
1214 	IEEE80211_SCAN_TABLE_UNLOCK(st);
1215 }
1216 
1217 static void
1218 sta_dec_fails(struct sta_table *st)
1219 {
1220 	struct sta_entry *se;
1221 
1222 	IEEE80211_SCAN_TABLE_LOCK(st);
1223 	TAILQ_FOREACH(se, &st->st_entry, se_list)
1224 		if (se->se_fails)
1225 			se->se_fails--;
1226 	IEEE80211_SCAN_TABLE_UNLOCK(st);
1227 }
1228 
1229 static struct sta_entry *
1230 select_bss(struct ieee80211_scan_state *ss, struct ieee80211vap *vap, int debug)
1231 {
1232 	struct sta_table *st = ss->ss_priv;
1233 	struct sta_entry *se, *selbs = NULL;
1234 
1235 	IEEE80211_DPRINTF(vap, debug, " %s\n",
1236 	    "macaddr          bssid         chan  rssi  rate flag  wep  essid");
1237 	IEEE80211_SCAN_TABLE_LOCK(st);
1238 	TAILQ_FOREACH(se, &st->st_entry, se_list) {
1239 		ieee80211_ies_expand(&se->base.se_ies);
1240 		if (match_bss(vap, ss, se, debug) == 0) {
1241 			if (selbs == NULL)
1242 				selbs = se;
1243 			else if (sta_compare(se, selbs) > 0)
1244 				selbs = se;
1245 		}
1246 	}
1247 	IEEE80211_SCAN_TABLE_UNLOCK(st);
1248 
1249 	return selbs;
1250 }
1251 
1252 /*
1253  * Pick an ap or ibss network to join or find a channel
1254  * to use to start an ibss network.
1255  */
1256 static int
1257 sta_pick_bss(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1258 {
1259 	struct sta_table *st = ss->ss_priv;
1260 	struct sta_entry *selbs;
1261 	struct ieee80211_channel *chan;
1262 
1263 	KASSERT(vap->iv_opmode == IEEE80211_M_STA,
1264 		("wrong mode %u", vap->iv_opmode));
1265 
1266 	if (st->st_newscan) {
1267 		sta_update_notseen(st);
1268 		st->st_newscan = 0;
1269 	}
1270 	if (ss->ss_flags & IEEE80211_SCAN_NOPICK) {
1271 		/*
1272 		 * Manual/background scan, don't select+join the
1273 		 * bss, just return.  The scanning framework will
1274 		 * handle notification that this has completed.
1275 		 */
1276 		ss->ss_flags &= ~IEEE80211_SCAN_NOPICK;
1277 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
1278 		    "%s: nopick; return 1\n", __func__);
1279 		return 1;
1280 	}
1281 	/*
1282 	 * Automatic sequencing; look for a candidate and
1283 	 * if found join the network.
1284 	 */
1285 	/* NB: unlocked read should be ok */
1286 	if (TAILQ_FIRST(&st->st_entry) == NULL) {
1287 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
1288 			"%s: no scan candidate, join=%d, return 0\n",
1289 			__func__,
1290 			!! (ss->ss_flags & IEEE80211_SCAN_NOJOIN));
1291 		if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1292 			return 0;
1293 notfound:
1294 		/*
1295 		 * If nothing suitable was found decrement
1296 		 * the failure counts so entries will be
1297 		 * reconsidered the next time around.  We
1298 		 * really want to do this only for sta's
1299 		 * where we've previously had some success.
1300 		 */
1301 		sta_dec_fails(st);
1302 		st->st_newscan = 1;
1303 		return 0;			/* restart scan */
1304 	}
1305 	selbs = select_bss(ss, vap, IEEE80211_MSG_SCAN);
1306 	if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1307 		return (selbs != NULL);
1308 	if (selbs == NULL)
1309 		goto notfound;
1310 	chan = selbs->base.se_chan;
1311 	if (selbs->se_flags & STA_DEMOTE11B)
1312 		chan = demote11b(vap, chan);
1313 	if (!ieee80211_sta_join(vap, chan, &selbs->base))
1314 		goto notfound;
1315 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
1316 	    "%s: terminate scan; return 1\n", __func__);
1317 	return 1;				/* terminate scan */
1318 }
1319 
1320 /*
1321  * Lookup an entry in the scan cache.  We assume we're
1322  * called from the bottom half or such that we don't need
1323  * to block the bottom half so that it's safe to return
1324  * a reference to an entry w/o holding the lock on the table.
1325  */
1326 static struct sta_entry *
1327 sta_lookup(struct sta_table *st, const uint8_t macaddr[IEEE80211_ADDR_LEN])
1328 {
1329 	struct sta_entry *se;
1330 	int hash = STA_HASH(macaddr);
1331 
1332 	IEEE80211_SCAN_TABLE_LOCK(st);
1333 	LIST_FOREACH(se, &st->st_hash[hash], se_hash)
1334 		if (IEEE80211_ADDR_EQ(se->base.se_macaddr, macaddr))
1335 			break;
1336 	IEEE80211_SCAN_TABLE_UNLOCK(st);
1337 
1338 	return se;		/* NB: unlocked */
1339 }
1340 
1341 static void
1342 sta_roam_check(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1343 {
1344 	struct ieee80211com *ic = vap->iv_ic;
1345 	struct ieee80211_node *ni = vap->iv_bss;
1346 	struct sta_table *st = ss->ss_priv;
1347 	enum ieee80211_phymode mode;
1348 	struct sta_entry *se, *selbs;
1349 	uint8_t roamRate, curRate, ucastRate;
1350 	int8_t roamRssi, curRssi;
1351 
1352 	se = sta_lookup(st, ni->ni_macaddr);
1353 	if (se == NULL) {
1354 		/* XXX something is wrong */
1355 		return;
1356 	}
1357 
1358 	mode = ieee80211_chan2mode(ic->ic_bsschan);
1359 	roamRate = vap->iv_roamparms[mode].rate;
1360 	roamRssi = vap->iv_roamparms[mode].rssi;
1361 	KASSERT(roamRate != 0 && roamRssi != 0, ("iv_roamparms are not"
1362 	    "initialized for %s mode!", ieee80211_phymode_name[mode]));
1363 
1364 	ucastRate = vap->iv_txparms[mode].ucastrate;
1365 	/* NB: the most up to date rssi is in the node, not the scan cache */
1366 	curRssi = ic->ic_node_getrssi(ni);
1367 	if (ucastRate == IEEE80211_FIXED_RATE_NONE) {
1368 		curRate = ni->ni_txrate;
1369 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_ROAM,
1370 		    "%s: currssi %d currate %u roamrssi %d roamrate %u\n",
1371 		    __func__, curRssi, curRate, roamRssi, roamRate);
1372 	} else {
1373 		curRate = roamRate;	/* NB: insure compare below fails */
1374 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_ROAM,
1375 		    "%s: currssi %d roamrssi %d\n", __func__, curRssi, roamRssi);
1376 	}
1377 	/*
1378 	 * Check if a new ap should be used and switch.
1379 	 * XXX deauth current ap
1380 	 */
1381 	if (curRate < roamRate || curRssi < roamRssi) {
1382 		if (ieee80211_time_after(ticks, ic->ic_lastscan + vap->iv_scanvalid)) {
1383 			/*
1384 			 * Scan cache contents are too old; force a scan now
1385 			 * if possible so we have current state to make a
1386 			 * decision with.  We don't kick off a bg scan if
1387 			 * we're using dynamic turbo and boosted or if the
1388 			 * channel is busy.
1389 			 * XXX force immediate switch on scan complete
1390 			 */
1391 			if (!IEEE80211_IS_CHAN_DTURBO(ic->ic_curchan) &&
1392 			    ((vap->iv_flags_ext & IEEE80211_FEXT_SCAN_OFFLOAD) ||
1393 			     ieee80211_time_after(ticks, ic->ic_lastdata + vap->iv_bgscanidle)))
1394 				ieee80211_bg_scan(vap, 0);
1395 			return;
1396 		}
1397 		se->base.se_rssi = curRssi;
1398 		selbs = select_bss(ss, vap, IEEE80211_MSG_ROAM);
1399 		if (selbs != NULL && selbs != se) {
1400 			struct ieee80211_channel *chan;
1401 
1402 			IEEE80211_DPRINTF(vap,
1403 			    IEEE80211_MSG_ROAM | IEEE80211_MSG_DEBUG,
1404 			    "%s: ROAM: curRate %u, roamRate %u, "
1405 			    "curRssi %d, roamRssi %d\n", __func__,
1406 			    curRate, roamRate, curRssi, roamRssi);
1407 
1408 			chan = selbs->base.se_chan;
1409 			if (selbs->se_flags & STA_DEMOTE11B)
1410 				chan = demote11b(vap, chan);
1411 			(void) ieee80211_sta_join(vap, chan, &selbs->base);
1412 		}
1413 	}
1414 }
1415 
1416 /*
1417  * Age entries in the scan cache.
1418  * XXX also do roaming since it's convenient
1419  */
1420 static void
1421 sta_age(struct ieee80211_scan_state *ss)
1422 {
1423 	struct ieee80211vap *vap = ss->ss_vap;
1424 
1425 	adhoc_age(ss);
1426 	/*
1427 	 * If rate control is enabled check periodically to see if
1428 	 * we should roam from our current connection to one that
1429 	 * might be better.  This only applies when we're operating
1430 	 * in sta mode and automatic roaming is set.
1431 	 * XXX defer if busy
1432 	 * XXX repeater station
1433 	 * XXX do when !bgscan?
1434 	 */
1435 	KASSERT(vap->iv_opmode == IEEE80211_M_STA,
1436 		("wrong mode %u", vap->iv_opmode));
1437 	if (vap->iv_roaming == IEEE80211_ROAMING_AUTO &&
1438 	    (vap->iv_flags & IEEE80211_F_BGSCAN) &&
1439 	    vap->iv_state >= IEEE80211_S_RUN)
1440 		/* XXX vap is implicit */
1441 		sta_roam_check(ss, vap);
1442 }
1443 
1444 /*
1445  * Iterate over the entries in the scan cache, invoking
1446  * the callback function on each one.
1447  */
1448 static void
1449 sta_iterate(struct ieee80211_scan_state *ss,
1450 	ieee80211_scan_iter_func *f, void *arg)
1451 {
1452 	struct sta_table *st = ss->ss_priv;
1453 	struct sta_entry *se;
1454 	u_int gen;
1455 
1456 	IEEE80211_SCAN_ITER_LOCK(st);
1457 	gen = st->st_scaniter++;
1458 restart:
1459 	IEEE80211_SCAN_TABLE_LOCK(st);
1460 	TAILQ_FOREACH(se, &st->st_entry, se_list) {
1461 		if (se->se_scangen != gen) {
1462 			se->se_scangen = gen;
1463 			/* update public state */
1464 			se->base.se_age = ticks - se->se_lastupdate;
1465 			IEEE80211_SCAN_TABLE_UNLOCK(st);
1466 			(*f)(arg, &se->base);
1467 			goto restart;
1468 		}
1469 	}
1470 	IEEE80211_SCAN_TABLE_UNLOCK(st);
1471 
1472 	IEEE80211_SCAN_ITER_UNLOCK(st);
1473 }
1474 
1475 static void
1476 sta_assoc_fail(struct ieee80211_scan_state *ss,
1477 	const uint8_t macaddr[IEEE80211_ADDR_LEN], int reason)
1478 {
1479 	struct sta_table *st = ss->ss_priv;
1480 	struct sta_entry *se;
1481 
1482 	se = sta_lookup(st, macaddr);
1483 	if (se != NULL) {
1484 		se->se_fails++;
1485 		se->se_lastfail = ticks;
1486 		IEEE80211_NOTE_MAC(ss->ss_vap, IEEE80211_MSG_SCAN,
1487 		    macaddr, "%s: reason %u fails %u",
1488 		    __func__, reason, se->se_fails);
1489 	}
1490 }
1491 
1492 static void
1493 sta_assoc_success(struct ieee80211_scan_state *ss,
1494 	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1495 {
1496 	struct sta_table *st = ss->ss_priv;
1497 	struct sta_entry *se;
1498 
1499 	se = sta_lookup(st, macaddr);
1500 	if (se != NULL) {
1501 #if 0
1502 		se->se_fails = 0;
1503 		IEEE80211_NOTE_MAC(ss->ss_vap, IEEE80211_MSG_SCAN,
1504 		    macaddr, "%s: fails %u",
1505 		    __func__, se->se_fails);
1506 #endif
1507 		se->se_lastassoc = ticks;
1508 	}
1509 }
1510 
1511 static const struct ieee80211_scanner sta_default = {
1512 	.scan_name		= "default",
1513 	.scan_attach		= sta_attach,
1514 	.scan_detach		= sta_detach,
1515 	.scan_start		= sta_start,
1516 	.scan_restart		= sta_restart,
1517 	.scan_cancel		= sta_cancel,
1518 	.scan_end		= sta_pick_bss,
1519 	.scan_flush		= sta_flush,
1520 	.scan_add		= sta_add,
1521 	.scan_age		= sta_age,
1522 	.scan_iterate		= sta_iterate,
1523 	.scan_assoc_fail	= sta_assoc_fail,
1524 	.scan_assoc_success	= sta_assoc_success,
1525 };
1526 IEEE80211_SCANNER_ALG(sta, IEEE80211_M_STA, sta_default);
1527 
1528 /*
1529  * Adhoc mode-specific support.
1530  */
1531 
1532 static const uint16_t adhocWorld[] =		/* 36, 40, 44, 48 */
1533 { 5180, 5200, 5220, 5240 };
1534 static const uint16_t adhocFcc3[] =		/* 36, 40, 44, 48 145, 149, 153, 157, 161, 165 */
1535 { 5180, 5200, 5220, 5240, 5725, 5745, 5765, 5785, 5805, 5825 };
1536 static const uint16_t adhocMkk[] =		/* 34, 38, 42, 46 */
1537 { 5170, 5190, 5210, 5230 };
1538 static const uint16_t adhoc11b[] =		/* 10, 11 */
1539 { 2457, 2462 };
1540 
1541 static const struct scanlist adhocScanTable[] = {
1542 	{ IEEE80211_MODE_11B,   	X(adhoc11b) },
1543 	{ IEEE80211_MODE_11A,   	X(adhocWorld) },
1544 	{ IEEE80211_MODE_11A,   	X(adhocFcc3) },
1545 	{ IEEE80211_MODE_11B,   	X(adhocMkk) },
1546 	{ .list = NULL }
1547 };
1548 #undef X
1549 
1550 /*
1551  * Start an adhoc-mode scan by populating the channel list.
1552  */
1553 static int
1554 adhoc_start(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1555 {
1556 	struct sta_table *st = ss->ss_priv;
1557 
1558 	makescanlist(ss, vap, adhocScanTable);
1559 
1560 	if (ss->ss_mindwell == 0)
1561 		ss->ss_mindwell = msecs_to_ticks(200);	/* 200ms */
1562 	if (ss->ss_maxdwell == 0)
1563 		ss->ss_maxdwell = msecs_to_ticks(200);	/* 200ms */
1564 
1565 	st->st_scangen++;
1566 	st->st_newscan = 1;
1567 
1568 	return 0;
1569 }
1570 
1571 /*
1572  * Select a channel to start an adhoc network on.
1573  * The channel list was populated with appropriate
1574  * channels so select one that looks least occupied.
1575  */
1576 static struct ieee80211_channel *
1577 adhoc_pick_channel(struct ieee80211_scan_state *ss, int flags)
1578 {
1579 	struct sta_table *st = ss->ss_priv;
1580 	struct sta_entry *se;
1581 	struct ieee80211_channel *c, *bestchan;
1582 	int i, bestrssi, maxrssi;
1583 
1584 	bestchan = NULL;
1585 	bestrssi = -1;
1586 
1587 	IEEE80211_SCAN_TABLE_LOCK(st);
1588 	for (i = 0; i < ss->ss_last; i++) {
1589 		c = ss->ss_chans[i];
1590 		/* never consider a channel with radar */
1591 		if (IEEE80211_IS_CHAN_RADAR(c))
1592 			continue;
1593 		/* skip channels disallowed by regulatory settings */
1594 		if (IEEE80211_IS_CHAN_NOADHOC(c))
1595 			continue;
1596 		/* check channel attributes for band compatibility */
1597 		if (flags != 0 && (c->ic_flags & flags) != flags)
1598 			continue;
1599 		maxrssi = 0;
1600 		TAILQ_FOREACH(se, &st->st_entry, se_list) {
1601 			if (se->base.se_chan != c)
1602 				continue;
1603 			if (se->base.se_rssi > maxrssi)
1604 				maxrssi = se->base.se_rssi;
1605 		}
1606 		if (bestchan == NULL || maxrssi < bestrssi)
1607 			bestchan = c;
1608 	}
1609 	IEEE80211_SCAN_TABLE_UNLOCK(st);
1610 
1611 	return bestchan;
1612 }
1613 
1614 /*
1615  * Pick an ibss network to join or find a channel
1616  * to use to start an ibss network.
1617  */
1618 static int
1619 adhoc_pick_bss(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1620 {
1621 	struct sta_table *st = ss->ss_priv;
1622 	struct sta_entry *selbs;
1623 	struct ieee80211_channel *chan;
1624 	struct ieee80211com *ic = vap->iv_ic;
1625 
1626 	KASSERT(vap->iv_opmode == IEEE80211_M_IBSS ||
1627 		vap->iv_opmode == IEEE80211_M_AHDEMO ||
1628 		vap->iv_opmode == IEEE80211_M_MBSS,
1629 		("wrong opmode %u", vap->iv_opmode));
1630 
1631 	if (st->st_newscan) {
1632 		sta_update_notseen(st);
1633 		st->st_newscan = 0;
1634 	}
1635 	if (ss->ss_flags & IEEE80211_SCAN_NOPICK) {
1636 		/*
1637 		 * Manual/background scan, don't select+join the
1638 		 * bss, just return.  The scanning framework will
1639 		 * handle notification that this has completed.
1640 		 */
1641 		ss->ss_flags &= ~IEEE80211_SCAN_NOPICK;
1642 		return 1;
1643 	}
1644 	/*
1645 	 * Automatic sequencing; look for a candidate and
1646 	 * if found join the network.
1647 	 */
1648 	/* NB: unlocked read should be ok */
1649 	if (TAILQ_FIRST(&st->st_entry) == NULL) {
1650 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
1651 			"%s: no scan candidate\n", __func__);
1652 		if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1653 			return 0;
1654 notfound:
1655 		/* NB: never auto-start a tdma network for slot !0 */
1656 #ifdef IEEE80211_SUPPORT_TDMA
1657 		if (vap->iv_des_nssid &&
1658 		    ((vap->iv_caps & IEEE80211_C_TDMA) == 0 ||
1659 		     ieee80211_tdma_getslot(vap) == 0)) {
1660 #else
1661 		if (vap->iv_des_nssid) {
1662 #endif
1663 			/*
1664 			 * No existing adhoc network to join and we have
1665 			 * an ssid; start one up.  If no channel was
1666 			 * specified, try to select a channel.
1667 			 */
1668 			if (vap->iv_des_chan == IEEE80211_CHAN_ANYC ||
1669 			    IEEE80211_IS_CHAN_RADAR(vap->iv_des_chan)) {
1670 				chan = adhoc_pick_channel(ss, 0);
1671 			} else
1672 				chan = vap->iv_des_chan;
1673 			if (chan != NULL) {
1674 				/*
1675 				 * Create a HT capable IBSS; the per-node
1676 				 * probe request/response will result in
1677 				 * "correct" rate control capabilities being
1678 				 * negotiated.
1679 				 */
1680 				chan = ieee80211_ht_adjust_channel(ic,
1681 				    chan, vap->iv_flags_ht);
1682 				chan = ieee80211_vht_adjust_channel(ic,
1683 				    chan, vap->iv_vht_flags);
1684 				ieee80211_create_ibss(vap, chan);
1685 				return 1;
1686 			}
1687 		}
1688 		/*
1689 		 * If nothing suitable was found decrement
1690 		 * the failure counts so entries will be
1691 		 * reconsidered the next time around.  We
1692 		 * really want to do this only for sta's
1693 		 * where we've previously had some success.
1694 		 */
1695 		sta_dec_fails(st);
1696 		st->st_newscan = 1;
1697 		return 0;			/* restart scan */
1698 	}
1699 	selbs = select_bss(ss, vap, IEEE80211_MSG_SCAN);
1700 	if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1701 		return (selbs != NULL);
1702 	if (selbs == NULL)
1703 		goto notfound;
1704 	chan = selbs->base.se_chan;
1705 	if (selbs->se_flags & STA_DEMOTE11B)
1706 		chan = demote11b(vap, chan);
1707 	/*
1708 	 * If HT is available, make it a possibility here.
1709 	 * The intent is to enable HT20/HT40 when joining a non-HT
1710 	 * IBSS node; we can then advertise HT IEs and speak HT
1711 	 * to any subsequent nodes that support it.
1712 	 */
1713 	chan = ieee80211_ht_adjust_channel(ic,
1714 	    chan, vap->iv_flags_ht);
1715 	chan = ieee80211_vht_adjust_channel(ic,
1716 	    chan, vap->iv_vht_flags);
1717 	if (!ieee80211_sta_join(vap, chan, &selbs->base))
1718 		goto notfound;
1719 	return 1;				/* terminate scan */
1720 }
1721 
1722 /*
1723  * Age entries in the scan cache.
1724  */
1725 static void
1726 adhoc_age(struct ieee80211_scan_state *ss)
1727 {
1728 	struct sta_table *st = ss->ss_priv;
1729 	struct sta_entry *se, *next;
1730 
1731 	IEEE80211_SCAN_TABLE_LOCK(st);
1732 	TAILQ_FOREACH_SAFE(se, &st->st_entry, se_list, next) {
1733 		if (se->se_notseen > STA_PURGE_SCANS) {
1734 			TAILQ_REMOVE(&st->st_entry, se, se_list);
1735 			LIST_REMOVE(se, se_hash);
1736 			ieee80211_ies_cleanup(&se->base.se_ies);
1737 			IEEE80211_FREE(se, M_80211_SCAN);
1738 		}
1739 	}
1740 	IEEE80211_SCAN_TABLE_UNLOCK(st);
1741 }
1742 
1743 static const struct ieee80211_scanner adhoc_default = {
1744 	.scan_name		= "default",
1745 	.scan_attach		= sta_attach,
1746 	.scan_detach		= sta_detach,
1747 	.scan_start		= adhoc_start,
1748 	.scan_restart		= sta_restart,
1749 	.scan_cancel		= sta_cancel,
1750 	.scan_end		= adhoc_pick_bss,
1751 	.scan_flush		= sta_flush,
1752 	.scan_pickchan		= adhoc_pick_channel,
1753 	.scan_add		= sta_add,
1754 	.scan_age		= adhoc_age,
1755 	.scan_iterate		= sta_iterate,
1756 	.scan_assoc_fail	= sta_assoc_fail,
1757 	.scan_assoc_success	= sta_assoc_success,
1758 };
1759 IEEE80211_SCANNER_ALG(ibss, IEEE80211_M_IBSS, adhoc_default);
1760 IEEE80211_SCANNER_ALG(ahdemo, IEEE80211_M_AHDEMO, adhoc_default);
1761 
1762 static int
1763 ap_start(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1764 {
1765 	struct sta_table *st = ss->ss_priv;
1766 
1767 	makescanlist(ss, vap, staScanTable);
1768 
1769 	if (ss->ss_mindwell == 0)
1770 		ss->ss_mindwell = msecs_to_ticks(200);	/* 200ms */
1771 	if (ss->ss_maxdwell == 0)
1772 		ss->ss_maxdwell = msecs_to_ticks(200);	/* 200ms */
1773 
1774 	st->st_scangen++;
1775 	st->st_newscan = 1;
1776 
1777 	return 0;
1778 }
1779 
1780 /*
1781  * Cancel an ongoing scan.
1782  */
1783 static int
1784 ap_cancel(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1785 {
1786 	return 0;
1787 }
1788 
1789 /*
1790  * Pick a quiet channel to use for ap operation.
1791  */
1792 static struct ieee80211_channel *
1793 ap_pick_channel(struct ieee80211_scan_state *ss, int flags)
1794 {
1795 	struct sta_table *st = ss->ss_priv;
1796 	struct ieee80211_channel *bestchan = NULL;
1797 	int i;
1798 
1799 	/* XXX select channel more intelligently, e.g. channel spread, power */
1800 	/* NB: use scan list order to preserve channel preference */
1801 	for (i = 0; i < ss->ss_last; i++) {
1802 		struct ieee80211_channel *chan = ss->ss_chans[i];
1803 		/*
1804 		 * If the channel is unoccupied the max rssi
1805 		 * should be zero; just take it.  Otherwise
1806 		 * track the channel with the lowest rssi and
1807 		 * use that when all channels appear occupied.
1808 		 */
1809 		if (IEEE80211_IS_CHAN_RADAR(chan))
1810 			continue;
1811 		if (IEEE80211_IS_CHAN_NOHOSTAP(chan))
1812 			continue;
1813 		/* check channel attributes for band compatibility */
1814 		if (flags != 0 && (chan->ic_flags & flags) != flags)
1815 			continue;
1816 		KASSERT(sizeof(chan->ic_ieee) == 1, ("ic_chan size"));
1817 		/* XXX channel have interference */
1818 		if (st->st_maxrssi[chan->ic_ieee] == 0) {
1819 			/* XXX use other considerations */
1820 			return chan;
1821 		}
1822 		if (bestchan == NULL ||
1823 		    st->st_maxrssi[chan->ic_ieee] < st->st_maxrssi[bestchan->ic_ieee])
1824 			bestchan = chan;
1825 	}
1826 	return bestchan;
1827 }
1828 
1829 /*
1830  * Pick a quiet channel to use for ap operation.
1831  */
1832 static int
1833 ap_end(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1834 {
1835 	struct ieee80211com *ic = vap->iv_ic;
1836 	struct ieee80211_channel *bestchan, *chan;
1837 
1838 	KASSERT(vap->iv_opmode == IEEE80211_M_HOSTAP,
1839 		("wrong opmode %u", vap->iv_opmode));
1840 	bestchan = ap_pick_channel(ss, 0);
1841 	if (bestchan == NULL) {
1842 		/* no suitable channel, should not happen */
1843 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
1844 		    "%s: no suitable channel! (should not happen)\n", __func__);
1845 		/* XXX print something? */
1846 		return 0;			/* restart scan */
1847 	}
1848 	/*
1849 	 * If this is a dynamic turbo channel, start with the unboosted one.
1850 	 */
1851 	if (IEEE80211_IS_CHAN_TURBO(bestchan)) {
1852 		bestchan = ieee80211_find_channel(ic, bestchan->ic_freq,
1853 			bestchan->ic_flags & ~IEEE80211_CHAN_TURBO);
1854 		if (bestchan == NULL) {
1855 			/* should never happen ?? */
1856 			return 0;
1857 		}
1858 	}
1859 	if (ss->ss_flags & (IEEE80211_SCAN_NOPICK | IEEE80211_SCAN_NOJOIN)) {
1860 		/*
1861 		 * Manual/background scan, don't select+join the
1862 		 * bss, just return.  The scanning framework will
1863 		 * handle notification that this has completed.
1864 		 */
1865 		ss->ss_flags &= ~IEEE80211_SCAN_NOPICK;
1866 		return 1;
1867 	}
1868 	chan = ieee80211_ht_adjust_channel(ic, bestchan, vap->iv_flags_ht);
1869 	chan = ieee80211_vht_adjust_channel(ic, chan, vap->iv_vht_flags);
1870 	ieee80211_create_ibss(vap, chan);
1871 
1872 	return 1;
1873 }
1874 
1875 static const struct ieee80211_scanner ap_default = {
1876 	.scan_name		= "default",
1877 	.scan_attach		= sta_attach,
1878 	.scan_detach		= sta_detach,
1879 	.scan_start		= ap_start,
1880 	.scan_restart		= sta_restart,
1881 	.scan_cancel		= ap_cancel,
1882 	.scan_end		= ap_end,
1883 	.scan_flush		= sta_flush,
1884 	.scan_pickchan		= ap_pick_channel,
1885 	.scan_add		= sta_add,
1886 	.scan_age		= adhoc_age,
1887 	.scan_iterate		= sta_iterate,
1888 	.scan_assoc_success	= sta_assoc_success,
1889 	.scan_assoc_fail	= sta_assoc_fail,
1890 };
1891 IEEE80211_SCANNER_ALG(ap, IEEE80211_M_HOSTAP, ap_default);
1892 
1893 #ifdef IEEE80211_SUPPORT_MESH
1894 /*
1895  * Pick an mbss network to join or find a channel
1896  * to use to start an mbss network.
1897  */
1898 static int
1899 mesh_pick_bss(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1900 {
1901 	struct sta_table *st = ss->ss_priv;
1902 	struct ieee80211_mesh_state *ms = vap->iv_mesh;
1903 	struct sta_entry *selbs;
1904 	struct ieee80211_channel *chan;
1905 
1906 	KASSERT(vap->iv_opmode == IEEE80211_M_MBSS,
1907 		("wrong opmode %u", vap->iv_opmode));
1908 
1909 	if (st->st_newscan) {
1910 		sta_update_notseen(st);
1911 		st->st_newscan = 0;
1912 	}
1913 	if (ss->ss_flags & IEEE80211_SCAN_NOPICK) {
1914 		/*
1915 		 * Manual/background scan, don't select+join the
1916 		 * bss, just return.  The scanning framework will
1917 		 * handle notification that this has completed.
1918 		 */
1919 		ss->ss_flags &= ~IEEE80211_SCAN_NOPICK;
1920 		return 1;
1921 	}
1922 	/*
1923 	 * Automatic sequencing; look for a candidate and
1924 	 * if found join the network.
1925 	 */
1926 	/* NB: unlocked read should be ok */
1927 	if (TAILQ_FIRST(&st->st_entry) == NULL) {
1928 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
1929 			"%s: no scan candidate\n", __func__);
1930 		if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1931 			return 0;
1932 notfound:
1933 		if (ms->ms_idlen != 0) {
1934 			/*
1935 			 * No existing mbss network to join and we have
1936 			 * a meshid; start one up.  If no channel was
1937 			 * specified, try to select a channel.
1938 			 */
1939 			if (vap->iv_des_chan == IEEE80211_CHAN_ANYC ||
1940 			    IEEE80211_IS_CHAN_RADAR(vap->iv_des_chan)) {
1941 				struct ieee80211com *ic = vap->iv_ic;
1942 
1943 				/* XXX VHT */
1944 				chan = adhoc_pick_channel(ss, 0);
1945 				if (chan != NULL) {
1946 					chan = ieee80211_ht_adjust_channel(ic,
1947 					    chan, vap->iv_flags_ht);
1948 					chan = ieee80211_vht_adjust_channel(ic,
1949 					    chan, vap->iv_vht_flags);
1950 					}
1951 			} else
1952 				chan = vap->iv_des_chan;
1953 			if (chan != NULL) {
1954 				ieee80211_create_ibss(vap, chan);
1955 				return 1;
1956 			}
1957 		}
1958 		/*
1959 		 * If nothing suitable was found decrement
1960 		 * the failure counts so entries will be
1961 		 * reconsidered the next time around.  We
1962 		 * really want to do this only for sta's
1963 		 * where we've previously had some success.
1964 		 */
1965 		sta_dec_fails(st);
1966 		st->st_newscan = 1;
1967 		return 0;			/* restart scan */
1968 	}
1969 	selbs = select_bss(ss, vap, IEEE80211_MSG_SCAN);
1970 	if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1971 		return (selbs != NULL);
1972 	if (selbs == NULL)
1973 		goto notfound;
1974 	chan = selbs->base.se_chan;
1975 	if (selbs->se_flags & STA_DEMOTE11B)
1976 		chan = demote11b(vap, chan);
1977 	if (!ieee80211_sta_join(vap, chan, &selbs->base))
1978 		goto notfound;
1979 	return 1;				/* terminate scan */
1980 }
1981 
1982 static const struct ieee80211_scanner mesh_default = {
1983 	.scan_name		= "default",
1984 	.scan_attach		= sta_attach,
1985 	.scan_detach		= sta_detach,
1986 	.scan_start		= adhoc_start,
1987 	.scan_restart		= sta_restart,
1988 	.scan_cancel		= sta_cancel,
1989 	.scan_end		= mesh_pick_bss,
1990 	.scan_flush		= sta_flush,
1991 	.scan_pickchan		= adhoc_pick_channel,
1992 	.scan_add		= sta_add,
1993 	.scan_age		= adhoc_age,
1994 	.scan_iterate		= sta_iterate,
1995 	.scan_assoc_fail	= sta_assoc_fail,
1996 	.scan_assoc_success	= sta_assoc_success,
1997 };
1998 IEEE80211_SCANNER_ALG(mesh, IEEE80211_M_MBSS, mesh_default);
1999 #endif /* IEEE80211_SUPPORT_MESH */
2000