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