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