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