xref: /freebsd/sys/net80211/ieee80211_scan.c (revision 2f834a0b41079f9be4dc33ff877d50a5fba869d4)
1 /*-
2  * Copyright (c) 2002-2008 Sam Leffler, Errno Consulting
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25 
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
28 
29 /*
30  * IEEE 802.11 scanning support.
31  */
32 #include "opt_wlan.h"
33 
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/proc.h>
37 #include <sys/kernel.h>
38 #include <sys/condvar.h>
39 
40 #include <sys/socket.h>
41 
42 #include <net/if.h>
43 #include <net/if_var.h>
44 #include <net/if_media.h>
45 #include <net/ethernet.h>
46 
47 #include <net80211/ieee80211_var.h>
48 
49 #include <net/bpf.h>
50 
51 struct scan_state {
52 	struct ieee80211_scan_state base;	/* public state */
53 
54 	u_int		ss_iflags;		/* flags used internally */
55 #define	ISCAN_MINDWELL 	0x0001		/* min dwell time reached */
56 #define	ISCAN_DISCARD	0x0002		/* discard rx'd frames */
57 #define	ISCAN_CANCEL	0x0004		/* cancel current scan */
58 #define	ISCAN_ABORT	0x0008		/* end the scan immediately */
59 	unsigned long	ss_chanmindwell;	/* min dwell on curchan */
60 	unsigned long	ss_scanend;		/* time scan must stop */
61 	u_int		ss_duration;		/* duration for next scan */
62 	struct task	ss_scan_task;		/* scan execution */
63 	struct cv	ss_scan_cv;		/* scan signal */
64 	struct callout	ss_scan_timer;		/* scan timer */
65 };
66 #define	SCAN_PRIVATE(ss)	((struct scan_state *) ss)
67 
68 /*
69  * Amount of time to go off-channel during a background
70  * scan.  This value should be large enough to catch most
71  * ap's but short enough that we can return on-channel
72  * before our listen interval expires.
73  *
74  * XXX tunable
75  * XXX check against configured listen interval
76  */
77 #define	IEEE80211_SCAN_OFFCHANNEL	msecs_to_ticks(150)
78 
79 /*
80  * Roaming-related defaults.  RSSI thresholds are as returned by the
81  * driver (.5dBm).  Transmit rate thresholds are IEEE rate codes (i.e
82  * .5M units) or MCS.
83  */
84 /* rssi thresholds */
85 #define	ROAM_RSSI_11A_DEFAULT		14	/* 11a bss */
86 #define	ROAM_RSSI_11B_DEFAULT		14	/* 11b bss */
87 #define	ROAM_RSSI_11BONLY_DEFAULT	14	/* 11b-only bss */
88 /* transmit rate thresholds */
89 #define	ROAM_RATE_11A_DEFAULT		2*12	/* 11a bss */
90 #define	ROAM_RATE_11B_DEFAULT		2*5	/* 11b bss */
91 #define	ROAM_RATE_11BONLY_DEFAULT	2*1	/* 11b-only bss */
92 #define	ROAM_RATE_HALF_DEFAULT		2*6	/* half-width 11a/g bss */
93 #define	ROAM_RATE_QUARTER_DEFAULT	2*3	/* quarter-width 11a/g bss */
94 #define	ROAM_MCS_11N_DEFAULT		(1 | IEEE80211_RATE_MCS) /* 11n bss */
95 
96 static	void scan_curchan(struct ieee80211_scan_state *, unsigned long);
97 static	void scan_mindwell(struct ieee80211_scan_state *);
98 static	void scan_signal(void *);
99 static	void scan_task(void *, int);
100 
101 MALLOC_DEFINE(M_80211_SCAN, "80211scan", "802.11 scan state");
102 
103 void
104 ieee80211_scan_attach(struct ieee80211com *ic)
105 {
106 	struct scan_state *ss;
107 
108 	ss = (struct scan_state *) malloc(sizeof(struct scan_state),
109 		M_80211_SCAN, M_NOWAIT | M_ZERO);
110 	if (ss == NULL) {
111 		ic->ic_scan = NULL;
112 		return;
113 	}
114 	callout_init_mtx(&ss->ss_scan_timer, IEEE80211_LOCK_OBJ(ic), 0);
115 	cv_init(&ss->ss_scan_cv, "scan");
116 	TASK_INIT(&ss->ss_scan_task, 0, scan_task, ss);
117 	ic->ic_scan = &ss->base;
118 	ss->base.ss_ic = ic;
119 
120 	ic->ic_scan_curchan = scan_curchan;
121 	ic->ic_scan_mindwell = scan_mindwell;
122 }
123 
124 void
125 ieee80211_scan_detach(struct ieee80211com *ic)
126 {
127 	struct ieee80211_scan_state *ss = ic->ic_scan;
128 
129 	if (ss != NULL) {
130 		IEEE80211_LOCK(ic);
131 		SCAN_PRIVATE(ss)->ss_iflags |= ISCAN_ABORT;
132 		scan_signal(ss);
133 		IEEE80211_UNLOCK(ic);
134 		ieee80211_draintask(ic, &SCAN_PRIVATE(ss)->ss_scan_task);
135 		callout_drain(&SCAN_PRIVATE(ss)->ss_scan_timer);
136 		KASSERT((ic->ic_flags & IEEE80211_F_SCAN) == 0,
137 		    ("scan still running"));
138 		if (ss->ss_ops != NULL) {
139 			ss->ss_ops->scan_detach(ss);
140 			ss->ss_ops = NULL;
141 		}
142 		ic->ic_scan = NULL;
143 		free(SCAN_PRIVATE(ss), M_80211_SCAN);
144 	}
145 }
146 
147 static const struct ieee80211_roamparam defroam[IEEE80211_MODE_MAX] = {
148 	[IEEE80211_MODE_11A]	= { .rssi = ROAM_RSSI_11A_DEFAULT,
149 				    .rate = ROAM_RATE_11A_DEFAULT },
150 	[IEEE80211_MODE_11G]	= { .rssi = ROAM_RSSI_11B_DEFAULT,
151 				    .rate = ROAM_RATE_11B_DEFAULT },
152 	[IEEE80211_MODE_11B]	= { .rssi = ROAM_RSSI_11BONLY_DEFAULT,
153 				    .rate = ROAM_RATE_11BONLY_DEFAULT },
154 	[IEEE80211_MODE_TURBO_A]= { .rssi = ROAM_RSSI_11A_DEFAULT,
155 				    .rate = ROAM_RATE_11A_DEFAULT },
156 	[IEEE80211_MODE_TURBO_G]= { .rssi = ROAM_RSSI_11A_DEFAULT,
157 				    .rate = ROAM_RATE_11A_DEFAULT },
158 	[IEEE80211_MODE_STURBO_A]={ .rssi = ROAM_RSSI_11A_DEFAULT,
159 				    .rate = ROAM_RATE_11A_DEFAULT },
160 	[IEEE80211_MODE_HALF]	= { .rssi = ROAM_RSSI_11A_DEFAULT,
161 				    .rate = ROAM_RATE_HALF_DEFAULT },
162 	[IEEE80211_MODE_QUARTER]= { .rssi = ROAM_RSSI_11A_DEFAULT,
163 				    .rate = ROAM_RATE_QUARTER_DEFAULT },
164 	[IEEE80211_MODE_11NA]	= { .rssi = ROAM_RSSI_11A_DEFAULT,
165 				    .rate = ROAM_MCS_11N_DEFAULT },
166 	[IEEE80211_MODE_11NG]	= { .rssi = ROAM_RSSI_11B_DEFAULT,
167 				    .rate = ROAM_MCS_11N_DEFAULT },
168 };
169 
170 void
171 ieee80211_scan_vattach(struct ieee80211vap *vap)
172 {
173 	vap->iv_bgscanidle = (IEEE80211_BGSCAN_IDLE_DEFAULT*1000)/hz;
174 	vap->iv_bgscanintvl = IEEE80211_BGSCAN_INTVAL_DEFAULT*hz;
175 	vap->iv_scanvalid = IEEE80211_SCAN_VALID_DEFAULT*hz;
176 
177 	vap->iv_roaming = IEEE80211_ROAMING_AUTO;
178 	memcpy(vap->iv_roamparms, defroam, sizeof(defroam));
179 }
180 
181 void
182 ieee80211_scan_vdetach(struct ieee80211vap *vap)
183 {
184 	struct ieee80211com *ic = vap->iv_ic;
185 	struct ieee80211_scan_state *ss;
186 
187 	IEEE80211_LOCK(ic);
188 	ss = ic->ic_scan;
189 	if (ss != NULL && ss->ss_vap == vap) {
190 		if (ic->ic_flags & IEEE80211_F_SCAN) {
191 			SCAN_PRIVATE(ss)->ss_iflags |= ISCAN_ABORT;
192 			scan_signal(ss);
193 		}
194 		if (ss->ss_ops != NULL) {
195 			ss->ss_ops->scan_detach(ss);
196 			ss->ss_ops = NULL;
197 		}
198 		ss->ss_vap = NULL;
199 	}
200 	IEEE80211_UNLOCK(ic);
201 }
202 
203 /*
204  * Simple-minded scanner module support.
205  */
206 static const char *scan_modnames[IEEE80211_OPMODE_MAX] = {
207 	"wlan_scan_sta",	/* IEEE80211_M_IBSS */
208 	"wlan_scan_sta",	/* IEEE80211_M_STA */
209 	"wlan_scan_wds",	/* IEEE80211_M_WDS */
210 	"wlan_scan_sta",	/* IEEE80211_M_AHDEMO */
211 	"wlan_scan_ap",		/* IEEE80211_M_HOSTAP */
212 	"wlan_scan_monitor",	/* IEEE80211_M_MONITOR */
213 	"wlan_scan_sta",	/* IEEE80211_M_MBSS */
214 };
215 static const struct ieee80211_scanner *scanners[IEEE80211_OPMODE_MAX];
216 
217 const struct ieee80211_scanner *
218 ieee80211_scanner_get(enum ieee80211_opmode mode)
219 {
220 	if (mode >= IEEE80211_OPMODE_MAX)
221 		return NULL;
222 	if (scanners[mode] == NULL)
223 		ieee80211_load_module(scan_modnames[mode]);
224 	return scanners[mode];
225 }
226 
227 void
228 ieee80211_scanner_register(enum ieee80211_opmode mode,
229 	const struct ieee80211_scanner *scan)
230 {
231 	if (mode >= IEEE80211_OPMODE_MAX)
232 		return;
233 	scanners[mode] = scan;
234 }
235 
236 void
237 ieee80211_scanner_unregister(enum ieee80211_opmode mode,
238 	const struct ieee80211_scanner *scan)
239 {
240 	if (mode >= IEEE80211_OPMODE_MAX)
241 		return;
242 	if (scanners[mode] == scan)
243 		scanners[mode] = NULL;
244 }
245 
246 void
247 ieee80211_scanner_unregister_all(const struct ieee80211_scanner *scan)
248 {
249 	int m;
250 
251 	for (m = 0; m < IEEE80211_OPMODE_MAX; m++)
252 		if (scanners[m] == scan)
253 			scanners[m] = NULL;
254 }
255 
256 /*
257  * Update common scanner state to reflect the current
258  * operating mode.  This is called when the state machine
259  * is transitioned to RUN state w/o scanning--e.g. when
260  * operating in monitor mode.  The purpose of this is to
261  * ensure later callbacks find ss_ops set to properly
262  * reflect current operating mode.
263  */
264 static void
265 scan_update_locked(struct ieee80211vap *vap,
266 	const struct ieee80211_scanner *scan)
267 {
268 	struct ieee80211com *ic = vap->iv_ic;
269 	struct ieee80211_scan_state *ss = ic->ic_scan;
270 
271 	IEEE80211_LOCK_ASSERT(ic);
272 
273 #ifdef IEEE80211_DEBUG
274 	if (ss->ss_vap != vap || ss->ss_ops != scan) {
275 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
276 		    "%s: current scanner is <%s:%s>, switch to <%s:%s>\n",
277 		    __func__,
278 		    ss->ss_vap != NULL ?
279 			ss->ss_vap->iv_ifp->if_xname : "none",
280 		    ss->ss_vap != NULL ?
281 			ieee80211_opmode_name[ss->ss_vap->iv_opmode] : "none",
282 		    vap->iv_ifp->if_xname,
283 		    ieee80211_opmode_name[vap->iv_opmode]);
284 	}
285 #endif
286 	ss->ss_vap = vap;
287 	if (ss->ss_ops != scan) {
288 		/*
289 		 * Switch scanners; detach old, attach new.  Special
290 		 * case where a single scan module implements multiple
291 		 * policies by using different scan ops but a common
292 		 * core.  We assume if the old and new attach methods
293 		 * are identical then it's ok to just change ss_ops
294 		 * and not flush the internal state of the module.
295 		 */
296 		if (scan == NULL || ss->ss_ops == NULL ||
297 		    ss->ss_ops->scan_attach != scan->scan_attach) {
298 			if (ss->ss_ops != NULL)
299 				ss->ss_ops->scan_detach(ss);
300 			if (scan != NULL && !scan->scan_attach(ss)) {
301 				/* XXX attach failure */
302 				/* XXX stat+msg */
303 				scan = NULL;
304 			}
305 		}
306 		ss->ss_ops = scan;
307 	}
308 }
309 
310 static char
311 channel_type(const struct ieee80211_channel *c)
312 {
313 	if (IEEE80211_IS_CHAN_ST(c))
314 		return 'S';
315 	if (IEEE80211_IS_CHAN_108A(c))
316 		return 'T';
317 	if (IEEE80211_IS_CHAN_108G(c))
318 		return 'G';
319 	if (IEEE80211_IS_CHAN_HT(c))
320 		return 'n';
321 	if (IEEE80211_IS_CHAN_A(c))
322 		return 'a';
323 	if (IEEE80211_IS_CHAN_ANYG(c))
324 		return 'g';
325 	if (IEEE80211_IS_CHAN_B(c))
326 		return 'b';
327 	return 'f';
328 }
329 
330 void
331 ieee80211_scan_dump_channels(const struct ieee80211_scan_state *ss)
332 {
333 	struct ieee80211com *ic = ss->ss_ic;
334 	const char *sep;
335 	int i;
336 
337 	sep = "";
338 	for (i = ss->ss_next; i < ss->ss_last; i++) {
339 		const struct ieee80211_channel *c = ss->ss_chans[i];
340 
341 		printf("%s%u%c", sep, ieee80211_chan2ieee(ic, c),
342 			channel_type(c));
343 		sep = ", ";
344 	}
345 }
346 
347 #ifdef IEEE80211_DEBUG
348 static void
349 scan_dump(struct ieee80211_scan_state *ss)
350 {
351 	struct ieee80211vap *vap = ss->ss_vap;
352 
353 	if_printf(vap->iv_ifp, "scan set ");
354 	ieee80211_scan_dump_channels(ss);
355 	printf(" dwell min %lums max %lums\n",
356 	    ticks_to_msecs(ss->ss_mindwell), ticks_to_msecs(ss->ss_maxdwell));
357 }
358 #endif /* IEEE80211_DEBUG */
359 
360 static void
361 copy_ssid(struct ieee80211vap *vap, struct ieee80211_scan_state *ss,
362 	int nssid, const struct ieee80211_scan_ssid ssids[])
363 {
364 	if (nssid > IEEE80211_SCAN_MAX_SSID) {
365 		/* XXX printf */
366 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
367 		    "%s: too many ssid %d, ignoring all of them\n",
368 		    __func__, nssid);
369 		return;
370 	}
371 	memcpy(ss->ss_ssid, ssids, nssid * sizeof(ssids[0]));
372 	ss->ss_nssid = nssid;
373 }
374 
375 /*
376  * Start a scan unless one is already going.
377  */
378 static int
379 start_scan_locked(const struct ieee80211_scanner *scan,
380 	struct ieee80211vap *vap, int flags, u_int duration,
381 	u_int mindwell, u_int maxdwell,
382 	u_int nssid, const struct ieee80211_scan_ssid ssids[])
383 {
384 	struct ieee80211com *ic = vap->iv_ic;
385 	struct ieee80211_scan_state *ss = ic->ic_scan;
386 
387 	IEEE80211_LOCK_ASSERT(ic);
388 
389 	if (ic->ic_flags & IEEE80211_F_CSAPENDING) {
390 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
391 		    "%s: scan inhibited by pending channel change\n", __func__);
392 	} else if ((ic->ic_flags & IEEE80211_F_SCAN) == 0) {
393 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
394 		    "%s: %s scan, duration %u mindwell %u maxdwell %u, desired mode %s, %s%s%s%s%s%s\n"
395 		    , __func__
396 		    , flags & IEEE80211_SCAN_ACTIVE ? "active" : "passive"
397 		    , duration, mindwell, maxdwell
398 		    , ieee80211_phymode_name[vap->iv_des_mode]
399 		    , flags & IEEE80211_SCAN_FLUSH ? "flush" : "append"
400 		    , flags & IEEE80211_SCAN_NOPICK ? ", nopick" : ""
401 		    , flags & IEEE80211_SCAN_NOJOIN ? ", nojoin" : ""
402 		    , flags & IEEE80211_SCAN_NOBCAST ? ", nobcast" : ""
403 		    , flags & IEEE80211_SCAN_PICK1ST ? ", pick1st" : ""
404 		    , flags & IEEE80211_SCAN_ONCE ? ", once" : ""
405 		);
406 
407 		scan_update_locked(vap, scan);
408 		if (ss->ss_ops != NULL) {
409 			if ((flags & IEEE80211_SCAN_NOSSID) == 0)
410 				copy_ssid(vap, ss, nssid, ssids);
411 
412 			/* NB: top 4 bits for internal use */
413 			ss->ss_flags = flags & 0xfff;
414 			if (ss->ss_flags & IEEE80211_SCAN_ACTIVE)
415 				vap->iv_stats.is_scan_active++;
416 			else
417 				vap->iv_stats.is_scan_passive++;
418 			if (flags & IEEE80211_SCAN_FLUSH)
419 				ss->ss_ops->scan_flush(ss);
420 			if (flags & IEEE80211_SCAN_BGSCAN)
421 				ic->ic_flags_ext |= IEEE80211_FEXT_BGSCAN;
422 
423 			/* NB: flush frames rx'd before 1st channel change */
424 			SCAN_PRIVATE(ss)->ss_iflags |= ISCAN_DISCARD;
425 			SCAN_PRIVATE(ss)->ss_duration = duration;
426 			ss->ss_next = 0;
427 			ss->ss_mindwell = mindwell;
428 			ss->ss_maxdwell = maxdwell;
429 			/* NB: scan_start must be before the scan runtask */
430 			ss->ss_ops->scan_start(ss, vap);
431 #ifdef IEEE80211_DEBUG
432 			if (ieee80211_msg_scan(vap))
433 				scan_dump(ss);
434 #endif /* IEEE80211_DEBUG */
435 			ic->ic_flags |= IEEE80211_F_SCAN;
436 			ieee80211_runtask(ic, &SCAN_PRIVATE(ss)->ss_scan_task);
437 		}
438 		return 1;
439 	} else {
440 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
441 		    "%s: %s scan already in progress\n", __func__,
442 		    ss->ss_flags & IEEE80211_SCAN_ACTIVE ? "active" : "passive");
443 	}
444 	return 0;
445 }
446 
447 /*
448  * Start a scan unless one is already going.
449  */
450 int
451 ieee80211_start_scan(struct ieee80211vap *vap, int flags,
452 	u_int duration, u_int mindwell, u_int maxdwell,
453 	u_int nssid, const struct ieee80211_scan_ssid ssids[])
454 {
455 	struct ieee80211com *ic = vap->iv_ic;
456 	const struct ieee80211_scanner *scan;
457 	int result;
458 
459 	scan = ieee80211_scanner_get(vap->iv_opmode);
460 	if (scan == NULL) {
461 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
462 		    "%s: no scanner support for %s mode\n",
463 		    __func__, ieee80211_opmode_name[vap->iv_opmode]);
464 		/* XXX stat */
465 		return 0;
466 	}
467 
468 	IEEE80211_LOCK(ic);
469 	result = start_scan_locked(scan, vap, flags, duration,
470 	    mindwell, maxdwell, nssid, ssids);
471 	IEEE80211_UNLOCK(ic);
472 
473 	return result;
474 }
475 
476 /*
477  * Check the scan cache for an ap/channel to use; if that
478  * fails then kick off a new scan.
479  */
480 int
481 ieee80211_check_scan(struct ieee80211vap *vap, int flags,
482 	u_int duration, u_int mindwell, u_int maxdwell,
483 	u_int nssid, const struct ieee80211_scan_ssid ssids[])
484 {
485 	struct ieee80211com *ic = vap->iv_ic;
486 	struct ieee80211_scan_state *ss = ic->ic_scan;
487 	const struct ieee80211_scanner *scan;
488 	int result;
489 
490 	scan = ieee80211_scanner_get(vap->iv_opmode);
491 	if (scan == NULL) {
492 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
493 		    "%s: no scanner support for %s mode\n",
494 		    __func__, vap->iv_opmode);
495 		/* XXX stat */
496 		return 0;
497 	}
498 
499 	/*
500 	 * Check if there's a list of scan candidates already.
501 	 * XXX want more than the ap we're currently associated with
502 	 */
503 
504 	IEEE80211_LOCK(ic);
505 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
506 	    "%s: %s scan, %s%s%s%s%s\n"
507 	    , __func__
508 	    , flags & IEEE80211_SCAN_ACTIVE ? "active" : "passive"
509 	    , flags & IEEE80211_SCAN_FLUSH ? "flush" : "append"
510 	    , flags & IEEE80211_SCAN_NOPICK ? ", nopick" : ""
511 	    , flags & IEEE80211_SCAN_NOJOIN ? ", nojoin" : ""
512 	    , flags & IEEE80211_SCAN_PICK1ST ? ", pick1st" : ""
513 	    , flags & IEEE80211_SCAN_ONCE ? ", once" : ""
514 	);
515 
516 	if (ss->ss_ops != scan) {
517 		/* XXX re-use cache contents? e.g. adhoc<->sta */
518 		flags |= IEEE80211_SCAN_FLUSH;
519 	}
520 	scan_update_locked(vap, scan);
521 	if (ss->ss_ops != NULL) {
522 		/* XXX verify ss_ops matches vap->iv_opmode */
523 		if ((flags & IEEE80211_SCAN_NOSSID) == 0) {
524 			/*
525 			 * Update the ssid list and mark flags so if
526 			 * we call start_scan it doesn't duplicate work.
527 			 */
528 			copy_ssid(vap, ss, nssid, ssids);
529 			flags |= IEEE80211_SCAN_NOSSID;
530 		}
531 		if ((ic->ic_flags & IEEE80211_F_SCAN) == 0 &&
532 		    (flags & IEEE80211_SCAN_FLUSH) == 0 &&
533 		    time_before(ticks, ic->ic_lastscan + vap->iv_scanvalid)) {
534 			/*
535 			 * We're not currently scanning and the cache is
536 			 * deemed hot enough to consult.  Lock out others
537 			 * by marking IEEE80211_F_SCAN while we decide if
538 			 * something is already in the scan cache we can
539 			 * use.  Also discard any frames that might come
540 			 * in while temporarily marked as scanning.
541 			 */
542 			SCAN_PRIVATE(ss)->ss_iflags |= ISCAN_DISCARD;
543 			ic->ic_flags |= IEEE80211_F_SCAN;
544 
545 			/* NB: need to use supplied flags in check */
546 			ss->ss_flags = flags & 0xff;
547 			result = ss->ss_ops->scan_end(ss, vap);
548 
549 			ic->ic_flags &= ~IEEE80211_F_SCAN;
550 			SCAN_PRIVATE(ss)->ss_iflags &= ~ISCAN_DISCARD;
551 			if (result) {
552 				ieee80211_notify_scan_done(vap);
553 				IEEE80211_UNLOCK(ic);
554 				return 1;
555 			}
556 		}
557 	}
558 	result = start_scan_locked(scan, vap, flags, duration,
559 	    mindwell, maxdwell, nssid, ssids);
560 	IEEE80211_UNLOCK(ic);
561 
562 	return result;
563 }
564 
565 /*
566  * Check the scan cache for an ap/channel to use; if that fails
567  * then kick off a scan using the current settings.
568  */
569 int
570 ieee80211_check_scan_current(struct ieee80211vap *vap)
571 {
572 	return ieee80211_check_scan(vap,
573 	    IEEE80211_SCAN_ACTIVE,
574 	    IEEE80211_SCAN_FOREVER, 0, 0,
575 	    vap->iv_des_nssid, vap->iv_des_ssid);
576 }
577 
578 /*
579  * Restart a previous scan.  If the previous scan completed
580  * then we start again using the existing channel list.
581  */
582 int
583 ieee80211_bg_scan(struct ieee80211vap *vap, int flags)
584 {
585 	struct ieee80211com *ic = vap->iv_ic;
586 	struct ieee80211_scan_state *ss = ic->ic_scan;
587 	const struct ieee80211_scanner *scan;
588 
589 	scan = ieee80211_scanner_get(vap->iv_opmode);
590 	if (scan == NULL) {
591 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
592 		    "%s: no scanner support for %s mode\n",
593 		    __func__, vap->iv_opmode);
594 		/* XXX stat */
595 		return 0;
596 	}
597 
598 	IEEE80211_LOCK(ic);
599 	if ((ic->ic_flags & IEEE80211_F_SCAN) == 0) {
600 		u_int duration;
601 		/*
602 		 * Go off-channel for a fixed interval that is large
603 		 * enough to catch most ap's but short enough that
604 		 * we can return on-channel before our listen interval
605 		 * expires.
606 		 */
607 		duration = IEEE80211_SCAN_OFFCHANNEL;
608 
609 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
610 		    "%s: %s scan, ticks %u duration %lu\n", __func__,
611 		    ss->ss_flags & IEEE80211_SCAN_ACTIVE ? "active" : "passive",
612 		    ticks, duration);
613 
614 		scan_update_locked(vap, scan);
615 		if (ss->ss_ops != NULL) {
616 			ss->ss_vap = vap;
617 			/*
618 			 * A background scan does not select a new sta; it
619 			 * just refreshes the scan cache.  Also, indicate
620 			 * the scan logic should follow the beacon schedule:
621 			 * we go off-channel and scan for a while, then
622 			 * return to the bss channel to receive a beacon,
623 			 * then go off-channel again.  All during this time
624 			 * we notify the ap we're in power save mode.  When
625 			 * the scan is complete we leave power save mode.
626 			 * If any beacon indicates there are frames pending
627 			 * for us then we drop out of power save mode
628 			 * (and background scan) automatically by way of the
629 			 * usual sta power save logic.
630 			 */
631 			ss->ss_flags |= IEEE80211_SCAN_NOPICK
632 				     |  IEEE80211_SCAN_BGSCAN
633 				     |  flags
634 				     ;
635 			/* if previous scan completed, restart */
636 			if (ss->ss_next >= ss->ss_last) {
637 				if (ss->ss_flags & IEEE80211_SCAN_ACTIVE)
638 					vap->iv_stats.is_scan_active++;
639 				else
640 					vap->iv_stats.is_scan_passive++;
641 				/*
642 				 * NB: beware of the scan cache being flushed;
643 				 *     if the channel list is empty use the
644 				 *     scan_start method to populate it.
645 				 */
646 				ss->ss_next = 0;
647 				if (ss->ss_last != 0)
648 					ss->ss_ops->scan_restart(ss, vap);
649 				else {
650 					ss->ss_ops->scan_start(ss, vap);
651 #ifdef IEEE80211_DEBUG
652 					if (ieee80211_msg_scan(vap))
653 						scan_dump(ss);
654 #endif /* IEEE80211_DEBUG */
655 				}
656 			}
657 			/* NB: flush frames rx'd before 1st channel change */
658 			SCAN_PRIVATE(ss)->ss_iflags |= ISCAN_DISCARD;
659 			SCAN_PRIVATE(ss)->ss_duration = duration;
660 			ss->ss_maxdwell = duration;
661 			ic->ic_flags |= IEEE80211_F_SCAN;
662 			ic->ic_flags_ext |= IEEE80211_FEXT_BGSCAN;
663 			ieee80211_runtask(ic, &SCAN_PRIVATE(ss)->ss_scan_task);
664 		} else {
665 			/* XXX msg+stat */
666 		}
667 	} else {
668 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
669 		    "%s: %s scan already in progress\n", __func__,
670 		    ss->ss_flags & IEEE80211_SCAN_ACTIVE ? "active" : "passive");
671 	}
672 	IEEE80211_UNLOCK(ic);
673 
674 	/* NB: racey, does it matter? */
675 	return (ic->ic_flags & IEEE80211_F_SCAN);
676 }
677 
678 /*
679  * Cancel any scan currently going on for the specified vap.
680  */
681 void
682 ieee80211_cancel_scan(struct ieee80211vap *vap)
683 {
684 	struct ieee80211com *ic = vap->iv_ic;
685 	struct ieee80211_scan_state *ss = ic->ic_scan;
686 
687 	IEEE80211_LOCK(ic);
688 	if ((ic->ic_flags & IEEE80211_F_SCAN) &&
689 	    ss->ss_vap == vap &&
690 	    (SCAN_PRIVATE(ss)->ss_iflags & ISCAN_CANCEL) == 0) {
691 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
692 		    "%s: cancel %s scan\n", __func__,
693 		    ss->ss_flags & IEEE80211_SCAN_ACTIVE ?
694 			"active" : "passive");
695 
696 		/* clear bg scan NOPICK and mark cancel request */
697 		ss->ss_flags &= ~IEEE80211_SCAN_NOPICK;
698 		SCAN_PRIVATE(ss)->ss_iflags |= ISCAN_CANCEL;
699 		/* wake up the scan task */
700 		scan_signal(ss);
701 	} else {
702 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
703 		    "%s: called; F_SCAN=%d, vap=%s, CANCEL=%d\n",
704 		        __func__,
705 			!! (ic->ic_flags & IEEE80211_F_SCAN),
706 			(ss->ss_vap == vap ? "match" : "nomatch"),
707 			!! (SCAN_PRIVATE(ss)->ss_iflags & ISCAN_CANCEL));
708 	}
709 	IEEE80211_UNLOCK(ic);
710 }
711 
712 /*
713  * Cancel any scan currently going on.
714  */
715 void
716 ieee80211_cancel_anyscan(struct ieee80211vap *vap)
717 {
718 	struct ieee80211com *ic = vap->iv_ic;
719 	struct ieee80211_scan_state *ss = ic->ic_scan;
720 
721 	IEEE80211_LOCK(ic);
722 	if ((ic->ic_flags & IEEE80211_F_SCAN) &&
723 	    (SCAN_PRIVATE(ss)->ss_iflags & ISCAN_CANCEL) == 0) {
724 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
725 		    "%s: cancel %s scan\n", __func__,
726 		    ss->ss_flags & IEEE80211_SCAN_ACTIVE ?
727 			"active" : "passive");
728 
729 		/* clear bg scan NOPICK and mark cancel request */
730 		ss->ss_flags &= ~IEEE80211_SCAN_NOPICK;
731 		SCAN_PRIVATE(ss)->ss_iflags |= ISCAN_CANCEL;
732 		/* wake up the scan task */
733 		scan_signal(ss);
734 	} else {
735 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
736 		    "%s: called; F_SCAN=%d, vap=%s, CANCEL=%d\n",
737 		        __func__,
738 			!! (ic->ic_flags & IEEE80211_F_SCAN),
739 			(ss->ss_vap == vap ? "match" : "nomatch"),
740 			!! (SCAN_PRIVATE(ss)->ss_iflags & ISCAN_CANCEL));
741 	}
742 	IEEE80211_UNLOCK(ic);
743 }
744 
745 /*
746  * Public access to scan_next for drivers that manage
747  * scanning themselves (e.g. for firmware-based devices).
748  */
749 void
750 ieee80211_scan_next(struct ieee80211vap *vap)
751 {
752 	struct ieee80211com *ic = vap->iv_ic;
753 	struct ieee80211_scan_state *ss = ic->ic_scan;
754 
755 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN, "%s: called\n", __func__);
756 
757 	/* wake up the scan task */
758 	IEEE80211_LOCK(ic);
759 	scan_signal(ss);
760 	IEEE80211_UNLOCK(ic);
761 }
762 
763 /*
764  * Public access to scan_next for drivers that are not able to scan single
765  * channels (e.g. for firmware-based devices).
766  */
767 void
768 ieee80211_scan_done(struct ieee80211vap *vap)
769 {
770 	struct ieee80211com *ic = vap->iv_ic;
771 	struct ieee80211_scan_state *ss;
772 
773 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN, "%s: called\n", __func__);
774 
775 	IEEE80211_LOCK(ic);
776 	ss = ic->ic_scan;
777 	ss->ss_next = ss->ss_last; /* all channels are complete */
778 	scan_signal(ss);
779 	IEEE80211_UNLOCK(ic);
780 }
781 
782 /*
783  * Probe the curent channel, if allowed, while scanning.
784  * If the channel is not marked passive-only then send
785  * a probe request immediately.  Otherwise mark state and
786  * listen for beacons on the channel; if we receive something
787  * then we'll transmit a probe request.
788  */
789 void
790 ieee80211_probe_curchan(struct ieee80211vap *vap, int force)
791 {
792 	struct ieee80211com *ic = vap->iv_ic;
793 	struct ieee80211_scan_state *ss = ic->ic_scan;
794 	struct ifnet *ifp = vap->iv_ifp;
795 	int i;
796 
797 	if ((ic->ic_curchan->ic_flags & IEEE80211_CHAN_PASSIVE) && !force) {
798 		ic->ic_flags_ext |= IEEE80211_FEXT_PROBECHAN;
799 		return;
800 	}
801 	/*
802 	 * Send directed probe requests followed by any
803 	 * broadcast probe request.
804 	 * XXX remove dependence on ic/vap->iv_bss
805 	 */
806 	for (i = 0; i < ss->ss_nssid; i++)
807 		ieee80211_send_probereq(vap->iv_bss,
808 			vap->iv_myaddr, ifp->if_broadcastaddr,
809 			ifp->if_broadcastaddr,
810 			ss->ss_ssid[i].ssid, ss->ss_ssid[i].len);
811 	if ((ss->ss_flags & IEEE80211_SCAN_NOBCAST) == 0)
812 		ieee80211_send_probereq(vap->iv_bss,
813 			vap->iv_myaddr, ifp->if_broadcastaddr,
814 			ifp->if_broadcastaddr,
815 			"", 0);
816 }
817 
818 /*
819  * Scan curchan.  If this is an active scan and the channel
820  * is not marked passive then send probe request frame(s).
821  * Arrange for the channel change after maxdwell ticks.
822  */
823 static void
824 scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell)
825 {
826 	struct ieee80211vap *vap  = ss->ss_vap;
827 
828 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
829 	    "%s: calling; maxdwell=%lu\n",
830 	    __func__,
831 	    maxdwell);
832 	IEEE80211_LOCK(vap->iv_ic);
833 	if (ss->ss_flags & IEEE80211_SCAN_ACTIVE)
834 		ieee80211_probe_curchan(vap, 0);
835 	callout_reset(&SCAN_PRIVATE(ss)->ss_scan_timer,
836 	    maxdwell, scan_signal, ss);
837 	IEEE80211_UNLOCK(vap->iv_ic);
838 }
839 
840 static void
841 scan_signal(void *arg)
842 {
843 	struct ieee80211_scan_state *ss = (struct ieee80211_scan_state *) arg;
844 
845 	IEEE80211_LOCK_ASSERT(ss->ss_ic);
846 	cv_signal(&SCAN_PRIVATE(ss)->ss_scan_cv);
847 }
848 
849 /*
850  * Handle mindwell requirements completed; initiate a channel
851  * change to the next channel asap.
852  */
853 static void
854 scan_mindwell(struct ieee80211_scan_state *ss)
855 {
856 	struct ieee80211com *ic = ss->ss_ic;
857 
858 	IEEE80211_DPRINTF(ss->ss_vap, IEEE80211_MSG_SCAN, "%s: called\n", __func__);
859 
860 	IEEE80211_LOCK(ic);
861 	scan_signal(ss);
862 	IEEE80211_UNLOCK(ic);
863 }
864 
865 static void
866 scan_task(void *arg, int pending)
867 {
868 #define	ISCAN_REP	(ISCAN_MINDWELL | ISCAN_DISCARD)
869 	struct ieee80211_scan_state *ss = (struct ieee80211_scan_state *) arg;
870 	struct ieee80211vap *vap = ss->ss_vap;
871 	struct ieee80211com *ic = ss->ss_ic;
872 	struct ieee80211_channel *chan;
873 	unsigned long maxdwell, scanend;
874 	int scandone = 0;
875 
876 	IEEE80211_LOCK(ic);
877 	if (vap == NULL || (ic->ic_flags & IEEE80211_F_SCAN) == 0 ||
878 	    (SCAN_PRIVATE(ss)->ss_iflags & ISCAN_ABORT)) {
879 		/* Cancelled before we started */
880 		goto done;
881 	}
882 
883 	if (ss->ss_next == ss->ss_last) {
884 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
885 			"%s: no channels to scan\n", __func__);
886 		scandone = 1;
887 		goto done;
888 	}
889 
890 	if (vap->iv_opmode == IEEE80211_M_STA &&
891 	    vap->iv_state == IEEE80211_S_RUN) {
892 		if ((vap->iv_bss->ni_flags & IEEE80211_NODE_PWR_MGT) == 0) {
893 			/* Enable station power save mode */
894 			vap->iv_sta_ps(vap, 1);
895 			/*
896 			 * Use an 1ms delay so the null data frame has a chance
897 			 * to go out.
898 			 * XXX Should use M_TXCB mechanism to eliminate this.
899 			 */
900 			cv_timedwait(&SCAN_PRIVATE(ss)->ss_scan_cv,
901 			    IEEE80211_LOCK_OBJ(ic), hz / 1000);
902 			if (SCAN_PRIVATE(ss)->ss_iflags & ISCAN_ABORT)
903 				goto done;
904 		}
905 	}
906 
907 	scanend = ticks + SCAN_PRIVATE(ss)->ss_duration;
908 
909 	/* XXX scan state can change! Re-validate scan state! */
910 
911 	IEEE80211_UNLOCK(ic);
912 	ic->ic_scan_start(ic);		/* notify driver */
913 	IEEE80211_LOCK(ic);
914 
915 	for (;;) {
916 
917 		scandone = (ss->ss_next >= ss->ss_last) ||
918 		    (SCAN_PRIVATE(ss)->ss_iflags & ISCAN_CANCEL) != 0;
919 
920 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
921 		    "%s: loop start; scandone=%d\n",
922 		    __func__,
923 		    scandone);
924 
925 		if (scandone || (ss->ss_flags & IEEE80211_SCAN_GOTPICK) ||
926 		    (SCAN_PRIVATE(ss)->ss_iflags & ISCAN_ABORT) ||
927 		     time_after(ticks + ss->ss_mindwell, scanend))
928 			break;
929 
930 		chan = ss->ss_chans[ss->ss_next++];
931 
932 		/*
933 		 * Watch for truncation due to the scan end time.
934 		 */
935 		if (time_after(ticks + ss->ss_maxdwell, scanend))
936 			maxdwell = scanend - ticks;
937 		else
938 			maxdwell = ss->ss_maxdwell;
939 
940 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
941 		    "%s: chan %3d%c -> %3d%c [%s, dwell min %lums max %lums]\n",
942 		    __func__,
943 		    ieee80211_chan2ieee(ic, ic->ic_curchan),
944 		        channel_type(ic->ic_curchan),
945 		    ieee80211_chan2ieee(ic, chan), channel_type(chan),
946 		    (ss->ss_flags & IEEE80211_SCAN_ACTIVE) &&
947 			(chan->ic_flags & IEEE80211_CHAN_PASSIVE) == 0 ?
948 			"active" : "passive",
949 		    ticks_to_msecs(ss->ss_mindwell), ticks_to_msecs(maxdwell));
950 
951 		/*
952 		 * Potentially change channel and phy mode.
953 		 */
954 		ic->ic_curchan = chan;
955 		ic->ic_rt = ieee80211_get_ratetable(chan);
956 		IEEE80211_UNLOCK(ic);
957 		/*
958 		 * Perform the channel change and scan unlocked so the driver
959 		 * may sleep. Once set_channel returns the hardware has
960 		 * completed the channel change.
961 		 */
962 		ic->ic_set_channel(ic);
963 		ieee80211_radiotap_chan_change(ic);
964 
965 		/*
966 		 * Scan curchan.  Drivers for "intelligent hardware"
967 		 * override ic_scan_curchan to tell the device to do
968 		 * the work.  Otherwise we manage the work outselves;
969 		 * sending a probe request (as needed), and arming the
970 		 * timeout to switch channels after maxdwell ticks.
971 		 *
972 		 * scan_curchan should only pause for the time required to
973 		 * prepare/initiate the hardware for the scan (if at all), the
974 		 * below condvar is used to sleep for the channels dwell time
975 		 * and allows it to be signalled for abort.
976 		 */
977 		ic->ic_scan_curchan(ss, maxdwell);
978 		IEEE80211_LOCK(ic);
979 
980 		/* XXX scan state can change! Re-validate scan state! */
981 
982 		SCAN_PRIVATE(ss)->ss_chanmindwell = ticks + ss->ss_mindwell;
983 		/* clear mindwell lock and initial channel change flush */
984 		SCAN_PRIVATE(ss)->ss_iflags &= ~ISCAN_REP;
985 
986 		if ((SCAN_PRIVATE(ss)->ss_iflags & (ISCAN_CANCEL|ISCAN_ABORT)))
987 			continue;
988 
989 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN, "%s: waiting\n", __func__);
990 		/* Wait to be signalled to scan the next channel */
991 		cv_wait(&SCAN_PRIVATE(ss)->ss_scan_cv, IEEE80211_LOCK_OBJ(ic));
992 	}
993 
994 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN, "%s: out\n", __func__);
995 
996 	if (SCAN_PRIVATE(ss)->ss_iflags & ISCAN_ABORT)
997 		goto done;
998 
999 	IEEE80211_UNLOCK(ic);
1000 	ic->ic_scan_end(ic);		/* notify driver */
1001 	IEEE80211_LOCK(ic);
1002 	/* XXX scan state can change! Re-validate scan state! */
1003 
1004 	/*
1005 	 * Since a cancellation may have occured during one of the
1006 	 * driver calls (whilst unlocked), update scandone.
1007 	 */
1008 	if (scandone == 0 &&
1009 	    ((SCAN_PRIVATE(ss)->ss_iflags & ISCAN_CANCEL) != 0)) {
1010 		/* XXX printf? */
1011 		if_printf(vap->iv_ifp,
1012 		    "%s: OOPS! scan cancelled during driver call (1)!\n",
1013 		    __func__);
1014 		scandone = 1;
1015 	}
1016 
1017 	/*
1018 	 * Record scan complete time.  Note that we also do
1019 	 * this when canceled so any background scan will
1020 	 * not be restarted for a while.
1021 	 */
1022 	if (scandone)
1023 		ic->ic_lastscan = ticks;
1024 	/* return to the bss channel */
1025 	if (ic->ic_bsschan != IEEE80211_CHAN_ANYC &&
1026 	    ic->ic_curchan != ic->ic_bsschan) {
1027 		ieee80211_setupcurchan(ic, ic->ic_bsschan);
1028 		IEEE80211_UNLOCK(ic);
1029 		ic->ic_set_channel(ic);
1030 		ieee80211_radiotap_chan_change(ic);
1031 		IEEE80211_LOCK(ic);
1032 	}
1033 	/* clear internal flags and any indication of a pick */
1034 	SCAN_PRIVATE(ss)->ss_iflags &= ~ISCAN_REP;
1035 	ss->ss_flags &= ~IEEE80211_SCAN_GOTPICK;
1036 
1037 	/*
1038 	 * If not canceled and scan completed, do post-processing.
1039 	 * If the callback function returns 0, then it wants to
1040 	 * continue/restart scanning.  Unfortunately we needed to
1041 	 * notify the driver to end the scan above to avoid having
1042 	 * rx frames alter the scan candidate list.
1043 	 */
1044 	if ((SCAN_PRIVATE(ss)->ss_iflags & ISCAN_CANCEL) == 0 &&
1045 	    !ss->ss_ops->scan_end(ss, vap) &&
1046 	    (ss->ss_flags & IEEE80211_SCAN_ONCE) == 0 &&
1047 	    time_before(ticks + ss->ss_mindwell, scanend)) {
1048 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
1049 		    "%s: done, restart "
1050 		    "[ticks %u, dwell min %lu scanend %lu]\n",
1051 		    __func__,
1052 		    ticks, ss->ss_mindwell, scanend);
1053 		ss->ss_next = 0;	/* reset to begining */
1054 		if (ss->ss_flags & IEEE80211_SCAN_ACTIVE)
1055 			vap->iv_stats.is_scan_active++;
1056 		else
1057 			vap->iv_stats.is_scan_passive++;
1058 
1059 		ss->ss_ops->scan_restart(ss, vap);	/* XXX? */
1060 		ieee80211_runtask(ic, &SCAN_PRIVATE(ss)->ss_scan_task);
1061 		IEEE80211_UNLOCK(ic);
1062 		return;
1063 	}
1064 
1065 	/* past here, scandone is ``true'' if not in bg mode */
1066 	if ((ss->ss_flags & IEEE80211_SCAN_BGSCAN) == 0)
1067 		scandone = 1;
1068 
1069 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
1070 	    "%s: %s, [ticks %u, dwell min %lu scanend %lu]\n",
1071 	    __func__, scandone ? "done" : "stopped",
1072 	    ticks, ss->ss_mindwell, scanend);
1073 
1074 	/*
1075 	 * Since a cancellation may have occured during one of the
1076 	 * driver calls (whilst unlocked), update scandone.
1077 	 */
1078 	if (scandone == 0 &&
1079 	    ((SCAN_PRIVATE(ss)->ss_iflags & ISCAN_CANCEL) != 0)) {
1080 		/* XXX printf? */
1081 		if_printf(vap->iv_ifp,
1082 		    "%s: OOPS! scan cancelled during driver call (2)!\n",
1083 		    __func__);
1084 		scandone = 1;
1085 	}
1086 
1087 	/*
1088 	 * Clear the SCAN bit first in case frames are
1089 	 * pending on the station power save queue.  If
1090 	 * we defer this then the dispatch of the frames
1091 	 * may generate a request to cancel scanning.
1092 	 */
1093 done:
1094 	ic->ic_flags &= ~IEEE80211_F_SCAN;
1095 	/*
1096 	 * Drop out of power save mode when a scan has
1097 	 * completed.  If this scan was prematurely terminated
1098 	 * because it is a background scan then don't notify
1099 	 * the ap; we'll either return to scanning after we
1100 	 * receive the beacon frame or we'll drop out of power
1101 	 * save mode because the beacon indicates we have frames
1102 	 * waiting for us.
1103 	 */
1104 	if (scandone) {
1105 		vap->iv_sta_ps(vap, 0);
1106 		if (ss->ss_next >= ss->ss_last) {
1107 			ieee80211_notify_scan_done(vap);
1108 			ic->ic_flags_ext &= ~IEEE80211_FEXT_BGSCAN;
1109 		}
1110 	}
1111 	SCAN_PRIVATE(ss)->ss_iflags &= ~(ISCAN_CANCEL|ISCAN_ABORT);
1112 	ss->ss_flags &= ~(IEEE80211_SCAN_ONCE | IEEE80211_SCAN_PICK1ST);
1113 	IEEE80211_UNLOCK(ic);
1114 #undef ISCAN_REP
1115 }
1116 
1117 #ifdef IEEE80211_DEBUG
1118 static void
1119 dump_country(const uint8_t *ie)
1120 {
1121 	const struct ieee80211_country_ie *cie =
1122 	   (const struct ieee80211_country_ie *) ie;
1123 	int i, nbands, schan, nchan;
1124 
1125 	if (cie->len < 3) {
1126 		printf(" <bogus country ie, len %d>", cie->len);
1127 		return;
1128 	}
1129 	printf(" country [%c%c%c", cie->cc[0], cie->cc[1], cie->cc[2]);
1130 	nbands = (cie->len - 3) / sizeof(cie->band[0]);
1131 	for (i = 0; i < nbands; i++) {
1132 		schan = cie->band[i].schan;
1133 		nchan = cie->band[i].nchan;
1134 		if (nchan != 1)
1135 			printf(" %u-%u,%u", schan, schan + nchan-1,
1136 			    cie->band[i].maxtxpwr);
1137 		else
1138 			printf(" %u,%u", schan, cie->band[i].maxtxpwr);
1139 	}
1140 	printf("]");
1141 }
1142 
1143 static void
1144 dump_probe_beacon(uint8_t subtype, int isnew,
1145 	const uint8_t mac[IEEE80211_ADDR_LEN],
1146 	const struct ieee80211_scanparams *sp, int rssi)
1147 {
1148 
1149 	printf("[%s] %s%s on chan %u (bss chan %u) ",
1150 	    ether_sprintf(mac), isnew ? "new " : "",
1151 	    ieee80211_mgt_subtype_name[subtype >> IEEE80211_FC0_SUBTYPE_SHIFT],
1152 	    sp->chan, sp->bchan);
1153 	ieee80211_print_essid(sp->ssid + 2, sp->ssid[1]);
1154 	printf(" rssi %d\n", rssi);
1155 
1156 	if (isnew) {
1157 		printf("[%s] caps 0x%x bintval %u erp 0x%x",
1158 			ether_sprintf(mac), sp->capinfo, sp->bintval, sp->erp);
1159 		if (sp->country != NULL)
1160 			dump_country(sp->country);
1161 		printf("\n");
1162 	}
1163 }
1164 #endif /* IEEE80211_DEBUG */
1165 
1166 /*
1167  * Process a beacon or probe response frame.
1168  */
1169 void
1170 ieee80211_add_scan(struct ieee80211vap *vap,
1171 	const struct ieee80211_scanparams *sp,
1172 	const struct ieee80211_frame *wh,
1173 	int subtype, int rssi, int noise)
1174 {
1175 	struct ieee80211com *ic = vap->iv_ic;
1176 	struct ieee80211_scan_state *ss = ic->ic_scan;
1177 
1178 	/* XXX locking */
1179 	/*
1180 	 * Frames received during startup are discarded to avoid
1181 	 * using scan state setup on the initial entry to the timer
1182 	 * callback.  This can occur because the device may enable
1183 	 * rx prior to our doing the initial channel change in the
1184 	 * timer routine.
1185 	 */
1186 	if (SCAN_PRIVATE(ss)->ss_iflags & ISCAN_DISCARD)
1187 		return;
1188 #ifdef IEEE80211_DEBUG
1189 	if (ieee80211_msg_scan(vap) && (ic->ic_flags & IEEE80211_F_SCAN))
1190 		dump_probe_beacon(subtype, 1, wh->i_addr2, sp, rssi);
1191 #endif
1192 	if (ss->ss_ops != NULL &&
1193 	    ss->ss_ops->scan_add(ss, sp, wh, subtype, rssi, noise)) {
1194 		/*
1195 		 * If we've reached the min dwell time terminate
1196 		 * the timer so we'll switch to the next channel.
1197 		 */
1198 		if ((SCAN_PRIVATE(ss)->ss_iflags & ISCAN_MINDWELL) == 0 &&
1199 		    time_after_eq(ticks, SCAN_PRIVATE(ss)->ss_chanmindwell)) {
1200 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
1201 			    "%s: chan %3d%c min dwell met (%u > %lu)\n",
1202 			    __func__,
1203 			    ieee80211_chan2ieee(ic, ic->ic_curchan),
1204 				channel_type(ic->ic_curchan),
1205 			    ticks, SCAN_PRIVATE(ss)->ss_chanmindwell);
1206 			SCAN_PRIVATE(ss)->ss_iflags |= ISCAN_MINDWELL;
1207 			/*
1208 			 * NB: trigger at next clock tick or wait for the
1209 			 * hardware.
1210 			 */
1211 			ic->ic_scan_mindwell(ss);
1212 		}
1213 	}
1214 }
1215 
1216 /*
1217  * Timeout/age scan cache entries; called from sta timeout
1218  * timer (XXX should be self-contained).
1219  */
1220 void
1221 ieee80211_scan_timeout(struct ieee80211com *ic)
1222 {
1223 	struct ieee80211_scan_state *ss = ic->ic_scan;
1224 
1225 	if (ss->ss_ops != NULL)
1226 		ss->ss_ops->scan_age(ss);
1227 }
1228 
1229 /*
1230  * Mark a scan cache entry after a successful associate.
1231  */
1232 void
1233 ieee80211_scan_assoc_success(struct ieee80211vap *vap, const uint8_t mac[])
1234 {
1235 	struct ieee80211_scan_state *ss = vap->iv_ic->ic_scan;
1236 
1237 	if (ss->ss_ops != NULL) {
1238 		IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_SCAN,
1239 			mac, "%s",  __func__);
1240 		ss->ss_ops->scan_assoc_success(ss, mac);
1241 	}
1242 }
1243 
1244 /*
1245  * Demerit a scan cache entry after failing to associate.
1246  */
1247 void
1248 ieee80211_scan_assoc_fail(struct ieee80211vap *vap,
1249 	const uint8_t mac[], int reason)
1250 {
1251 	struct ieee80211_scan_state *ss = vap->iv_ic->ic_scan;
1252 
1253 	if (ss->ss_ops != NULL) {
1254 		IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_SCAN, mac,
1255 			"%s: reason %u", __func__, reason);
1256 		ss->ss_ops->scan_assoc_fail(ss, mac, reason);
1257 	}
1258 }
1259 
1260 /*
1261  * Iterate over the contents of the scan cache.
1262  */
1263 void
1264 ieee80211_scan_iterate(struct ieee80211vap *vap,
1265 	ieee80211_scan_iter_func *f, void *arg)
1266 {
1267 	struct ieee80211_scan_state *ss = vap->iv_ic->ic_scan;
1268 
1269 	if (ss->ss_ops != NULL)
1270 		ss->ss_ops->scan_iterate(ss, f, arg);
1271 }
1272 
1273 /*
1274  * Flush the contents of the scan cache.
1275  */
1276 void
1277 ieee80211_scan_flush(struct ieee80211vap *vap)
1278 {
1279 	struct ieee80211_scan_state *ss = vap->iv_ic->ic_scan;
1280 
1281 	if (ss->ss_ops != NULL && ss->ss_vap == vap) {
1282 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN, "%s\n",  __func__);
1283 		ss->ss_ops->scan_flush(ss);
1284 	}
1285 }
1286 
1287 /*
1288  * Check the scan cache for an ap/channel to use; if that
1289  * fails then kick off a new scan.
1290  */
1291 struct ieee80211_channel *
1292 ieee80211_scan_pickchannel(struct ieee80211com *ic, int flags)
1293 {
1294 	struct ieee80211_scan_state *ss = ic->ic_scan;
1295 
1296 	IEEE80211_LOCK_ASSERT(ic);
1297 
1298 	if (ss == NULL || ss->ss_ops == NULL || ss->ss_vap == NULL) {
1299 		/* XXX printf? */
1300 		return NULL;
1301 	}
1302 	if (ss->ss_ops->scan_pickchan == NULL) {
1303 		IEEE80211_DPRINTF(ss->ss_vap, IEEE80211_MSG_SCAN,
1304 		    "%s: scan module does not support picking a channel, "
1305 		    "opmode %s\n", __func__, ss->ss_vap->iv_opmode);
1306 		return NULL;
1307 	}
1308 	return ss->ss_ops->scan_pickchan(ss, flags);
1309 }
1310