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