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