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