ieee80211_scan_sta.c revision 170530
1/*-
2 * Copyright (c) 2002-2007 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 170530 2007-06-11 03:36:55Z sam $");
28
29/*
30 * IEEE 802.11 station scanning support.
31 */
32#include <sys/param.h>
33#include <sys/systm.h>
34#include <sys/kernel.h>
35#include <sys/module.h>
36
37#include <sys/socket.h>
38
39#include <net/if.h>
40#include <net/if_media.h>
41#include <net/ethernet.h>
42
43#include <net80211/ieee80211_var.h>
44
45#include <net/bpf.h>
46
47/*
48 * Parameters for managing cache entries:
49 *
50 * o a station with STA_FAILS_MAX failures is not considered
51 *   when picking a candidate
52 * o a station that hasn't had an update in STA_PURGE_SCANS
53 *   (background) scans is discarded
54 * o after STA_FAILS_AGE seconds we clear the failure count
55 */
56#define	STA_FAILS_MAX	2		/* assoc failures before ignored */
57#define	STA_FAILS_AGE	(2*60)		/* time before clearing fails (secs) */
58#define	STA_PURGE_SCANS	2		/* age for purging entries (scans) */
59
60/* XXX tunable */
61#define	STA_RSSI_MIN	8		/* min acceptable rssi */
62#define	STA_RSSI_MAX	40		/* max rssi for comparison */
63
64#define RSSI_LPF_LEN	10
65#define	RSSI_EP_MULTIPLIER	(1<<7)	/* pow2 to optimize out * and / */
66#define RSSI_IN(x)		((x) * RSSI_EP_MULTIPLIER)
67#define LPF_RSSI(x, y, len)	(((x) * ((len) - 1) + (y)) / (len))
68#define RSSI_LPF(x, y) do {						\
69    if ((y) >= -20)							\
70    	x = LPF_RSSI((x), RSSI_IN((y)), RSSI_LPF_LEN);			\
71} while (0)
72#define	EP_RND(x, mul) \
73	((((x)%(mul)) >= ((mul)/2)) ? howmany(x, mul) : (x)/(mul))
74#define	RSSI_GET(x)	EP_RND(x, RSSI_EP_MULTIPLIER)
75
76struct sta_entry {
77	struct ieee80211_scan_entry base;
78	TAILQ_ENTRY(sta_entry) se_list;
79	LIST_ENTRY(sta_entry) se_hash;
80	uint8_t		se_fails;		/* failure to associate count */
81	uint8_t		se_seen;		/* seen during current scan */
82	uint8_t		se_notseen;		/* not seen in previous scans */
83	uint8_t		se_flags;
84#define	STA_SSID_MATCH	0x01
85#define	STA_BSSID_MATCH	0x02
86	uint32_t	se_avgrssi;		/* LPF rssi state */
87	unsigned long	se_lastupdate;		/* time of last update */
88	unsigned long	se_lastfail;		/* time of last failure */
89	unsigned long	se_lastassoc;		/* time of last association */
90	u_int		se_scangen;		/* iterator scan gen# */
91};
92
93#define	STA_HASHSIZE	32
94/* simple hash is enough for variation of macaddr */
95#define	STA_HASH(addr)	\
96	(((const uint8_t *)(addr))[IEEE80211_ADDR_LEN - 1] % STA_HASHSIZE)
97
98struct sta_table {
99	struct mtx	st_lock;		/* on scan table */
100	TAILQ_HEAD(, sta_entry) st_entry;	/* all entries */
101	LIST_HEAD(, sta_entry) st_hash[STA_HASHSIZE];
102	struct mtx	st_scanlock;		/* on st_scangen */
103	u_int		st_scangen;		/* gen# for iterator */
104	int		st_newscan;
105};
106
107static void sta_flush_table(struct sta_table *);
108static int match_bss(struct ieee80211com *,
109	const struct ieee80211_scan_state *, struct sta_entry *, int);
110
111/* number of references from net80211 layer */
112static	int nrefs = 0;
113
114/*
115 * Attach prior to any scanning work.
116 */
117static int
118sta_attach(struct ieee80211_scan_state *ss)
119{
120	struct sta_table *st;
121
122	MALLOC(st, struct sta_table *, sizeof(struct sta_table),
123		M_80211_SCAN, M_NOWAIT | M_ZERO);
124	if (st == NULL)
125		return 0;
126	mtx_init(&st->st_lock, "scantable", "802.11 scan table", MTX_DEF);
127	mtx_init(&st->st_scanlock, "scangen", "802.11 scangen", MTX_DEF);
128	TAILQ_INIT(&st->st_entry);
129	ss->ss_priv = st;
130	nrefs++;			/* NB: we assume caller locking */
131	return 1;
132}
133
134/*
135 * Cleanup any private state.
136 */
137static int
138sta_detach(struct ieee80211_scan_state *ss)
139{
140	struct sta_table *st = ss->ss_priv;
141
142	if (st != NULL) {
143		sta_flush_table(st);
144		mtx_destroy(&st->st_lock);
145		mtx_destroy(&st->st_scanlock);
146		FREE(st, M_80211_SCAN);
147		KASSERT(nrefs > 0, ("imbalanced attach/detach"));
148		nrefs--;		/* NB: we assume caller locking */
149	}
150	return 1;
151}
152
153/*
154 * Flush all per-scan state.
155 */
156static int
157sta_flush(struct ieee80211_scan_state *ss)
158{
159	struct sta_table *st = ss->ss_priv;
160
161	mtx_lock(&st->st_lock);
162	sta_flush_table(st);
163	mtx_unlock(&st->st_lock);
164	ss->ss_last = 0;
165	return 0;
166}
167
168/*
169 * Flush all entries in the scan cache.
170 */
171static void
172sta_flush_table(struct sta_table *st)
173{
174	struct sta_entry *se, *next;
175
176	TAILQ_FOREACH_SAFE(se, &st->st_entry, se_list, next) {
177		TAILQ_REMOVE(&st->st_entry, se, se_list);
178		LIST_REMOVE(se, se_hash);
179		FREE(se, M_80211_SCAN);
180	}
181}
182
183static void
184saveie(uint8_t **iep, const uint8_t *ie)
185{
186
187	if (ie == NULL)
188		*iep = NULL;
189	else
190		ieee80211_saveie(iep, ie);
191}
192
193/*
194 * Process a beacon or probe response frame; create an
195 * entry in the scan cache or update any previous entry.
196 */
197static int
198sta_add(struct ieee80211_scan_state *ss,
199	const struct ieee80211_scanparams *sp,
200	const struct ieee80211_frame *wh,
201	int subtype, int rssi, int noise, int rstamp)
202{
203#define	ISPROBE(_st)	((_st) == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
204#define	PICK1ST(_ss) \
205	((ss->ss_flags & (IEEE80211_SCAN_PICK1ST | IEEE80211_SCAN_GOTPICK)) == \
206	IEEE80211_SCAN_PICK1ST)
207	struct sta_table *st = ss->ss_priv;
208	const uint8_t *macaddr = wh->i_addr2;
209	struct ieee80211com *ic = ss->ss_ic;
210	struct sta_entry *se;
211	struct ieee80211_scan_entry *ise;
212	int hash;
213
214	hash = STA_HASH(macaddr);
215
216	mtx_lock(&st->st_lock);
217	LIST_FOREACH(se, &st->st_hash[hash], se_hash)
218		if (IEEE80211_ADDR_EQ(se->base.se_macaddr, macaddr))
219			goto found;
220	MALLOC(se, struct sta_entry *, sizeof(struct sta_entry),
221		M_80211_SCAN, M_NOWAIT | M_ZERO);
222	if (se == NULL) {
223		mtx_unlock(&st->st_lock);
224		return 0;
225	}
226	se->se_scangen = st->st_scangen-1;
227	IEEE80211_ADDR_COPY(se->base.se_macaddr, macaddr);
228	TAILQ_INSERT_TAIL(&st->st_entry, se, se_list);
229	LIST_INSERT_HEAD(&st->st_hash[hash], se, se_hash);
230found:
231	ise = &se->base;
232	/* XXX ap beaconing multiple ssid w/ same bssid */
233	if (sp->ssid[1] != 0 &&
234	    (ISPROBE(subtype) || ise->se_ssid[1] == 0))
235		memcpy(ise->se_ssid, sp->ssid, 2+sp->ssid[1]);
236	KASSERT(sp->rates[1] <= IEEE80211_RATE_MAXSIZE,
237		("rate set too large: %u", sp->rates[1]));
238	memcpy(ise->se_rates, sp->rates, 2+sp->rates[1]);
239	if (sp->xrates != NULL) {
240		/* XXX validate xrates[1] */
241		KASSERT(sp->xrates[1] + sp->rates[1] <= IEEE80211_RATE_MAXSIZE,
242			("xrate set too large: %u", sp->xrates[1]));
243		memcpy(ise->se_xrates, sp->xrates, 2+sp->xrates[1]);
244	} else
245		ise->se_xrates[1] = 0;
246	IEEE80211_ADDR_COPY(ise->se_bssid, wh->i_addr3);
247	/*
248	 * Record rssi data using extended precision LPF filter.
249	 */
250	if (se->se_lastupdate == 0)		/* first sample */
251		se->se_avgrssi = RSSI_IN(rssi);
252	else					/* avg w/ previous samples */
253		RSSI_LPF(se->se_avgrssi, rssi);
254	se->base.se_rssi = RSSI_GET(se->se_avgrssi);
255	se->base.se_noise = noise;
256	ise->se_rstamp = rstamp;
257	memcpy(ise->se_tstamp.data, sp->tstamp, sizeof(ise->se_tstamp));
258	ise->se_intval = sp->bintval;
259	ise->se_capinfo = sp->capinfo;
260	ise->se_chan = ic->ic_curchan;
261	ise->se_fhdwell = sp->fhdwell;
262	ise->se_fhindex = sp->fhindex;
263	ise->se_erp = sp->erp;
264	ise->se_timoff = sp->timoff;
265	if (sp->tim != NULL) {
266		const struct ieee80211_tim_ie *tim =
267		    (const struct ieee80211_tim_ie *) sp->tim;
268		ise->se_dtimperiod = tim->tim_period;
269	}
270	saveie(&ise->se_wme_ie, sp->wme);
271	saveie(&ise->se_wpa_ie, sp->wpa);
272	saveie(&ise->se_rsn_ie, sp->rsn);
273	saveie(&ise->se_ath_ie, sp->ath);
274	saveie(&ise->se_htcap_ie, sp->htcap);
275	saveie(&ise->se_htinfo_ie, sp->htinfo);
276
277	/* clear failure count after STA_FAIL_AGE passes */
278	if (se->se_fails && (ticks - se->se_lastfail) > STA_FAILS_AGE*hz) {
279		se->se_fails = 0;
280		IEEE80211_NOTE_MAC(ic, IEEE80211_MSG_SCAN, macaddr,
281		    "%s: fails %u", __func__, se->se_fails);
282	}
283
284	se->se_lastupdate = ticks;		/* update time */
285	se->se_seen = 1;
286	se->se_notseen = 0;
287
288	mtx_unlock(&st->st_lock);
289
290	/*
291	 * If looking for a quick choice and nothing's
292	 * been found check here.
293	 */
294	if (PICK1ST(ss) && match_bss(ic, ss, se, IEEE80211_MSG_SCAN) == 0)
295		ss->ss_flags |= IEEE80211_SCAN_GOTPICK;
296
297	return 1;
298#undef PICK1ST
299#undef ISPROBE
300}
301
302/*
303 * Check if a channel is excluded by user request.
304 */
305static int
306isexcluded(struct ieee80211com *ic, const struct ieee80211_channel *c)
307{
308	return (isclr(ic->ic_chan_active, c->ic_ieee) ||
309	    (ic->ic_des_chan != IEEE80211_CHAN_ANYC &&
310	     c->ic_freq != ic->ic_des_chan->ic_freq));
311}
312
313static struct ieee80211_channel *
314find11gchannel(struct ieee80211com *ic, int i, int freq)
315{
316	struct ieee80211_channel *c;
317	int j;
318
319	/*
320	 * The normal ordering in the channel list is b channel
321	 * immediately followed by g so optimize the search for
322	 * this.  We'll still do a full search just in case.
323	 */
324	for (j = i+1; j < ic->ic_nchans; j++) {
325		c = &ic->ic_channels[j];
326		if (c->ic_freq == freq && IEEE80211_IS_CHAN_ANYG(c))
327			return c;
328	}
329	for (j = 0; j < i; j++) {
330		c = &ic->ic_channels[j];
331		if (c->ic_freq == freq && IEEE80211_IS_CHAN_ANYG(c))
332			return c;
333	}
334	return NULL;
335}
336static const u_int chanflags[IEEE80211_MODE_MAX] = {
337	IEEE80211_CHAN_B,	/* IEEE80211_MODE_AUTO */
338	IEEE80211_CHAN_A,	/* IEEE80211_MODE_11A */
339	IEEE80211_CHAN_B,	/* IEEE80211_MODE_11B */
340	IEEE80211_CHAN_G,	/* IEEE80211_MODE_11G */
341	IEEE80211_CHAN_FHSS,	/* IEEE80211_MODE_FH */
342	IEEE80211_CHAN_A,	/* IEEE80211_MODE_TURBO_A (check base channel)*/
343	IEEE80211_CHAN_G,	/* IEEE80211_MODE_TURBO_G */
344	IEEE80211_CHAN_ST,	/* IEEE80211_MODE_STURBO_A */
345	IEEE80211_CHAN_A,	/* IEEE80211_MODE_11NA (check legacy) */
346	IEEE80211_CHAN_G,	/* IEEE80211_MODE_11NG (check legacy) */
347};
348
349static void
350add_channels(struct ieee80211com *ic,
351	struct ieee80211_scan_state *ss,
352	enum ieee80211_phymode mode, const uint16_t freq[], int nfreq)
353{
354#define	N(a)	(sizeof(a) / sizeof(a[0]))
355	struct ieee80211_channel *c, *cg;
356	u_int modeflags;
357	int i;
358
359	KASSERT(mode < N(chanflags), ("Unexpected mode %u", mode));
360	modeflags = chanflags[mode];
361	for (i = 0; i < nfreq; i++) {
362		if (ss->ss_last >= IEEE80211_SCAN_MAX)
363			break;
364
365		c = ieee80211_find_channel(ic, freq[i], modeflags);
366		if (c == NULL || isexcluded(ic, c))
367			continue;
368		if (mode == IEEE80211_MODE_AUTO) {
369			/*
370			 * XXX special-case 11b/g channels so we select
371			 *     the g channel if both are present.
372			 */
373			if (IEEE80211_IS_CHAN_B(c) &&
374			    (cg = find11gchannel(ic, i, c->ic_freq)) != NULL)
375				c = cg;
376		}
377		ss->ss_chans[ss->ss_last++] = c;
378	}
379#undef N
380}
381
382static const uint16_t rcl1[] =		/* 8 FCC channel: 52, 56, 60, 64, 36, 40, 44, 48 */
383{ 5260, 5280, 5300, 5320, 5180, 5200, 5220, 5240 };
384static const uint16_t rcl2[] =		/* 4 MKK channels: 34, 38, 42, 46 */
385{ 5170, 5190, 5210, 5230 };
386static const uint16_t rcl3[] =		/* 2.4Ghz ch: 1,6,11,7,13 */
387{ 2412, 2437, 2462, 2442, 2472 };
388static const uint16_t rcl4[] =		/* 5 FCC channel: 149, 153, 161, 165 */
389{ 5745, 5765, 5785, 5805, 5825 };
390static const uint16_t rcl7[] =		/* 11 ETSI channel: 100,104,108,112,116,120,124,128,132,136,140 */
391{ 5500, 5520, 5540, 5560, 5580, 5600, 5620, 5640, 5660, 5680, 5700 };
392static const uint16_t rcl8[] =		/* 2.4Ghz ch: 2,3,4,5,8,9,10,12 */
393{ 2417, 2422, 2427, 2432, 2447, 2452, 2457, 2467 };
394static const uint16_t rcl9[] =		/* 2.4Ghz ch: 14 */
395{ 2484 };
396static const uint16_t rcl10[] =		/* Added Korean channels 2312-2372 */
397{ 2312, 2317, 2322, 2327, 2332, 2337, 2342, 2347, 2352, 2357, 2362, 2367, 2372 };
398static const uint16_t rcl11[] =		/* Added Japan channels in 4.9/5.0 spectrum */
399{ 5040, 5060, 5080, 4920, 4940, 4960, 4980 };
400#ifdef ATH_TURBO_SCAN
401static const uint16_t rcl5[] =		/* 3 static turbo channels */
402{ 5210, 5250, 5290 };
403static const uint16_t rcl6[] =		/* 2 static turbo channels */
404{ 5760, 5800 };
405static const uint16_t rcl6x[] =		/* 4 FCC3 turbo channels */
406{ 5540, 5580, 5620, 5660 };
407static const uint16_t rcl12[] =		/* 2.4Ghz Turbo channel 6 */
408{ 2437 };
409static const uint16_t rcl13[] =		/* dynamic Turbo channels */
410{ 5200, 5240, 5280, 5765, 5805 };
411#endif /* ATH_TURBO_SCAN */
412
413struct scanlist {
414	uint16_t	mode;
415	uint16_t	count;
416	const uint16_t	*list;
417};
418
419#define	X(a)	.count = sizeof(a)/sizeof(a[0]), .list = a
420
421static const struct scanlist staScanTable[] = {
422	{ IEEE80211_MODE_11B,   	X(rcl3) },
423	{ IEEE80211_MODE_11A,   	X(rcl1) },
424	{ IEEE80211_MODE_11A,   	X(rcl2) },
425	{ IEEE80211_MODE_11B,   	X(rcl8) },
426	{ IEEE80211_MODE_11B,   	X(rcl9) },
427	{ IEEE80211_MODE_11A,   	X(rcl4) },
428#ifdef ATH_TURBO_SCAN
429	{ IEEE80211_MODE_STURBO_A,	X(rcl5) },
430	{ IEEE80211_MODE_STURBO_A,	X(rcl6) },
431	{ IEEE80211_MODE_TURBO_A,	X(rcl6x) },
432	{ IEEE80211_MODE_TURBO_A,	X(rcl13) },
433#endif /* ATH_TURBO_SCAN */
434	{ IEEE80211_MODE_11A,		X(rcl7) },
435	{ IEEE80211_MODE_11B,		X(rcl10) },
436	{ IEEE80211_MODE_11A,		X(rcl11) },
437#ifdef ATH_TURBO_SCAN
438	{ IEEE80211_MODE_TURBO_G,	X(rcl12) },
439#endif /* ATH_TURBO_SCAN */
440	{ .list = NULL }
441};
442
443static int
444checktable(const struct scanlist *scan, const struct ieee80211_channel *c)
445{
446	int i;
447
448	for (; scan->list != NULL; scan++) {
449		for (i = 0; i < scan->count; i++)
450			if (scan->list[i] == c->ic_freq)
451				return 1;
452	}
453	return 0;
454}
455
456/*
457 * Start a station-mode scan by populating the channel list.
458 */
459static int
460sta_start(struct ieee80211_scan_state *ss, struct ieee80211com *ic)
461{
462#define	N(a)	(sizeof(a)/sizeof(a[0]))
463	struct sta_table *st = ss->ss_priv;
464	const struct scanlist *scan;
465	enum ieee80211_phymode mode;
466	struct ieee80211_channel *c;
467	int i;
468
469	ss->ss_last = 0;
470	/*
471	 * Use the table of ordered channels to construct the list
472	 * of channels for scanning.  Any channels in the ordered
473	 * list not in the master list will be discarded.
474	 */
475	for (scan = staScanTable; scan->list != NULL; scan++) {
476		mode = scan->mode;
477		if (ic->ic_des_mode != IEEE80211_MODE_AUTO) {
478			/*
479			 * If a desired mode was specified, scan only
480			 * channels that satisfy that constraint.
481			 */
482			if (ic->ic_des_mode != mode) {
483				/*
484				 * The scan table marks 2.4Ghz channels as b
485				 * so if the desired mode is 11g, then use
486				 * the 11b channel list but upgrade the mode.
487				 */
488				if (ic->ic_des_mode != IEEE80211_MODE_11G ||
489				    mode != IEEE80211_MODE_11B)
490					continue;
491				mode = IEEE80211_MODE_11G;	/* upgrade */
492			}
493		} else {
494			/*
495			 * This lets add_channels upgrade an 11b channel
496			 * to 11g if available.
497			 */
498			if (mode == IEEE80211_MODE_11B)
499				mode = IEEE80211_MODE_AUTO;
500		}
501#ifdef IEEE80211_F_XR
502		/* XR does not operate on turbo channels */
503		if ((ic->ic_flags & IEEE80211_F_XR) &&
504		    (mode == IEEE80211_MODE_TURBO_A ||
505		     mode == IEEE80211_MODE_TURBO_G ||
506		     mode == IEEE80211_MODE_STURBO_A))
507			continue;
508#endif
509		/*
510		 * Add the list of the channels; any that are not
511		 * in the master channel list will be discarded.
512		 */
513		add_channels(ic, ss, mode, scan->list, scan->count);
514	}
515
516	/*
517	 * Add the channels from the ic (from HAL) that are not present
518	 * in the staScanTable.
519	 */
520	for (i = 0; i < ic->ic_nchans; i++) {
521		if (ss->ss_last >= IEEE80211_SCAN_MAX)
522			break;
523
524		c = &ic->ic_channels[i];
525		/*
526		 * Ignore dynamic turbo channels; we scan them
527		 * in normal mode (i.e. not boosted).  Likewise
528		 * for HT channels, they get scanned using
529		 * legacy rates.
530		 */
531		if (IEEE80211_IS_CHAN_DTURBO(c) || IEEE80211_IS_CHAN_HT(c))
532			continue;
533
534		/*
535		 * If a desired mode was specified, scan only
536		 * channels that satisfy that constraint.
537		 */
538		if (ic->ic_des_mode != IEEE80211_MODE_AUTO &&
539		    ic->ic_des_mode != ieee80211_chan2mode(c))
540			continue;
541
542		/*
543		 * Skip channels excluded by user request.
544		 */
545		if (isexcluded(ic, c))
546			continue;
547
548		/*
549		 * Add the channel unless it is listed in the
550		 * fixed scan order tables.  This insures we
551		 * don't sweep back in channels we filtered out
552		 * above.
553		 */
554		if (checktable(staScanTable, c))
555			continue;
556
557		/* Add channel to scanning list. */
558		ss->ss_chans[ss->ss_last++] = c;
559	}
560
561	ss->ss_next = 0;
562	/* XXX tunables */
563	ss->ss_mindwell = msecs_to_ticks(20);		/* 20ms */
564	ss->ss_maxdwell = msecs_to_ticks(200);		/* 200ms */
565
566#ifdef IEEE80211_DEBUG
567	if (ieee80211_msg_scan(ic)) {
568		if_printf(ic->ic_ifp, "scan set ");
569		ieee80211_scan_dump_channels(ss);
570		printf(" dwell min %ld max %ld\n",
571			ss->ss_mindwell, ss->ss_maxdwell);
572	}
573#endif /* IEEE80211_DEBUG */
574
575	st->st_newscan = 1;
576
577	return 0;
578#undef N
579}
580
581/*
582 * Restart a bg scan.
583 */
584static int
585sta_restart(struct ieee80211_scan_state *ss, struct ieee80211com *ic)
586{
587	struct sta_table *st = ss->ss_priv;
588
589	st->st_newscan = 1;
590	return 0;
591}
592
593/*
594 * Cancel an ongoing scan.
595 */
596static int
597sta_cancel(struct ieee80211_scan_state *ss, struct ieee80211com *ic)
598{
599	return 0;
600}
601
602static uint8_t
603maxrate(const struct ieee80211_scan_entry *se)
604{
605	uint8_t rmax, r;
606	int i;
607
608	rmax = 0;
609	for (i = 0; i < se->se_rates[1]; i++) {
610		r = se->se_rates[2+i] & IEEE80211_RATE_VAL;
611		if (r > rmax)
612			rmax = r;
613	}
614	for (i = 0; i < se->se_xrates[1]; i++) {
615		r = se->se_xrates[2+i] & IEEE80211_RATE_VAL;
616		if (r > rmax)
617			rmax = r;
618	}
619	return rmax;
620}
621
622/*
623 * Compare the capabilities of two entries and decide which is
624 * more desirable (return >0 if a is considered better).  Note
625 * that we assume compatibility/usability has already been checked
626 * so we don't need to (e.g. validate whether privacy is supported).
627 * Used to select the best scan candidate for association in a BSS.
628 */
629static int
630sta_compare(const struct sta_entry *a, const struct sta_entry *b)
631{
632#define	PREFER(_a,_b,_what) do {			\
633	if (((_a) ^ (_b)) & (_what))			\
634		return ((_a) & (_what)) ? 1 : -1;	\
635} while (0)
636	uint8_t maxa, maxb;
637	int8_t rssia, rssib;
638	int weight;
639
640	/* desired bssid */
641	PREFER(a->se_flags, b->se_flags, STA_BSSID_MATCH);
642	/* desired ssid */
643	PREFER(a->se_flags, b->se_flags, STA_SSID_MATCH);
644	/* privacy support */
645	PREFER(a->base.se_capinfo, b->base.se_capinfo,
646		IEEE80211_CAPINFO_PRIVACY);
647
648	/* compare count of previous failures */
649	weight = b->se_fails - a->se_fails;
650	if (abs(weight) > 1)
651		return weight;
652
653	/*
654	 * Compare rssi.  If the two are considered equivalent
655	 * then fallback to other criteria.  We threshold the
656	 * comparisons to avoid selecting an ap purely by rssi
657	 * when both values may be good but one ap is otherwise
658	 * more desirable (e.g. an 11b-only ap with stronger
659	 * signal than an 11g ap).
660	 */
661	rssia = MIN(a->base.se_rssi, STA_RSSI_MAX);
662	rssib = MIN(b->base.se_rssi, STA_RSSI_MAX);
663	if (abs(rssib - rssia) < 5) {
664		/* best/max rate preferred if signal level close enough XXX */
665		maxa = maxrate(&a->base);
666		maxb = maxrate(&b->base);
667		if (maxa != maxb)
668			return maxa - maxb;
669		/* XXX use freq for channel preference */
670		/* for now just prefer 5Ghz band to all other bands */
671		if (IEEE80211_IS_CHAN_5GHZ(a->base.se_chan) &&
672		   !IEEE80211_IS_CHAN_5GHZ(b->base.se_chan))
673			return 1;
674		if (!IEEE80211_IS_CHAN_5GHZ(a->base.se_chan) &&
675		     IEEE80211_IS_CHAN_5GHZ(b->base.se_chan))
676			return -1;
677	}
678	/* all things being equal, use signal level */
679	return a->base.se_rssi - b->base.se_rssi;
680#undef PREFER
681}
682
683/*
684 * Check rate set suitability and return the best supported rate.
685 */
686static int
687check_rate(struct ieee80211com *ic, const struct ieee80211_scan_entry *se)
688{
689#define	RV(v)	((v) & IEEE80211_RATE_VAL)
690	const struct ieee80211_rateset *srs;
691	int i, j, nrs, r, okrate, badrate, fixedrate;
692	const uint8_t *rs;
693
694	okrate = badrate = fixedrate = 0;
695
696	srs = ieee80211_get_suprates(ic, se->se_chan);
697	nrs = se->se_rates[1];
698	rs = se->se_rates+2;
699	fixedrate = IEEE80211_FIXED_RATE_NONE;
700again:
701	for (i = 0; i < nrs; i++) {
702		r = RV(rs[i]);
703		badrate = r;
704		/*
705		 * Check any fixed rate is included.
706		 */
707		if (r == ic->ic_fixed_rate)
708			fixedrate = r;
709		/*
710		 * Check against our supported rates.
711		 */
712		for (j = 0; j < srs->rs_nrates; j++)
713			if (r == RV(srs->rs_rates[j])) {
714				if (r > okrate)		/* NB: track max */
715					okrate = r;
716				break;
717			}
718
719		if (j == srs->rs_nrates && (rs[i] & IEEE80211_RATE_BASIC)) {
720			/*
721			 * Don't try joining a BSS, if we don't support
722			 * one of its basic rates.
723			 */
724			okrate = 0;
725			goto back;
726		}
727	}
728	if (rs == se->se_rates+2) {
729		/* scan xrates too; sort of an algol68-style for loop */
730		nrs = se->se_xrates[1];
731		rs = se->se_xrates+2;
732		goto again;
733	}
734
735back:
736	if (okrate == 0 || ic->ic_fixed_rate != fixedrate)
737		return badrate | IEEE80211_RATE_BASIC;
738	else
739		return RV(okrate);
740#undef RV
741}
742
743static int
744match_ssid(const uint8_t *ie,
745	int nssid, const struct ieee80211_scan_ssid ssids[])
746{
747	int i;
748
749	for (i = 0; i < nssid; i++) {
750		if (ie[1] == ssids[i].len &&
751		     memcmp(ie+2, ssids[i].ssid, ie[1]) == 0)
752			return 1;
753	}
754	return 0;
755}
756
757/*
758 * Test a scan candidate for suitability/compatibility.
759 */
760static int
761match_bss(struct ieee80211com *ic,
762	const struct ieee80211_scan_state *ss, struct sta_entry *se0,
763	int debug)
764{
765	struct ieee80211_scan_entry *se = &se0->base;
766	uint8_t rate;
767	int fail;
768
769	fail = 0;
770	if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, se->se_chan)))
771		fail |= 0x01;
772	/*
773	 * NB: normally the desired mode is used to construct
774	 * the channel list, but it's possible for the scan
775	 * cache to include entries for stations outside this
776	 * list so we check the desired mode here to weed them
777	 * out.
778	 */
779	if (ic->ic_des_mode != IEEE80211_MODE_AUTO &&
780	    (se->se_chan->ic_flags & IEEE80211_CHAN_ALLTURBO) !=
781	    chanflags[ic->ic_des_mode])
782		fail |= 0x01;
783	if (ic->ic_opmode == IEEE80211_M_IBSS) {
784		if ((se->se_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
785			fail |= 0x02;
786	} else {
787		if ((se->se_capinfo & IEEE80211_CAPINFO_ESS) == 0)
788			fail |= 0x02;
789	}
790	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
791		if ((se->se_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
792			fail |= 0x04;
793	} else {
794		/* XXX does this mean privacy is supported or required? */
795		if (se->se_capinfo & IEEE80211_CAPINFO_PRIVACY)
796			fail |= 0x04;
797	}
798	rate = check_rate(ic, se);
799	if (rate & IEEE80211_RATE_BASIC)
800		fail |= 0x08;
801	if (ss->ss_nssid != 0 &&
802	    match_ssid(se->se_ssid, ss->ss_nssid, ss->ss_ssid))
803		se0->se_flags |= STA_SSID_MATCH;
804	else
805		se0->se_flags &= ~STA_SSID_MATCH;
806	if ((ic->ic_flags & IEEE80211_F_DESBSSID) &&
807	    IEEE80211_ADDR_EQ(ic->ic_des_bssid, se->se_bssid))
808		se0->se_flags |= STA_BSSID_MATCH;
809	else
810		se0->se_flags &= ~STA_BSSID_MATCH;
811	if (se0->se_fails >= STA_FAILS_MAX)
812		fail |= 0x40;
813	if (se0->se_notseen >= STA_PURGE_SCANS)
814		fail |= 0x80;
815	if (se->se_rssi < STA_RSSI_MIN)
816		fail |= 0x100;
817#ifdef IEEE80211_DEBUG
818	if (ieee80211_msg(ic, debug)) {
819		printf(" %c %s",
820		    fail & 0x40 ? '=' : fail & 0x80 ? '^' : fail ? '-' : '+',
821		    ether_sprintf(se->se_macaddr));
822		printf(" %s%c", ether_sprintf(se->se_bssid),
823		    se0->se_flags & STA_BSSID_MATCH ? '*' : ' ');
824		printf(" %3d%c", ieee80211_chan2ieee(ic, se->se_chan),
825			fail & 0x01 ? '!' : ' ');
826		printf(" %+4d%c", se->se_rssi, fail & 0x100 ? '!' : ' ');
827		printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
828		    fail & 0x08 ? '!' : ' ');
829		printf(" %4s%c",
830		    (se->se_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
831		    (se->se_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
832		    "????",
833		    fail & 0x02 ? '!' : ' ');
834		printf(" %3s%c ",
835		    (se->se_capinfo & IEEE80211_CAPINFO_PRIVACY) ?
836		    "wep" : "no",
837		    fail & 0x04 ? '!' : ' ');
838		ieee80211_print_essid(se->se_ssid+2, se->se_ssid[1]);
839		printf("%s\n", se0->se_flags & STA_SSID_MATCH ? "*" : "");
840	}
841#endif
842	return fail;
843}
844
845static void
846sta_update_notseen(struct sta_table *st)
847{
848	struct sta_entry *se;
849
850	mtx_lock(&st->st_lock);
851	TAILQ_FOREACH(se, &st->st_entry, se_list) {
852		/*
853		 * If seen the reset and don't bump the count;
854		 * otherwise bump the ``not seen'' count.  Note
855		 * that this insures that stations for which we
856		 * see frames while not scanning but not during
857		 * this scan will not be penalized.
858		 */
859		if (se->se_seen)
860			se->se_seen = 0;
861		else
862			se->se_notseen++;
863	}
864	mtx_unlock(&st->st_lock);
865}
866
867static void
868sta_dec_fails(struct sta_table *st)
869{
870	struct sta_entry *se;
871
872	mtx_lock(&st->st_lock);
873	TAILQ_FOREACH(se, &st->st_entry, se_list)
874		if (se->se_fails)
875			se->se_fails--;
876	mtx_unlock(&st->st_lock);
877}
878
879static struct sta_entry *
880select_bss(struct ieee80211_scan_state *ss, struct ieee80211com *ic, int debug)
881{
882	struct sta_table *st = ss->ss_priv;
883	struct sta_entry *se, *selbs = NULL;
884
885	IEEE80211_DPRINTF(ic, debug, " %s\n",
886	    "macaddr          bssid         chan  rssi  rate flag  wep  essid");
887	mtx_lock(&st->st_lock);
888	TAILQ_FOREACH(se, &st->st_entry, se_list) {
889		if (match_bss(ic, ss, se, debug) == 0) {
890			if (selbs == NULL)
891				selbs = se;
892			else if (sta_compare(se, selbs) > 0)
893				selbs = se;
894		}
895	}
896	mtx_unlock(&st->st_lock);
897
898	return selbs;
899}
900
901/*
902 * Pick an ap or ibss network to join or find a channel
903 * to use to start an ibss network.
904 */
905static int
906sta_pick_bss(struct ieee80211_scan_state *ss, struct ieee80211com *ic)
907{
908	struct sta_table *st = ss->ss_priv;
909	struct sta_entry *selbs;
910
911	KASSERT(ic->ic_opmode == IEEE80211_M_STA,
912		("wrong mode %u", ic->ic_opmode));
913
914	if (st->st_newscan) {
915		sta_update_notseen(st);
916		st->st_newscan = 0;
917	}
918	if (ss->ss_flags & IEEE80211_SCAN_NOPICK) {
919		/*
920		 * Manual/background scan, don't select+join the
921		 * bss, just return.  The scanning framework will
922		 * handle notification that this has completed.
923		 */
924		ss->ss_flags &= ~IEEE80211_SCAN_NOPICK;
925		return 1;
926	}
927	/*
928	 * Automatic sequencing; look for a candidate and
929	 * if found join the network.
930	 */
931	/* NB: unlocked read should be ok */
932	if (TAILQ_FIRST(&st->st_entry) == NULL) {
933		IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
934			"%s: no scan candidate\n", __func__);
935notfound:
936		/*
937		 * If nothing suitable was found decrement
938		 * the failure counts so entries will be
939		 * reconsidered the next time around.  We
940		 * really want to do this only for sta's
941		 * where we've previously had some success.
942		 */
943		sta_dec_fails(st);
944		st->st_newscan = 1;
945		return 0;			/* restart scan */
946	}
947	selbs = select_bss(ss, ic, IEEE80211_MSG_SCAN);
948	if (selbs == NULL || !ieee80211_sta_join(ic, &selbs->base))
949		goto notfound;
950	return 1;				/* terminate scan */
951}
952
953/*
954 * Lookup an entry in the scan cache.  We assume we're
955 * called from the bottom half or such that we don't need
956 * to block the bottom half so that it's safe to return
957 * a reference to an entry w/o holding the lock on the table.
958 */
959static struct sta_entry *
960sta_lookup(struct sta_table *st, const uint8_t macaddr[IEEE80211_ADDR_LEN])
961{
962	struct sta_entry *se;
963	int hash = STA_HASH(macaddr);
964
965	mtx_lock(&st->st_lock);
966	LIST_FOREACH(se, &st->st_hash[hash], se_hash)
967		if (IEEE80211_ADDR_EQ(se->base.se_macaddr, macaddr))
968			break;
969	mtx_unlock(&st->st_lock);
970
971	return se;		/* NB: unlocked */
972}
973
974static void
975sta_roam_check(struct ieee80211_scan_state *ss, struct ieee80211com *ic)
976{
977	struct ieee80211_node *ni = ic->ic_bss;
978	struct sta_table *st = ss->ss_priv;
979	struct sta_entry *se, *selbs;
980	uint8_t roamRate, curRate;
981	int8_t roamRssi, curRssi;
982
983	se = sta_lookup(st, ni->ni_macaddr);
984	if (se == NULL) {
985		/* XXX something is wrong */
986		return;
987	}
988
989	/* XXX do we need 11g too? */
990	if (IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan)) {
991		roamRate = ic->ic_roam.rate11b;
992		roamRssi = ic->ic_roam.rssi11b;
993	} else if (IEEE80211_IS_CHAN_B(ic->ic_bsschan)) {
994		roamRate = ic->ic_roam.rate11bOnly;
995		roamRssi = ic->ic_roam.rssi11bOnly;
996	} else {
997		roamRate = ic->ic_roam.rate11a;
998		roamRssi = ic->ic_roam.rssi11a;
999	}
1000	/* NB: the most up to date rssi is in the node, not the scan cache */
1001	curRssi = ic->ic_node_getrssi(ni);
1002	if (ic->ic_fixed_rate == IEEE80211_FIXED_RATE_NONE) {
1003		curRate = ni->ni_rates.rs_rates[ni->ni_txrate] & IEEE80211_RATE_VAL;
1004		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ROAM,
1005		    "%s: currssi %d currate %u roamrssi %d roamrate %u\n",
1006		    __func__, curRssi, curRate, roamRssi, roamRate);
1007	} else {
1008		curRate = roamRate;	/* NB: insure compare below fails */
1009		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ROAM,
1010		    "%s: currssi %d roamrssi %d\n", __func__, curRssi, roamRssi);
1011	}
1012	/*
1013	 * Check if a new ap should be used and switch.
1014	 * XXX deauth current ap
1015	 */
1016	if (curRate < roamRate || curRssi < roamRssi) {
1017		if (time_after(ticks, ic->ic_lastscan + ic->ic_scanvalid)) {
1018			/*
1019			 * Scan cache contents are too old; force a scan now
1020			 * if possible so we have current state to make a
1021			 * decision with.  We don't kick off a bg scan if
1022			 * we're using dynamic turbo and boosted or if the
1023			 * channel is busy.
1024			 * XXX force immediate switch on scan complete
1025			 */
1026			if (!IEEE80211_IS_CHAN_DTURBO(ic->ic_curchan) &&
1027			    time_after(ticks, ic->ic_lastdata + ic->ic_bgscanidle))
1028				ieee80211_bg_scan(ic);
1029			return;
1030		}
1031		se->base.se_rssi = curRssi;
1032		selbs = select_bss(ss, ic, IEEE80211_MSG_ROAM);
1033		if (selbs != NULL && selbs != se) {
1034			IEEE80211_DPRINTF(ic,
1035			    IEEE80211_MSG_ROAM | IEEE80211_MSG_DEBUG,
1036			    "%s: ROAM: curRate %u, roamRate %u, "
1037			    "curRssi %d, roamRssi %d\n", __func__,
1038			    curRate, roamRate, curRssi, roamRssi);
1039			ieee80211_sta_join(ic, &selbs->base);
1040		}
1041	}
1042}
1043
1044/*
1045 * Age entries in the scan cache.
1046 * XXX also do roaming since it's convenient
1047 */
1048static void
1049sta_age(struct ieee80211_scan_state *ss)
1050{
1051	struct ieee80211com *ic = ss->ss_ic;
1052	struct sta_table *st = ss->ss_priv;
1053	struct sta_entry *se, *next;
1054
1055	mtx_lock(&st->st_lock);
1056	TAILQ_FOREACH_SAFE(se, &st->st_entry, se_list, next) {
1057		if (se->se_notseen > STA_PURGE_SCANS) {
1058			TAILQ_REMOVE(&st->st_entry, se, se_list);
1059			LIST_REMOVE(se, se_hash);
1060			FREE(se, M_80211_SCAN);
1061		}
1062	}
1063	mtx_unlock(&st->st_lock);
1064	/*
1065	 * If rate control is enabled check periodically to see if
1066	 * we should roam from our current connection to one that
1067	 * might be better.  This only applies when we're operating
1068	 * in sta mode and automatic roaming is set.
1069	 * XXX defer if busy
1070	 * XXX repeater station
1071	 * XXX do when !bgscan?
1072	 */
1073	KASSERT(ic->ic_opmode == IEEE80211_M_STA,
1074		("wrong mode %u", ic->ic_opmode));
1075	if (ic->ic_roaming == IEEE80211_ROAMING_AUTO &&
1076	    (ic->ic_flags & IEEE80211_F_BGSCAN) &&
1077	    ic->ic_state >= IEEE80211_S_RUN)
1078		/* XXX vap is implicit */
1079		sta_roam_check(ss, ic);
1080}
1081
1082/*
1083 * Iterate over the entries in the scan cache, invoking
1084 * the callback function on each one.
1085 */
1086static void
1087sta_iterate(struct ieee80211_scan_state *ss,
1088	ieee80211_scan_iter_func *f, void *arg)
1089{
1090	struct sta_table *st = ss->ss_priv;
1091	struct sta_entry *se;
1092	u_int gen;
1093
1094	mtx_lock(&st->st_scanlock);
1095	gen = st->st_scangen++;
1096restart:
1097	mtx_lock(&st->st_lock);
1098	TAILQ_FOREACH(se, &st->st_entry, se_list) {
1099		if (se->se_scangen != gen) {
1100			se->se_scangen = gen;
1101			/* update public state */
1102			se->base.se_age = ticks - se->se_lastupdate;
1103			mtx_unlock(&st->st_lock);
1104			(*f)(arg, &se->base);
1105			goto restart;
1106		}
1107	}
1108	mtx_unlock(&st->st_lock);
1109
1110	mtx_unlock(&st->st_scanlock);
1111}
1112
1113static void
1114sta_assoc_fail(struct ieee80211_scan_state *ss,
1115	const uint8_t macaddr[IEEE80211_ADDR_LEN], int reason)
1116{
1117	struct sta_table *st = ss->ss_priv;
1118	struct sta_entry *se;
1119
1120	se = sta_lookup(st, macaddr);
1121	if (se != NULL) {
1122		se->se_fails++;
1123		se->se_lastfail = ticks;
1124		IEEE80211_NOTE_MAC(ss->ss_ic, IEEE80211_MSG_SCAN,
1125		    macaddr, "%s: reason %u fails %u",
1126		    __func__, reason, se->se_fails);
1127	}
1128}
1129
1130static void
1131sta_assoc_success(struct ieee80211_scan_state *ss,
1132	const uint8_t macaddr[IEEE80211_ADDR_LEN])
1133{
1134	struct sta_table *st = ss->ss_priv;
1135	struct sta_entry *se;
1136
1137	se = sta_lookup(st, macaddr);
1138	if (se != NULL) {
1139#if 0
1140		se->se_fails = 0;
1141		IEEE80211_NOTE_MAC(ss->ss_ic, IEEE80211_MSG_SCAN,
1142		    macaddr, "%s: fails %u",
1143		    __func__, se->se_fails);
1144#endif
1145		se->se_lastassoc = ticks;
1146	}
1147}
1148
1149static const struct ieee80211_scanner sta_default = {
1150	.scan_name		= "default",
1151	.scan_attach		= sta_attach,
1152	.scan_detach		= sta_detach,
1153	.scan_start		= sta_start,
1154	.scan_restart		= sta_restart,
1155	.scan_cancel		= sta_cancel,
1156	.scan_end		= sta_pick_bss,
1157	.scan_flush		= sta_flush,
1158	.scan_add		= sta_add,
1159	.scan_age		= sta_age,
1160	.scan_iterate		= sta_iterate,
1161	.scan_assoc_fail	= sta_assoc_fail,
1162	.scan_assoc_success	= sta_assoc_success,
1163};
1164
1165/*
1166 * Adhoc mode-specific support.
1167 */
1168
1169static const uint16_t adhocWorld[] =		/* 36, 40, 44, 48 */
1170{ 5180, 5200, 5220, 5240 };
1171static const uint16_t adhocFcc3[] =		/* 36, 40, 44, 48 145, 149, 153, 157, 161, 165 */
1172{ 5180, 5200, 5220, 5240, 5725, 5745, 5765, 5785, 5805, 5825 };
1173static const uint16_t adhocMkk[] =		/* 34, 38, 42, 46 */
1174{ 5170, 5190, 5210, 5230 };
1175static const uint16_t adhoc11b[] =		/* 10, 11 */
1176{ 2457, 2462 };
1177
1178static const struct scanlist adhocScanTable[] = {
1179	{ IEEE80211_MODE_11B,   	X(adhoc11b) },
1180	{ IEEE80211_MODE_11A,   	X(adhocWorld) },
1181	{ IEEE80211_MODE_11A,   	X(adhocFcc3) },
1182	{ IEEE80211_MODE_11B,   	X(adhocMkk) },
1183	{ .list = NULL }
1184};
1185#undef X
1186
1187/*
1188 * Start an adhoc-mode scan by populating the channel list.
1189 */
1190static int
1191adhoc_start(struct ieee80211_scan_state *ss, struct ieee80211com *ic)
1192{
1193#define	N(a)	(sizeof(a)/sizeof(a[0]))
1194	struct sta_table *st = ss->ss_priv;
1195	const struct scanlist *scan;
1196	enum ieee80211_phymode mode;
1197
1198	ss->ss_last = 0;
1199	/*
1200	 * Use the table of ordered channels to construct the list
1201	 * of channels for scanning.  Any channels in the ordered
1202	 * list not in the master list will be discarded.
1203	 */
1204	for (scan = adhocScanTable; scan->list != NULL; scan++) {
1205		mode = scan->mode;
1206		if (ic->ic_des_mode != IEEE80211_MODE_AUTO) {
1207			/*
1208			 * If a desired mode was specified, scan only
1209			 * channels that satisfy that constraint.
1210			 */
1211			if (ic->ic_des_mode != mode) {
1212				/*
1213				 * The scan table marks 2.4Ghz channels as b
1214				 * so if the desired mode is 11g, then use
1215				 * the 11b channel list but upgrade the mode.
1216				 */
1217				if (ic->ic_des_mode != IEEE80211_MODE_11G ||
1218				    mode != IEEE80211_MODE_11B)
1219					continue;
1220				mode = IEEE80211_MODE_11G;	/* upgrade */
1221			}
1222		} else {
1223			/*
1224			 * This lets add_channels upgrade an 11b channel
1225			 * to 11g if available.
1226			 */
1227			if (mode == IEEE80211_MODE_11B)
1228				mode = IEEE80211_MODE_AUTO;
1229		}
1230#ifdef IEEE80211_F_XR
1231		/* XR does not operate on turbo channels */
1232		if ((ic->ic_flags & IEEE80211_F_XR) &&
1233		    (mode == IEEE80211_MODE_TURBO_A ||
1234		     mode == IEEE80211_MODE_TURBO_G))
1235			continue;
1236#endif
1237		/*
1238		 * Add the list of the channels; any that are not
1239		 * in the master channel list will be discarded.
1240		 */
1241		add_channels(ic, ss, mode, scan->list, scan->count);
1242	}
1243	ss->ss_next = 0;
1244	/* XXX tunables */
1245	ss->ss_mindwell = msecs_to_ticks(200);		/* 200ms */
1246	ss->ss_maxdwell = msecs_to_ticks(200);		/* 200ms */
1247
1248#ifdef IEEE80211_DEBUG
1249	if (ieee80211_msg_scan(ic)) {
1250		if_printf(ic->ic_ifp, "scan set ");
1251		ieee80211_scan_dump_channels(ss);
1252		printf(" dwell min %ld max %ld\n",
1253			ss->ss_mindwell, ss->ss_maxdwell);
1254	}
1255#endif /* IEEE80211_DEBUG */
1256
1257	st->st_newscan = 1;
1258
1259	return 0;
1260#undef N
1261}
1262
1263/*
1264 * Select a channel to start an adhoc network on.
1265 * The channel list was populated with appropriate
1266 * channels so select one that looks least occupied.
1267 * XXX need regulatory domain constraints
1268 */
1269static struct ieee80211_channel *
1270adhoc_pick_channel(struct ieee80211_scan_state *ss)
1271{
1272	struct sta_table *st = ss->ss_priv;
1273	struct sta_entry *se;
1274	struct ieee80211_channel *c, *bestchan;
1275	int i, bestrssi, maxrssi;
1276
1277	bestchan = NULL;
1278	bestrssi = -1;
1279
1280	mtx_lock(&st->st_lock);
1281	for (i = 0; i < ss->ss_last; i++) {
1282		c = ss->ss_chans[i];
1283		maxrssi = 0;
1284		TAILQ_FOREACH(se, &st->st_entry, se_list) {
1285			if (se->base.se_chan != c)
1286				continue;
1287			if (se->base.se_rssi > maxrssi)
1288				maxrssi = se->base.se_rssi;
1289		}
1290		if (bestchan == NULL || maxrssi < bestrssi)
1291			bestchan = c;
1292	}
1293	mtx_unlock(&st->st_lock);
1294
1295	return bestchan;
1296}
1297
1298/*
1299 * Pick an ibss network to join or find a channel
1300 * to use to start an ibss network.
1301 */
1302static int
1303adhoc_pick_bss(struct ieee80211_scan_state *ss, struct ieee80211com *ic)
1304{
1305	struct sta_table *st = ss->ss_priv;
1306	struct sta_entry *selbs;
1307	struct ieee80211_channel *chan;
1308
1309	KASSERT(ic->ic_opmode == IEEE80211_M_IBSS ||
1310		ic->ic_opmode == IEEE80211_M_AHDEMO,
1311		("wrong opmode %u", ic->ic_opmode));
1312
1313	if (st->st_newscan) {
1314		sta_update_notseen(st);
1315		st->st_newscan = 0;
1316	}
1317	if (ss->ss_flags & IEEE80211_SCAN_NOPICK) {
1318		/*
1319		 * Manual/background scan, don't select+join the
1320		 * bss, just return.  The scanning framework will
1321		 * handle notification that this has completed.
1322		 */
1323		ss->ss_flags &= ~IEEE80211_SCAN_NOPICK;
1324		return 1;
1325	}
1326	/*
1327	 * Automatic sequencing; look for a candidate and
1328	 * if found join the network.
1329	 */
1330	/* NB: unlocked read should be ok */
1331	if (TAILQ_FIRST(&st->st_entry) == NULL) {
1332		IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
1333			"%s: no scan candidate\n", __func__);
1334notfound:
1335		if (ic->ic_des_nssid) {
1336			/*
1337			 * No existing adhoc network to join and we have
1338			 * an ssid; start one up.  If no channel was
1339			 * specified, try to select a channel.
1340			 */
1341			if (ic->ic_des_chan == IEEE80211_CHAN_ANYC)
1342				chan = adhoc_pick_channel(ss);
1343			else
1344				chan = ic->ic_des_chan;
1345			if (chan != NULL) {
1346				ieee80211_create_ibss(ic, chan);
1347				return 1;
1348			}
1349		}
1350		/*
1351		 * If nothing suitable was found decrement
1352		 * the failure counts so entries will be
1353		 * reconsidered the next time around.  We
1354		 * really want to do this only for sta's
1355		 * where we've previously had some success.
1356		 */
1357		sta_dec_fails(st);
1358		st->st_newscan = 1;
1359		return 0;			/* restart scan */
1360	}
1361	selbs = select_bss(ss, ic, IEEE80211_MSG_SCAN);
1362	if (selbs == NULL || !ieee80211_sta_join(ic, &selbs->base))
1363		goto notfound;
1364	return 1;				/* terminate scan */
1365}
1366
1367/*
1368 * Age entries in the scan cache.
1369 */
1370static void
1371adhoc_age(struct ieee80211_scan_state *ss)
1372{
1373	struct sta_table *st = ss->ss_priv;
1374	struct sta_entry *se, *next;
1375
1376	mtx_lock(&st->st_lock);
1377	TAILQ_FOREACH_SAFE(se, &st->st_entry, se_list, next) {
1378		if (se->se_notseen > STA_PURGE_SCANS) {
1379			TAILQ_REMOVE(&st->st_entry, se, se_list);
1380			LIST_REMOVE(se, se_hash);
1381			FREE(se, M_80211_SCAN);
1382		}
1383	}
1384	mtx_unlock(&st->st_lock);
1385}
1386
1387static const struct ieee80211_scanner adhoc_default = {
1388	.scan_name		= "default",
1389	.scan_attach		= sta_attach,
1390	.scan_detach		= sta_detach,
1391	.scan_start		= adhoc_start,
1392	.scan_restart		= sta_restart,
1393	.scan_cancel		= sta_cancel,
1394	.scan_end		= adhoc_pick_bss,
1395	.scan_flush		= sta_flush,
1396	.scan_add		= sta_add,
1397	.scan_age		= adhoc_age,
1398	.scan_iterate		= sta_iterate,
1399	.scan_assoc_fail	= sta_assoc_fail,
1400	.scan_assoc_success	= sta_assoc_success,
1401};
1402
1403/*
1404 * Module glue.
1405 */
1406static int
1407wlan_modevent(module_t mod, int type, void *unused)
1408{
1409	switch (type) {
1410	case MOD_LOAD:
1411		ieee80211_scanner_register(IEEE80211_M_STA, &sta_default);
1412		ieee80211_scanner_register(IEEE80211_M_IBSS, &adhoc_default);
1413		ieee80211_scanner_register(IEEE80211_M_AHDEMO, &adhoc_default);
1414		return 0;
1415	case MOD_UNLOAD:
1416	case MOD_QUIESCE:
1417		if (nrefs) {
1418			printf("wlan_scan_sta: still in use (%u dynamic refs)\n",
1419				nrefs);
1420			return EBUSY;
1421		}
1422		if (type == MOD_UNLOAD) {
1423			ieee80211_scanner_unregister_all(&sta_default);
1424			ieee80211_scanner_unregister_all(&adhoc_default);
1425		}
1426		return 0;
1427	}
1428	return EINVAL;
1429}
1430
1431static moduledata_t wlan_mod = {
1432	"wlan_scan_sta",
1433	wlan_modevent,
1434	0
1435};
1436DECLARE_MODULE(wlan_scan_sta, wlan_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
1437MODULE_VERSION(wlan_scan_sta, 1);
1438MODULE_DEPEND(wlan_scan_sta, wlan, 1, 1, 1);
1439