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