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