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