ieee80211_scan_sta.c revision 188777
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 188777 2009-02-19 04:40:47Z 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	/* check legacy */
420	[IEEE80211_MODE_11NA]	  = IEEE80211_CHAN_A,
421	[IEEE80211_MODE_11NG]	  = IEEE80211_CHAN_G,
422};
423
424static void
425add_channels(struct ieee80211vap *vap,
426	struct ieee80211_scan_state *ss,
427	enum ieee80211_phymode mode, const uint16_t freq[], int nfreq)
428{
429#define	N(a)	(sizeof(a) / sizeof(a[0]))
430	struct ieee80211com *ic = vap->iv_ic;
431	struct ieee80211_channel *c, *cg;
432	u_int modeflags;
433	int i;
434
435	KASSERT(mode < N(chanflags), ("Unexpected mode %u", mode));
436	modeflags = chanflags[mode];
437	for (i = 0; i < nfreq; i++) {
438		if (ss->ss_last >= IEEE80211_SCAN_MAX)
439			break;
440
441		c = ieee80211_find_channel(ic, freq[i], modeflags);
442		if (c == NULL || isexcluded(vap, c))
443			continue;
444		if (mode == IEEE80211_MODE_AUTO) {
445			/*
446			 * XXX special-case 11b/g channels so we select
447			 *     the g channel if both are present.
448			 */
449			if (IEEE80211_IS_CHAN_B(c) &&
450			    (cg = find11gchannel(ic, i, c->ic_freq)) != NULL)
451				c = cg;
452		}
453		ss->ss_chans[ss->ss_last++] = c;
454	}
455#undef N
456}
457
458struct scanlist {
459	uint16_t	mode;
460	uint16_t	count;
461	const uint16_t	*list;
462};
463
464static int
465checktable(const struct scanlist *scan, const struct ieee80211_channel *c)
466{
467	int i;
468
469	for (; scan->list != NULL; scan++) {
470		for (i = 0; i < scan->count; i++)
471			if (scan->list[i] == c->ic_freq)
472				return 1;
473	}
474	return 0;
475}
476
477static void
478sweepchannels(struct ieee80211_scan_state *ss, struct ieee80211vap *vap,
479	const struct scanlist table[])
480{
481	struct ieee80211com *ic = vap->iv_ic;
482	struct ieee80211_channel *c;
483	int i;
484
485	for (i = 0; i < ic->ic_nchans; i++) {
486		if (ss->ss_last >= IEEE80211_SCAN_MAX)
487			break;
488
489		c = &ic->ic_channels[i];
490		/*
491		 * Ignore dynamic turbo channels; we scan them
492		 * in normal mode (i.e. not boosted).  Likewise
493		 * for HT channels, they get scanned using
494		 * legacy rates.
495		 */
496		if (IEEE80211_IS_CHAN_DTURBO(c) || IEEE80211_IS_CHAN_HT(c))
497			continue;
498
499		/*
500		 * If a desired mode was specified, scan only
501		 * channels that satisfy that constraint.
502		 */
503		if (vap->iv_des_mode != IEEE80211_MODE_AUTO &&
504		    vap->iv_des_mode != ieee80211_chan2mode(c))
505			continue;
506
507		/*
508		 * Skip channels excluded by user request.
509		 */
510		if (isexcluded(vap, c))
511			continue;
512
513		/*
514		 * Add the channel unless it is listed in the
515		 * fixed scan order tables.  This insures we
516		 * don't sweep back in channels we filtered out
517		 * above.
518		 */
519		if (checktable(table, c))
520			continue;
521
522		/* Add channel to scanning list. */
523		ss->ss_chans[ss->ss_last++] = c;
524	}
525}
526
527static void
528makescanlist(struct ieee80211_scan_state *ss, struct ieee80211vap *vap,
529	const struct scanlist table[])
530{
531	const struct scanlist *scan;
532	enum ieee80211_phymode mode;
533
534	ss->ss_last = 0;
535	/*
536	 * Use the table of ordered channels to construct the list
537	 * of channels for scanning.  Any channels in the ordered
538	 * list not in the master list will be discarded.
539	 */
540	for (scan = table; scan->list != NULL; scan++) {
541		mode = scan->mode;
542		if (vap->iv_des_mode != IEEE80211_MODE_AUTO) {
543			/*
544			 * If a desired mode was specified, scan only
545			 * channels that satisfy that constraint.
546			 */
547			if (vap->iv_des_mode != mode) {
548				/*
549				 * The scan table marks 2.4Ghz channels as b
550				 * so if the desired mode is 11g, then use
551				 * the 11b channel list but upgrade the mode.
552				 */
553				if (vap->iv_des_mode != IEEE80211_MODE_11G ||
554				    mode != IEEE80211_MODE_11B)
555					continue;
556				mode = IEEE80211_MODE_11G;	/* upgrade */
557			}
558		} else {
559			/*
560			 * This lets add_channels upgrade an 11b channel
561			 * to 11g if available.
562			 */
563			if (mode == IEEE80211_MODE_11B)
564				mode = IEEE80211_MODE_AUTO;
565		}
566#ifdef IEEE80211_F_XR
567		/* XR does not operate on turbo channels */
568		if ((vap->iv_flags & IEEE80211_F_XR) &&
569		    (mode == IEEE80211_MODE_TURBO_A ||
570		     mode == IEEE80211_MODE_TURBO_G ||
571		     mode == IEEE80211_MODE_STURBO_A))
572			continue;
573#endif
574		/*
575		 * Add the list of the channels; any that are not
576		 * in the master channel list will be discarded.
577		 */
578		add_channels(vap, ss, mode, scan->list, scan->count);
579	}
580
581	/*
582	 * Add the channels from the ic that are not present
583	 * in the table.
584	 */
585	sweepchannels(ss, vap, table);
586}
587
588static const uint16_t rcl1[] =		/* 8 FCC channel: 52, 56, 60, 64, 36, 40, 44, 48 */
589{ 5260, 5280, 5300, 5320, 5180, 5200, 5220, 5240 };
590static const uint16_t rcl2[] =		/* 4 MKK channels: 34, 38, 42, 46 */
591{ 5170, 5190, 5210, 5230 };
592static const uint16_t rcl3[] =		/* 2.4Ghz ch: 1,6,11,7,13 */
593{ 2412, 2437, 2462, 2442, 2472 };
594static const uint16_t rcl4[] =		/* 5 FCC channel: 149, 153, 161, 165 */
595{ 5745, 5765, 5785, 5805, 5825 };
596static const uint16_t rcl7[] =		/* 11 ETSI channel: 100,104,108,112,116,120,124,128,132,136,140 */
597{ 5500, 5520, 5540, 5560, 5580, 5600, 5620, 5640, 5660, 5680, 5700 };
598static const uint16_t rcl8[] =		/* 2.4Ghz ch: 2,3,4,5,8,9,10,12 */
599{ 2417, 2422, 2427, 2432, 2447, 2452, 2457, 2467 };
600static const uint16_t rcl9[] =		/* 2.4Ghz ch: 14 */
601{ 2484 };
602static const uint16_t rcl10[] =	/* Added Korean channels 2312-2372 */
603{ 2312, 2317, 2322, 2327, 2332, 2337, 2342, 2347, 2352, 2357, 2362, 2367, 2372 };
604static const uint16_t rcl11[] =	/* Added Japan channels in 4.9/5.0 spectrum */
605{ 5040, 5060, 5080, 4920, 4940, 4960, 4980 };
606#ifdef ATH_TURBO_SCAN
607static const uint16_t rcl5[] =		/* 3 static turbo channels */
608{ 5210, 5250, 5290 };
609static const uint16_t rcl6[] =		/* 2 static turbo channels */
610{ 5760, 5800 };
611static const uint16_t rcl6x[] =	/* 4 FCC3 turbo channels */
612{ 5540, 5580, 5620, 5660 };
613static const uint16_t rcl12[] =	/* 2.4Ghz Turbo channel 6 */
614{ 2437 };
615static const uint16_t rcl13[] =	/* dynamic Turbo channels */
616{ 5200, 5240, 5280, 5765, 5805 };
617#endif /* ATH_TURBO_SCAN */
618
619#define	X(a)	.count = sizeof(a)/sizeof(a[0]), .list = a
620
621static const struct scanlist staScanTable[] = {
622	{ IEEE80211_MODE_11B,   	X(rcl3) },
623	{ IEEE80211_MODE_11A,   	X(rcl1) },
624	{ IEEE80211_MODE_11A,   	X(rcl2) },
625	{ IEEE80211_MODE_11B,   	X(rcl8) },
626	{ IEEE80211_MODE_11B,   	X(rcl9) },
627	{ IEEE80211_MODE_11A,   	X(rcl4) },
628#ifdef ATH_TURBO_SCAN
629	{ IEEE80211_MODE_STURBO_A,	X(rcl5) },
630	{ IEEE80211_MODE_STURBO_A,	X(rcl6) },
631	{ IEEE80211_MODE_TURBO_A,	X(rcl6x) },
632	{ IEEE80211_MODE_TURBO_A,	X(rcl13) },
633#endif /* ATH_TURBO_SCAN */
634	{ IEEE80211_MODE_11A,		X(rcl7) },
635	{ IEEE80211_MODE_11B,		X(rcl10) },
636	{ IEEE80211_MODE_11A,		X(rcl11) },
637#ifdef ATH_TURBO_SCAN
638	{ IEEE80211_MODE_TURBO_G,	X(rcl12) },
639#endif /* ATH_TURBO_SCAN */
640	{ .list = NULL }
641};
642
643/*
644 * Start a station-mode scan by populating the channel list.
645 */
646static int
647sta_start(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
648{
649	struct sta_table *st = ss->ss_priv;
650
651	makescanlist(ss, vap, staScanTable);
652
653	if (ss->ss_mindwell == 0)
654		ss->ss_mindwell = msecs_to_ticks(20);	/* 20ms */
655	if (ss->ss_maxdwell == 0)
656		ss->ss_maxdwell = msecs_to_ticks(200);	/* 200ms */
657
658	st->st_scangen++;
659	st->st_newscan = 1;
660
661	return 0;
662}
663
664/*
665 * Restart a scan, typically a bg scan but can
666 * also be a fg scan that came up empty.
667 */
668static int
669sta_restart(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
670{
671	struct sta_table *st = ss->ss_priv;
672
673	st->st_newscan = 1;
674	return 0;
675}
676
677/*
678 * Cancel an ongoing scan.
679 */
680static int
681sta_cancel(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
682{
683	return 0;
684}
685
686/* unalligned little endian access */
687#define LE_READ_2(p)					\
688	((uint16_t)					\
689	 ((((const uint8_t *)(p))[0]      ) |		\
690	  (((const uint8_t *)(p))[1] <<  8)))
691
692/*
693 * Demote any supplied 11g channel to 11b.  There should
694 * always be an 11b channel but we check anyway...
695 */
696static struct ieee80211_channel *
697demote11b(struct ieee80211vap *vap, struct ieee80211_channel *chan)
698{
699	struct ieee80211_channel *c;
700
701	if (IEEE80211_IS_CHAN_ANYG(chan) &&
702	    vap->iv_des_mode == IEEE80211_MODE_AUTO) {
703		c = ieee80211_find_channel(vap->iv_ic, chan->ic_freq,
704		    (chan->ic_flags &~ (IEEE80211_CHAN_PUREG | IEEE80211_CHAN_G)) |
705		    IEEE80211_CHAN_B);
706		if (c != NULL)
707			chan = c;
708	}
709	return chan;
710}
711
712static int
713maxrate(const struct ieee80211_scan_entry *se)
714{
715	const struct ieee80211_ie_htcap *htcap =
716	    (const struct ieee80211_ie_htcap *) se->se_ies.htcap_ie;
717	int rmax, r, i;
718	uint16_t caps;
719
720	rmax = 0;
721	if (htcap != NULL) {
722		/*
723		 * HT station; inspect supported MCS and then adjust
724		 * rate by channel width.  Could also include short GI
725		 * in this if we want to be extra accurate.
726		 */
727		/* XXX assumes MCS15 is max */
728		for (i = 15; i >= 0 && isclr(htcap->hc_mcsset, i); i--)
729			;
730		if (i >= 0) {
731			caps = LE_READ_2(&htcap->hc_cap);
732			/* XXX short/long GI */
733			if (caps & IEEE80211_HTCAP_CHWIDTH40)
734				rmax = ieee80211_htrates[i].ht40_rate_400ns;
735			else
736				rmax = ieee80211_htrates[i].ht40_rate_800ns;
737		}
738	}
739	for (i = 0; i < se->se_rates[1]; i++) {
740		r = se->se_rates[2+i] & IEEE80211_RATE_VAL;
741		if (r > rmax)
742			rmax = r;
743	}
744	for (i = 0; i < se->se_xrates[1]; i++) {
745		r = se->se_xrates[2+i] & IEEE80211_RATE_VAL;
746		if (r > rmax)
747			rmax = r;
748	}
749	return rmax;
750}
751
752/*
753 * Compare the capabilities of two entries and decide which is
754 * more desirable (return >0 if a is considered better).  Note
755 * that we assume compatibility/usability has already been checked
756 * so we don't need to (e.g. validate whether privacy is supported).
757 * Used to select the best scan candidate for association in a BSS.
758 */
759static int
760sta_compare(const struct sta_entry *a, const struct sta_entry *b)
761{
762#define	PREFER(_a,_b,_what) do {			\
763	if (((_a) ^ (_b)) & (_what))			\
764		return ((_a) & (_what)) ? 1 : -1;	\
765} while (0)
766	int maxa, maxb;
767	int8_t rssia, rssib;
768	int weight;
769
770	/* privacy support */
771	PREFER(a->base.se_capinfo, b->base.se_capinfo,
772		IEEE80211_CAPINFO_PRIVACY);
773
774	/* compare count of previous failures */
775	weight = b->se_fails - a->se_fails;
776	if (abs(weight) > 1)
777		return weight;
778
779	/*
780	 * Compare rssi.  If the two are considered equivalent
781	 * then fallback to other criteria.  We threshold the
782	 * comparisons to avoid selecting an ap purely by rssi
783	 * when both values may be good but one ap is otherwise
784	 * more desirable (e.g. an 11b-only ap with stronger
785	 * signal than an 11g ap).
786	 */
787	rssia = MIN(a->base.se_rssi, STA_RSSI_MAX);
788	rssib = MIN(b->base.se_rssi, STA_RSSI_MAX);
789	if (abs(rssib - rssia) < 5) {
790		/* best/max rate preferred if signal level close enough XXX */
791		maxa = maxrate(&a->base);
792		maxb = maxrate(&b->base);
793		if (maxa != maxb)
794			return maxa - maxb;
795		/* XXX use freq for channel preference */
796		/* for now just prefer 5Ghz band to all other bands */
797		PREFER(IEEE80211_IS_CHAN_5GHZ(a->base.se_chan),
798		       IEEE80211_IS_CHAN_5GHZ(b->base.se_chan), 1);
799	}
800	/* all things being equal, use signal level */
801	return a->base.se_rssi - b->base.se_rssi;
802#undef PREFER
803}
804
805/*
806 * Check rate set suitability and return the best supported rate.
807 * XXX inspect MCS for HT
808 */
809static int
810check_rate(struct ieee80211vap *vap, const struct ieee80211_channel *chan,
811    const struct ieee80211_scan_entry *se)
812{
813#define	RV(v)	((v) & IEEE80211_RATE_VAL)
814	const struct ieee80211_rateset *srs;
815	int i, j, nrs, r, okrate, badrate, fixedrate, ucastrate;
816	const uint8_t *rs;
817
818	okrate = badrate = 0;
819
820	srs = ieee80211_get_suprates(vap->iv_ic, chan);
821	nrs = se->se_rates[1];
822	rs = se->se_rates+2;
823	/* XXX MCS */
824	ucastrate = vap->iv_txparms[ieee80211_chan2mode(chan)].ucastrate;
825	fixedrate = IEEE80211_FIXED_RATE_NONE;
826again:
827	for (i = 0; i < nrs; i++) {
828		r = RV(rs[i]);
829		badrate = r;
830		/*
831		 * Check any fixed rate is included.
832		 */
833		if (r == ucastrate)
834			fixedrate = r;
835		/*
836		 * Check against our supported rates.
837		 */
838		for (j = 0; j < srs->rs_nrates; j++)
839			if (r == RV(srs->rs_rates[j])) {
840				if (r > okrate)		/* NB: track max */
841					okrate = r;
842				break;
843			}
844
845		if (j == srs->rs_nrates && (rs[i] & IEEE80211_RATE_BASIC)) {
846			/*
847			 * Don't try joining a BSS, if we don't support
848			 * one of its basic rates.
849			 */
850			okrate = 0;
851			goto back;
852		}
853	}
854	if (rs == se->se_rates+2) {
855		/* scan xrates too; sort of an algol68-style for loop */
856		nrs = se->se_xrates[1];
857		rs = se->se_xrates+2;
858		goto again;
859	}
860
861back:
862	if (okrate == 0 || ucastrate != fixedrate)
863		return badrate | IEEE80211_RATE_BASIC;
864	else
865		return RV(okrate);
866#undef RV
867}
868
869static int
870match_ssid(const uint8_t *ie,
871	int nssid, const struct ieee80211_scan_ssid ssids[])
872{
873	int i;
874
875	for (i = 0; i < nssid; i++) {
876		if (ie[1] == ssids[i].len &&
877		     memcmp(ie+2, ssids[i].ssid, ie[1]) == 0)
878			return 1;
879	}
880	return 0;
881}
882
883#ifdef IEEE80211_SUPPORT_TDMA
884static int
885tdma_isfull(const struct ieee80211_tdma_param *tdma)
886{
887	int slot, slotcnt;
888
889	slotcnt = tdma->tdma_slotcnt;
890	for (slot = slotcnt-1; slot >= 0; slot--)
891		if (isclr(tdma->tdma_inuse, slot))
892			return 0;
893	return 1;
894}
895#endif /* IEEE80211_SUPPORT_TDMA */
896
897/*
898 * Test a scan candidate for suitability/compatibility.
899 */
900static int
901match_bss(struct ieee80211vap *vap,
902	const struct ieee80211_scan_state *ss, struct sta_entry *se0,
903	int debug)
904{
905	struct ieee80211com *ic = vap->iv_ic;
906	struct ieee80211_scan_entry *se = &se0->base;
907        uint8_t rate;
908        int fail;
909
910	fail = 0;
911	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, se->se_chan)))
912		fail |= MATCH_CHANNEL;
913	/*
914	 * NB: normally the desired mode is used to construct
915	 * the channel list, but it's possible for the scan
916	 * cache to include entries for stations outside this
917	 * list so we check the desired mode here to weed them
918	 * out.
919	 */
920	if (vap->iv_des_mode != IEEE80211_MODE_AUTO &&
921	    (se->se_chan->ic_flags & IEEE80211_CHAN_ALLTURBO) !=
922	    chanflags[vap->iv_des_mode])
923		fail |= MATCH_CHANNEL;
924	if (vap->iv_opmode == IEEE80211_M_IBSS) {
925		if ((se->se_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
926			fail |= MATCH_CAPINFO;
927#ifdef IEEE80211_SUPPORT_TDMA
928	} else if (vap->iv_opmode == IEEE80211_M_AHDEMO) {
929		/*
930		 * Adhoc demo network setup shouldn't really be scanning
931		 * but just in case skip stations operating in IBSS or
932		 * BSS mode.
933		 */
934		if (se->se_capinfo & (IEEE80211_CAPINFO_IBSS|IEEE80211_CAPINFO_ESS))
935			fail |= MATCH_CAPINFO;
936		/*
937		 * TDMA operation cannot coexist with a normal 802.11 network;
938		 * skip if IBSS or ESS capabilities are marked and require
939		 * the beacon have a TDMA ie present.
940		 */
941		if (vap->iv_caps & IEEE80211_C_TDMA) {
942			const struct ieee80211_tdma_param *tdma =
943			    (const struct ieee80211_tdma_param *)se->se_ies.tdma_ie;
944
945			if (tdma == NULL)
946				fail |= MATCH_TDMA_NOIE;
947			else if (tdma->tdma_slot != 0)
948				fail |= MATCH_TDMA_NOTMASTER;
949			else if (tdma_isfull(tdma))
950				fail |= MATCH_TDMA_NOSLOT;
951#if 0
952			else if (ieee80211_local_address(se->se_macaddr))
953				fail |= MATCH_TDMA_LOCAL;
954#endif
955		}
956#endif /* IEEE80211_SUPPORT_TDMA */
957	} else {
958		if ((se->se_capinfo & IEEE80211_CAPINFO_ESS) == 0)
959			fail |= MATCH_CAPINFO;
960		/*
961		 * If 11d is enabled and we're attempting to join a bss
962		 * that advertises it's country code then compare our
963		 * current settings to what we fetched from the country ie.
964		 * If our country code is unspecified or different then do
965		 * not attempt to join the bss.  We should have already
966		 * dispatched an event to user space that identifies the
967		 * new country code so our regdomain config should match.
968		 */
969		if ((IEEE80211_IS_CHAN_11D(se->se_chan) ||
970		    (vap->iv_flags_ext & IEEE80211_FEXT_DOTD)) &&
971		    se->se_cc[0] != 0 &&
972		    (ic->ic_regdomain.country == CTRY_DEFAULT ||
973		     !isocmp(se->se_cc, ic->ic_regdomain.isocc)))
974			fail |= MATCH_CC;
975	}
976	if (vap->iv_flags & IEEE80211_F_PRIVACY) {
977		if ((se->se_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
978			fail |= MATCH_PRIVACY;
979	} else {
980		/* XXX does this mean privacy is supported or required? */
981		if (se->se_capinfo & IEEE80211_CAPINFO_PRIVACY)
982			fail |= MATCH_PRIVACY;
983	}
984	se0->se_flags &= ~STA_DEMOTE11B;
985	rate = check_rate(vap, se->se_chan, se);
986	if (rate & IEEE80211_RATE_BASIC) {
987		fail |= MATCH_RATE;
988		/*
989		 * An 11b-only ap will give a rate mismatch if there is an
990		 * OFDM fixed tx rate for 11g.  Try downgrading the channel
991		 * in the scan list to 11b and retry the rate check.
992		 */
993		if (IEEE80211_IS_CHAN_ANYG(se->se_chan)) {
994			rate = check_rate(vap, demote11b(vap, se->se_chan), se);
995			if ((rate & IEEE80211_RATE_BASIC) == 0) {
996				fail &= ~MATCH_RATE;
997				se0->se_flags |= STA_DEMOTE11B;
998			}
999		}
1000	} else if (rate < 2*24) {
1001		/*
1002		 * This is an 11b-only ap.  Check the desired mode in
1003		 * case that needs to be honored (mode 11g filters out
1004		 * 11b-only ap's).  Otherwise force any 11g channel used
1005		 * in scanning to be demoted.
1006		 *
1007		 * NB: we cheat a bit here by looking at the max rate;
1008		 *     we could/should check the rates.
1009		 */
1010		if (!(vap->iv_des_mode == IEEE80211_MODE_AUTO ||
1011		      vap->iv_des_mode == IEEE80211_MODE_11B))
1012			fail |= MATCH_RATE;
1013		else
1014			se0->se_flags |= STA_DEMOTE11B;
1015	}
1016	if (ss->ss_nssid != 0 &&
1017	    !match_ssid(se->se_ssid, ss->ss_nssid, ss->ss_ssid))
1018		fail |= MATCH_SSID;
1019	if ((vap->iv_flags & IEEE80211_F_DESBSSID) &&
1020	    !IEEE80211_ADDR_EQ(vap->iv_des_bssid, se->se_bssid))
1021		fail |= MATCH_BSSID;
1022	if (se0->se_fails >= STA_FAILS_MAX)
1023		fail |= MATCH_FAILS;
1024	if (se0->se_notseen >= STA_PURGE_SCANS)
1025		fail |= MATCH_NOTSEEN;
1026	if (se->se_rssi < STA_RSSI_MIN)
1027		fail |= MATCH_RSSI;
1028#ifdef IEEE80211_DEBUG
1029	if (ieee80211_msg(vap, debug)) {
1030		printf(" %c %s",
1031		    fail & MATCH_FAILS ? '=' :
1032		    fail & MATCH_NOTSEEN ? '^' :
1033		    fail & MATCH_CC ? '$' :
1034#ifdef IEEE80211_SUPPORT_TDMA
1035		    fail & MATCH_TDMA_NOIE ? '&' :
1036		    fail & MATCH_TDMA_NOTMASTER ? ':' :
1037		    fail & MATCH_TDMA_NOSLOT ? '@' :
1038		    fail & MATCH_TDMA_LOCAL ? '#' :
1039#endif
1040		    fail ? '-' : '+', ether_sprintf(se->se_macaddr));
1041		printf(" %s%c", ether_sprintf(se->se_bssid),
1042		    fail & MATCH_BSSID ? '!' : ' ');
1043		printf(" %3d%c", ieee80211_chan2ieee(ic, se->se_chan),
1044			fail & MATCH_CHANNEL ? '!' : ' ');
1045		printf(" %+4d%c", se->se_rssi, fail & MATCH_RSSI ? '!' : ' ');
1046		printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
1047		    fail & MATCH_RATE ? '!' : ' ');
1048		printf(" %4s%c",
1049		    (se->se_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
1050		    (se->se_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
1051		    "????",
1052		    fail & MATCH_CAPINFO ? '!' : ' ');
1053		printf(" %3s%c ",
1054		    (se->se_capinfo & IEEE80211_CAPINFO_PRIVACY) ?
1055		    "wep" : "no",
1056		    fail & MATCH_PRIVACY ? '!' : ' ');
1057		ieee80211_print_essid(se->se_ssid+2, se->se_ssid[1]);
1058		printf("%s\n", fail & MATCH_SSID ? "!" : "");
1059	}
1060#endif
1061	return fail;
1062}
1063
1064static void
1065sta_update_notseen(struct sta_table *st)
1066{
1067	struct sta_entry *se;
1068
1069	mtx_lock(&st->st_lock);
1070	TAILQ_FOREACH(se, &st->st_entry, se_list) {
1071		/*
1072		 * If seen the reset and don't bump the count;
1073		 * otherwise bump the ``not seen'' count.  Note
1074		 * that this insures that stations for which we
1075		 * see frames while not scanning but not during
1076		 * this scan will not be penalized.
1077		 */
1078		if (se->se_seen)
1079			se->se_seen = 0;
1080		else
1081			se->se_notseen++;
1082	}
1083	mtx_unlock(&st->st_lock);
1084}
1085
1086static void
1087sta_dec_fails(struct sta_table *st)
1088{
1089	struct sta_entry *se;
1090
1091	mtx_lock(&st->st_lock);
1092	TAILQ_FOREACH(se, &st->st_entry, se_list)
1093		if (se->se_fails)
1094			se->se_fails--;
1095	mtx_unlock(&st->st_lock);
1096}
1097
1098static struct sta_entry *
1099select_bss(struct ieee80211_scan_state *ss, struct ieee80211vap *vap, int debug)
1100{
1101	struct sta_table *st = ss->ss_priv;
1102	struct sta_entry *se, *selbs = NULL;
1103
1104	IEEE80211_DPRINTF(vap, debug, " %s\n",
1105	    "macaddr          bssid         chan  rssi  rate flag  wep  essid");
1106	mtx_lock(&st->st_lock);
1107	TAILQ_FOREACH(se, &st->st_entry, se_list) {
1108		ieee80211_ies_expand(&se->base.se_ies);
1109		if (match_bss(vap, ss, se, debug) == 0) {
1110			if (selbs == NULL)
1111				selbs = se;
1112			else if (sta_compare(se, selbs) > 0)
1113				selbs = se;
1114		}
1115	}
1116	mtx_unlock(&st->st_lock);
1117
1118	return selbs;
1119}
1120
1121/*
1122 * Pick an ap or ibss network to join or find a channel
1123 * to use to start an ibss network.
1124 */
1125static int
1126sta_pick_bss(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1127{
1128	struct sta_table *st = ss->ss_priv;
1129	struct sta_entry *selbs;
1130	struct ieee80211_channel *chan;
1131
1132	KASSERT(vap->iv_opmode == IEEE80211_M_STA,
1133		("wrong mode %u", vap->iv_opmode));
1134
1135	if (st->st_newscan) {
1136		sta_update_notseen(st);
1137		st->st_newscan = 0;
1138	}
1139	if (ss->ss_flags & IEEE80211_SCAN_NOPICK) {
1140		/*
1141		 * Manual/background scan, don't select+join the
1142		 * bss, just return.  The scanning framework will
1143		 * handle notification that this has completed.
1144		 */
1145		ss->ss_flags &= ~IEEE80211_SCAN_NOPICK;
1146		return 1;
1147	}
1148	/*
1149	 * Automatic sequencing; look for a candidate and
1150	 * if found join the network.
1151	 */
1152	/* NB: unlocked read should be ok */
1153	if (TAILQ_FIRST(&st->st_entry) == NULL) {
1154		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
1155			"%s: no scan candidate\n", __func__);
1156		if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1157			return 0;
1158notfound:
1159		/*
1160		 * If nothing suitable was found decrement
1161		 * the failure counts so entries will be
1162		 * reconsidered the next time around.  We
1163		 * really want to do this only for sta's
1164		 * where we've previously had some success.
1165		 */
1166		sta_dec_fails(st);
1167		st->st_newscan = 1;
1168		return 0;			/* restart scan */
1169	}
1170	selbs = select_bss(ss, vap, IEEE80211_MSG_SCAN);
1171	if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1172		return (selbs != NULL);
1173	if (selbs == NULL)
1174		goto notfound;
1175	chan = selbs->base.se_chan;
1176	if (selbs->se_flags & STA_DEMOTE11B)
1177		chan = demote11b(vap, chan);
1178	if (!ieee80211_sta_join(vap, chan, &selbs->base))
1179		goto notfound;
1180	return 1;				/* terminate scan */
1181}
1182
1183/*
1184 * Lookup an entry in the scan cache.  We assume we're
1185 * called from the bottom half or such that we don't need
1186 * to block the bottom half so that it's safe to return
1187 * a reference to an entry w/o holding the lock on the table.
1188 */
1189static struct sta_entry *
1190sta_lookup(struct sta_table *st, const uint8_t macaddr[IEEE80211_ADDR_LEN])
1191{
1192	struct sta_entry *se;
1193	int hash = STA_HASH(macaddr);
1194
1195	mtx_lock(&st->st_lock);
1196	LIST_FOREACH(se, &st->st_hash[hash], se_hash)
1197		if (IEEE80211_ADDR_EQ(se->base.se_macaddr, macaddr))
1198			break;
1199	mtx_unlock(&st->st_lock);
1200
1201	return se;		/* NB: unlocked */
1202}
1203
1204static void
1205sta_roam_check(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1206{
1207	struct ieee80211com *ic = vap->iv_ic;
1208	struct ieee80211_node *ni = vap->iv_bss;
1209	struct sta_table *st = ss->ss_priv;
1210	enum ieee80211_phymode mode;
1211	struct sta_entry *se, *selbs;
1212	uint8_t roamRate, curRate, ucastRate;
1213	int8_t roamRssi, curRssi;
1214
1215	se = sta_lookup(st, ni->ni_macaddr);
1216	if (se == NULL) {
1217		/* XXX something is wrong */
1218		return;
1219	}
1220
1221	mode = ieee80211_chan2mode(ic->ic_bsschan);
1222	roamRate = vap->iv_roamparms[mode].rate;
1223	roamRssi = vap->iv_roamparms[mode].rssi;
1224	ucastRate = vap->iv_txparms[mode].ucastrate;
1225	/* NB: the most up to date rssi is in the node, not the scan cache */
1226	curRssi = ic->ic_node_getrssi(ni);
1227	if (ucastRate == IEEE80211_FIXED_RATE_NONE) {
1228		curRate = ni->ni_txrate;
1229		roamRate &= IEEE80211_RATE_VAL;
1230		IEEE80211_DPRINTF(vap, IEEE80211_MSG_ROAM,
1231		    "%s: currssi %d currate %u roamrssi %d roamrate %u\n",
1232		    __func__, curRssi, curRate, roamRssi, roamRate);
1233	} else {
1234		curRate = roamRate;	/* NB: insure compare below fails */
1235		IEEE80211_DPRINTF(vap, IEEE80211_MSG_ROAM,
1236		    "%s: currssi %d roamrssi %d\n", __func__, curRssi, roamRssi);
1237	}
1238	/*
1239	 * Check if a new ap should be used and switch.
1240	 * XXX deauth current ap
1241	 */
1242	if (curRate < roamRate || curRssi < roamRssi) {
1243		if (time_after(ticks, ic->ic_lastscan + vap->iv_scanvalid)) {
1244			/*
1245			 * Scan cache contents are too old; force a scan now
1246			 * if possible so we have current state to make a
1247			 * decision with.  We don't kick off a bg scan if
1248			 * we're using dynamic turbo and boosted or if the
1249			 * channel is busy.
1250			 * XXX force immediate switch on scan complete
1251			 */
1252			if (!IEEE80211_IS_CHAN_DTURBO(ic->ic_curchan) &&
1253			    time_after(ticks, ic->ic_lastdata + vap->iv_bgscanidle))
1254				ieee80211_bg_scan(vap, 0);
1255			return;
1256		}
1257		se->base.se_rssi = curRssi;
1258		selbs = select_bss(ss, vap, IEEE80211_MSG_ROAM);
1259		if (selbs != NULL && selbs != se) {
1260			struct ieee80211_channel *chan;
1261
1262			IEEE80211_DPRINTF(vap,
1263			    IEEE80211_MSG_ROAM | IEEE80211_MSG_DEBUG,
1264			    "%s: ROAM: curRate %u, roamRate %u, "
1265			    "curRssi %d, roamRssi %d\n", __func__,
1266			    curRate, roamRate, curRssi, roamRssi);
1267
1268			chan = selbs->base.se_chan;
1269			if (selbs->se_flags & STA_DEMOTE11B)
1270				chan = demote11b(vap, chan);
1271			(void) ieee80211_sta_join(vap, chan, &selbs->base);
1272		}
1273	}
1274}
1275
1276/*
1277 * Age entries in the scan cache.
1278 * XXX also do roaming since it's convenient
1279 */
1280static void
1281sta_age(struct ieee80211_scan_state *ss)
1282{
1283	struct ieee80211vap *vap = ss->ss_vap;
1284
1285	adhoc_age(ss);
1286	/*
1287	 * If rate control is enabled check periodically to see if
1288	 * we should roam from our current connection to one that
1289	 * might be better.  This only applies when we're operating
1290	 * in sta mode and automatic roaming is set.
1291	 * XXX defer if busy
1292	 * XXX repeater station
1293	 * XXX do when !bgscan?
1294	 */
1295	KASSERT(vap->iv_opmode == IEEE80211_M_STA,
1296		("wrong mode %u", vap->iv_opmode));
1297	if (vap->iv_roaming == IEEE80211_ROAMING_AUTO &&
1298	    (vap->iv_ic->ic_flags & IEEE80211_F_BGSCAN) &&
1299	    vap->iv_state >= IEEE80211_S_RUN)
1300		/* XXX vap is implicit */
1301		sta_roam_check(ss, vap);
1302}
1303
1304/*
1305 * Iterate over the entries in the scan cache, invoking
1306 * the callback function on each one.
1307 */
1308static void
1309sta_iterate(struct ieee80211_scan_state *ss,
1310	ieee80211_scan_iter_func *f, void *arg)
1311{
1312	struct sta_table *st = ss->ss_priv;
1313	struct sta_entry *se;
1314	u_int gen;
1315
1316	mtx_lock(&st->st_scanlock);
1317	gen = st->st_scaniter++;
1318restart:
1319	mtx_lock(&st->st_lock);
1320	TAILQ_FOREACH(se, &st->st_entry, se_list) {
1321		if (se->se_scangen != gen) {
1322			se->se_scangen = gen;
1323			/* update public state */
1324			se->base.se_age = ticks - se->se_lastupdate;
1325			mtx_unlock(&st->st_lock);
1326			(*f)(arg, &se->base);
1327			goto restart;
1328		}
1329	}
1330	mtx_unlock(&st->st_lock);
1331
1332	mtx_unlock(&st->st_scanlock);
1333}
1334
1335static void
1336sta_assoc_fail(struct ieee80211_scan_state *ss,
1337	const uint8_t macaddr[IEEE80211_ADDR_LEN], int reason)
1338{
1339	struct sta_table *st = ss->ss_priv;
1340	struct sta_entry *se;
1341
1342	se = sta_lookup(st, macaddr);
1343	if (se != NULL) {
1344		se->se_fails++;
1345		se->se_lastfail = ticks;
1346		IEEE80211_NOTE_MAC(ss->ss_vap, IEEE80211_MSG_SCAN,
1347		    macaddr, "%s: reason %u fails %u",
1348		    __func__, reason, se->se_fails);
1349	}
1350}
1351
1352static void
1353sta_assoc_success(struct ieee80211_scan_state *ss,
1354	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1355{
1356	struct sta_table *st = ss->ss_priv;
1357	struct sta_entry *se;
1358
1359	se = sta_lookup(st, macaddr);
1360	if (se != NULL) {
1361#if 0
1362		se->se_fails = 0;
1363		IEEE80211_NOTE_MAC(ss->ss_vap, IEEE80211_MSG_SCAN,
1364		    macaddr, "%s: fails %u",
1365		    __func__, se->se_fails);
1366#endif
1367		se->se_lastassoc = ticks;
1368	}
1369}
1370
1371static const struct ieee80211_scanner sta_default = {
1372	.scan_name		= "default",
1373	.scan_attach		= sta_attach,
1374	.scan_detach		= sta_detach,
1375	.scan_start		= sta_start,
1376	.scan_restart		= sta_restart,
1377	.scan_cancel		= sta_cancel,
1378	.scan_end		= sta_pick_bss,
1379	.scan_flush		= sta_flush,
1380	.scan_add		= sta_add,
1381	.scan_age		= sta_age,
1382	.scan_iterate		= sta_iterate,
1383	.scan_assoc_fail	= sta_assoc_fail,
1384	.scan_assoc_success	= sta_assoc_success,
1385};
1386
1387/*
1388 * Adhoc mode-specific support.
1389 */
1390
1391static const uint16_t adhocWorld[] =		/* 36, 40, 44, 48 */
1392{ 5180, 5200, 5220, 5240 };
1393static const uint16_t adhocFcc3[] =		/* 36, 40, 44, 48 145, 149, 153, 157, 161, 165 */
1394{ 5180, 5200, 5220, 5240, 5725, 5745, 5765, 5785, 5805, 5825 };
1395static const uint16_t adhocMkk[] =		/* 34, 38, 42, 46 */
1396{ 5170, 5190, 5210, 5230 };
1397static const uint16_t adhoc11b[] =		/* 10, 11 */
1398{ 2457, 2462 };
1399
1400static const struct scanlist adhocScanTable[] = {
1401	{ IEEE80211_MODE_11B,   	X(adhoc11b) },
1402	{ IEEE80211_MODE_11A,   	X(adhocWorld) },
1403	{ IEEE80211_MODE_11A,   	X(adhocFcc3) },
1404	{ IEEE80211_MODE_11B,   	X(adhocMkk) },
1405	{ .list = NULL }
1406};
1407#undef X
1408
1409/*
1410 * Start an adhoc-mode scan by populating the channel list.
1411 */
1412static int
1413adhoc_start(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1414{
1415	struct sta_table *st = ss->ss_priv;
1416
1417	makescanlist(ss, vap, adhocScanTable);
1418
1419	if (ss->ss_mindwell == 0)
1420		ss->ss_mindwell = msecs_to_ticks(200);	/* 200ms */
1421	if (ss->ss_maxdwell == 0)
1422		ss->ss_maxdwell = msecs_to_ticks(200);	/* 200ms */
1423
1424	st->st_scangen++;
1425	st->st_newscan = 1;
1426
1427	return 0;
1428}
1429
1430/*
1431 * Select a channel to start an adhoc network on.
1432 * The channel list was populated with appropriate
1433 * channels so select one that looks least occupied.
1434 */
1435static struct ieee80211_channel *
1436adhoc_pick_channel(struct ieee80211_scan_state *ss, int flags)
1437{
1438	struct sta_table *st = ss->ss_priv;
1439	struct sta_entry *se;
1440	struct ieee80211_channel *c, *bestchan;
1441	int i, bestrssi, maxrssi;
1442
1443	bestchan = NULL;
1444	bestrssi = -1;
1445
1446	mtx_lock(&st->st_lock);
1447	for (i = 0; i < ss->ss_last; i++) {
1448		c = ss->ss_chans[i];
1449		/* never consider a channel with radar */
1450		if (IEEE80211_IS_CHAN_RADAR(c))
1451			continue;
1452		/* skip channels disallowed by regulatory settings */
1453		if (IEEE80211_IS_CHAN_NOADHOC(c))
1454			continue;
1455		/* check channel attributes for band compatibility */
1456		if (flags != 0 && (c->ic_flags & flags) != flags)
1457			continue;
1458		maxrssi = 0;
1459		TAILQ_FOREACH(se, &st->st_entry, se_list) {
1460			if (se->base.se_chan != c)
1461				continue;
1462			if (se->base.se_rssi > maxrssi)
1463				maxrssi = se->base.se_rssi;
1464		}
1465		if (bestchan == NULL || maxrssi < bestrssi)
1466			bestchan = c;
1467	}
1468	mtx_unlock(&st->st_lock);
1469
1470	return bestchan;
1471}
1472
1473/*
1474 * Pick an ibss network to join or find a channel
1475 * to use to start an ibss network.
1476 */
1477static int
1478adhoc_pick_bss(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1479{
1480	struct sta_table *st = ss->ss_priv;
1481	struct sta_entry *selbs;
1482	struct ieee80211_channel *chan;
1483
1484	KASSERT(vap->iv_opmode == IEEE80211_M_IBSS ||
1485		vap->iv_opmode == IEEE80211_M_AHDEMO,
1486		("wrong opmode %u", vap->iv_opmode));
1487
1488	if (st->st_newscan) {
1489		sta_update_notseen(st);
1490		st->st_newscan = 0;
1491	}
1492	if (ss->ss_flags & IEEE80211_SCAN_NOPICK) {
1493		/*
1494		 * Manual/background scan, don't select+join the
1495		 * bss, just return.  The scanning framework will
1496		 * handle notification that this has completed.
1497		 */
1498		ss->ss_flags &= ~IEEE80211_SCAN_NOPICK;
1499		return 1;
1500	}
1501	/*
1502	 * Automatic sequencing; look for a candidate and
1503	 * if found join the network.
1504	 */
1505	/* NB: unlocked read should be ok */
1506	if (TAILQ_FIRST(&st->st_entry) == NULL) {
1507		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
1508			"%s: no scan candidate\n", __func__);
1509		if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1510			return 0;
1511notfound:
1512		/* NB: never auto-start a tdma network for slot !0 */
1513#ifdef IEEE80211_SUPPORT_TDMA
1514		if (vap->iv_des_nssid &&
1515		    ((vap->iv_caps & IEEE80211_C_TDMA) == 0 ||
1516		     ieee80211_tdma_getslot(vap) == 0)) {
1517#else
1518		if (vap->iv_des_nssid) {
1519#endif
1520			/*
1521			 * No existing adhoc network to join and we have
1522			 * an ssid; start one up.  If no channel was
1523			 * specified, try to select a channel.
1524			 */
1525			if (vap->iv_des_chan == IEEE80211_CHAN_ANYC ||
1526			    IEEE80211_IS_CHAN_RADAR(vap->iv_des_chan)) {
1527				struct ieee80211com *ic = vap->iv_ic;
1528
1529				chan = adhoc_pick_channel(ss, 0);
1530				if (chan != NULL)
1531					chan = ieee80211_ht_adjust_channel(ic,
1532					    chan, vap->iv_flags_ext);
1533			} else
1534				chan = vap->iv_des_chan;
1535			if (chan != NULL) {
1536				ieee80211_create_ibss(vap, chan);
1537				return 1;
1538			}
1539		}
1540		/*
1541		 * If nothing suitable was found decrement
1542		 * the failure counts so entries will be
1543		 * reconsidered the next time around.  We
1544		 * really want to do this only for sta's
1545		 * where we've previously had some success.
1546		 */
1547		sta_dec_fails(st);
1548		st->st_newscan = 1;
1549		return 0;			/* restart scan */
1550	}
1551	selbs = select_bss(ss, vap, IEEE80211_MSG_SCAN);
1552	if (ss->ss_flags & IEEE80211_SCAN_NOJOIN)
1553		return (selbs != NULL);
1554	if (selbs == NULL)
1555		goto notfound;
1556	chan = selbs->base.se_chan;
1557	if (selbs->se_flags & STA_DEMOTE11B)
1558		chan = demote11b(vap, chan);
1559	if (!ieee80211_sta_join(vap, chan, &selbs->base))
1560		goto notfound;
1561	return 1;				/* terminate scan */
1562}
1563
1564/*
1565 * Age entries in the scan cache.
1566 */
1567static void
1568adhoc_age(struct ieee80211_scan_state *ss)
1569{
1570	struct sta_table *st = ss->ss_priv;
1571	struct sta_entry *se, *next;
1572
1573	mtx_lock(&st->st_lock);
1574	TAILQ_FOREACH_SAFE(se, &st->st_entry, se_list, next) {
1575		if (se->se_notseen > STA_PURGE_SCANS) {
1576			TAILQ_REMOVE(&st->st_entry, se, se_list);
1577			LIST_REMOVE(se, se_hash);
1578			ieee80211_ies_cleanup(&se->base.se_ies);
1579			free(se, M_80211_SCAN);
1580		}
1581	}
1582	mtx_unlock(&st->st_lock);
1583}
1584
1585static const struct ieee80211_scanner adhoc_default = {
1586	.scan_name		= "default",
1587	.scan_attach		= sta_attach,
1588	.scan_detach		= sta_detach,
1589	.scan_start		= adhoc_start,
1590	.scan_restart		= sta_restart,
1591	.scan_cancel		= sta_cancel,
1592	.scan_end		= adhoc_pick_bss,
1593	.scan_flush		= sta_flush,
1594	.scan_pickchan		= adhoc_pick_channel,
1595	.scan_add		= sta_add,
1596	.scan_age		= adhoc_age,
1597	.scan_iterate		= sta_iterate,
1598	.scan_assoc_fail	= sta_assoc_fail,
1599	.scan_assoc_success	= sta_assoc_success,
1600};
1601
1602static void
1603ap_force_promisc(struct ieee80211com *ic)
1604{
1605	struct ifnet *ifp = ic->ic_ifp;
1606
1607	IEEE80211_LOCK(ic);
1608	/* set interface into promiscuous mode */
1609	ifp->if_flags |= IFF_PROMISC;
1610	ic->ic_update_promisc(ifp);
1611	IEEE80211_UNLOCK(ic);
1612}
1613
1614static void
1615ap_reset_promisc(struct ieee80211com *ic)
1616{
1617	IEEE80211_LOCK(ic);
1618	ieee80211_syncifflag_locked(ic, IFF_PROMISC);
1619	IEEE80211_UNLOCK(ic);
1620}
1621
1622static int
1623ap_start(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1624{
1625	struct sta_table *st = ss->ss_priv;
1626
1627	makescanlist(ss, vap, staScanTable);
1628
1629	if (ss->ss_mindwell == 0)
1630		ss->ss_mindwell = msecs_to_ticks(200);	/* 200ms */
1631	if (ss->ss_maxdwell == 0)
1632		ss->ss_maxdwell = msecs_to_ticks(200);	/* 200ms */
1633
1634	st->st_scangen++;
1635	st->st_newscan = 1;
1636
1637	ap_force_promisc(vap->iv_ic);
1638	return 0;
1639}
1640
1641/*
1642 * Cancel an ongoing scan.
1643 */
1644static int
1645ap_cancel(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1646{
1647	ap_reset_promisc(vap->iv_ic);
1648	return 0;
1649}
1650
1651/*
1652 * Pick a quiet channel to use for ap operation.
1653 */
1654static struct ieee80211_channel *
1655ap_pick_channel(struct ieee80211_scan_state *ss, int flags)
1656{
1657	struct sta_table *st = ss->ss_priv;
1658	struct ieee80211_channel *bestchan = NULL;
1659	int i;
1660
1661	/* XXX select channel more intelligently, e.g. channel spread, power */
1662	/* NB: use scan list order to preserve channel preference */
1663	for (i = 0; i < ss->ss_last; i++) {
1664		struct ieee80211_channel *chan = ss->ss_chans[i];
1665		/*
1666		 * If the channel is unoccupied the max rssi
1667		 * should be zero; just take it.  Otherwise
1668		 * track the channel with the lowest rssi and
1669		 * use that when all channels appear occupied.
1670		 */
1671		if (IEEE80211_IS_CHAN_RADAR(chan))
1672			continue;
1673		if (IEEE80211_IS_CHAN_NOHOSTAP(chan))
1674			continue;
1675		/* check channel attributes for band compatibility */
1676		if (flags != 0 && (chan->ic_flags & flags) != flags)
1677			continue;
1678		KASSERT(sizeof(chan->ic_ieee) == 1, ("ic_chan size"));
1679		/* XXX channel have interference */
1680		if (st->st_maxrssi[chan->ic_ieee] == 0) {
1681			/* XXX use other considerations */
1682			return chan;
1683		}
1684		if (bestchan == NULL ||
1685		    st->st_maxrssi[chan->ic_ieee] < st->st_maxrssi[bestchan->ic_ieee])
1686			bestchan = chan;
1687	}
1688	return bestchan;
1689}
1690
1691/*
1692 * Pick a quiet channel to use for ap operation.
1693 */
1694static int
1695ap_end(struct ieee80211_scan_state *ss, struct ieee80211vap *vap)
1696{
1697	struct ieee80211com *ic = vap->iv_ic;
1698	struct ieee80211_channel *bestchan;
1699
1700	KASSERT(vap->iv_opmode == IEEE80211_M_HOSTAP,
1701		("wrong opmode %u", vap->iv_opmode));
1702	bestchan = ap_pick_channel(ss, 0);
1703	if (bestchan == NULL) {
1704		/* no suitable channel, should not happen */
1705		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
1706		    "%s: no suitable channel! (should not happen)\n", __func__);
1707		/* XXX print something? */
1708		return 0;			/* restart scan */
1709	}
1710	/*
1711	 * If this is a dynamic turbo channel, start with the unboosted one.
1712	 */
1713	if (IEEE80211_IS_CHAN_TURBO(bestchan)) {
1714		bestchan = ieee80211_find_channel(ic, bestchan->ic_freq,
1715			bestchan->ic_flags & ~IEEE80211_CHAN_TURBO);
1716		if (bestchan == NULL) {
1717			/* should never happen ?? */
1718			return 0;
1719		}
1720	}
1721	ap_reset_promisc(ic);
1722	if (ss->ss_flags & (IEEE80211_SCAN_NOPICK | IEEE80211_SCAN_NOJOIN)) {
1723		/*
1724		 * Manual/background scan, don't select+join the
1725		 * bss, just return.  The scanning framework will
1726		 * handle notification that this has completed.
1727		 */
1728		ss->ss_flags &= ~IEEE80211_SCAN_NOPICK;
1729		return 1;
1730	}
1731	ieee80211_create_ibss(vap,
1732	    ieee80211_ht_adjust_channel(ic, bestchan, vap->iv_flags_ext));
1733	return 1;
1734}
1735
1736static const struct ieee80211_scanner ap_default = {
1737	.scan_name		= "default",
1738	.scan_attach		= sta_attach,
1739	.scan_detach		= sta_detach,
1740	.scan_start		= ap_start,
1741	.scan_restart		= sta_restart,
1742	.scan_cancel		= ap_cancel,
1743	.scan_end		= ap_end,
1744	.scan_flush		= sta_flush,
1745	.scan_pickchan		= ap_pick_channel,
1746	.scan_add		= sta_add,
1747	.scan_age		= adhoc_age,
1748	.scan_iterate		= sta_iterate,
1749	.scan_assoc_success	= sta_assoc_success,
1750	.scan_assoc_fail	= sta_assoc_fail,
1751};
1752
1753/*
1754 * Module glue.
1755 */
1756IEEE80211_SCANNER_MODULE(sta, 1);
1757IEEE80211_SCANNER_ALG(sta, IEEE80211_M_STA, sta_default);
1758IEEE80211_SCANNER_ALG(ibss, IEEE80211_M_IBSS, adhoc_default);
1759IEEE80211_SCANNER_ALG(ahdemo, IEEE80211_M_AHDEMO, adhoc_default);
1760IEEE80211_SCANNER_ALG(ap, IEEE80211_M_HOSTAP, ap_default);
1761