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