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