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