]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net80211/ieee80211.c
net80211: fix 'pending CAC -> RUN transition lost' bug.
[FreeBSD/FreeBSD.git] / sys / net80211 / ieee80211.c
1 /*-
2  * Copyright (c) 2001 Atsushi Onoe
3  * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 /*
31  * IEEE 802.11 generic handler
32  */
33 #include "opt_wlan.h"
34
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/malloc.h>
39 #include <sys/socket.h>
40 #include <sys/sbuf.h>
41
42 #include <machine/stdarg.h>
43
44 #include <net/if.h>
45 #include <net/if_var.h>
46 #include <net/if_dl.h>
47 #include <net/if_media.h>
48 #include <net/if_types.h>
49 #include <net/ethernet.h>
50
51 #include <net80211/ieee80211_var.h>
52 #include <net80211/ieee80211_regdomain.h>
53 #ifdef IEEE80211_SUPPORT_SUPERG
54 #include <net80211/ieee80211_superg.h>
55 #endif
56 #include <net80211/ieee80211_ratectl.h>
57
58 #include <net/bpf.h>
59
60 const char *ieee80211_phymode_name[IEEE80211_MODE_MAX] = {
61         [IEEE80211_MODE_AUTO]     = "auto",
62         [IEEE80211_MODE_11A]      = "11a",
63         [IEEE80211_MODE_11B]      = "11b",
64         [IEEE80211_MODE_11G]      = "11g",
65         [IEEE80211_MODE_FH]       = "FH",
66         [IEEE80211_MODE_TURBO_A]  = "turboA",
67         [IEEE80211_MODE_TURBO_G]  = "turboG",
68         [IEEE80211_MODE_STURBO_A] = "sturboA",
69         [IEEE80211_MODE_HALF]     = "half",
70         [IEEE80211_MODE_QUARTER]  = "quarter",
71         [IEEE80211_MODE_11NA]     = "11na",
72         [IEEE80211_MODE_11NG]     = "11ng",
73 };
74 /* map ieee80211_opmode to the corresponding capability bit */
75 const int ieee80211_opcap[IEEE80211_OPMODE_MAX] = {
76         [IEEE80211_M_IBSS]      = IEEE80211_C_IBSS,
77         [IEEE80211_M_WDS]       = IEEE80211_C_WDS,
78         [IEEE80211_M_STA]       = IEEE80211_C_STA,
79         [IEEE80211_M_AHDEMO]    = IEEE80211_C_AHDEMO,
80         [IEEE80211_M_HOSTAP]    = IEEE80211_C_HOSTAP,
81         [IEEE80211_M_MONITOR]   = IEEE80211_C_MONITOR,
82 #ifdef IEEE80211_SUPPORT_MESH
83         [IEEE80211_M_MBSS]      = IEEE80211_C_MBSS,
84 #endif
85 };
86
87 const uint8_t ieee80211broadcastaddr[IEEE80211_ADDR_LEN] =
88         { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
89
90 static  void ieee80211_syncflag_locked(struct ieee80211com *ic, int flag);
91 static  void ieee80211_syncflag_ht_locked(struct ieee80211com *ic, int flag);
92 static  void ieee80211_syncflag_ext_locked(struct ieee80211com *ic, int flag);
93 static  int ieee80211_media_setup(struct ieee80211com *ic,
94                 struct ifmedia *media, int caps, int addsta,
95                 ifm_change_cb_t media_change, ifm_stat_cb_t media_stat);
96 static  int media_status(enum ieee80211_opmode,
97                 const struct ieee80211_channel *);
98 static uint64_t ieee80211_get_counter(struct ifnet *, ift_counter);
99
100 MALLOC_DEFINE(M_80211_VAP, "80211vap", "802.11 vap state");
101
102 /*
103  * Default supported rates for 802.11 operation (in IEEE .5Mb units).
104  */
105 #define B(r)    ((r) | IEEE80211_RATE_BASIC)
106 static const struct ieee80211_rateset ieee80211_rateset_11a =
107         { 8, { B(12), 18, B(24), 36, B(48), 72, 96, 108 } };
108 static const struct ieee80211_rateset ieee80211_rateset_half =
109         { 8, { B(6), 9, B(12), 18, B(24), 36, 48, 54 } };
110 static const struct ieee80211_rateset ieee80211_rateset_quarter =
111         { 8, { B(3), 4, B(6), 9, B(12), 18, 24, 27 } };
112 static const struct ieee80211_rateset ieee80211_rateset_11b =
113         { 4, { B(2), B(4), B(11), B(22) } };
114 /* NB: OFDM rates are handled specially based on mode */
115 static const struct ieee80211_rateset ieee80211_rateset_11g =
116         { 12, { B(2), B(4), B(11), B(22), 12, 18, 24, 36, 48, 72, 96, 108 } };
117 #undef B
118
119 /*
120  * Fill in 802.11 available channel set, mark
121  * all available channels as active, and pick
122  * a default channel if not already specified.
123  */
124 void
125 ieee80211_chan_init(struct ieee80211com *ic)
126 {
127 #define DEFAULTRATES(m, def) do { \
128         if (ic->ic_sup_rates[m].rs_nrates == 0) \
129                 ic->ic_sup_rates[m] = def; \
130 } while (0)
131         struct ieee80211_channel *c;
132         int i;
133
134         KASSERT(0 < ic->ic_nchans && ic->ic_nchans <= IEEE80211_CHAN_MAX,
135                 ("invalid number of channels specified: %u", ic->ic_nchans));
136         memset(ic->ic_chan_avail, 0, sizeof(ic->ic_chan_avail));
137         memset(ic->ic_modecaps, 0, sizeof(ic->ic_modecaps));
138         setbit(ic->ic_modecaps, IEEE80211_MODE_AUTO);
139         for (i = 0; i < ic->ic_nchans; i++) {
140                 c = &ic->ic_channels[i];
141                 KASSERT(c->ic_flags != 0, ("channel with no flags"));
142                 /*
143                  * Help drivers that work only with frequencies by filling
144                  * in IEEE channel #'s if not already calculated.  Note this
145                  * mimics similar work done in ieee80211_setregdomain when
146                  * changing regulatory state.
147                  */
148                 if (c->ic_ieee == 0)
149                         c->ic_ieee = ieee80211_mhz2ieee(c->ic_freq,c->ic_flags);
150                 if (IEEE80211_IS_CHAN_HT40(c) && c->ic_extieee == 0)
151                         c->ic_extieee = ieee80211_mhz2ieee(c->ic_freq +
152                             (IEEE80211_IS_CHAN_HT40U(c) ? 20 : -20),
153                             c->ic_flags);
154                 /* default max tx power to max regulatory */
155                 if (c->ic_maxpower == 0)
156                         c->ic_maxpower = 2*c->ic_maxregpower;
157                 setbit(ic->ic_chan_avail, c->ic_ieee);
158                 /*
159                  * Identify mode capabilities.
160                  */
161                 if (IEEE80211_IS_CHAN_A(c))
162                         setbit(ic->ic_modecaps, IEEE80211_MODE_11A);
163                 if (IEEE80211_IS_CHAN_B(c))
164                         setbit(ic->ic_modecaps, IEEE80211_MODE_11B);
165                 if (IEEE80211_IS_CHAN_ANYG(c))
166                         setbit(ic->ic_modecaps, IEEE80211_MODE_11G);
167                 if (IEEE80211_IS_CHAN_FHSS(c))
168                         setbit(ic->ic_modecaps, IEEE80211_MODE_FH);
169                 if (IEEE80211_IS_CHAN_108A(c))
170                         setbit(ic->ic_modecaps, IEEE80211_MODE_TURBO_A);
171                 if (IEEE80211_IS_CHAN_108G(c))
172                         setbit(ic->ic_modecaps, IEEE80211_MODE_TURBO_G);
173                 if (IEEE80211_IS_CHAN_ST(c))
174                         setbit(ic->ic_modecaps, IEEE80211_MODE_STURBO_A);
175                 if (IEEE80211_IS_CHAN_HALF(c))
176                         setbit(ic->ic_modecaps, IEEE80211_MODE_HALF);
177                 if (IEEE80211_IS_CHAN_QUARTER(c))
178                         setbit(ic->ic_modecaps, IEEE80211_MODE_QUARTER);
179                 if (IEEE80211_IS_CHAN_HTA(c))
180                         setbit(ic->ic_modecaps, IEEE80211_MODE_11NA);
181                 if (IEEE80211_IS_CHAN_HTG(c))
182                         setbit(ic->ic_modecaps, IEEE80211_MODE_11NG);
183         }
184         /* initialize candidate channels to all available */
185         memcpy(ic->ic_chan_active, ic->ic_chan_avail,
186                 sizeof(ic->ic_chan_avail));
187
188         /* sort channel table to allow lookup optimizations */
189         ieee80211_sort_channels(ic->ic_channels, ic->ic_nchans);
190
191         /* invalidate any previous state */
192         ic->ic_bsschan = IEEE80211_CHAN_ANYC;
193         ic->ic_prevchan = NULL;
194         ic->ic_csa_newchan = NULL;
195         /* arbitrarily pick the first channel */
196         ic->ic_curchan = &ic->ic_channels[0];
197         ic->ic_rt = ieee80211_get_ratetable(ic->ic_curchan);
198
199         /* fillin well-known rate sets if driver has not specified */
200         DEFAULTRATES(IEEE80211_MODE_11B,         ieee80211_rateset_11b);
201         DEFAULTRATES(IEEE80211_MODE_11G,         ieee80211_rateset_11g);
202         DEFAULTRATES(IEEE80211_MODE_11A,         ieee80211_rateset_11a);
203         DEFAULTRATES(IEEE80211_MODE_TURBO_A,     ieee80211_rateset_11a);
204         DEFAULTRATES(IEEE80211_MODE_TURBO_G,     ieee80211_rateset_11g);
205         DEFAULTRATES(IEEE80211_MODE_STURBO_A,    ieee80211_rateset_11a);
206         DEFAULTRATES(IEEE80211_MODE_HALF,        ieee80211_rateset_half);
207         DEFAULTRATES(IEEE80211_MODE_QUARTER,     ieee80211_rateset_quarter);
208         DEFAULTRATES(IEEE80211_MODE_11NA,        ieee80211_rateset_11a);
209         DEFAULTRATES(IEEE80211_MODE_11NG,        ieee80211_rateset_11g);
210
211         /*
212          * Setup required information to fill the mcsset field, if driver did
213          * not. Assume a 2T2R setup for historic reasons.
214          */
215         if (ic->ic_rxstream == 0)
216                 ic->ic_rxstream = 2;
217         if (ic->ic_txstream == 0)
218                 ic->ic_txstream = 2;
219
220         /*
221          * Set auto mode to reset active channel state and any desired channel.
222          */
223         (void) ieee80211_setmode(ic, IEEE80211_MODE_AUTO);
224 #undef DEFAULTRATES
225 }
226
227 static void
228 null_update_mcast(struct ieee80211com *ic)
229 {
230
231         ic_printf(ic, "need multicast update callback\n");
232 }
233
234 static void
235 null_update_promisc(struct ieee80211com *ic)
236 {
237
238         ic_printf(ic, "need promiscuous mode update callback\n");
239 }
240
241 static void
242 null_update_chw(struct ieee80211com *ic)
243 {
244
245         ic_printf(ic, "%s: need callback\n", __func__);
246 }
247
248 int
249 ic_printf(struct ieee80211com *ic, const char * fmt, ...)
250
251         va_list ap;
252         int retval;
253
254         retval = printf("%s: ", ic->ic_name);
255         va_start(ap, fmt);
256         retval += vprintf(fmt, ap);
257         va_end(ap);  
258         return (retval);
259 }
260
261 static LIST_HEAD(, ieee80211com) ic_head = LIST_HEAD_INITIALIZER(ic_head);
262 static struct mtx ic_list_mtx;
263 MTX_SYSINIT(ic_list, &ic_list_mtx, "ieee80211com list", MTX_DEF);
264
265 static int
266 sysctl_ieee80211coms(SYSCTL_HANDLER_ARGS)
267 {
268         struct ieee80211com *ic;
269         struct sbuf sb;
270         char *sp;
271         int error;
272
273         error = sysctl_wire_old_buffer(req, 0);
274         if (error)
275                 return (error);
276         sbuf_new_for_sysctl(&sb, NULL, 8, req);
277         sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
278         sp = "";
279         mtx_lock(&ic_list_mtx);
280         LIST_FOREACH(ic, &ic_head, ic_next) {
281                 sbuf_printf(&sb, "%s%s", sp, ic->ic_name);
282                 sp = " ";
283         }
284         mtx_unlock(&ic_list_mtx);
285         error = sbuf_finish(&sb);
286         sbuf_delete(&sb);
287         return (error);
288 }
289
290 SYSCTL_PROC(_net_wlan, OID_AUTO, devices,
291     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
292     sysctl_ieee80211coms, "A", "names of available 802.11 devices");
293
294 /*
295  * Attach/setup the common net80211 state.  Called by
296  * the driver on attach to prior to creating any vap's.
297  */
298 void
299 ieee80211_ifattach(struct ieee80211com *ic)
300 {
301
302         IEEE80211_LOCK_INIT(ic, ic->ic_name);
303         IEEE80211_TX_LOCK_INIT(ic, ic->ic_name);
304         TAILQ_INIT(&ic->ic_vaps);
305
306         /* Create a taskqueue for all state changes */
307         ic->ic_tq = taskqueue_create("ic_taskq", M_WAITOK | M_ZERO,
308             taskqueue_thread_enqueue, &ic->ic_tq);
309         taskqueue_start_threads(&ic->ic_tq, 1, PI_NET, "%s net80211 taskq",
310             ic->ic_name);
311         ic->ic_ierrors = counter_u64_alloc(M_WAITOK);
312         ic->ic_oerrors = counter_u64_alloc(M_WAITOK);
313         /*
314          * Fill in 802.11 available channel set, mark all
315          * available channels as active, and pick a default
316          * channel if not already specified.
317          */
318         ieee80211_chan_init(ic);
319
320         ic->ic_update_mcast = null_update_mcast;
321         ic->ic_update_promisc = null_update_promisc;
322         ic->ic_update_chw = null_update_chw;
323
324         ic->ic_hash_key = arc4random();
325         ic->ic_bintval = IEEE80211_BINTVAL_DEFAULT;
326         ic->ic_lintval = ic->ic_bintval;
327         ic->ic_txpowlimit = IEEE80211_TXPOWER_MAX;
328
329         ieee80211_crypto_attach(ic);
330         ieee80211_node_attach(ic);
331         ieee80211_power_attach(ic);
332         ieee80211_proto_attach(ic);
333 #ifdef IEEE80211_SUPPORT_SUPERG
334         ieee80211_superg_attach(ic);
335 #endif
336         ieee80211_ht_attach(ic);
337         ieee80211_scan_attach(ic);
338         ieee80211_regdomain_attach(ic);
339         ieee80211_dfs_attach(ic);
340
341         ieee80211_sysctl_attach(ic);
342
343         mtx_lock(&ic_list_mtx);
344         LIST_INSERT_HEAD(&ic_head, ic, ic_next);
345         mtx_unlock(&ic_list_mtx);
346 }
347
348 /*
349  * Detach net80211 state on device detach.  Tear down
350  * all vap's and reclaim all common state prior to the
351  * device state going away.  Note we may call back into
352  * driver; it must be prepared for this.
353  */
354 void
355 ieee80211_ifdetach(struct ieee80211com *ic)
356 {
357         struct ieee80211vap *vap;
358
359         mtx_lock(&ic_list_mtx);
360         LIST_REMOVE(ic, ic_next);
361         mtx_unlock(&ic_list_mtx);
362
363         taskqueue_drain(taskqueue_thread, &ic->ic_restart_task);
364
365         /*
366          * The VAP is responsible for setting and clearing
367          * the VIMAGE context.
368          */
369         while ((vap = TAILQ_FIRST(&ic->ic_vaps)) != NULL)
370                 ieee80211_vap_destroy(vap);
371         ieee80211_waitfor_parent(ic);
372
373         ieee80211_sysctl_detach(ic);
374         ieee80211_dfs_detach(ic);
375         ieee80211_regdomain_detach(ic);
376         ieee80211_scan_detach(ic);
377 #ifdef IEEE80211_SUPPORT_SUPERG
378         ieee80211_superg_detach(ic);
379 #endif
380         ieee80211_ht_detach(ic);
381         /* NB: must be called before ieee80211_node_detach */
382         ieee80211_proto_detach(ic);
383         ieee80211_crypto_detach(ic);
384         ieee80211_power_detach(ic);
385         ieee80211_node_detach(ic);
386
387         counter_u64_free(ic->ic_ierrors);
388         counter_u64_free(ic->ic_oerrors);
389
390         taskqueue_free(ic->ic_tq);
391         IEEE80211_TX_LOCK_DESTROY(ic);
392         IEEE80211_LOCK_DESTROY(ic);
393 }
394
395 struct ieee80211com *
396 ieee80211_find_com(const char *name)
397 {
398         struct ieee80211com *ic;
399
400         mtx_lock(&ic_list_mtx);
401         LIST_FOREACH(ic, &ic_head, ic_next)
402                 if (strcmp(ic->ic_name, name) == 0)
403                         break;
404         mtx_unlock(&ic_list_mtx);
405
406         return (ic);
407 }
408
409 void
410 ieee80211_iterate_coms(ieee80211_com_iter_func *f, void *arg)
411 {
412         struct ieee80211com *ic;
413
414         mtx_lock(&ic_list_mtx);
415         LIST_FOREACH(ic, &ic_head, ic_next)
416                 (*f)(arg, ic);
417         mtx_unlock(&ic_list_mtx);
418 }
419
420 /*
421  * Default reset method for use with the ioctl support.  This
422  * method is invoked after any state change in the 802.11
423  * layer that should be propagated to the hardware but not
424  * require re-initialization of the 802.11 state machine (e.g
425  * rescanning for an ap).  We always return ENETRESET which
426  * should cause the driver to re-initialize the device. Drivers
427  * can override this method to implement more optimized support.
428  */
429 static int
430 default_reset(struct ieee80211vap *vap, u_long cmd)
431 {
432         return ENETRESET;
433 }
434
435 /*
436  * Add underlying device errors to vap errors.
437  */
438 static uint64_t
439 ieee80211_get_counter(struct ifnet *ifp, ift_counter cnt)
440 {
441         struct ieee80211vap *vap = ifp->if_softc;
442         struct ieee80211com *ic = vap->iv_ic;
443         uint64_t rv;
444
445         rv = if_get_counter_default(ifp, cnt);
446         switch (cnt) {
447         case IFCOUNTER_OERRORS:
448                 rv += counter_u64_fetch(ic->ic_oerrors);
449                 break;
450         case IFCOUNTER_IERRORS:
451                 rv += counter_u64_fetch(ic->ic_ierrors);
452                 break;
453         default:
454                 break;
455         }
456
457         return (rv);
458 }
459
460 /*
461  * Prepare a vap for use.  Drivers use this call to
462  * setup net80211 state in new vap's prior attaching
463  * them with ieee80211_vap_attach (below).
464  */
465 int
466 ieee80211_vap_setup(struct ieee80211com *ic, struct ieee80211vap *vap,
467     const char name[IFNAMSIZ], int unit, enum ieee80211_opmode opmode,
468     int flags, const uint8_t bssid[IEEE80211_ADDR_LEN])
469 {
470         struct ifnet *ifp;
471
472         ifp = if_alloc(IFT_ETHER);
473         if (ifp == NULL) {
474                 ic_printf(ic, "%s: unable to allocate ifnet\n",
475                     __func__);
476                 return ENOMEM;
477         }
478         if_initname(ifp, name, unit);
479         ifp->if_softc = vap;                    /* back pointer */
480         ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
481         ifp->if_transmit = ieee80211_vap_transmit;
482         ifp->if_qflush = ieee80211_vap_qflush;
483         ifp->if_ioctl = ieee80211_ioctl;
484         ifp->if_init = ieee80211_init;
485         ifp->if_get_counter = ieee80211_get_counter;
486
487         vap->iv_ifp = ifp;
488         vap->iv_ic = ic;
489         vap->iv_flags = ic->ic_flags;           /* propagate common flags */
490         vap->iv_flags_ext = ic->ic_flags_ext;
491         vap->iv_flags_ven = ic->ic_flags_ven;
492         vap->iv_caps = ic->ic_caps &~ IEEE80211_C_OPMODE;
493         vap->iv_htcaps = ic->ic_htcaps;
494         vap->iv_htextcaps = ic->ic_htextcaps;
495         vap->iv_opmode = opmode;
496         vap->iv_caps |= ieee80211_opcap[opmode];
497         IEEE80211_ADDR_COPY(vap->iv_myaddr, ic->ic_macaddr);
498         switch (opmode) {
499         case IEEE80211_M_WDS:
500                 /*
501                  * WDS links must specify the bssid of the far end.
502                  * For legacy operation this is a static relationship.
503                  * For non-legacy operation the station must associate
504                  * and be authorized to pass traffic.  Plumbing the
505                  * vap to the proper node happens when the vap
506                  * transitions to RUN state.
507                  */
508                 IEEE80211_ADDR_COPY(vap->iv_des_bssid, bssid);
509                 vap->iv_flags |= IEEE80211_F_DESBSSID;
510                 if (flags & IEEE80211_CLONE_WDSLEGACY)
511                         vap->iv_flags_ext |= IEEE80211_FEXT_WDSLEGACY;
512                 break;
513 #ifdef IEEE80211_SUPPORT_TDMA
514         case IEEE80211_M_AHDEMO:
515                 if (flags & IEEE80211_CLONE_TDMA) {
516                         /* NB: checked before clone operation allowed */
517                         KASSERT(ic->ic_caps & IEEE80211_C_TDMA,
518                             ("not TDMA capable, ic_caps 0x%x", ic->ic_caps));
519                         /*
520                          * Propagate TDMA capability to mark vap; this
521                          * cannot be removed and is used to distinguish
522                          * regular ahdemo operation from ahdemo+tdma.
523                          */
524                         vap->iv_caps |= IEEE80211_C_TDMA;
525                 }
526                 break;
527 #endif
528         default:
529                 break;
530         }
531         /* auto-enable s/w beacon miss support */
532         if (flags & IEEE80211_CLONE_NOBEACONS)
533                 vap->iv_flags_ext |= IEEE80211_FEXT_SWBMISS;
534         /* auto-generated or user supplied MAC address */
535         if (flags & (IEEE80211_CLONE_BSSID|IEEE80211_CLONE_MACADDR))
536                 vap->iv_flags_ext |= IEEE80211_FEXT_UNIQMAC;
537         /*
538          * Enable various functionality by default if we're
539          * capable; the driver can override us if it knows better.
540          */
541         if (vap->iv_caps & IEEE80211_C_WME)
542                 vap->iv_flags |= IEEE80211_F_WME;
543         if (vap->iv_caps & IEEE80211_C_BURST)
544                 vap->iv_flags |= IEEE80211_F_BURST;
545         /* NB: bg scanning only makes sense for station mode right now */
546         if (vap->iv_opmode == IEEE80211_M_STA &&
547             (vap->iv_caps & IEEE80211_C_BGSCAN))
548                 vap->iv_flags |= IEEE80211_F_BGSCAN;
549         vap->iv_flags |= IEEE80211_F_DOTH;      /* XXX no cap, just ena */
550         /* NB: DFS support only makes sense for ap mode right now */
551         if (vap->iv_opmode == IEEE80211_M_HOSTAP &&
552             (vap->iv_caps & IEEE80211_C_DFS))
553                 vap->iv_flags_ext |= IEEE80211_FEXT_DFS;
554
555         vap->iv_des_chan = IEEE80211_CHAN_ANYC;         /* any channel is ok */
556         vap->iv_bmissthreshold = IEEE80211_HWBMISS_DEFAULT;
557         vap->iv_dtim_period = IEEE80211_DTIM_DEFAULT;
558         /*
559          * Install a default reset method for the ioctl support;
560          * the driver can override this.
561          */
562         vap->iv_reset = default_reset;
563
564         ieee80211_sysctl_vattach(vap);
565         ieee80211_crypto_vattach(vap);
566         ieee80211_node_vattach(vap);
567         ieee80211_power_vattach(vap);
568         ieee80211_proto_vattach(vap);
569 #ifdef IEEE80211_SUPPORT_SUPERG
570         ieee80211_superg_vattach(vap);
571 #endif
572         ieee80211_ht_vattach(vap);
573         ieee80211_scan_vattach(vap);
574         ieee80211_regdomain_vattach(vap);
575         ieee80211_radiotap_vattach(vap);
576         ieee80211_ratectl_set(vap, IEEE80211_RATECTL_NONE);
577
578         return 0;
579 }
580
581 /*
582  * Activate a vap.  State should have been prepared with a
583  * call to ieee80211_vap_setup and by the driver.  On return
584  * from this call the vap is ready for use.
585  */
586 int
587 ieee80211_vap_attach(struct ieee80211vap *vap, ifm_change_cb_t media_change,
588     ifm_stat_cb_t media_stat, const uint8_t macaddr[IEEE80211_ADDR_LEN])
589 {
590         struct ifnet *ifp = vap->iv_ifp;
591         struct ieee80211com *ic = vap->iv_ic;
592         struct ifmediareq imr;
593         int maxrate;
594
595         IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
596             "%s: %s parent %s flags 0x%x flags_ext 0x%x\n",
597             __func__, ieee80211_opmode_name[vap->iv_opmode],
598             ic->ic_name, vap->iv_flags, vap->iv_flags_ext);
599
600         /*
601          * Do late attach work that cannot happen until after
602          * the driver has had a chance to override defaults.
603          */
604         ieee80211_node_latevattach(vap);
605         ieee80211_power_latevattach(vap);
606
607         maxrate = ieee80211_media_setup(ic, &vap->iv_media, vap->iv_caps,
608             vap->iv_opmode == IEEE80211_M_STA, media_change, media_stat);
609         ieee80211_media_status(ifp, &imr);
610         /* NB: strip explicit mode; we're actually in autoselect */
611         ifmedia_set(&vap->iv_media,
612             imr.ifm_active &~ (IFM_MMASK | IFM_IEEE80211_TURBO));
613         if (maxrate)
614                 ifp->if_baudrate = IF_Mbps(maxrate);
615
616         ether_ifattach(ifp, macaddr);
617         IEEE80211_ADDR_COPY(vap->iv_myaddr, IF_LLADDR(ifp));
618         /* hook output method setup by ether_ifattach */
619         vap->iv_output = ifp->if_output;
620         ifp->if_output = ieee80211_output;
621         /* NB: if_mtu set by ether_ifattach to ETHERMTU */
622
623         IEEE80211_LOCK(ic);
624         TAILQ_INSERT_TAIL(&ic->ic_vaps, vap, iv_next);
625         ieee80211_syncflag_locked(ic, IEEE80211_F_WME);
626 #ifdef IEEE80211_SUPPORT_SUPERG
627         ieee80211_syncflag_locked(ic, IEEE80211_F_TURBOP);
628 #endif
629         ieee80211_syncflag_locked(ic, IEEE80211_F_PCF);
630         ieee80211_syncflag_locked(ic, IEEE80211_F_BURST);
631         ieee80211_syncflag_ht_locked(ic, IEEE80211_FHT_HT);
632         ieee80211_syncflag_ht_locked(ic, IEEE80211_FHT_USEHT40);
633         IEEE80211_UNLOCK(ic);
634
635         return 1;
636 }
637
638 /* 
639  * Tear down vap state and reclaim the ifnet.
640  * The driver is assumed to have prepared for
641  * this; e.g. by turning off interrupts for the
642  * underlying device.
643  */
644 void
645 ieee80211_vap_detach(struct ieee80211vap *vap)
646 {
647         struct ieee80211com *ic = vap->iv_ic;
648         struct ifnet *ifp = vap->iv_ifp;
649
650         CURVNET_SET(ifp->if_vnet);
651
652         IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE, "%s: %s parent %s\n",
653             __func__, ieee80211_opmode_name[vap->iv_opmode], ic->ic_name);
654
655         /* NB: bpfdetach is called by ether_ifdetach and claims all taps */
656         ether_ifdetach(ifp);
657
658         ieee80211_stop(vap);
659
660         /*
661          * Flush any deferred vap tasks.
662          */
663         ieee80211_draintask(ic, &vap->iv_nstate_task);
664         ieee80211_draintask(ic, &vap->iv_swbmiss_task);
665
666         /* XXX band-aid until ifnet handles this for us */
667         taskqueue_drain(taskqueue_swi, &ifp->if_linktask);
668
669         IEEE80211_LOCK(ic);
670         KASSERT(vap->iv_state == IEEE80211_S_INIT , ("vap still running"));
671         TAILQ_REMOVE(&ic->ic_vaps, vap, iv_next);
672         ieee80211_syncflag_locked(ic, IEEE80211_F_WME);
673 #ifdef IEEE80211_SUPPORT_SUPERG
674         ieee80211_syncflag_locked(ic, IEEE80211_F_TURBOP);
675 #endif
676         ieee80211_syncflag_locked(ic, IEEE80211_F_PCF);
677         ieee80211_syncflag_locked(ic, IEEE80211_F_BURST);
678         ieee80211_syncflag_ht_locked(ic, IEEE80211_FHT_HT);
679         ieee80211_syncflag_ht_locked(ic, IEEE80211_FHT_USEHT40);
680         /* NB: this handles the bpfdetach done below */
681         ieee80211_syncflag_ext_locked(ic, IEEE80211_FEXT_BPF);
682         if (vap->iv_ifflags & IFF_PROMISC)
683                 ieee80211_promisc(vap, false);
684         if (vap->iv_ifflags & IFF_ALLMULTI)
685                 ieee80211_allmulti(vap, false);
686         IEEE80211_UNLOCK(ic);
687
688         ifmedia_removeall(&vap->iv_media);
689
690         ieee80211_radiotap_vdetach(vap);
691         ieee80211_regdomain_vdetach(vap);
692         ieee80211_scan_vdetach(vap);
693 #ifdef IEEE80211_SUPPORT_SUPERG
694         ieee80211_superg_vdetach(vap);
695 #endif
696         ieee80211_ht_vdetach(vap);
697         /* NB: must be before ieee80211_node_vdetach */
698         ieee80211_proto_vdetach(vap);
699         ieee80211_crypto_vdetach(vap);
700         ieee80211_power_vdetach(vap);
701         ieee80211_node_vdetach(vap);
702         ieee80211_sysctl_vdetach(vap);
703
704         if_free(ifp);
705
706         CURVNET_RESTORE();
707 }
708
709 /*
710  * Count number of vaps in promisc, and issue promisc on
711  * parent respectively.
712  */
713 void
714 ieee80211_promisc(struct ieee80211vap *vap, bool on)
715 {
716         struct ieee80211com *ic = vap->iv_ic;
717
718         IEEE80211_LOCK_ASSERT(ic);
719
720         if (on) {
721                 if (++ic->ic_promisc == 1)
722                         ieee80211_runtask(ic, &ic->ic_promisc_task);
723         } else {
724                 KASSERT(ic->ic_promisc > 0, ("%s: ic %p not promisc",
725                     __func__, ic));
726                 if (--ic->ic_promisc == 0)
727                         ieee80211_runtask(ic, &ic->ic_promisc_task);
728         }
729 }
730
731 /*
732  * Count number of vaps in allmulti, and issue allmulti on
733  * parent respectively.
734  */
735 void
736 ieee80211_allmulti(struct ieee80211vap *vap, bool on)
737 {
738         struct ieee80211com *ic = vap->iv_ic;
739
740         IEEE80211_LOCK_ASSERT(ic);
741
742         if (on) {
743                 if (++ic->ic_allmulti == 1)
744                         ieee80211_runtask(ic, &ic->ic_mcast_task);
745         } else {
746                 KASSERT(ic->ic_allmulti > 0, ("%s: ic %p not allmulti",
747                     __func__, ic));
748                 if (--ic->ic_allmulti == 0)
749                         ieee80211_runtask(ic, &ic->ic_mcast_task);
750         }
751 }
752
753 /*
754  * Synchronize flag bit state in the com structure
755  * according to the state of all vap's.  This is used,
756  * for example, to handle state changes via ioctls.
757  */
758 static void
759 ieee80211_syncflag_locked(struct ieee80211com *ic, int flag)
760 {
761         struct ieee80211vap *vap;
762         int bit;
763
764         IEEE80211_LOCK_ASSERT(ic);
765
766         bit = 0;
767         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
768                 if (vap->iv_flags & flag) {
769                         bit = 1;
770                         break;
771                 }
772         if (bit)
773                 ic->ic_flags |= flag;
774         else
775                 ic->ic_flags &= ~flag;
776 }
777
778 void
779 ieee80211_syncflag(struct ieee80211vap *vap, int flag)
780 {
781         struct ieee80211com *ic = vap->iv_ic;
782
783         IEEE80211_LOCK(ic);
784         if (flag < 0) {
785                 flag = -flag;
786                 vap->iv_flags &= ~flag;
787         } else
788                 vap->iv_flags |= flag;
789         ieee80211_syncflag_locked(ic, flag);
790         IEEE80211_UNLOCK(ic);
791 }
792
793 /*
794  * Synchronize flags_ht bit state in the com structure
795  * according to the state of all vap's.  This is used,
796  * for example, to handle state changes via ioctls.
797  */
798 static void
799 ieee80211_syncflag_ht_locked(struct ieee80211com *ic, int flag)
800 {
801         struct ieee80211vap *vap;
802         int bit;
803
804         IEEE80211_LOCK_ASSERT(ic);
805
806         bit = 0;
807         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
808                 if (vap->iv_flags_ht & flag) {
809                         bit = 1;
810                         break;
811                 }
812         if (bit)
813                 ic->ic_flags_ht |= flag;
814         else
815                 ic->ic_flags_ht &= ~flag;
816 }
817
818 void
819 ieee80211_syncflag_ht(struct ieee80211vap *vap, int flag)
820 {
821         struct ieee80211com *ic = vap->iv_ic;
822
823         IEEE80211_LOCK(ic);
824         if (flag < 0) {
825                 flag = -flag;
826                 vap->iv_flags_ht &= ~flag;
827         } else
828                 vap->iv_flags_ht |= flag;
829         ieee80211_syncflag_ht_locked(ic, flag);
830         IEEE80211_UNLOCK(ic);
831 }
832
833 /*
834  * Synchronize flags_ext bit state in the com structure
835  * according to the state of all vap's.  This is used,
836  * for example, to handle state changes via ioctls.
837  */
838 static void
839 ieee80211_syncflag_ext_locked(struct ieee80211com *ic, int flag)
840 {
841         struct ieee80211vap *vap;
842         int bit;
843
844         IEEE80211_LOCK_ASSERT(ic);
845
846         bit = 0;
847         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
848                 if (vap->iv_flags_ext & flag) {
849                         bit = 1;
850                         break;
851                 }
852         if (bit)
853                 ic->ic_flags_ext |= flag;
854         else
855                 ic->ic_flags_ext &= ~flag;
856 }
857
858 void
859 ieee80211_syncflag_ext(struct ieee80211vap *vap, int flag)
860 {
861         struct ieee80211com *ic = vap->iv_ic;
862
863         IEEE80211_LOCK(ic);
864         if (flag < 0) {
865                 flag = -flag;
866                 vap->iv_flags_ext &= ~flag;
867         } else
868                 vap->iv_flags_ext |= flag;
869         ieee80211_syncflag_ext_locked(ic, flag);
870         IEEE80211_UNLOCK(ic);
871 }
872
873 static __inline int
874 mapgsm(u_int freq, u_int flags)
875 {
876         freq *= 10;
877         if (flags & IEEE80211_CHAN_QUARTER)
878                 freq += 5;
879         else if (flags & IEEE80211_CHAN_HALF)
880                 freq += 10;
881         else
882                 freq += 20;
883         /* NB: there is no 907/20 wide but leave room */
884         return (freq - 906*10) / 5;
885 }
886
887 static __inline int
888 mappsb(u_int freq, u_int flags)
889 {
890         return 37 + ((freq * 10) + ((freq % 5) == 2 ? 5 : 0) - 49400) / 5;
891 }
892
893 /*
894  * Convert MHz frequency to IEEE channel number.
895  */
896 int
897 ieee80211_mhz2ieee(u_int freq, u_int flags)
898 {
899 #define IS_FREQ_IN_PSB(_freq) ((_freq) > 4940 && (_freq) < 4990)
900         if (flags & IEEE80211_CHAN_GSM)
901                 return mapgsm(freq, flags);
902         if (flags & IEEE80211_CHAN_2GHZ) {      /* 2GHz band */
903                 if (freq == 2484)
904                         return 14;
905                 if (freq < 2484)
906                         return ((int) freq - 2407) / 5;
907                 else
908                         return 15 + ((freq - 2512) / 20);
909         } else if (flags & IEEE80211_CHAN_5GHZ) {       /* 5Ghz band */
910                 if (freq <= 5000) {
911                         /* XXX check regdomain? */
912                         if (IS_FREQ_IN_PSB(freq))
913                                 return mappsb(freq, flags);
914                         return (freq - 4000) / 5;
915                 } else
916                         return (freq - 5000) / 5;
917         } else {                                /* either, guess */
918                 if (freq == 2484)
919                         return 14;
920                 if (freq < 2484) {
921                         if (907 <= freq && freq <= 922)
922                                 return mapgsm(freq, flags);
923                         return ((int) freq - 2407) / 5;
924                 }
925                 if (freq < 5000) {
926                         if (IS_FREQ_IN_PSB(freq))
927                                 return mappsb(freq, flags);
928                         else if (freq > 4900)
929                                 return (freq - 4000) / 5;
930                         else
931                                 return 15 + ((freq - 2512) / 20);
932                 }
933                 return (freq - 5000) / 5;
934         }
935 #undef IS_FREQ_IN_PSB
936 }
937
938 /*
939  * Convert channel to IEEE channel number.
940  */
941 int
942 ieee80211_chan2ieee(struct ieee80211com *ic, const struct ieee80211_channel *c)
943 {
944         if (c == NULL) {
945                 ic_printf(ic, "invalid channel (NULL)\n");
946                 return 0;               /* XXX */
947         }
948         return (c == IEEE80211_CHAN_ANYC ?  IEEE80211_CHAN_ANY : c->ic_ieee);
949 }
950
951 /*
952  * Convert IEEE channel number to MHz frequency.
953  */
954 u_int
955 ieee80211_ieee2mhz(u_int chan, u_int flags)
956 {
957         if (flags & IEEE80211_CHAN_GSM)
958                 return 907 + 5 * (chan / 10);
959         if (flags & IEEE80211_CHAN_2GHZ) {      /* 2GHz band */
960                 if (chan == 14)
961                         return 2484;
962                 if (chan < 14)
963                         return 2407 + chan*5;
964                 else
965                         return 2512 + ((chan-15)*20);
966         } else if (flags & IEEE80211_CHAN_5GHZ) {/* 5Ghz band */
967                 if (flags & (IEEE80211_CHAN_HALF|IEEE80211_CHAN_QUARTER)) {
968                         chan -= 37;
969                         return 4940 + chan*5 + (chan % 5 ? 2 : 0);
970                 }
971                 return 5000 + (chan*5);
972         } else {                                /* either, guess */
973                 /* XXX can't distinguish PSB+GSM channels */
974                 if (chan == 14)
975                         return 2484;
976                 if (chan < 14)                  /* 0-13 */
977                         return 2407 + chan*5;
978                 if (chan < 27)                  /* 15-26 */
979                         return 2512 + ((chan-15)*20);
980                 return 5000 + (chan*5);
981         }
982 }
983
984 static __inline void
985 set_extchan(struct ieee80211_channel *c)
986 {
987
988         /*
989          * IEEE Std 802.11-2012, page 1738, subclause 20.3.15.4:
990          * "the secondary channel number shall be 'N + [1,-1] * 4'
991          */
992         if (c->ic_flags & IEEE80211_CHAN_HT40U)
993                 c->ic_extieee = c->ic_ieee + 4;
994         else if (c->ic_flags & IEEE80211_CHAN_HT40D)
995                 c->ic_extieee = c->ic_ieee - 4;
996         else
997                 c->ic_extieee = 0;
998 }
999
1000 static int
1001 addchan(struct ieee80211_channel chans[], int maxchans, int *nchans,
1002     uint8_t ieee, uint16_t freq, int8_t maxregpower, uint32_t flags)
1003 {
1004         struct ieee80211_channel *c;
1005
1006         if (*nchans >= maxchans)
1007                 return (ENOBUFS);
1008
1009         c = &chans[(*nchans)++];
1010         c->ic_ieee = ieee;
1011         c->ic_freq = freq != 0 ? freq : ieee80211_ieee2mhz(ieee, flags);
1012         c->ic_maxregpower = maxregpower;
1013         c->ic_maxpower = 2 * maxregpower;
1014         c->ic_flags = flags;
1015         set_extchan(c);
1016
1017         return (0);
1018 }
1019
1020 static int
1021 copychan_prev(struct ieee80211_channel chans[], int maxchans, int *nchans,
1022     uint32_t flags)
1023 {
1024         struct ieee80211_channel *c;
1025
1026         KASSERT(*nchans > 0, ("channel list is empty\n"));
1027
1028         if (*nchans >= maxchans)
1029                 return (ENOBUFS);
1030
1031         c = &chans[(*nchans)++];
1032         c[0] = c[-1];
1033         c->ic_flags = flags;
1034         set_extchan(c);
1035
1036         return (0);
1037 }
1038
1039 static void
1040 getflags_2ghz(const uint8_t bands[], uint32_t flags[], int ht40)
1041 {
1042         int nmodes;
1043
1044         nmodes = 0;
1045         if (isset(bands, IEEE80211_MODE_11B))
1046                 flags[nmodes++] = IEEE80211_CHAN_B;
1047         if (isset(bands, IEEE80211_MODE_11G))
1048                 flags[nmodes++] = IEEE80211_CHAN_G;
1049         if (isset(bands, IEEE80211_MODE_11NG))
1050                 flags[nmodes++] = IEEE80211_CHAN_G | IEEE80211_CHAN_HT20;
1051         if (ht40) {
1052                 flags[nmodes++] = IEEE80211_CHAN_G | IEEE80211_CHAN_HT40U;
1053                 flags[nmodes++] = IEEE80211_CHAN_G | IEEE80211_CHAN_HT40D;
1054         }
1055         flags[nmodes] = 0;
1056 }
1057
1058 static void
1059 getflags_5ghz(const uint8_t bands[], uint32_t flags[], int ht40)
1060 {
1061         int nmodes;
1062
1063         nmodes = 0;
1064         if (isset(bands, IEEE80211_MODE_11A))
1065                 flags[nmodes++] = IEEE80211_CHAN_A;
1066         if (isset(bands, IEEE80211_MODE_11NA))
1067                 flags[nmodes++] = IEEE80211_CHAN_A | IEEE80211_CHAN_HT20;
1068         if (ht40) {
1069                 flags[nmodes++] = IEEE80211_CHAN_A | IEEE80211_CHAN_HT40U;
1070                 flags[nmodes++] = IEEE80211_CHAN_A | IEEE80211_CHAN_HT40D;
1071         }
1072         flags[nmodes] = 0;
1073 }
1074
1075 static void
1076 getflags(const uint8_t bands[], uint32_t flags[], int ht40)
1077 {
1078
1079         flags[0] = 0;
1080         if (isset(bands, IEEE80211_MODE_11A) ||
1081             isset(bands, IEEE80211_MODE_11NA)) {
1082                 if (isset(bands, IEEE80211_MODE_11B) ||
1083                     isset(bands, IEEE80211_MODE_11G) ||
1084                     isset(bands, IEEE80211_MODE_11NG))
1085                         return;
1086
1087                 getflags_5ghz(bands, flags, ht40);
1088         } else
1089                 getflags_2ghz(bands, flags, ht40);
1090 }
1091
1092 /*
1093  * Add one 20 MHz channel into specified channel list.
1094  */
1095 int
1096 ieee80211_add_channel(struct ieee80211_channel chans[], int maxchans,
1097     int *nchans, uint8_t ieee, uint16_t freq, int8_t maxregpower,
1098     uint32_t chan_flags, const uint8_t bands[])
1099 {
1100         uint32_t flags[IEEE80211_MODE_MAX];
1101         int i, error;
1102
1103         getflags(bands, flags, 0);
1104         KASSERT(flags[0] != 0, ("%s: no correct mode provided\n", __func__));
1105
1106         error = addchan(chans, maxchans, nchans, ieee, freq, maxregpower,
1107             flags[0] | chan_flags);
1108         for (i = 1; flags[i] != 0 && error == 0; i++) {
1109                 error = copychan_prev(chans, maxchans, nchans,
1110                     flags[i] | chan_flags);
1111         }
1112
1113         return (error);
1114 }
1115
1116 static struct ieee80211_channel *
1117 findchannel(struct ieee80211_channel chans[], int nchans, uint16_t freq,
1118     uint32_t flags)
1119 {
1120         struct ieee80211_channel *c;
1121         int i;
1122
1123         flags &= IEEE80211_CHAN_ALLTURBO;
1124         /* brute force search */
1125         for (i = 0; i < nchans; i++) {
1126                 c = &chans[i];
1127                 if (c->ic_freq == freq &&
1128                     (c->ic_flags & IEEE80211_CHAN_ALLTURBO) == flags)
1129                         return c;
1130         }
1131         return NULL;
1132 }
1133
1134 /*
1135  * Add 40 MHz channel pair into specified channel list.
1136  */
1137 int
1138 ieee80211_add_channel_ht40(struct ieee80211_channel chans[], int maxchans,
1139     int *nchans, uint8_t ieee, int8_t maxregpower, uint32_t flags)
1140 {
1141         struct ieee80211_channel *cent, *extc;
1142         uint16_t freq;
1143         int error;
1144
1145         freq = ieee80211_ieee2mhz(ieee, flags);
1146
1147         /*
1148          * Each entry defines an HT40 channel pair; find the
1149          * center channel, then the extension channel above.
1150          */
1151         flags |= IEEE80211_CHAN_HT20;
1152         cent = findchannel(chans, *nchans, freq, flags);
1153         if (cent == NULL)
1154                 return (EINVAL);
1155
1156         extc = findchannel(chans, *nchans, freq + 20, flags);
1157         if (extc == NULL)
1158                 return (ENOENT);
1159
1160         flags &= ~IEEE80211_CHAN_HT;
1161         error = addchan(chans, maxchans, nchans, cent->ic_ieee, cent->ic_freq,
1162             maxregpower, flags | IEEE80211_CHAN_HT40U);
1163         if (error != 0)
1164                 return (error);
1165
1166         error = addchan(chans, maxchans, nchans, extc->ic_ieee, extc->ic_freq,
1167             maxregpower, flags | IEEE80211_CHAN_HT40D);
1168
1169         return (error);
1170 }
1171
1172 /*
1173  * Fetch the center frequency for the primary channel.
1174  */
1175 uint32_t
1176 ieee80211_get_channel_center_freq(const struct ieee80211_channel *c)
1177 {
1178
1179         return (c->ic_freq);
1180 }
1181
1182 /*
1183  * Fetch the center frequency for the primary BAND channel.
1184  *
1185  * For 5, 10, 20MHz channels it'll be the normally configured channel
1186  * frequency.
1187  *
1188  * For 40MHz, 80MHz, 160Mhz channels it'll the the centre of the
1189  * wide channel, not the centre of the primary channel (that's ic_freq).
1190  *
1191  * For 80+80MHz channels this will be the centre of the primary
1192  * 80MHz channel; the secondary 80MHz channel will be center_freq2().
1193  */
1194
1195 uint32_t
1196 ieee80211_get_channel_center_freq1(const struct ieee80211_channel *c)
1197 {
1198
1199         if (IEEE80211_IS_CHAN_HT40U(c)) {
1200                 return (c->ic_freq + 10);
1201         }
1202         if (IEEE80211_IS_CHAN_HT40D(c)) {
1203                 return (c->ic_freq - 10);
1204         }
1205
1206         return (c->ic_freq);
1207 }
1208
1209 /*
1210  * For now, no 80+80 support; this is zero.
1211  */
1212 uint32_t
1213 ieee80211_get_channel_center_freq2(const struct ieee80211_channel *c)
1214 {
1215
1216         return (0);
1217 }
1218
1219 /*
1220  * Adds channels into specified channel list (ieee[] array must be sorted).
1221  * Channels are already sorted.
1222  */
1223 static int
1224 add_chanlist(struct ieee80211_channel chans[], int maxchans, int *nchans,
1225     const uint8_t ieee[], int nieee, uint32_t flags[])
1226 {
1227         uint16_t freq;
1228         int i, j, error;
1229
1230         for (i = 0; i < nieee; i++) {
1231                 freq = ieee80211_ieee2mhz(ieee[i], flags[0]);
1232                 for (j = 0; flags[j] != 0; j++) {
1233                         if (flags[j] & IEEE80211_CHAN_HT40D)
1234                                 if (i == 0 || ieee[i] < ieee[0] + 4 ||
1235                                     freq - 20 !=
1236                                     ieee80211_ieee2mhz(ieee[i] - 4, flags[j]))
1237                                         continue;
1238                         if (flags[j] & IEEE80211_CHAN_HT40U)
1239                                 if (i == nieee - 1 ||
1240                                     ieee[i] + 4 > ieee[nieee - 1] ||
1241                                     freq + 20 !=
1242                                     ieee80211_ieee2mhz(ieee[i] + 4, flags[j]))
1243                                         continue;
1244
1245                         if (j == 0) {
1246                                 error = addchan(chans, maxchans, nchans,
1247                                     ieee[i], freq, 0, flags[j]);
1248                         } else {
1249                                 error = copychan_prev(chans, maxchans, nchans,
1250                                     flags[j]);
1251                         }
1252                         if (error != 0)
1253                                 return (error);
1254                 }
1255         }
1256
1257         return (0);
1258 }
1259
1260 int
1261 ieee80211_add_channel_list_2ghz(struct ieee80211_channel chans[], int maxchans,
1262     int *nchans, const uint8_t ieee[], int nieee, const uint8_t bands[],
1263     int ht40)
1264 {
1265         uint32_t flags[IEEE80211_MODE_MAX];
1266
1267         getflags_2ghz(bands, flags, ht40);
1268         KASSERT(flags[0] != 0, ("%s: no correct mode provided\n", __func__));
1269
1270         return (add_chanlist(chans, maxchans, nchans, ieee, nieee, flags));
1271 }
1272
1273 int
1274 ieee80211_add_channel_list_5ghz(struct ieee80211_channel chans[], int maxchans,
1275     int *nchans, const uint8_t ieee[], int nieee, const uint8_t bands[],
1276     int ht40)
1277 {
1278         uint32_t flags[IEEE80211_MODE_MAX];
1279
1280         getflags_5ghz(bands, flags, ht40);
1281         KASSERT(flags[0] != 0, ("%s: no correct mode provided\n", __func__));
1282
1283         return (add_chanlist(chans, maxchans, nchans, ieee, nieee, flags));
1284 }
1285
1286 /*
1287  * Locate a channel given a frequency+flags.  We cache
1288  * the previous lookup to optimize switching between two
1289  * channels--as happens with dynamic turbo.
1290  */
1291 struct ieee80211_channel *
1292 ieee80211_find_channel(struct ieee80211com *ic, int freq, int flags)
1293 {
1294         struct ieee80211_channel *c;
1295
1296         flags &= IEEE80211_CHAN_ALLTURBO;
1297         c = ic->ic_prevchan;
1298         if (c != NULL && c->ic_freq == freq &&
1299             (c->ic_flags & IEEE80211_CHAN_ALLTURBO) == flags)
1300                 return c;
1301         /* brute force search */
1302         return (findchannel(ic->ic_channels, ic->ic_nchans, freq, flags));
1303 }
1304
1305 /*
1306  * Locate a channel given a channel number+flags.  We cache
1307  * the previous lookup to optimize switching between two
1308  * channels--as happens with dynamic turbo.
1309  */
1310 struct ieee80211_channel *
1311 ieee80211_find_channel_byieee(struct ieee80211com *ic, int ieee, int flags)
1312 {
1313         struct ieee80211_channel *c;
1314         int i;
1315
1316         flags &= IEEE80211_CHAN_ALLTURBO;
1317         c = ic->ic_prevchan;
1318         if (c != NULL && c->ic_ieee == ieee &&
1319             (c->ic_flags & IEEE80211_CHAN_ALLTURBO) == flags)
1320                 return c;
1321         /* brute force search */
1322         for (i = 0; i < ic->ic_nchans; i++) {
1323                 c = &ic->ic_channels[i];
1324                 if (c->ic_ieee == ieee &&
1325                     (c->ic_flags & IEEE80211_CHAN_ALLTURBO) == flags)
1326                         return c;
1327         }
1328         return NULL;
1329 }
1330
1331 /*
1332  * Lookup a channel suitable for the given rx status.
1333  *
1334  * This is used to find a channel for a frame (eg beacon, probe
1335  * response) based purely on the received PHY information.
1336  *
1337  * For now it tries to do it based on R_FREQ / R_IEEE.
1338  * This is enough for 11bg and 11a (and thus 11ng/11na)
1339  * but it will not be enough for GSM, PSB channels and the
1340  * like.  It also doesn't know about legacy-turbog and
1341  * legacy-turbo modes, which some offload NICs actually
1342  * support in weird ways.
1343  *
1344  * Takes the ic and rxstatus; returns the channel or NULL
1345  * if not found.
1346  *
1347  * XXX TODO: Add support for that when the need arises.
1348  */
1349 struct ieee80211_channel *
1350 ieee80211_lookup_channel_rxstatus(struct ieee80211vap *vap,
1351     const struct ieee80211_rx_stats *rxs)
1352 {
1353         struct ieee80211com *ic = vap->iv_ic;
1354         uint32_t flags;
1355         struct ieee80211_channel *c;
1356
1357         if (rxs == NULL)
1358                 return (NULL);
1359
1360         /*
1361          * Strictly speaking we only use freq for now,
1362          * however later on we may wish to just store
1363          * the ieee for verification.
1364          */
1365         if ((rxs->r_flags & IEEE80211_R_FREQ) == 0)
1366                 return (NULL);
1367         if ((rxs->r_flags & IEEE80211_R_IEEE) == 0)
1368                 return (NULL);
1369
1370         /*
1371          * If the rx status contains a valid ieee/freq, then
1372          * ensure we populate the correct channel information
1373          * in rxchan before passing it up to the scan infrastructure.
1374          * Offload NICs will pass up beacons from all channels
1375          * during background scans.
1376          */
1377
1378         /* Determine a band */
1379         /* XXX should be done by the driver? */
1380         if (rxs->c_freq < 3000) {
1381                 flags = IEEE80211_CHAN_G;
1382         } else {
1383                 flags = IEEE80211_CHAN_A;
1384         }
1385
1386         /* Channel lookup */
1387         c = ieee80211_find_channel(ic, rxs->c_freq, flags);
1388
1389         IEEE80211_DPRINTF(vap, IEEE80211_MSG_INPUT,
1390             "%s: freq=%d, ieee=%d, flags=0x%08x; c=%p\n",
1391             __func__,
1392             (int) rxs->c_freq,
1393             (int) rxs->c_ieee,
1394             flags,
1395             c);
1396
1397         return (c);
1398 }
1399
1400 static void
1401 addmedia(struct ifmedia *media, int caps, int addsta, int mode, int mword)
1402 {
1403 #define ADD(_ic, _s, _o) \
1404         ifmedia_add(media, \
1405                 IFM_MAKEWORD(IFM_IEEE80211, (_s), (_o), 0), 0, NULL)
1406         static const u_int mopts[IEEE80211_MODE_MAX] = { 
1407             [IEEE80211_MODE_AUTO]       = IFM_AUTO,
1408             [IEEE80211_MODE_11A]        = IFM_IEEE80211_11A,
1409             [IEEE80211_MODE_11B]        = IFM_IEEE80211_11B,
1410             [IEEE80211_MODE_11G]        = IFM_IEEE80211_11G,
1411             [IEEE80211_MODE_FH]         = IFM_IEEE80211_FH,
1412             [IEEE80211_MODE_TURBO_A]    = IFM_IEEE80211_11A|IFM_IEEE80211_TURBO,
1413             [IEEE80211_MODE_TURBO_G]    = IFM_IEEE80211_11G|IFM_IEEE80211_TURBO,
1414             [IEEE80211_MODE_STURBO_A]   = IFM_IEEE80211_11A|IFM_IEEE80211_TURBO,
1415             [IEEE80211_MODE_HALF]       = IFM_IEEE80211_11A,    /* XXX */
1416             [IEEE80211_MODE_QUARTER]    = IFM_IEEE80211_11A,    /* XXX */
1417             [IEEE80211_MODE_11NA]       = IFM_IEEE80211_11NA,
1418             [IEEE80211_MODE_11NG]       = IFM_IEEE80211_11NG,
1419         };
1420         u_int mopt;
1421
1422         mopt = mopts[mode];
1423         if (addsta)
1424                 ADD(ic, mword, mopt);   /* STA mode has no cap */
1425         if (caps & IEEE80211_C_IBSS)
1426                 ADD(media, mword, mopt | IFM_IEEE80211_ADHOC);
1427         if (caps & IEEE80211_C_HOSTAP)
1428                 ADD(media, mword, mopt | IFM_IEEE80211_HOSTAP);
1429         if (caps & IEEE80211_C_AHDEMO)
1430                 ADD(media, mword, mopt | IFM_IEEE80211_ADHOC | IFM_FLAG0);
1431         if (caps & IEEE80211_C_MONITOR)
1432                 ADD(media, mword, mopt | IFM_IEEE80211_MONITOR);
1433         if (caps & IEEE80211_C_WDS)
1434                 ADD(media, mword, mopt | IFM_IEEE80211_WDS);
1435         if (caps & IEEE80211_C_MBSS)
1436                 ADD(media, mword, mopt | IFM_IEEE80211_MBSS);
1437 #undef ADD
1438 }
1439
1440 /*
1441  * Setup the media data structures according to the channel and
1442  * rate tables.
1443  */
1444 static int
1445 ieee80211_media_setup(struct ieee80211com *ic,
1446         struct ifmedia *media, int caps, int addsta,
1447         ifm_change_cb_t media_change, ifm_stat_cb_t media_stat)
1448 {
1449         int i, j, rate, maxrate, mword, r;
1450         enum ieee80211_phymode mode;
1451         const struct ieee80211_rateset *rs;
1452         struct ieee80211_rateset allrates;
1453
1454         /*
1455          * Fill in media characteristics.
1456          */
1457         ifmedia_init(media, 0, media_change, media_stat);
1458         maxrate = 0;
1459         /*
1460          * Add media for legacy operating modes.
1461          */
1462         memset(&allrates, 0, sizeof(allrates));
1463         for (mode = IEEE80211_MODE_AUTO; mode < IEEE80211_MODE_11NA; mode++) {
1464                 if (isclr(ic->ic_modecaps, mode))
1465                         continue;
1466                 addmedia(media, caps, addsta, mode, IFM_AUTO);
1467                 if (mode == IEEE80211_MODE_AUTO)
1468                         continue;
1469                 rs = &ic->ic_sup_rates[mode];
1470                 for (i = 0; i < rs->rs_nrates; i++) {
1471                         rate = rs->rs_rates[i];
1472                         mword = ieee80211_rate2media(ic, rate, mode);
1473                         if (mword == 0)
1474                                 continue;
1475                         addmedia(media, caps, addsta, mode, mword);
1476                         /*
1477                          * Add legacy rate to the collection of all rates.
1478                          */
1479                         r = rate & IEEE80211_RATE_VAL;
1480                         for (j = 0; j < allrates.rs_nrates; j++)
1481                                 if (allrates.rs_rates[j] == r)
1482                                         break;
1483                         if (j == allrates.rs_nrates) {
1484                                 /* unique, add to the set */
1485                                 allrates.rs_rates[j] = r;
1486                                 allrates.rs_nrates++;
1487                         }
1488                         rate = (rate & IEEE80211_RATE_VAL) / 2;
1489                         if (rate > maxrate)
1490                                 maxrate = rate;
1491                 }
1492         }
1493         for (i = 0; i < allrates.rs_nrates; i++) {
1494                 mword = ieee80211_rate2media(ic, allrates.rs_rates[i],
1495                                 IEEE80211_MODE_AUTO);
1496                 if (mword == 0)
1497                         continue;
1498                 /* NB: remove media options from mword */
1499                 addmedia(media, caps, addsta,
1500                     IEEE80211_MODE_AUTO, IFM_SUBTYPE(mword));
1501         }
1502         /*
1503          * Add HT/11n media.  Note that we do not have enough
1504          * bits in the media subtype to express the MCS so we
1505          * use a "placeholder" media subtype and any fixed MCS
1506          * must be specified with a different mechanism.
1507          */
1508         for (; mode <= IEEE80211_MODE_11NG; mode++) {
1509                 if (isclr(ic->ic_modecaps, mode))
1510                         continue;
1511                 addmedia(media, caps, addsta, mode, IFM_AUTO);
1512                 addmedia(media, caps, addsta, mode, IFM_IEEE80211_MCS);
1513         }
1514         if (isset(ic->ic_modecaps, IEEE80211_MODE_11NA) ||
1515             isset(ic->ic_modecaps, IEEE80211_MODE_11NG)) {
1516                 addmedia(media, caps, addsta,
1517                     IEEE80211_MODE_AUTO, IFM_IEEE80211_MCS);
1518                 i = ic->ic_txstream * 8 - 1;
1519                 if ((ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40) &&
1520                     (ic->ic_htcaps & IEEE80211_HTCAP_SHORTGI40))
1521                         rate = ieee80211_htrates[i].ht40_rate_400ns;
1522                 else if ((ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40))
1523                         rate = ieee80211_htrates[i].ht40_rate_800ns;
1524                 else if ((ic->ic_htcaps & IEEE80211_HTCAP_SHORTGI20))
1525                         rate = ieee80211_htrates[i].ht20_rate_400ns;
1526                 else
1527                         rate = ieee80211_htrates[i].ht20_rate_800ns;
1528                 if (rate > maxrate)
1529                         maxrate = rate;
1530         }
1531         return maxrate;
1532 }
1533
1534 /* XXX inline or eliminate? */
1535 const struct ieee80211_rateset *
1536 ieee80211_get_suprates(struct ieee80211com *ic, const struct ieee80211_channel *c)
1537 {
1538         /* XXX does this work for 11ng basic rates? */
1539         return &ic->ic_sup_rates[ieee80211_chan2mode(c)];
1540 }
1541
1542 void
1543 ieee80211_announce(struct ieee80211com *ic)
1544 {
1545         int i, rate, mword;
1546         enum ieee80211_phymode mode;
1547         const struct ieee80211_rateset *rs;
1548
1549         /* NB: skip AUTO since it has no rates */
1550         for (mode = IEEE80211_MODE_AUTO+1; mode < IEEE80211_MODE_11NA; mode++) {
1551                 if (isclr(ic->ic_modecaps, mode))
1552                         continue;
1553                 ic_printf(ic, "%s rates: ", ieee80211_phymode_name[mode]);
1554                 rs = &ic->ic_sup_rates[mode];
1555                 for (i = 0; i < rs->rs_nrates; i++) {
1556                         mword = ieee80211_rate2media(ic, rs->rs_rates[i], mode);
1557                         if (mword == 0)
1558                                 continue;
1559                         rate = ieee80211_media2rate(mword);
1560                         printf("%s%d%sMbps", (i != 0 ? " " : ""),
1561                             rate / 2, ((rate & 0x1) != 0 ? ".5" : ""));
1562                 }
1563                 printf("\n");
1564         }
1565         ieee80211_ht_announce(ic);
1566 }
1567
1568 void
1569 ieee80211_announce_channels(struct ieee80211com *ic)
1570 {
1571         const struct ieee80211_channel *c;
1572         char type;
1573         int i, cw;
1574
1575         printf("Chan  Freq  CW  RegPwr  MinPwr  MaxPwr\n");
1576         for (i = 0; i < ic->ic_nchans; i++) {
1577                 c = &ic->ic_channels[i];
1578                 if (IEEE80211_IS_CHAN_ST(c))
1579                         type = 'S';
1580                 else if (IEEE80211_IS_CHAN_108A(c))
1581                         type = 'T';
1582                 else if (IEEE80211_IS_CHAN_108G(c))
1583                         type = 'G';
1584                 else if (IEEE80211_IS_CHAN_HT(c))
1585                         type = 'n';
1586                 else if (IEEE80211_IS_CHAN_A(c))
1587                         type = 'a';
1588                 else if (IEEE80211_IS_CHAN_ANYG(c))
1589                         type = 'g';
1590                 else if (IEEE80211_IS_CHAN_B(c))
1591                         type = 'b';
1592                 else
1593                         type = 'f';
1594                 if (IEEE80211_IS_CHAN_HT40(c) || IEEE80211_IS_CHAN_TURBO(c))
1595                         cw = 40;
1596                 else if (IEEE80211_IS_CHAN_HALF(c))
1597                         cw = 10;
1598                 else if (IEEE80211_IS_CHAN_QUARTER(c))
1599                         cw = 5;
1600                 else
1601                         cw = 20;
1602                 printf("%4d  %4d%c %2d%c %6d  %4d.%d  %4d.%d\n"
1603                         , c->ic_ieee, c->ic_freq, type
1604                         , cw
1605                         , IEEE80211_IS_CHAN_HT40U(c) ? '+' :
1606                           IEEE80211_IS_CHAN_HT40D(c) ? '-' : ' '
1607                         , c->ic_maxregpower
1608                         , c->ic_minpower / 2, c->ic_minpower & 1 ? 5 : 0
1609                         , c->ic_maxpower / 2, c->ic_maxpower & 1 ? 5 : 0
1610                 );
1611         }
1612 }
1613
1614 static int
1615 media2mode(const struct ifmedia_entry *ime, uint32_t flags, uint16_t *mode)
1616 {
1617         switch (IFM_MODE(ime->ifm_media)) {
1618         case IFM_IEEE80211_11A:
1619                 *mode = IEEE80211_MODE_11A;
1620                 break;
1621         case IFM_IEEE80211_11B:
1622                 *mode = IEEE80211_MODE_11B;
1623                 break;
1624         case IFM_IEEE80211_11G:
1625                 *mode = IEEE80211_MODE_11G;
1626                 break;
1627         case IFM_IEEE80211_FH:
1628                 *mode = IEEE80211_MODE_FH;
1629                 break;
1630         case IFM_IEEE80211_11NA:
1631                 *mode = IEEE80211_MODE_11NA;
1632                 break;
1633         case IFM_IEEE80211_11NG:
1634                 *mode = IEEE80211_MODE_11NG;
1635                 break;
1636         case IFM_AUTO:
1637                 *mode = IEEE80211_MODE_AUTO;
1638                 break;
1639         default:
1640                 return 0;
1641         }
1642         /*
1643          * Turbo mode is an ``option''.
1644          * XXX does not apply to AUTO
1645          */
1646         if (ime->ifm_media & IFM_IEEE80211_TURBO) {
1647                 if (*mode == IEEE80211_MODE_11A) {
1648                         if (flags & IEEE80211_F_TURBOP)
1649                                 *mode = IEEE80211_MODE_TURBO_A;
1650                         else
1651                                 *mode = IEEE80211_MODE_STURBO_A;
1652                 } else if (*mode == IEEE80211_MODE_11G)
1653                         *mode = IEEE80211_MODE_TURBO_G;
1654                 else
1655                         return 0;
1656         }
1657         /* XXX HT40 +/- */
1658         return 1;
1659 }
1660
1661 /*
1662  * Handle a media change request on the vap interface.
1663  */
1664 int
1665 ieee80211_media_change(struct ifnet *ifp)
1666 {
1667         struct ieee80211vap *vap = ifp->if_softc;
1668         struct ifmedia_entry *ime = vap->iv_media.ifm_cur;
1669         uint16_t newmode;
1670
1671         if (!media2mode(ime, vap->iv_flags, &newmode))
1672                 return EINVAL;
1673         if (vap->iv_des_mode != newmode) {
1674                 vap->iv_des_mode = newmode;
1675                 /* XXX kick state machine if up+running */
1676         }
1677         return 0;
1678 }
1679
1680 /*
1681  * Common code to calculate the media status word
1682  * from the operating mode and channel state.
1683  */
1684 static int
1685 media_status(enum ieee80211_opmode opmode, const struct ieee80211_channel *chan)
1686 {
1687         int status;
1688
1689         status = IFM_IEEE80211;
1690         switch (opmode) {
1691         case IEEE80211_M_STA:
1692                 break;
1693         case IEEE80211_M_IBSS:
1694                 status |= IFM_IEEE80211_ADHOC;
1695                 break;
1696         case IEEE80211_M_HOSTAP:
1697                 status |= IFM_IEEE80211_HOSTAP;
1698                 break;
1699         case IEEE80211_M_MONITOR:
1700                 status |= IFM_IEEE80211_MONITOR;
1701                 break;
1702         case IEEE80211_M_AHDEMO:
1703                 status |= IFM_IEEE80211_ADHOC | IFM_FLAG0;
1704                 break;
1705         case IEEE80211_M_WDS:
1706                 status |= IFM_IEEE80211_WDS;
1707                 break;
1708         case IEEE80211_M_MBSS:
1709                 status |= IFM_IEEE80211_MBSS;
1710                 break;
1711         }
1712         if (IEEE80211_IS_CHAN_HTA(chan)) {
1713                 status |= IFM_IEEE80211_11NA;
1714         } else if (IEEE80211_IS_CHAN_HTG(chan)) {
1715                 status |= IFM_IEEE80211_11NG;
1716         } else if (IEEE80211_IS_CHAN_A(chan)) {
1717                 status |= IFM_IEEE80211_11A;
1718         } else if (IEEE80211_IS_CHAN_B(chan)) {
1719                 status |= IFM_IEEE80211_11B;
1720         } else if (IEEE80211_IS_CHAN_ANYG(chan)) {
1721                 status |= IFM_IEEE80211_11G;
1722         } else if (IEEE80211_IS_CHAN_FHSS(chan)) {
1723                 status |= IFM_IEEE80211_FH;
1724         }
1725         /* XXX else complain? */
1726
1727         if (IEEE80211_IS_CHAN_TURBO(chan))
1728                 status |= IFM_IEEE80211_TURBO;
1729 #if 0
1730         if (IEEE80211_IS_CHAN_HT20(chan))
1731                 status |= IFM_IEEE80211_HT20;
1732         if (IEEE80211_IS_CHAN_HT40(chan))
1733                 status |= IFM_IEEE80211_HT40;
1734 #endif
1735         return status;
1736 }
1737
1738 void
1739 ieee80211_media_status(struct ifnet *ifp, struct ifmediareq *imr)
1740 {
1741         struct ieee80211vap *vap = ifp->if_softc;
1742         struct ieee80211com *ic = vap->iv_ic;
1743         enum ieee80211_phymode mode;
1744
1745         imr->ifm_status = IFM_AVALID;
1746         /*
1747          * NB: use the current channel's mode to lock down a xmit
1748          * rate only when running; otherwise we may have a mismatch
1749          * in which case the rate will not be convertible.
1750          */
1751         if (vap->iv_state == IEEE80211_S_RUN ||
1752             vap->iv_state == IEEE80211_S_SLEEP) {
1753                 imr->ifm_status |= IFM_ACTIVE;
1754                 mode = ieee80211_chan2mode(ic->ic_curchan);
1755         } else
1756                 mode = IEEE80211_MODE_AUTO;
1757         imr->ifm_active = media_status(vap->iv_opmode, ic->ic_curchan);
1758         /*
1759          * Calculate a current rate if possible.
1760          */
1761         if (vap->iv_txparms[mode].ucastrate != IEEE80211_FIXED_RATE_NONE) {
1762                 /*
1763                  * A fixed rate is set, report that.
1764                  */
1765                 imr->ifm_active |= ieee80211_rate2media(ic,
1766                         vap->iv_txparms[mode].ucastrate, mode);
1767         } else if (vap->iv_opmode == IEEE80211_M_STA) {
1768                 /*
1769                  * In station mode report the current transmit rate.
1770                  */
1771                 imr->ifm_active |= ieee80211_rate2media(ic,
1772                         vap->iv_bss->ni_txrate, mode);
1773         } else
1774                 imr->ifm_active |= IFM_AUTO;
1775         if (imr->ifm_status & IFM_ACTIVE)
1776                 imr->ifm_current = imr->ifm_active;
1777 }
1778
1779 /*
1780  * Set the current phy mode and recalculate the active channel
1781  * set based on the available channels for this mode.  Also
1782  * select a new default/current channel if the current one is
1783  * inappropriate for this mode.
1784  */
1785 int
1786 ieee80211_setmode(struct ieee80211com *ic, enum ieee80211_phymode mode)
1787 {
1788         /*
1789          * Adjust basic rates in 11b/11g supported rate set.
1790          * Note that if operating on a hal/quarter rate channel
1791          * this is a noop as those rates sets are different
1792          * and used instead.
1793          */
1794         if (mode == IEEE80211_MODE_11G || mode == IEEE80211_MODE_11B)
1795                 ieee80211_setbasicrates(&ic->ic_sup_rates[mode], mode);
1796
1797         ic->ic_curmode = mode;
1798         ieee80211_reset_erp(ic);        /* reset ERP state */
1799
1800         return 0;
1801 }
1802
1803 /*
1804  * Return the phy mode for with the specified channel.
1805  */
1806 enum ieee80211_phymode
1807 ieee80211_chan2mode(const struct ieee80211_channel *chan)
1808 {
1809
1810         if (IEEE80211_IS_CHAN_HTA(chan))
1811                 return IEEE80211_MODE_11NA;
1812         else if (IEEE80211_IS_CHAN_HTG(chan))
1813                 return IEEE80211_MODE_11NG;
1814         else if (IEEE80211_IS_CHAN_108G(chan))
1815                 return IEEE80211_MODE_TURBO_G;
1816         else if (IEEE80211_IS_CHAN_ST(chan))
1817                 return IEEE80211_MODE_STURBO_A;
1818         else if (IEEE80211_IS_CHAN_TURBO(chan))
1819                 return IEEE80211_MODE_TURBO_A;
1820         else if (IEEE80211_IS_CHAN_HALF(chan))
1821                 return IEEE80211_MODE_HALF;
1822         else if (IEEE80211_IS_CHAN_QUARTER(chan))
1823                 return IEEE80211_MODE_QUARTER;
1824         else if (IEEE80211_IS_CHAN_A(chan))
1825                 return IEEE80211_MODE_11A;
1826         else if (IEEE80211_IS_CHAN_ANYG(chan))
1827                 return IEEE80211_MODE_11G;
1828         else if (IEEE80211_IS_CHAN_B(chan))
1829                 return IEEE80211_MODE_11B;
1830         else if (IEEE80211_IS_CHAN_FHSS(chan))
1831                 return IEEE80211_MODE_FH;
1832
1833         /* NB: should not get here */
1834         printf("%s: cannot map channel to mode; freq %u flags 0x%x\n",
1835                 __func__, chan->ic_freq, chan->ic_flags);
1836         return IEEE80211_MODE_11B;
1837 }
1838
1839 struct ratemedia {
1840         u_int   match;  /* rate + mode */
1841         u_int   media;  /* if_media rate */
1842 };
1843
1844 static int
1845 findmedia(const struct ratemedia rates[], int n, u_int match)
1846 {
1847         int i;
1848
1849         for (i = 0; i < n; i++)
1850                 if (rates[i].match == match)
1851                         return rates[i].media;
1852         return IFM_AUTO;
1853 }
1854
1855 /*
1856  * Convert IEEE80211 rate value to ifmedia subtype.
1857  * Rate is either a legacy rate in units of 0.5Mbps
1858  * or an MCS index.
1859  */
1860 int
1861 ieee80211_rate2media(struct ieee80211com *ic, int rate, enum ieee80211_phymode mode)
1862 {
1863         static const struct ratemedia rates[] = {
1864                 {   2 | IFM_IEEE80211_FH, IFM_IEEE80211_FH1 },
1865                 {   4 | IFM_IEEE80211_FH, IFM_IEEE80211_FH2 },
1866                 {   2 | IFM_IEEE80211_11B, IFM_IEEE80211_DS1 },
1867                 {   4 | IFM_IEEE80211_11B, IFM_IEEE80211_DS2 },
1868                 {  11 | IFM_IEEE80211_11B, IFM_IEEE80211_DS5 },
1869                 {  22 | IFM_IEEE80211_11B, IFM_IEEE80211_DS11 },
1870                 {  44 | IFM_IEEE80211_11B, IFM_IEEE80211_DS22 },
1871                 {  12 | IFM_IEEE80211_11A, IFM_IEEE80211_OFDM6 },
1872                 {  18 | IFM_IEEE80211_11A, IFM_IEEE80211_OFDM9 },
1873                 {  24 | IFM_IEEE80211_11A, IFM_IEEE80211_OFDM12 },
1874                 {  36 | IFM_IEEE80211_11A, IFM_IEEE80211_OFDM18 },
1875                 {  48 | IFM_IEEE80211_11A, IFM_IEEE80211_OFDM24 },
1876                 {  72 | IFM_IEEE80211_11A, IFM_IEEE80211_OFDM36 },
1877                 {  96 | IFM_IEEE80211_11A, IFM_IEEE80211_OFDM48 },
1878                 { 108 | IFM_IEEE80211_11A, IFM_IEEE80211_OFDM54 },
1879                 {   2 | IFM_IEEE80211_11G, IFM_IEEE80211_DS1 },
1880                 {   4 | IFM_IEEE80211_11G, IFM_IEEE80211_DS2 },
1881                 {  11 | IFM_IEEE80211_11G, IFM_IEEE80211_DS5 },
1882                 {  22 | IFM_IEEE80211_11G, IFM_IEEE80211_DS11 },
1883                 {  12 | IFM_IEEE80211_11G, IFM_IEEE80211_OFDM6 },
1884                 {  18 | IFM_IEEE80211_11G, IFM_IEEE80211_OFDM9 },
1885                 {  24 | IFM_IEEE80211_11G, IFM_IEEE80211_OFDM12 },
1886                 {  36 | IFM_IEEE80211_11G, IFM_IEEE80211_OFDM18 },
1887                 {  48 | IFM_IEEE80211_11G, IFM_IEEE80211_OFDM24 },
1888                 {  72 | IFM_IEEE80211_11G, IFM_IEEE80211_OFDM36 },
1889                 {  96 | IFM_IEEE80211_11G, IFM_IEEE80211_OFDM48 },
1890                 { 108 | IFM_IEEE80211_11G, IFM_IEEE80211_OFDM54 },
1891                 {   6 | IFM_IEEE80211_11A, IFM_IEEE80211_OFDM3 },
1892                 {   9 | IFM_IEEE80211_11A, IFM_IEEE80211_OFDM4 },
1893                 {  54 | IFM_IEEE80211_11A, IFM_IEEE80211_OFDM27 },
1894                 /* NB: OFDM72 doesn't really exist so we don't handle it */
1895         };
1896         static const struct ratemedia htrates[] = {
1897                 {   0, IFM_IEEE80211_MCS },
1898                 {   1, IFM_IEEE80211_MCS },
1899                 {   2, IFM_IEEE80211_MCS },
1900                 {   3, IFM_IEEE80211_MCS },
1901                 {   4, IFM_IEEE80211_MCS },
1902                 {   5, IFM_IEEE80211_MCS },
1903                 {   6, IFM_IEEE80211_MCS },
1904                 {   7, IFM_IEEE80211_MCS },
1905                 {   8, IFM_IEEE80211_MCS },
1906                 {   9, IFM_IEEE80211_MCS },
1907                 {  10, IFM_IEEE80211_MCS },
1908                 {  11, IFM_IEEE80211_MCS },
1909                 {  12, IFM_IEEE80211_MCS },
1910                 {  13, IFM_IEEE80211_MCS },
1911                 {  14, IFM_IEEE80211_MCS },
1912                 {  15, IFM_IEEE80211_MCS },
1913                 {  16, IFM_IEEE80211_MCS },
1914                 {  17, IFM_IEEE80211_MCS },
1915                 {  18, IFM_IEEE80211_MCS },
1916                 {  19, IFM_IEEE80211_MCS },
1917                 {  20, IFM_IEEE80211_MCS },
1918                 {  21, IFM_IEEE80211_MCS },
1919                 {  22, IFM_IEEE80211_MCS },
1920                 {  23, IFM_IEEE80211_MCS },
1921                 {  24, IFM_IEEE80211_MCS },
1922                 {  25, IFM_IEEE80211_MCS },
1923                 {  26, IFM_IEEE80211_MCS },
1924                 {  27, IFM_IEEE80211_MCS },
1925                 {  28, IFM_IEEE80211_MCS },
1926                 {  29, IFM_IEEE80211_MCS },
1927                 {  30, IFM_IEEE80211_MCS },
1928                 {  31, IFM_IEEE80211_MCS },
1929                 {  32, IFM_IEEE80211_MCS },
1930                 {  33, IFM_IEEE80211_MCS },
1931                 {  34, IFM_IEEE80211_MCS },
1932                 {  35, IFM_IEEE80211_MCS },
1933                 {  36, IFM_IEEE80211_MCS },
1934                 {  37, IFM_IEEE80211_MCS },
1935                 {  38, IFM_IEEE80211_MCS },
1936                 {  39, IFM_IEEE80211_MCS },
1937                 {  40, IFM_IEEE80211_MCS },
1938                 {  41, IFM_IEEE80211_MCS },
1939                 {  42, IFM_IEEE80211_MCS },
1940                 {  43, IFM_IEEE80211_MCS },
1941                 {  44, IFM_IEEE80211_MCS },
1942                 {  45, IFM_IEEE80211_MCS },
1943                 {  46, IFM_IEEE80211_MCS },
1944                 {  47, IFM_IEEE80211_MCS },
1945                 {  48, IFM_IEEE80211_MCS },
1946                 {  49, IFM_IEEE80211_MCS },
1947                 {  50, IFM_IEEE80211_MCS },
1948                 {  51, IFM_IEEE80211_MCS },
1949                 {  52, IFM_IEEE80211_MCS },
1950                 {  53, IFM_IEEE80211_MCS },
1951                 {  54, IFM_IEEE80211_MCS },
1952                 {  55, IFM_IEEE80211_MCS },
1953                 {  56, IFM_IEEE80211_MCS },
1954                 {  57, IFM_IEEE80211_MCS },
1955                 {  58, IFM_IEEE80211_MCS },
1956                 {  59, IFM_IEEE80211_MCS },
1957                 {  60, IFM_IEEE80211_MCS },
1958                 {  61, IFM_IEEE80211_MCS },
1959                 {  62, IFM_IEEE80211_MCS },
1960                 {  63, IFM_IEEE80211_MCS },
1961                 {  64, IFM_IEEE80211_MCS },
1962                 {  65, IFM_IEEE80211_MCS },
1963                 {  66, IFM_IEEE80211_MCS },
1964                 {  67, IFM_IEEE80211_MCS },
1965                 {  68, IFM_IEEE80211_MCS },
1966                 {  69, IFM_IEEE80211_MCS },
1967                 {  70, IFM_IEEE80211_MCS },
1968                 {  71, IFM_IEEE80211_MCS },
1969                 {  72, IFM_IEEE80211_MCS },
1970                 {  73, IFM_IEEE80211_MCS },
1971                 {  74, IFM_IEEE80211_MCS },
1972                 {  75, IFM_IEEE80211_MCS },
1973                 {  76, IFM_IEEE80211_MCS },
1974         };
1975         int m;
1976
1977         /*
1978          * Check 11n rates first for match as an MCS.
1979          */
1980         if (mode == IEEE80211_MODE_11NA) {
1981                 if (rate & IEEE80211_RATE_MCS) {
1982                         rate &= ~IEEE80211_RATE_MCS;
1983                         m = findmedia(htrates, nitems(htrates), rate);
1984                         if (m != IFM_AUTO)
1985                                 return m | IFM_IEEE80211_11NA;
1986                 }
1987         } else if (mode == IEEE80211_MODE_11NG) {
1988                 /* NB: 12 is ambiguous, it will be treated as an MCS */
1989                 if (rate & IEEE80211_RATE_MCS) {
1990                         rate &= ~IEEE80211_RATE_MCS;
1991                         m = findmedia(htrates, nitems(htrates), rate);
1992                         if (m != IFM_AUTO)
1993                                 return m | IFM_IEEE80211_11NG;
1994                 }
1995         }
1996         rate &= IEEE80211_RATE_VAL;
1997         switch (mode) {
1998         case IEEE80211_MODE_11A:
1999         case IEEE80211_MODE_HALF:               /* XXX good 'nuf */
2000         case IEEE80211_MODE_QUARTER:
2001         case IEEE80211_MODE_11NA:
2002         case IEEE80211_MODE_TURBO_A:
2003         case IEEE80211_MODE_STURBO_A:
2004                 return findmedia(rates, nitems(rates), 
2005                     rate | IFM_IEEE80211_11A);
2006         case IEEE80211_MODE_11B:
2007                 return findmedia(rates, nitems(rates), 
2008                     rate | IFM_IEEE80211_11B);
2009         case IEEE80211_MODE_FH:
2010                 return findmedia(rates, nitems(rates), 
2011                     rate | IFM_IEEE80211_FH);
2012         case IEEE80211_MODE_AUTO:
2013                 /* NB: ic may be NULL for some drivers */
2014                 if (ic != NULL && ic->ic_phytype == IEEE80211_T_FH)
2015                         return findmedia(rates, nitems(rates),
2016                             rate | IFM_IEEE80211_FH);
2017                 /* NB: hack, 11g matches both 11b+11a rates */
2018                 /* fall thru... */
2019         case IEEE80211_MODE_11G:
2020         case IEEE80211_MODE_11NG:
2021         case IEEE80211_MODE_TURBO_G:
2022                 return findmedia(rates, nitems(rates), rate | IFM_IEEE80211_11G);
2023         case IEEE80211_MODE_VHT_2GHZ:
2024         case IEEE80211_MODE_VHT_5GHZ:
2025                 /* XXX TODO: need to figure out mapping for VHT rates */
2026                 return IFM_AUTO;
2027         }
2028         return IFM_AUTO;
2029 }
2030
2031 int
2032 ieee80211_media2rate(int mword)
2033 {
2034         static const int ieeerates[] = {
2035                 -1,             /* IFM_AUTO */
2036                 0,              /* IFM_MANUAL */
2037                 0,              /* IFM_NONE */
2038                 2,              /* IFM_IEEE80211_FH1 */
2039                 4,              /* IFM_IEEE80211_FH2 */
2040                 2,              /* IFM_IEEE80211_DS1 */
2041                 4,              /* IFM_IEEE80211_DS2 */
2042                 11,             /* IFM_IEEE80211_DS5 */
2043                 22,             /* IFM_IEEE80211_DS11 */
2044                 44,             /* IFM_IEEE80211_DS22 */
2045                 12,             /* IFM_IEEE80211_OFDM6 */
2046                 18,             /* IFM_IEEE80211_OFDM9 */
2047                 24,             /* IFM_IEEE80211_OFDM12 */
2048                 36,             /* IFM_IEEE80211_OFDM18 */
2049                 48,             /* IFM_IEEE80211_OFDM24 */
2050                 72,             /* IFM_IEEE80211_OFDM36 */
2051                 96,             /* IFM_IEEE80211_OFDM48 */
2052                 108,            /* IFM_IEEE80211_OFDM54 */
2053                 144,            /* IFM_IEEE80211_OFDM72 */
2054                 0,              /* IFM_IEEE80211_DS354k */
2055                 0,              /* IFM_IEEE80211_DS512k */
2056                 6,              /* IFM_IEEE80211_OFDM3 */
2057                 9,              /* IFM_IEEE80211_OFDM4 */
2058                 54,             /* IFM_IEEE80211_OFDM27 */
2059                 -1,             /* IFM_IEEE80211_MCS */
2060                 -1,             /* IFM_IEEE80211_VHT */
2061         };
2062         return IFM_SUBTYPE(mword) < nitems(ieeerates) ?
2063                 ieeerates[IFM_SUBTYPE(mword)] : 0;
2064 }
2065
2066 /*
2067  * The following hash function is adapted from "Hash Functions" by Bob Jenkins
2068  * ("Algorithm Alley", Dr. Dobbs Journal, September 1997).
2069  */
2070 #define mix(a, b, c)                                                    \
2071 do {                                                                    \
2072         a -= b; a -= c; a ^= (c >> 13);                                 \
2073         b -= c; b -= a; b ^= (a << 8);                                  \
2074         c -= a; c -= b; c ^= (b >> 13);                                 \
2075         a -= b; a -= c; a ^= (c >> 12);                                 \
2076         b -= c; b -= a; b ^= (a << 16);                                 \
2077         c -= a; c -= b; c ^= (b >> 5);                                  \
2078         a -= b; a -= c; a ^= (c >> 3);                                  \
2079         b -= c; b -= a; b ^= (a << 10);                                 \
2080         c -= a; c -= b; c ^= (b >> 15);                                 \
2081 } while (/*CONSTCOND*/0)
2082
2083 uint32_t
2084 ieee80211_mac_hash(const struct ieee80211com *ic,
2085         const uint8_t addr[IEEE80211_ADDR_LEN])
2086 {
2087         uint32_t a = 0x9e3779b9, b = 0x9e3779b9, c = ic->ic_hash_key;
2088
2089         b += addr[5] << 8;
2090         b += addr[4];
2091         a += addr[3] << 24;
2092         a += addr[2] << 16;
2093         a += addr[1] << 8;
2094         a += addr[0];
2095
2096         mix(a, b, c);
2097
2098         return c;
2099 }
2100 #undef mix
2101
2102 char
2103 ieee80211_channel_type_char(const struct ieee80211_channel *c)
2104 {
2105         if (IEEE80211_IS_CHAN_ST(c))
2106                 return 'S';
2107         if (IEEE80211_IS_CHAN_108A(c))
2108                 return 'T';
2109         if (IEEE80211_IS_CHAN_108G(c))
2110                 return 'G';
2111         if (IEEE80211_IS_CHAN_VHT(c))
2112                 return 'v';
2113         if (IEEE80211_IS_CHAN_HT(c))
2114                 return 'n';
2115         if (IEEE80211_IS_CHAN_A(c))
2116                 return 'a';
2117         if (IEEE80211_IS_CHAN_ANYG(c))
2118                 return 'g';
2119         if (IEEE80211_IS_CHAN_B(c))
2120                 return 'b';
2121         return 'f';
2122 }