Merge branch 'vendor/LIBEDIT'
[dragonfly.git] / sys / netproto / 802_11 / wlan / ieee80211_proto.c
1 /*-
2  * Copyright (c) 2001 Atsushi Onoe
3  * Copyright (c) 2002-2008 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  * $FreeBSD: head/sys/net80211/ieee80211_proto.c 195618 2009-07-11 15:02:45Z rpaulo $
27  */
28
29 /*
30  * IEEE 802.11 protocol support.
31  */
32
33 #include "opt_inet.h"
34 #include "opt_wlan.h"
35
36 #include <sys/param.h>
37 #include <sys/kernel.h>
38 #include <sys/systm.h>
39
40 #include <sys/socket.h>
41 #include <sys/sockio.h>
42
43 #include <net/if.h>
44 #include <net/if_media.h>
45 #include <net/route.h>
46
47 #include <netproto/802_11/ieee80211_var.h>
48 #include <netproto/802_11/ieee80211_adhoc.h>
49 #include <netproto/802_11/ieee80211_sta.h>
50 #include <netproto/802_11/ieee80211_hostap.h>
51 #include <netproto/802_11/ieee80211_wds.h>
52 #ifdef IEEE80211_SUPPORT_MESH
53 #include <netproto/802_11/ieee80211_mesh.h>
54 #endif
55 #include <netproto/802_11/ieee80211_monitor.h>
56 #include <netproto/802_11/ieee80211_input.h>
57
58 /* XXX tunables */
59 #define AGGRESSIVE_MODE_SWITCH_HYSTERESIS       3       /* pkts / 100ms */
60 #define HIGH_PRI_SWITCH_THRESH                  10      /* pkts / 100ms */
61
62 const char *ieee80211_mgt_subtype_name[] = {
63         "assoc_req",    "assoc_resp",   "reassoc_req",  "reassoc_resp",
64         "probe_req",    "probe_resp",   "reserved#6",   "reserved#7",
65         "beacon",       "atim",         "disassoc",     "auth",
66         "deauth",       "action",       "reserved#14",  "reserved#15"
67 };
68 const char *ieee80211_ctl_subtype_name[] = {
69         "reserved#0",   "reserved#1",   "reserved#2",   "reserved#3",
70         "reserved#3",   "reserved#5",   "reserved#6",   "reserved#7",
71         "reserved#8",   "reserved#9",   "ps_poll",      "rts",
72         "cts",          "ack",          "cf_end",       "cf_end_ack"
73 };
74 const char *ieee80211_opmode_name[IEEE80211_OPMODE_MAX] = {
75         "IBSS",         /* IEEE80211_M_IBSS */
76         "STA",          /* IEEE80211_M_STA */
77         "WDS",          /* IEEE80211_M_WDS */
78         "AHDEMO",       /* IEEE80211_M_AHDEMO */
79         "HOSTAP",       /* IEEE80211_M_HOSTAP */
80         "MONITOR",      /* IEEE80211_M_MONITOR */
81         "MBSS"          /* IEEE80211_M_MBSS */
82 };
83 const char *ieee80211_state_name[IEEE80211_S_MAX] = {
84         "INIT",         /* IEEE80211_S_INIT */
85         "SCAN",         /* IEEE80211_S_SCAN */
86         "AUTH",         /* IEEE80211_S_AUTH */
87         "ASSOC",        /* IEEE80211_S_ASSOC */
88         "CAC",          /* IEEE80211_S_CAC */
89         "RUN",          /* IEEE80211_S_RUN */
90         "CSA",          /* IEEE80211_S_CSA */
91         "SLEEP",        /* IEEE80211_S_SLEEP */
92 };
93 const char *ieee80211_wme_acnames[] = {
94         "WME_AC_BE",
95         "WME_AC_BK",
96         "WME_AC_VI",
97         "WME_AC_VO",
98         "WME_UPSD",
99 };
100
101 static void beacon_miss_task(void *, int);
102 static void beacon_swmiss_task(void *, int);
103 static void parent_updown_task(void *, int);
104 static void update_mcast_task(void *, int);
105 static void update_promisc_task(void *, int);
106 static void update_channel_task(void *, int);
107 static void ieee80211_newstate_task(void *, int);
108 static int ieee80211_new_state_locked(struct ieee80211vap *,
109         enum ieee80211_state, int);
110
111 static int
112 null_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
113         const struct ieee80211_bpf_params *params)
114 {
115         struct ifnet *ifp = ni->ni_ic->ic_ifp;
116
117         if_printf(ifp, "missing ic_raw_xmit callback, drop frame\n");
118         m_freem(m);
119         return ENETDOWN;
120 }
121
122 void
123 ieee80211_proto_attach(struct ieee80211com *ic)
124 {
125         struct ifnet *ifp = ic->ic_ifp;
126
127         /* override the 802.3 setting */
128         ifp->if_hdrlen = ic->ic_headroom
129                 + sizeof(struct ieee80211_qosframe_addr4)
130                 + IEEE80211_WEP_IVLEN + IEEE80211_WEP_KIDLEN
131                 + IEEE80211_WEP_EXTIVLEN;
132         /* XXX no way to recalculate on ifdetach */
133         if (ALIGN(ifp->if_hdrlen) > max_linkhdr) {
134                 /* XXX sanity check... */
135                 max_linkhdr = ALIGN(ifp->if_hdrlen);
136                 max_hdr = max_linkhdr + max_protohdr;
137                 max_datalen = MHLEN - max_hdr;
138         }
139         ic->ic_protmode = IEEE80211_PROT_CTSONLY;
140
141         TASK_INIT(&ic->ic_parent_task, 0, parent_updown_task, ifp);
142         TASK_INIT(&ic->ic_mcast_task, 0, update_mcast_task, ic);
143         TASK_INIT(&ic->ic_promisc_task, 0, update_promisc_task, ic);
144         TASK_INIT(&ic->ic_chan_task, 0, update_channel_task, ic);
145         TASK_INIT(&ic->ic_bmiss_task, 0, beacon_miss_task, ic);
146
147         ic->ic_wme.wme_hipri_switch_hysteresis =
148                 AGGRESSIVE_MODE_SWITCH_HYSTERESIS;
149
150         /* initialize management frame handlers */
151         ic->ic_send_mgmt = ieee80211_send_mgmt;
152         ic->ic_raw_xmit = null_raw_xmit;
153
154         ieee80211_adhoc_attach(ic);
155         ieee80211_sta_attach(ic);
156         ieee80211_wds_attach(ic);
157         ieee80211_hostap_attach(ic);
158 #ifdef IEEE80211_SUPPORT_MESH
159         ieee80211_mesh_attach(ic);
160 #endif
161         ieee80211_monitor_attach(ic);
162 }
163
164 void
165 ieee80211_proto_detach(struct ieee80211com *ic)
166 {
167         ieee80211_monitor_detach(ic);
168 #ifdef IEEE80211_SUPPORT_MESH
169         ieee80211_mesh_detach(ic);
170 #endif
171         ieee80211_hostap_detach(ic);
172         ieee80211_wds_detach(ic);
173         ieee80211_adhoc_detach(ic);
174         ieee80211_sta_detach(ic);
175 }
176
177 static void
178 null_update_beacon(struct ieee80211vap *vap, int item)
179 {
180 }
181
182 void
183 ieee80211_proto_vattach(struct ieee80211vap *vap)
184 {
185         struct ieee80211com *ic = vap->iv_ic;
186         struct ifnet *ifp = vap->iv_ifp;
187         int i;
188
189         /* override the 802.3 setting */
190         ifp->if_hdrlen = ic->ic_ifp->if_hdrlen;
191
192         vap->iv_rtsthreshold = IEEE80211_RTS_DEFAULT;
193         vap->iv_fragthreshold = IEEE80211_FRAG_DEFAULT;
194         vap->iv_bmiss_max = IEEE80211_BMISS_MAX;
195         callout_init_mp(&vap->iv_swbmiss);
196         callout_init_mp(&vap->iv_mgtsend);
197         TASK_INIT(&vap->iv_nstate_task, 0, ieee80211_newstate_task, vap);
198         TASK_INIT(&vap->iv_swbmiss_task, 0, beacon_swmiss_task, vap);
199         /*
200          * Install default tx rate handling: no fixed rate, lowest
201          * supported rate for mgmt and multicast frames.  Default
202          * max retry count.  These settings can be changed by the
203          * driver and/or user applications.
204          */
205         for (i = IEEE80211_MODE_11A; i < IEEE80211_MODE_MAX; i++) {
206                 const struct ieee80211_rateset *rs = &ic->ic_sup_rates[i];
207
208                 vap->iv_txparms[i].ucastrate = IEEE80211_FIXED_RATE_NONE;
209                 if (i == IEEE80211_MODE_11NA || i == IEEE80211_MODE_11NG) {
210                         vap->iv_txparms[i].mgmtrate = 0 | IEEE80211_RATE_MCS;
211                         vap->iv_txparms[i].mcastrate = 0 | IEEE80211_RATE_MCS;
212                 } else {
213                         vap->iv_txparms[i].mgmtrate =
214                             rs->rs_rates[0] & IEEE80211_RATE_VAL;
215                         vap->iv_txparms[i].mcastrate = 
216                             rs->rs_rates[0] & IEEE80211_RATE_VAL;
217                 }
218                 vap->iv_txparms[i].maxretry = IEEE80211_TXMAX_DEFAULT;
219         }
220         vap->iv_roaming = IEEE80211_ROAMING_AUTO;
221
222         vap->iv_update_beacon = null_update_beacon;
223         vap->iv_deliver_data = ieee80211_deliver_data;
224
225         /* attach support for operating mode */
226         ic->ic_vattach[vap->iv_opmode](vap);
227 }
228
229 void
230 ieee80211_proto_vdetach(struct ieee80211vap *vap)
231 {
232 #define FREEAPPIE(ie) do { \
233         if (ie != NULL) \
234                 kfree(ie, M_80211_NODE_IE); \
235 } while (0)
236         /*
237          * Detach operating mode module.
238          */
239         if (vap->iv_opdetach != NULL)
240                 vap->iv_opdetach(vap);
241         /*
242          * This should not be needed as we detach when reseting
243          * the state but be conservative here since the
244          * authenticator may do things like spawn kernel threads.
245          */
246         if (vap->iv_auth->ia_detach != NULL)
247                 vap->iv_auth->ia_detach(vap);
248         /*
249          * Detach any ACL'ator.
250          */
251         if (vap->iv_acl != NULL)
252                 vap->iv_acl->iac_detach(vap);
253
254         FREEAPPIE(vap->iv_appie_beacon);
255         FREEAPPIE(vap->iv_appie_probereq);
256         FREEAPPIE(vap->iv_appie_proberesp);
257         FREEAPPIE(vap->iv_appie_assocreq);
258         FREEAPPIE(vap->iv_appie_assocresp);
259         FREEAPPIE(vap->iv_appie_wpa);
260 #undef FREEAPPIE
261 }
262
263 /*
264  * Simple-minded authenticator module support.
265  */
266
267 #define IEEE80211_AUTH_MAX      (IEEE80211_AUTH_WPA+1)
268 /* XXX well-known names */
269 static const char *auth_modnames[IEEE80211_AUTH_MAX] = {
270         "wlan_internal",        /* IEEE80211_AUTH_NONE */
271         "wlan_internal",        /* IEEE80211_AUTH_OPEN */
272         "wlan_internal",        /* IEEE80211_AUTH_SHARED */
273         "wlan_xauth",           /* IEEE80211_AUTH_8021X  */
274         "wlan_internal",        /* IEEE80211_AUTH_AUTO */
275         "wlan_xauth",           /* IEEE80211_AUTH_WPA */
276 };
277 static const struct ieee80211_authenticator *authenticators[IEEE80211_AUTH_MAX];
278
279 static const struct ieee80211_authenticator auth_internal = {
280         .ia_name                = "wlan_internal",
281         .ia_attach              = NULL,
282         .ia_detach              = NULL,
283         .ia_node_join           = NULL,
284         .ia_node_leave          = NULL,
285 };
286
287 /*
288  * Setup internal authenticators once; they are never unregistered.
289  */
290 static void
291 ieee80211_auth_setup(void)
292 {
293         ieee80211_authenticator_register(IEEE80211_AUTH_OPEN, &auth_internal);
294         ieee80211_authenticator_register(IEEE80211_AUTH_SHARED, &auth_internal);
295         ieee80211_authenticator_register(IEEE80211_AUTH_AUTO, &auth_internal);
296 }
297 SYSINIT(wlan_auth, SI_SUB_DRIVERS, SI_ORDER_FIRST, ieee80211_auth_setup, NULL);
298
299 const struct ieee80211_authenticator *
300 ieee80211_authenticator_get(int auth)
301 {
302         if (auth >= IEEE80211_AUTH_MAX)
303                 return NULL;
304         if (authenticators[auth] == NULL)
305                 ieee80211_load_module(auth_modnames[auth]);
306         return authenticators[auth];
307 }
308
309 void
310 ieee80211_authenticator_register(int type,
311         const struct ieee80211_authenticator *auth)
312 {
313         if (type >= IEEE80211_AUTH_MAX)
314                 return;
315         authenticators[type] = auth;
316 }
317
318 void
319 ieee80211_authenticator_unregister(int type)
320 {
321
322         if (type >= IEEE80211_AUTH_MAX)
323                 return;
324         authenticators[type] = NULL;
325 }
326
327 /*
328  * Very simple-minded ACL module support.
329  */
330 /* XXX just one for now */
331 static  const struct ieee80211_aclator *acl = NULL;
332
333 void
334 ieee80211_aclator_register(const struct ieee80211_aclator *iac)
335 {
336         kprintf("wlan: %s acl policy registered\n", iac->iac_name);
337         acl = iac;
338 }
339
340 void
341 ieee80211_aclator_unregister(const struct ieee80211_aclator *iac)
342 {
343         if (acl == iac)
344                 acl = NULL;
345         kprintf("wlan: %s acl policy unregistered\n", iac->iac_name);
346 }
347
348 const struct ieee80211_aclator *
349 ieee80211_aclator_get(const char *name)
350 {
351         if (acl == NULL)
352                 ieee80211_load_module("wlan_acl");
353         return acl != NULL && strcmp(acl->iac_name, name) == 0 ? acl : NULL;
354 }
355
356 void
357 ieee80211_print_essid(const uint8_t *essid, int len)
358 {
359         const uint8_t *p;
360         int i;
361
362         if (len > IEEE80211_NWID_LEN)
363                 len = IEEE80211_NWID_LEN;
364         /* determine printable or not */
365         for (i = 0, p = essid; i < len; i++, p++) {
366                 if (*p < ' ' || *p > 0x7e)
367                         break;
368         }
369         if (i == len) {
370                 kprintf("\"");
371                 for (i = 0, p = essid; i < len; i++, p++)
372                         kprintf("%c", *p);
373                 kprintf("\"");
374         } else {
375                 kprintf("0x");
376                 for (i = 0, p = essid; i < len; i++, p++)
377                         kprintf("%02x", *p);
378         }
379 }
380
381 void
382 ieee80211_dump_pkt(struct ieee80211com *ic,
383         const uint8_t *buf, int len, int rate, int rssi)
384 {
385         const struct ieee80211_frame *wh;
386         int i;
387
388         wh = (const struct ieee80211_frame *)buf;
389         switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
390         case IEEE80211_FC1_DIR_NODS:
391                 kprintf("NODS %6D", wh->i_addr2, ":");
392                 kprintf("->%6D", wh->i_addr1, ":");
393                 kprintf("(%6D)", wh->i_addr3, ":");
394                 break;
395         case IEEE80211_FC1_DIR_TODS:
396                 kprintf("TODS %6D", wh->i_addr2, ":");
397                 kprintf("->%6D", wh->i_addr3, ":");
398                 kprintf("(%6D)", wh->i_addr1, ":");
399                 break;
400         case IEEE80211_FC1_DIR_FROMDS:
401                 kprintf("FRDS %6D", wh->i_addr3, ":");
402                 kprintf("->%6D", wh->i_addr1, ":");
403                 kprintf("(%6D)", wh->i_addr2, ":");
404                 break;
405         case IEEE80211_FC1_DIR_DSTODS:
406                 kprintf("DSDS %6D", (const uint8_t *)&wh[1], ":");
407                 kprintf("->%6D", wh->i_addr3, ":");
408                 kprintf("(%6D", wh->i_addr2, ":");
409                 kprintf("->%6D)", wh->i_addr1, ":");
410                 break;
411         }
412         switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
413         case IEEE80211_FC0_TYPE_DATA:
414                 kprintf(" data");
415                 break;
416         case IEEE80211_FC0_TYPE_MGT:
417                 kprintf(" %s", ieee80211_mgt_subtype_name[
418                     (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK)
419                     >> IEEE80211_FC0_SUBTYPE_SHIFT]);
420                 break;
421         default:
422                 kprintf(" type#%d", wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK);
423                 break;
424         }
425         if (IEEE80211_QOS_HAS_SEQ(wh)) {
426                 const struct ieee80211_qosframe *qwh = 
427                         (const struct ieee80211_qosframe *)buf;
428                 kprintf(" QoS [TID %u%s]", qwh->i_qos[0] & IEEE80211_QOS_TID,
429                         qwh->i_qos[0] & IEEE80211_QOS_ACKPOLICY ? " ACM" : "");
430         }
431         if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
432                 int off;
433
434                 off = ieee80211_anyhdrspace(ic, wh);
435                 kprintf(" WEP [IV %.02x %.02x %.02x",
436                         buf[off+0], buf[off+1], buf[off+2]);
437                 if (buf[off+IEEE80211_WEP_IVLEN] & IEEE80211_WEP_EXTIV)
438                         kprintf(" %.02x %.02x %.02x",
439                                 buf[off+4], buf[off+5], buf[off+6]);
440                 kprintf(" KID %u]", buf[off+IEEE80211_WEP_IVLEN] >> 6);
441         }
442         if (rate >= 0)
443                 kprintf(" %dM", rate / 2);
444         if (rssi >= 0)
445                 kprintf(" +%d", rssi);
446         kprintf("\n");
447         if (len > 0) {
448                 for (i = 0; i < len; i++) {
449                         if ((i & 1) == 0)
450                                 kprintf(" ");
451                         kprintf("%02x", buf[i]);
452                 }
453                 kprintf("\n");
454         }
455 }
456
457 static __inline int
458 findrix(const struct ieee80211_rateset *rs, int r)
459 {
460         int i;
461
462         for (i = 0; i < rs->rs_nrates; i++)
463                 if ((rs->rs_rates[i] & IEEE80211_RATE_VAL) == r)
464                         return i;
465         return -1;
466 }
467
468 int
469 ieee80211_fix_rate(struct ieee80211_node *ni,
470         struct ieee80211_rateset *nrs, int flags)
471 {
472 #define RV(v)   ((v) & IEEE80211_RATE_VAL)
473         struct ieee80211vap *vap = ni->ni_vap;
474         struct ieee80211com *ic = ni->ni_ic;
475         int i, j, rix, error;
476         int okrate, badrate, fixedrate, ucastrate;
477         const struct ieee80211_rateset *srs;
478         uint8_t r;
479
480         error = 0;
481         okrate = badrate = 0;
482         ucastrate = vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)].ucastrate;
483         if (ucastrate != IEEE80211_FIXED_RATE_NONE) {
484                 /*
485                  * Workaround awkwardness with fixed rate.  We are called
486                  * to check both the legacy rate set and the HT rate set
487                  * but we must apply any legacy fixed rate check only to the
488                  * legacy rate set and vice versa.  We cannot tell what type
489                  * of rate set we've been given (legacy or HT) but we can
490                  * distinguish the fixed rate type (MCS have 0x80 set).
491                  * So to deal with this the caller communicates whether to
492                  * check MCS or legacy rate using the flags and we use the
493                  * type of any fixed rate to avoid applying an MCS to a
494                  * legacy rate and vice versa.
495                  */
496                 if (ucastrate & 0x80) {
497                         if (flags & IEEE80211_F_DOFRATE)
498                                 flags &= ~IEEE80211_F_DOFRATE;
499                 } else if ((ucastrate & 0x80) == 0) {
500                         if (flags & IEEE80211_F_DOFMCS)
501                                 flags &= ~IEEE80211_F_DOFMCS;
502                 }
503                 /* NB: required to make MCS match below work */
504                 ucastrate &= IEEE80211_RATE_VAL;
505         }
506         fixedrate = IEEE80211_FIXED_RATE_NONE;
507         /*
508          * XXX we are called to process both MCS and legacy rates;
509          * we must use the appropriate basic rate set or chaos will
510          * ensue; for now callers that want MCS must supply
511          * IEEE80211_F_DOBRS; at some point we'll need to split this
512          * function so there are two variants, one for MCS and one
513          * for legacy rates.
514          */
515         if (flags & IEEE80211_F_DOBRS)
516                 srs = (const struct ieee80211_rateset *)
517                     ieee80211_get_suphtrates(ic, ni->ni_chan);
518         else
519                 srs = ieee80211_get_suprates(ic, ni->ni_chan);
520         for (i = 0; i < nrs->rs_nrates; ) {
521                 if (flags & IEEE80211_F_DOSORT) {
522                         /*
523                          * Sort rates.
524                          */
525                         for (j = i + 1; j < nrs->rs_nrates; j++) {
526                                 if (RV(nrs->rs_rates[i]) > RV(nrs->rs_rates[j])) {
527                                         r = nrs->rs_rates[i];
528                                         nrs->rs_rates[i] = nrs->rs_rates[j];
529                                         nrs->rs_rates[j] = r;
530                                 }
531                         }
532                 }
533                 r = nrs->rs_rates[i] & IEEE80211_RATE_VAL;
534                 badrate = r;
535                 /*
536                  * Check for fixed rate.
537                  */
538                 if (r == ucastrate)
539                         fixedrate = r;
540                 /*
541                  * Check against supported rates.
542                  */
543                 rix = findrix(srs, r);
544                 if (flags & IEEE80211_F_DONEGO) {
545                         if (rix < 0) {
546                                 /*
547                                  * A rate in the node's rate set is not
548                                  * supported.  If this is a basic rate and we
549                                  * are operating as a STA then this is an error.
550                                  * Otherwise we just discard/ignore the rate.
551                                  */
552                                 if ((flags & IEEE80211_F_JOIN) &&
553                                     (nrs->rs_rates[i] & IEEE80211_RATE_BASIC))
554                                         error++;
555                         } else if ((flags & IEEE80211_F_JOIN) == 0) {
556                                 /*
557                                  * Overwrite with the supported rate
558                                  * value so any basic rate bit is set.
559                                  */
560                                 nrs->rs_rates[i] = srs->rs_rates[rix];
561                         }
562                 }
563                 if ((flags & IEEE80211_F_DODEL) && rix < 0) {
564                         /*
565                          * Delete unacceptable rates.
566                          */
567                         nrs->rs_nrates--;
568                         for (j = i; j < nrs->rs_nrates; j++)
569                                 nrs->rs_rates[j] = nrs->rs_rates[j + 1];
570                         nrs->rs_rates[j] = 0;
571                         continue;
572                 }
573                 if (rix >= 0)
574                         okrate = nrs->rs_rates[i];
575                 i++;
576         }
577         if (okrate == 0 || error != 0 ||
578             ((flags & (IEEE80211_F_DOFRATE|IEEE80211_F_DOFMCS)) &&
579              fixedrate != ucastrate)) {
580                 IEEE80211_NOTE(vap, IEEE80211_MSG_XRATE | IEEE80211_MSG_11N, ni,
581                     "%s: flags 0x%x okrate %d error %d fixedrate 0x%x "
582                     "ucastrate %x\n", __func__, flags, okrate, error,
583                     fixedrate, ucastrate);
584                 return badrate | IEEE80211_RATE_BASIC;
585         } else
586                 return RV(okrate);
587 #undef RV
588 }
589
590 /*
591  * Reset 11g-related state.
592  */
593 void
594 ieee80211_reset_erp(struct ieee80211com *ic)
595 {
596         ic->ic_flags &= ~IEEE80211_F_USEPROT;
597         ic->ic_nonerpsta = 0;
598         ic->ic_longslotsta = 0;
599         /*
600          * Short slot time is enabled only when operating in 11g
601          * and not in an IBSS.  We must also honor whether or not
602          * the driver is capable of doing it.
603          */
604         ieee80211_set_shortslottime(ic,
605                 IEEE80211_IS_CHAN_A(ic->ic_curchan) ||
606                 IEEE80211_IS_CHAN_HT(ic->ic_curchan) ||
607                 (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan) &&
608                 ic->ic_opmode == IEEE80211_M_HOSTAP &&
609                 (ic->ic_caps & IEEE80211_C_SHSLOT)));
610         /*
611          * Set short preamble and ERP barker-preamble flags.
612          */
613         if (IEEE80211_IS_CHAN_A(ic->ic_curchan) ||
614             (ic->ic_caps & IEEE80211_C_SHPREAMBLE)) {
615                 ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
616                 ic->ic_flags &= ~IEEE80211_F_USEBARKER;
617         } else {
618                 ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
619                 ic->ic_flags |= IEEE80211_F_USEBARKER;
620         }
621 }
622
623 /*
624  * Set the short slot time state and notify the driver.
625  */
626 void
627 ieee80211_set_shortslottime(struct ieee80211com *ic, int onoff)
628 {
629         if (onoff)
630                 ic->ic_flags |= IEEE80211_F_SHSLOT;
631         else
632                 ic->ic_flags &= ~IEEE80211_F_SHSLOT;
633         /* notify driver */
634         if (ic->ic_updateslot != NULL)
635                 ic->ic_updateslot(ic->ic_ifp);
636 }
637
638 /*
639  * Check if the specified rate set supports ERP.
640  * NB: the rate set is assumed to be sorted.
641  */
642 int
643 ieee80211_iserp_rateset(const struct ieee80211_rateset *rs)
644 {
645         static const int rates[] = { 2, 4, 11, 22, 12, 24, 48 };
646         int i, j;
647
648         if (rs->rs_nrates < NELEM(rates))
649                 return 0;
650         for (i = 0; i < NELEM(rates); i++) {
651                 for (j = 0; j < rs->rs_nrates; j++) {
652                         int r = rs->rs_rates[j] & IEEE80211_RATE_VAL;
653                         if (rates[i] == r)
654                                 goto next;
655                         if (r > rates[i])
656                                 return 0;
657                 }
658                 return 0;
659         next:
660                 ;
661         }
662         return 1;
663 }
664
665 /*
666  * Mark the basic rates for the rate table based on the
667  * operating mode.  For real 11g we mark all the 11b rates
668  * and 6, 12, and 24 OFDM.  For 11b compatibility we mark only
669  * 11b rates.  There's also a pseudo 11a-mode used to mark only
670  * the basic OFDM rates.
671  */
672 static void
673 setbasicrates(struct ieee80211_rateset *rs,
674     enum ieee80211_phymode mode, int add)
675 {
676         static const struct ieee80211_rateset basic[IEEE80211_MODE_MAX] = {
677             [IEEE80211_MODE_11A]        = { 3, { 12, 24, 48 } },
678             [IEEE80211_MODE_11B]        = { 2, { 2, 4 } },
679                                             /* NB: mixed b/g */
680             [IEEE80211_MODE_11G]        = { 4, { 2, 4, 11, 22 } },
681             [IEEE80211_MODE_TURBO_A]    = { 3, { 12, 24, 48 } },
682             [IEEE80211_MODE_TURBO_G]    = { 4, { 2, 4, 11, 22 } },
683             [IEEE80211_MODE_STURBO_A]   = { 3, { 12, 24, 48 } },
684             [IEEE80211_MODE_HALF]       = { 3, { 6, 12, 24 } },
685             [IEEE80211_MODE_QUARTER]    = { 3, { 3, 6, 12 } },
686             [IEEE80211_MODE_11NA]       = { 3, { 12, 24, 48 } },
687                                             /* NB: mixed b/g */
688             [IEEE80211_MODE_11NG]       = { 4, { 2, 4, 11, 22 } },
689         };
690         int i, j;
691
692         for (i = 0; i < rs->rs_nrates; i++) {
693                 if (!add)
694                         rs->rs_rates[i] &= IEEE80211_RATE_VAL;
695                 for (j = 0; j < basic[mode].rs_nrates; j++)
696                         if (basic[mode].rs_rates[j] == rs->rs_rates[i]) {
697                                 rs->rs_rates[i] |= IEEE80211_RATE_BASIC;
698                                 break;
699                         }
700         }
701 }
702
703 /*
704  * Set the basic rates in a rate set.
705  */
706 void
707 ieee80211_setbasicrates(struct ieee80211_rateset *rs,
708     enum ieee80211_phymode mode)
709 {
710         setbasicrates(rs, mode, 0);
711 }
712
713 /*
714  * Add basic rates to a rate set.
715  */
716 void
717 ieee80211_addbasicrates(struct ieee80211_rateset *rs,
718     enum ieee80211_phymode mode)
719 {
720         setbasicrates(rs, mode, 1);
721 }
722
723 /*
724  * WME protocol support.
725  *
726  * The default 11a/b/g/n parameters come from the WiFi Alliance WMM
727  * System Interopability Test Plan (v1.4, Appendix F) and the 802.11n
728  * Draft 2.0 Test Plan (Appendix D).
729  *
730  * Static/Dynamic Turbo mode settings come from Atheros.
731  */
732 typedef struct phyParamType {
733         uint8_t         aifsn;
734         uint8_t         logcwmin;
735         uint8_t         logcwmax;
736         uint16_t        txopLimit;
737         uint8_t         acm;
738 } paramType;
739
740 static const struct phyParamType phyParamForAC_BE[IEEE80211_MODE_MAX] = {
741         [IEEE80211_MODE_AUTO]   = { 3, 4,  6,  0, 0 },
742         [IEEE80211_MODE_11A]    = { 3, 4,  6,  0, 0 },
743         [IEEE80211_MODE_11B]    = { 3, 4,  6,  0, 0 },
744         [IEEE80211_MODE_11G]    = { 3, 4,  6,  0, 0 },
745         [IEEE80211_MODE_FH]     = { 3, 4,  6,  0, 0 },
746         [IEEE80211_MODE_TURBO_A]= { 2, 3,  5,  0, 0 },
747         [IEEE80211_MODE_TURBO_G]= { 2, 3,  5,  0, 0 },
748         [IEEE80211_MODE_STURBO_A]={ 2, 3,  5,  0, 0 },
749         [IEEE80211_MODE_HALF]   = { 3, 4,  6,  0, 0 },
750         [IEEE80211_MODE_QUARTER]= { 3, 4,  6,  0, 0 },
751         [IEEE80211_MODE_11NA]   = { 3, 4,  6,  0, 0 },
752         [IEEE80211_MODE_11NG]   = { 3, 4,  6,  0, 0 },
753 };
754 static const struct phyParamType phyParamForAC_BK[IEEE80211_MODE_MAX] = {
755         [IEEE80211_MODE_AUTO]   = { 7, 4, 10,  0, 0 },
756         [IEEE80211_MODE_11A]    = { 7, 4, 10,  0, 0 },
757         [IEEE80211_MODE_11B]    = { 7, 4, 10,  0, 0 },
758         [IEEE80211_MODE_11G]    = { 7, 4, 10,  0, 0 },
759         [IEEE80211_MODE_FH]     = { 7, 4, 10,  0, 0 },
760         [IEEE80211_MODE_TURBO_A]= { 7, 3, 10,  0, 0 },
761         [IEEE80211_MODE_TURBO_G]= { 7, 3, 10,  0, 0 },
762         [IEEE80211_MODE_STURBO_A]={ 7, 3, 10,  0, 0 },
763         [IEEE80211_MODE_HALF]   = { 7, 4, 10,  0, 0 },
764         [IEEE80211_MODE_QUARTER]= { 7, 4, 10,  0, 0 },
765         [IEEE80211_MODE_11NA]   = { 7, 4, 10,  0, 0 },
766         [IEEE80211_MODE_11NG]   = { 7, 4, 10,  0, 0 },
767 };
768 static const struct phyParamType phyParamForAC_VI[IEEE80211_MODE_MAX] = {
769         [IEEE80211_MODE_AUTO]   = { 1, 3, 4,  94, 0 },
770         [IEEE80211_MODE_11A]    = { 1, 3, 4,  94, 0 },
771         [IEEE80211_MODE_11B]    = { 1, 3, 4, 188, 0 },
772         [IEEE80211_MODE_11G]    = { 1, 3, 4,  94, 0 },
773         [IEEE80211_MODE_FH]     = { 1, 3, 4, 188, 0 },
774         [IEEE80211_MODE_TURBO_A]= { 1, 2, 3,  94, 0 },
775         [IEEE80211_MODE_TURBO_G]= { 1, 2, 3,  94, 0 },
776         [IEEE80211_MODE_STURBO_A]={ 1, 2, 3,  94, 0 },
777         [IEEE80211_MODE_HALF]   = { 1, 3, 4,  94, 0 },
778         [IEEE80211_MODE_QUARTER]= { 1, 3, 4,  94, 0 },
779         [IEEE80211_MODE_11NA]   = { 1, 3, 4,  94, 0 },
780         [IEEE80211_MODE_11NG]   = { 1, 3, 4,  94, 0 },
781 };
782 static const struct phyParamType phyParamForAC_VO[IEEE80211_MODE_MAX] = {
783         [IEEE80211_MODE_AUTO]   = { 1, 2, 3,  47, 0 },
784         [IEEE80211_MODE_11A]    = { 1, 2, 3,  47, 0 },
785         [IEEE80211_MODE_11B]    = { 1, 2, 3, 102, 0 },
786         [IEEE80211_MODE_11G]    = { 1, 2, 3,  47, 0 },
787         [IEEE80211_MODE_FH]     = { 1, 2, 3, 102, 0 },
788         [IEEE80211_MODE_TURBO_A]= { 1, 2, 2,  47, 0 },
789         [IEEE80211_MODE_TURBO_G]= { 1, 2, 2,  47, 0 },
790         [IEEE80211_MODE_STURBO_A]={ 1, 2, 2,  47, 0 },
791         [IEEE80211_MODE_HALF]   = { 1, 2, 3,  47, 0 },
792         [IEEE80211_MODE_QUARTER]= { 1, 2, 3,  47, 0 },
793         [IEEE80211_MODE_11NA]   = { 1, 2, 3,  47, 0 },
794         [IEEE80211_MODE_11NG]   = { 1, 2, 3,  47, 0 },
795 };
796
797 static const struct phyParamType bssPhyParamForAC_BE[IEEE80211_MODE_MAX] = {
798         [IEEE80211_MODE_AUTO]   = { 3, 4, 10,  0, 0 },
799         [IEEE80211_MODE_11A]    = { 3, 4, 10,  0, 0 },
800         [IEEE80211_MODE_11B]    = { 3, 4, 10,  0, 0 },
801         [IEEE80211_MODE_11G]    = { 3, 4, 10,  0, 0 },
802         [IEEE80211_MODE_FH]     = { 3, 4, 10,  0, 0 },
803         [IEEE80211_MODE_TURBO_A]= { 2, 3, 10,  0, 0 },
804         [IEEE80211_MODE_TURBO_G]= { 2, 3, 10,  0, 0 },
805         [IEEE80211_MODE_STURBO_A]={ 2, 3, 10,  0, 0 },
806         [IEEE80211_MODE_HALF]   = { 3, 4, 10,  0, 0 },
807         [IEEE80211_MODE_QUARTER]= { 3, 4, 10,  0, 0 },
808         [IEEE80211_MODE_11NA]   = { 3, 4, 10,  0, 0 },
809         [IEEE80211_MODE_11NG]   = { 3, 4, 10,  0, 0 },
810 };
811 static const struct phyParamType bssPhyParamForAC_VI[IEEE80211_MODE_MAX] = {
812         [IEEE80211_MODE_AUTO]   = { 2, 3, 4,  94, 0 },
813         [IEEE80211_MODE_11A]    = { 2, 3, 4,  94, 0 },
814         [IEEE80211_MODE_11B]    = { 2, 3, 4, 188, 0 },
815         [IEEE80211_MODE_11G]    = { 2, 3, 4,  94, 0 },
816         [IEEE80211_MODE_FH]     = { 2, 3, 4, 188, 0 },
817         [IEEE80211_MODE_TURBO_A]= { 2, 2, 3,  94, 0 },
818         [IEEE80211_MODE_TURBO_G]= { 2, 2, 3,  94, 0 },
819         [IEEE80211_MODE_STURBO_A]={ 2, 2, 3,  94, 0 },
820         [IEEE80211_MODE_HALF]   = { 2, 3, 4,  94, 0 },
821         [IEEE80211_MODE_QUARTER]= { 2, 3, 4,  94, 0 },
822         [IEEE80211_MODE_11NA]   = { 2, 3, 4,  94, 0 },
823         [IEEE80211_MODE_11NG]   = { 2, 3, 4,  94, 0 },
824 };
825 static const struct phyParamType bssPhyParamForAC_VO[IEEE80211_MODE_MAX] = {
826         [IEEE80211_MODE_AUTO]   = { 2, 2, 3,  47, 0 },
827         [IEEE80211_MODE_11A]    = { 2, 2, 3,  47, 0 },
828         [IEEE80211_MODE_11B]    = { 2, 2, 3, 102, 0 },
829         [IEEE80211_MODE_11G]    = { 2, 2, 3,  47, 0 },
830         [IEEE80211_MODE_FH]     = { 2, 2, 3, 102, 0 },
831         [IEEE80211_MODE_TURBO_A]= { 1, 2, 2,  47, 0 },
832         [IEEE80211_MODE_TURBO_G]= { 1, 2, 2,  47, 0 },
833         [IEEE80211_MODE_STURBO_A]={ 1, 2, 2,  47, 0 },
834         [IEEE80211_MODE_HALF]   = { 2, 2, 3,  47, 0 },
835         [IEEE80211_MODE_QUARTER]= { 2, 2, 3,  47, 0 },
836         [IEEE80211_MODE_11NA]   = { 2, 2, 3,  47, 0 },
837         [IEEE80211_MODE_11NG]   = { 2, 2, 3,  47, 0 },
838 };
839
840 static void
841 _setifsparams(struct wmeParams *wmep, const paramType *phy)
842 {
843         wmep->wmep_aifsn = phy->aifsn;
844         wmep->wmep_logcwmin = phy->logcwmin;    
845         wmep->wmep_logcwmax = phy->logcwmax;            
846         wmep->wmep_txopLimit = phy->txopLimit;
847 }
848
849 static void
850 setwmeparams(struct ieee80211vap *vap, const char *type, int ac,
851         struct wmeParams *wmep, const paramType *phy)
852 {
853         wmep->wmep_acm = phy->acm;
854         _setifsparams(wmep, phy);
855
856         IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
857             "set %s (%s) [acm %u aifsn %u logcwmin %u logcwmax %u txop %u]\n",
858             ieee80211_wme_acnames[ac], type,
859             wmep->wmep_acm, wmep->wmep_aifsn, wmep->wmep_logcwmin,
860             wmep->wmep_logcwmax, wmep->wmep_txopLimit);
861 }
862
863 static void
864 ieee80211_wme_initparams_locked(struct ieee80211vap *vap)
865 {
866         struct ieee80211com *ic = vap->iv_ic;
867         struct ieee80211_wme_state *wme = &ic->ic_wme;
868         const paramType *pPhyParam, *pBssPhyParam;
869         struct wmeParams *wmep;
870         enum ieee80211_phymode mode;
871         int i;
872
873         if ((ic->ic_caps & IEEE80211_C_WME) == 0 || ic->ic_nrunning > 1)
874                 return;
875
876         /*
877          * Select mode; we can be called early in which case we
878          * always use auto mode.  We know we'll be called when
879          * entering the RUN state with bsschan setup properly
880          * so state will eventually get set correctly
881          */
882         if (ic->ic_bsschan != IEEE80211_CHAN_ANYC)
883                 mode = ieee80211_chan2mode(ic->ic_bsschan);
884         else
885                 mode = IEEE80211_MODE_AUTO;
886         for (i = 0; i < WME_NUM_AC; i++) {
887                 switch (i) {
888                 case WME_AC_BK:
889                         pPhyParam = &phyParamForAC_BK[mode];
890                         pBssPhyParam = &phyParamForAC_BK[mode];
891                         break;
892                 case WME_AC_VI:
893                         pPhyParam = &phyParamForAC_VI[mode];
894                         pBssPhyParam = &bssPhyParamForAC_VI[mode];
895                         break;
896                 case WME_AC_VO:
897                         pPhyParam = &phyParamForAC_VO[mode];
898                         pBssPhyParam = &bssPhyParamForAC_VO[mode];
899                         break;
900                 case WME_AC_BE:
901                 default:
902                         pPhyParam = &phyParamForAC_BE[mode];
903                         pBssPhyParam = &bssPhyParamForAC_BE[mode];
904                         break;
905                 }
906                 wmep = &wme->wme_wmeChanParams.cap_wmeParams[i];
907                 if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
908                         setwmeparams(vap, "chan", i, wmep, pPhyParam);
909                 } else {
910                         setwmeparams(vap, "chan", i, wmep, pBssPhyParam);
911                 }       
912                 wmep = &wme->wme_wmeBssChanParams.cap_wmeParams[i];
913                 setwmeparams(vap, "bss ", i, wmep, pBssPhyParam);
914         }
915         /* NB: check ic_bss to avoid NULL deref on initial attach */
916         if (vap->iv_bss != NULL) {
917                 /*
918                  * Calculate agressive mode switching threshold based
919                  * on beacon interval.  This doesn't need locking since
920                  * we're only called before entering the RUN state at
921                  * which point we start sending beacon frames.
922                  */
923                 wme->wme_hipri_switch_thresh =
924                         (HIGH_PRI_SWITCH_THRESH * vap->iv_bss->ni_intval) / 100;
925                 wme->wme_flags &= ~WME_F_AGGRMODE;
926                 ieee80211_wme_updateparams(vap);
927         }
928 }
929
930 void
931 ieee80211_wme_initparams(struct ieee80211vap *vap)
932 {
933         struct ieee80211com *ic = vap->iv_ic;
934
935         ic = vap->iv_ic;
936         ieee80211_wme_initparams_locked(vap);
937 }
938
939 /*
940  * Update WME parameters for ourself and the BSS.
941  */
942 void
943 ieee80211_wme_updateparams_locked(struct ieee80211vap *vap)
944 {
945         static const paramType aggrParam[IEEE80211_MODE_MAX] = {
946             [IEEE80211_MODE_AUTO]       = { 2, 4, 10, 64, 0 },
947             [IEEE80211_MODE_11A]        = { 2, 4, 10, 64, 0 },
948             [IEEE80211_MODE_11B]        = { 2, 5, 10, 64, 0 },
949             [IEEE80211_MODE_11G]        = { 2, 4, 10, 64, 0 },
950             [IEEE80211_MODE_FH]         = { 2, 5, 10, 64, 0 },
951             [IEEE80211_MODE_TURBO_A]    = { 1, 3, 10, 64, 0 },
952             [IEEE80211_MODE_TURBO_G]    = { 1, 3, 10, 64, 0 },
953             [IEEE80211_MODE_STURBO_A]   = { 1, 3, 10, 64, 0 },
954             [IEEE80211_MODE_HALF]       = { 2, 4, 10, 64, 0 },
955             [IEEE80211_MODE_QUARTER]    = { 2, 4, 10, 64, 0 },
956             [IEEE80211_MODE_11NA]       = { 2, 4, 10, 64, 0 },  /* XXXcheck*/
957             [IEEE80211_MODE_11NG]       = { 2, 4, 10, 64, 0 },  /* XXXcheck*/
958         };
959         struct ieee80211com *ic = vap->iv_ic;
960         struct ieee80211_wme_state *wme = &ic->ic_wme;
961         const struct wmeParams *wmep;
962         struct wmeParams *chanp, *bssp;
963         enum ieee80211_phymode mode;
964         int i;
965
966         /*
967          * Set up the channel access parameters for the physical
968          * device.  First populate the configured settings.
969          */
970         for (i = 0; i < WME_NUM_AC; i++) {
971                 chanp = &wme->wme_chanParams.cap_wmeParams[i];
972                 wmep = &wme->wme_wmeChanParams.cap_wmeParams[i];
973                 chanp->wmep_aifsn = wmep->wmep_aifsn;
974                 chanp->wmep_logcwmin = wmep->wmep_logcwmin;
975                 chanp->wmep_logcwmax = wmep->wmep_logcwmax;
976                 chanp->wmep_txopLimit = wmep->wmep_txopLimit;
977
978                 chanp = &wme->wme_bssChanParams.cap_wmeParams[i];
979                 wmep = &wme->wme_wmeBssChanParams.cap_wmeParams[i];
980                 chanp->wmep_aifsn = wmep->wmep_aifsn;
981                 chanp->wmep_logcwmin = wmep->wmep_logcwmin;
982                 chanp->wmep_logcwmax = wmep->wmep_logcwmax;
983                 chanp->wmep_txopLimit = wmep->wmep_txopLimit;
984         }
985
986         /*
987          * Select mode; we can be called early in which case we
988          * always use auto mode.  We know we'll be called when
989          * entering the RUN state with bsschan setup properly
990          * so state will eventually get set correctly
991          */
992         if (ic->ic_bsschan != IEEE80211_CHAN_ANYC)
993                 mode = ieee80211_chan2mode(ic->ic_bsschan);
994         else
995                 mode = IEEE80211_MODE_AUTO;
996
997         /*
998          * This implements agressive mode as found in certain
999          * vendors' AP's.  When there is significant high
1000          * priority (VI/VO) traffic in the BSS throttle back BE
1001          * traffic by using conservative parameters.  Otherwise
1002          * BE uses agressive params to optimize performance of
1003          * legacy/non-QoS traffic.
1004          */
1005         if ((vap->iv_opmode == IEEE80211_M_HOSTAP &&
1006              (wme->wme_flags & WME_F_AGGRMODE) != 0) ||
1007             (vap->iv_opmode == IEEE80211_M_STA &&
1008              (vap->iv_bss->ni_flags & IEEE80211_NODE_QOS) == 0) ||
1009             (vap->iv_flags & IEEE80211_F_WME) == 0) {
1010                 chanp = &wme->wme_chanParams.cap_wmeParams[WME_AC_BE];
1011                 bssp = &wme->wme_bssChanParams.cap_wmeParams[WME_AC_BE];
1012
1013                 chanp->wmep_aifsn = bssp->wmep_aifsn = aggrParam[mode].aifsn;
1014                 chanp->wmep_logcwmin = bssp->wmep_logcwmin =
1015                     aggrParam[mode].logcwmin;
1016                 chanp->wmep_logcwmax = bssp->wmep_logcwmax =
1017                     aggrParam[mode].logcwmax;
1018                 chanp->wmep_txopLimit = bssp->wmep_txopLimit =
1019                     (vap->iv_flags & IEEE80211_F_BURST) ?
1020                         aggrParam[mode].txopLimit : 0;          
1021                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
1022                     "update %s (chan+bss) [acm %u aifsn %u logcwmin %u "
1023                     "logcwmax %u txop %u]\n", ieee80211_wme_acnames[WME_AC_BE],
1024                     chanp->wmep_acm, chanp->wmep_aifsn, chanp->wmep_logcwmin,
1025                     chanp->wmep_logcwmax, chanp->wmep_txopLimit);
1026         }
1027         
1028         if (vap->iv_opmode == IEEE80211_M_HOSTAP &&
1029             ic->ic_sta_assoc < 2 && (wme->wme_flags & WME_F_AGGRMODE) != 0) {
1030                 static const uint8_t logCwMin[IEEE80211_MODE_MAX] = {
1031                     [IEEE80211_MODE_AUTO]       = 3,
1032                     [IEEE80211_MODE_11A]        = 3,
1033                     [IEEE80211_MODE_11B]        = 4,
1034                     [IEEE80211_MODE_11G]        = 3,
1035                     [IEEE80211_MODE_FH]         = 4,
1036                     [IEEE80211_MODE_TURBO_A]    = 3,
1037                     [IEEE80211_MODE_TURBO_G]    = 3,
1038                     [IEEE80211_MODE_STURBO_A]   = 3,
1039                     [IEEE80211_MODE_HALF]       = 3,
1040                     [IEEE80211_MODE_QUARTER]    = 3,
1041                     [IEEE80211_MODE_11NA]       = 3,
1042                     [IEEE80211_MODE_11NG]       = 3,
1043                 };
1044                 chanp = &wme->wme_chanParams.cap_wmeParams[WME_AC_BE];
1045                 bssp = &wme->wme_bssChanParams.cap_wmeParams[WME_AC_BE];
1046
1047                 chanp->wmep_logcwmin = bssp->wmep_logcwmin = logCwMin[mode];
1048                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
1049                     "update %s (chan+bss) logcwmin %u\n",
1050                     ieee80211_wme_acnames[WME_AC_BE], chanp->wmep_logcwmin);
1051         }       
1052         if (vap->iv_opmode == IEEE80211_M_HOSTAP) {     /* XXX ibss? */
1053                 /*
1054                  * Arrange for a beacon update and bump the parameter
1055                  * set number so associated stations load the new values.
1056                  */
1057                 wme->wme_bssChanParams.cap_info =
1058                         (wme->wme_bssChanParams.cap_info+1) & WME_QOSINFO_COUNT;
1059                 ieee80211_beacon_notify(vap, IEEE80211_BEACON_WME);
1060         }
1061
1062         wme->wme_update(ic);
1063
1064         IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
1065             "%s: WME params updated, cap_info 0x%x\n", __func__,
1066             vap->iv_opmode == IEEE80211_M_STA ?
1067                 wme->wme_wmeChanParams.cap_info :
1068                 wme->wme_bssChanParams.cap_info);
1069 }
1070
1071 void
1072 ieee80211_wme_updateparams(struct ieee80211vap *vap)
1073 {
1074         struct ieee80211com *ic = vap->iv_ic;
1075
1076         if (ic->ic_caps & IEEE80211_C_WME) {
1077                 ieee80211_wme_updateparams_locked(vap);
1078         }
1079 }
1080
1081 static void
1082 parent_updown_task(void *arg, int npending)
1083 {
1084         struct ifnet *parent = arg;
1085
1086         wlan_serialize_enter();
1087         parent->if_ioctl(parent, SIOCSIFFLAGS, NULL, curthread->td_ucred);
1088         wlan_serialize_exit();
1089 }
1090
1091 static void
1092 update_mcast_task(void *arg, int npending)
1093 {
1094         struct ieee80211com *ic = arg;
1095         struct ifnet *parent = ic->ic_ifp;
1096
1097         wlan_serialize_enter();
1098         ic->ic_update_mcast(parent);
1099         wlan_serialize_exit();
1100 }
1101
1102 static void
1103 update_promisc_task(void *arg, int npending)
1104 {
1105         struct ieee80211com *ic = arg;
1106         struct ifnet *parent = ic->ic_ifp;
1107
1108         wlan_serialize_enter();
1109         ic->ic_update_promisc(parent);
1110         wlan_serialize_exit();
1111 }
1112
1113 static void
1114 update_channel_task(void *arg, int npending)
1115 {
1116         struct ieee80211com *ic = arg;
1117
1118         wlan_serialize_enter();
1119         ic->ic_set_channel(ic);
1120         ieee80211_radiotap_chan_change(ic);
1121         wlan_serialize_exit();
1122 }
1123
1124 /*
1125  * Block until the parent is in a known state.  This is
1126  * used after any operations that dispatch a task (e.g.
1127  * to auto-configure the parent device up/down).
1128  */
1129 void
1130 ieee80211_waitfor_parent(struct ieee80211com *ic)
1131 {
1132         wlan_assert_serialized();
1133         wlan_serialize_exit();  /* exit to block */
1134         taskqueue_block(ic->ic_tq);
1135         ieee80211_draintask(ic, &ic->ic_parent_task);
1136         ieee80211_draintask(ic, &ic->ic_mcast_task);
1137         ieee80211_draintask(ic, &ic->ic_promisc_task);
1138         ieee80211_draintask(ic, &ic->ic_chan_task);
1139         ieee80211_draintask(ic, &ic->ic_bmiss_task);
1140         taskqueue_unblock(ic->ic_tq);
1141         wlan_serialize_enter(); /* then re-enter */
1142 }
1143
1144 /*
1145  * Start a vap running.  If this is the first vap to be
1146  * set running on the underlying device then we
1147  * automatically bring the device up.
1148  */
1149 void
1150 ieee80211_start_locked(struct ieee80211vap *vap)
1151 {
1152         struct ifnet *ifp = vap->iv_ifp;
1153         struct ieee80211com *ic = vap->iv_ic;
1154         struct ifnet *parent = ic->ic_ifp;
1155
1156         IEEE80211_DPRINTF(vap,
1157                 IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1158                 "start running, %d vaps running\n", ic->ic_nrunning);
1159
1160         if ((ifp->if_flags & IFF_RUNNING) == 0) {
1161                 /*
1162                  * Mark us running.  Note that it's ok to do this first;
1163                  * if we need to bring the parent device up we defer that
1164                  * to avoid dropping the com lock.  We expect the device
1165                  * to respond to being marked up by calling back into us
1166                  * through ieee80211_start_all at which point we'll come
1167                  * back in here and complete the work.
1168                  */
1169                 ifp->if_flags |= IFF_RUNNING;
1170                 /*
1171                  * We are not running; if this we are the first vap
1172                  * to be brought up auto-up the parent if necessary.
1173                  */
1174                 if (ic->ic_nrunning++ == 0 &&
1175                     (parent->if_flags & IFF_RUNNING) == 0) {
1176                         IEEE80211_DPRINTF(vap,
1177                             IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1178                             "%s: up parent %s\n", __func__, parent->if_xname);
1179                         parent->if_flags |= IFF_UP;
1180                         ieee80211_runtask(ic, &ic->ic_parent_task);
1181                         return;
1182                 }
1183         }
1184         /*
1185          * If the parent is up and running, then kick the
1186          * 802.11 state machine as appropriate.
1187          */
1188         if ((parent->if_flags & IFF_RUNNING) &&
1189             vap->iv_roaming != IEEE80211_ROAMING_MANUAL) {
1190                 if (vap->iv_opmode == IEEE80211_M_STA) {
1191 #if 0
1192                         /* XXX bypasses scan too easily; disable for now */
1193                         /*
1194                          * Try to be intelligent about clocking the state
1195                          * machine.  If we're currently in RUN state then
1196                          * we should be able to apply any new state/parameters
1197                          * simply by re-associating.  Otherwise we need to
1198                          * re-scan to select an appropriate ap.
1199                          */ 
1200                         if (vap->iv_state >= IEEE80211_S_RUN)
1201                                 ieee80211_new_state_locked(vap,
1202                                     IEEE80211_S_ASSOC, 1);
1203                         else
1204 #endif
1205                                 ieee80211_new_state_locked(vap,
1206                                     IEEE80211_S_SCAN, 0);
1207                 } else {
1208                         /*
1209                          * For monitor+wds mode there's nothing to do but
1210                          * start running.  Otherwise if this is the first
1211                          * vap to be brought up, start a scan which may be
1212                          * preempted if the station is locked to a particular
1213                          * channel.
1214                          */
1215                         vap->iv_flags_ext |= IEEE80211_FEXT_REINIT;
1216                         if (vap->iv_opmode == IEEE80211_M_MONITOR ||
1217                             vap->iv_opmode == IEEE80211_M_WDS)
1218                                 ieee80211_new_state_locked(vap,
1219                                     IEEE80211_S_RUN, -1);
1220                         else
1221                                 ieee80211_new_state_locked(vap,
1222                                     IEEE80211_S_SCAN, 0);
1223                 }
1224         }
1225 }
1226
1227 /*
1228  * Start a single vap.
1229  */
1230 void
1231 ieee80211_init(void *arg)
1232 {
1233         struct ieee80211vap *vap = arg;
1234
1235         IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1236             "%s\n", __func__);
1237
1238         ieee80211_start_locked(vap);
1239 }
1240
1241 /*
1242  * Start all runnable vap's on a device.
1243  */
1244 void
1245 ieee80211_start_all(struct ieee80211com *ic)
1246 {
1247         struct ieee80211vap *vap;
1248
1249         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1250                 struct ifnet *ifp = vap->iv_ifp;
1251                 if (IFNET_IS_UP_RUNNING(ifp))   /* NB: avoid recursion */
1252                         ieee80211_start_locked(vap);
1253         }
1254 }
1255
1256 /*
1257  * Stop a vap.  We force it down using the state machine
1258  * then mark it's ifnet not running.  If this is the last
1259  * vap running on the underlying device then we close it
1260  * too to insure it will be properly initialized when the
1261  * next vap is brought up.
1262  */
1263 void
1264 ieee80211_stop_locked(struct ieee80211vap *vap)
1265 {
1266         struct ieee80211com *ic = vap->iv_ic;
1267         struct ifnet *ifp = vap->iv_ifp;
1268         struct ifnet *parent = ic->ic_ifp;
1269
1270         IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1271             "stop running, %d vaps running\n", ic->ic_nrunning);
1272
1273         ieee80211_new_state_locked(vap, IEEE80211_S_INIT, -1);
1274         if (ifp->if_flags & IFF_RUNNING) {
1275                 ifp->if_flags &= ~IFF_RUNNING;  /* mark us stopped */
1276                 if (--ic->ic_nrunning == 0 &&
1277                     (parent->if_flags & IFF_RUNNING)) {
1278                         IEEE80211_DPRINTF(vap,
1279                             IEEE80211_MSG_STATE | IEEE80211_MSG_DEBUG,
1280                             "down parent %s\n", parent->if_xname);
1281                         parent->if_flags &= ~IFF_UP;
1282                         ieee80211_runtask(ic, &ic->ic_parent_task);
1283                 }
1284         }
1285 }
1286
1287 void
1288 ieee80211_stop(struct ieee80211vap *vap)
1289 {
1290         struct ieee80211com *ic = vap->iv_ic;
1291
1292         ic = vap->iv_ic;
1293         ieee80211_stop_locked(vap);
1294 }
1295
1296 /*
1297  * Stop all vap's running on a device.
1298  */
1299 void
1300 ieee80211_stop_all(struct ieee80211com *ic)
1301 {
1302         struct ieee80211vap *vap;
1303
1304         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1305                 struct ifnet *ifp = vap->iv_ifp;
1306                 if (IFNET_IS_UP_RUNNING(ifp))   /* NB: avoid recursion */
1307                         ieee80211_stop_locked(vap);
1308         }
1309
1310         ieee80211_waitfor_parent(ic);
1311 }
1312
1313 /*
1314  * Stop all vap's running on a device and arrange
1315  * for those that were running to be resumed.
1316  */
1317 void
1318 ieee80211_suspend_all(struct ieee80211com *ic)
1319 {
1320         struct ieee80211vap *vap;
1321
1322         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1323                 struct ifnet *ifp = vap->iv_ifp;
1324                 if (IFNET_IS_UP_RUNNING(ifp)) { /* NB: avoid recursion */
1325                         vap->iv_flags_ext |= IEEE80211_FEXT_RESUME;
1326                         ieee80211_stop_locked(vap);
1327                 }
1328         }
1329
1330         ieee80211_waitfor_parent(ic);
1331 }
1332
1333 /*
1334  * Start all vap's marked for resume.
1335  */
1336 void
1337 ieee80211_resume_all(struct ieee80211com *ic)
1338 {
1339         struct ieee80211vap *vap;
1340
1341         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1342                 struct ifnet *ifp = vap->iv_ifp;
1343                 if (!IFNET_IS_UP_RUNNING(ifp) &&
1344                     (vap->iv_flags_ext & IEEE80211_FEXT_RESUME)) {
1345                         vap->iv_flags_ext &= ~IEEE80211_FEXT_RESUME;
1346                         ieee80211_start_locked(vap);
1347                 }
1348         }
1349 }
1350
1351 void
1352 ieee80211_beacon_miss(struct ieee80211com *ic)
1353 {
1354         if ((ic->ic_flags & IEEE80211_F_SCAN) == 0) {
1355                 /* Process in a taskq, the handler may reenter the driver */
1356                 ieee80211_runtask(ic, &ic->ic_bmiss_task);
1357         }
1358 }
1359
1360 static void
1361 beacon_miss_task(void *arg, int npending)
1362 {
1363         struct ieee80211com *ic = arg;
1364         struct ieee80211vap *vap;
1365
1366         wlan_serialize_enter();
1367         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1368                 /*
1369                  * We only pass events through for sta vap's in RUN state;
1370                  * may be too restrictive but for now this saves all the
1371                  * handlers duplicating these checks.
1372                  */
1373                 if (vap->iv_opmode == IEEE80211_M_STA &&
1374                     vap->iv_state >= IEEE80211_S_RUN &&
1375                     vap->iv_bmiss != NULL)
1376                         vap->iv_bmiss(vap);
1377         }
1378         wlan_serialize_exit();
1379 }
1380
1381 static void
1382 beacon_swmiss_task(void *arg, int npending)
1383 {
1384         struct ieee80211vap *vap = arg;
1385
1386         wlan_serialize_enter();
1387         if (vap->iv_state == IEEE80211_S_RUN) {
1388                 /* XXX Call multiple times if npending > zero? */
1389                 vap->iv_bmiss(vap);
1390         }
1391         wlan_serialize_exit();
1392 }
1393
1394 /*
1395  * Software beacon miss handling.  Check if any beacons
1396  * were received in the last period.  If not post a
1397  * beacon miss; otherwise reset the counter.
1398  */
1399 void
1400 ieee80211_swbmiss_callout(void *arg)
1401 {
1402         struct ieee80211vap *vap = arg;
1403         struct ieee80211com *ic = vap->iv_ic;
1404
1405         wlan_serialize_enter();
1406         KASSERT(vap->iv_state == IEEE80211_S_RUN,
1407             ("wrong state %d", vap->iv_state));
1408
1409         if (ic->ic_flags & IEEE80211_F_SCAN) {
1410                 /*
1411                  * If scanning just ignore and reset state.  If we get a
1412                  * bmiss after coming out of scan because we haven't had
1413                  * time to receive a beacon then we should probe the AP
1414                  * before posting a real bmiss (unless iv_bmiss_max has
1415                  * been artifiically lowered).  A cleaner solution might
1416                  * be to disable the timer on scan start/end but to handle
1417                  * case of multiple sta vap's we'd need to disable the
1418                  * timers of all affected vap's.
1419                  */
1420                 vap->iv_swbmiss_count = 0;
1421         } else if (vap->iv_swbmiss_count == 0) {
1422                 if (vap->iv_bmiss != NULL)
1423                         ieee80211_runtask(ic, &vap->iv_swbmiss_task);
1424                 if (vap->iv_bmiss_count == 0)   /* don't re-arm timer */
1425                         goto done;
1426         } else {
1427                 vap->iv_swbmiss_count = 0;
1428         }
1429         callout_reset(&vap->iv_swbmiss, vap->iv_swbmiss_period,
1430                       ieee80211_swbmiss_callout, vap);
1431 done:
1432         wlan_serialize_exit();
1433 }
1434
1435 /*
1436  * Start an 802.11h channel switch.  We record the parameters,
1437  * mark the operation pending, notify each vap through the
1438  * beacon update mechanism so it can update the beacon frame
1439  * contents, and then switch vap's to CSA state to block outbound
1440  * traffic.  Devices that handle CSA directly can use the state
1441  * switch to do the right thing so long as they call
1442  * ieee80211_csa_completeswitch when it's time to complete the
1443  * channel change.  Devices that depend on the net80211 layer can
1444  * use ieee80211_beacon_update to handle the countdown and the
1445  * channel switch.
1446  */
1447 void
1448 ieee80211_csa_startswitch(struct ieee80211com *ic,
1449         struct ieee80211_channel *c, int mode, int count)
1450 {
1451         struct ieee80211vap *vap;
1452
1453         ic->ic_csa_newchan = c;
1454         ic->ic_csa_mode = mode;
1455         ic->ic_csa_count = count;
1456         ic->ic_flags |= IEEE80211_F_CSAPENDING;
1457         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1458                 if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
1459                     vap->iv_opmode == IEEE80211_M_IBSS ||
1460                     vap->iv_opmode == IEEE80211_M_MBSS)
1461                         ieee80211_beacon_notify(vap, IEEE80211_BEACON_CSA);
1462                 /* switch to CSA state to block outbound traffic */
1463                 if (vap->iv_state == IEEE80211_S_RUN)
1464                         ieee80211_new_state_locked(vap, IEEE80211_S_CSA, 0);
1465         }
1466         ieee80211_notify_csa(ic, c, mode, count);
1467 }
1468
1469 static void
1470 csa_completeswitch(struct ieee80211com *ic)
1471 {
1472         struct ieee80211vap *vap;
1473
1474         ic->ic_csa_newchan = NULL;
1475         ic->ic_flags &= ~IEEE80211_F_CSAPENDING;
1476
1477         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
1478                 if (vap->iv_state == IEEE80211_S_CSA)
1479                         ieee80211_new_state_locked(vap, IEEE80211_S_RUN, 0);
1480 }
1481
1482 /*
1483  * Complete an 802.11h channel switch started by ieee80211_csa_startswitch.
1484  * We clear state and move all vap's in CSA state to RUN state
1485  * so they can again transmit.
1486  */
1487 void
1488 ieee80211_csa_completeswitch(struct ieee80211com *ic)
1489 {
1490         KASSERT(ic->ic_flags & IEEE80211_F_CSAPENDING, ("csa not pending"));
1491
1492         ieee80211_setcurchan(ic, ic->ic_csa_newchan);
1493         csa_completeswitch(ic);
1494 }
1495
1496 /*
1497  * Cancel an 802.11h channel switch started by ieee80211_csa_startswitch.
1498  * We clear state and move all vap's in CSA state to RUN state
1499  * so they can again transmit.
1500  */
1501 void
1502 ieee80211_csa_cancelswitch(struct ieee80211com *ic)
1503 {
1504         csa_completeswitch(ic);
1505 }
1506
1507 /*
1508  * Complete a DFS CAC started by ieee80211_dfs_cac_start.
1509  * We clear state and move all vap's in CAC state to RUN state.
1510  */
1511 void
1512 ieee80211_cac_completeswitch(struct ieee80211vap *vap0)
1513 {
1514         struct ieee80211com *ic = vap0->iv_ic;
1515         struct ieee80211vap *vap;
1516
1517         /*
1518          * Complete CAC state change for lead vap first; then
1519          * clock all the other vap's waiting.
1520          */
1521         KASSERT(vap0->iv_state == IEEE80211_S_CAC,
1522             ("wrong state %d", vap0->iv_state));
1523         ieee80211_new_state_locked(vap0, IEEE80211_S_RUN, 0);
1524
1525         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
1526                 if (vap->iv_state == IEEE80211_S_CAC)
1527                         ieee80211_new_state_locked(vap, IEEE80211_S_RUN, 0);
1528 }
1529
1530 /*
1531  * Force all vap's other than the specified vap to the INIT state
1532  * and mark them as waiting for a scan to complete.  These vaps
1533  * will be brought up when the scan completes and the scanning vap
1534  * reaches RUN state by wakeupwaiting.
1535  */
1536 static void
1537 markwaiting(struct ieee80211vap *vap0)
1538 {
1539         struct ieee80211com *ic = vap0->iv_ic;
1540         struct ieee80211vap *vap;
1541
1542         /*
1543          * A vap list entry can not disappear since we are running on the
1544          * taskqueue and a vap destroy will queue and drain another state
1545          * change task.
1546          */
1547         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1548                 if (vap == vap0)
1549                         continue;
1550                 if (vap->iv_state != IEEE80211_S_INIT) {
1551                         /* NB: iv_newstate may drop the lock */
1552                         vap->iv_newstate(vap, IEEE80211_S_INIT, 0);
1553                         vap->iv_flags_ext |= IEEE80211_FEXT_SCANWAIT;
1554                 }
1555         }
1556 }
1557
1558 /*
1559  * Wakeup all vap's waiting for a scan to complete.  This is the
1560  * companion to markwaiting (above) and is used to coordinate
1561  * multiple vaps scanning.
1562  * This is called from the state taskqueue.
1563  */
1564 static void
1565 wakeupwaiting(struct ieee80211vap *vap0)
1566 {
1567         struct ieee80211com *ic = vap0->iv_ic;
1568         struct ieee80211vap *vap;
1569
1570         /*
1571          * A vap list entry can not disappear since we are running on the
1572          * taskqueue and a vap destroy will queue and drain another state
1573          * change task.
1574          */
1575         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
1576                 if (vap == vap0)
1577                         continue;
1578                 if (vap->iv_flags_ext & IEEE80211_FEXT_SCANWAIT) {
1579                         vap->iv_flags_ext &= ~IEEE80211_FEXT_SCANWAIT;
1580                         /* NB: sta's cannot go INIT->RUN */
1581                         /* NB: iv_newstate may drop the lock */
1582                         vap->iv_newstate(vap,
1583                             vap->iv_opmode == IEEE80211_M_STA ?
1584                                 IEEE80211_S_SCAN : IEEE80211_S_RUN, 0);
1585                 }
1586         }
1587 }
1588
1589 /*
1590  * Handle post state change work common to all operating modes.
1591  */
1592 static void
1593 ieee80211_newstate_task(void *xvap, int npending)
1594 {
1595         struct ieee80211vap *vap = xvap;
1596         struct ieee80211com *ic;
1597         enum ieee80211_state nstate, ostate;
1598         int arg, rc;
1599
1600         wlan_serialize_enter();
1601
1602         ic = vap->iv_ic;
1603         nstate = vap->iv_nstate;
1604         arg = vap->iv_nstate_arg;
1605
1606         if (vap->iv_flags_ext & IEEE80211_FEXT_REINIT) {
1607                 /*
1608                  * We have been requested to drop back to the INIT before
1609                  * proceeding to the new state.
1610                  */
1611                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1612                     "%s: %s -> %s arg %d\n", __func__,
1613                     ieee80211_state_name[vap->iv_state],
1614                     ieee80211_state_name[IEEE80211_S_INIT], arg);
1615                 vap->iv_newstate(vap, IEEE80211_S_INIT, arg);
1616                 vap->iv_flags_ext &= ~IEEE80211_FEXT_REINIT;
1617         }
1618
1619         ostate = vap->iv_state;
1620         if (nstate == IEEE80211_S_SCAN && ostate != IEEE80211_S_INIT) {
1621                 /*
1622                  * SCAN was forced; e.g. on beacon miss.  Force other running
1623                  * vap's to INIT state and mark them as waiting for the scan to
1624                  * complete.  This insures they don't interfere with our
1625                  * scanning.  Since we are single threaded the vaps can not
1626                  * transition again while we are executing.
1627                  *
1628                  * XXX not always right, assumes ap follows sta
1629                  */
1630                 markwaiting(vap);
1631         }
1632         IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1633             "%s: %s -> %s arg %d\n", __func__,
1634             ieee80211_state_name[ostate], ieee80211_state_name[nstate], arg);
1635
1636         rc = vap->iv_newstate(vap, nstate, arg);
1637         vap->iv_flags_ext &= ~IEEE80211_FEXT_STATEWAIT;
1638         if (rc != 0) {
1639                 /* State transition failed */
1640                 KASSERT(rc != EINPROGRESS, ("iv_newstate was deferred"));
1641                 KASSERT(nstate != IEEE80211_S_INIT,
1642                     ("INIT state change failed"));
1643                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1644                     "%s: %s returned error %d\n", __func__,
1645                     ieee80211_state_name[nstate], rc);
1646                 goto done;
1647         }
1648
1649         /* No actual transition, skip post processing */
1650         if (ostate == nstate)
1651                 goto done;
1652
1653         if (nstate == IEEE80211_S_RUN) {
1654                 /*
1655                  * OACTIVE may be set on the vap if the upper layer
1656                  * tried to transmit (e.g. IPv6 NDP) before we reach
1657                  * RUN state.  Clear it and restart xmit.
1658                  *
1659                  * Note this can also happen as a result of SLEEP->RUN
1660                  * (i.e. coming out of power save mode).
1661                  */
1662                 vap->iv_ifp->if_flags &= ~IFF_OACTIVE;
1663                 vap->iv_ifp->if_start(vap->iv_ifp);
1664
1665                 /* bring up any vaps waiting on us */
1666                 wakeupwaiting(vap);
1667         } else if (nstate == IEEE80211_S_INIT) {
1668                 /*
1669                  * Flush the scan cache if we did the last scan (XXX?)
1670                  * and flush any frames on send queues from this vap.
1671                  * Note the mgt q is used only for legacy drivers and
1672                  * will go away shortly.
1673                  */
1674                 ieee80211_scan_flush(vap);
1675
1676                 /* XXX NB: cast for altq */
1677                 ieee80211_flush_ifq((struct ifqueue *)&ic->ic_ifp->if_snd, vap);
1678         }
1679 done:
1680         wlan_serialize_exit();
1681 }
1682
1683 /*
1684  * Public interface for initiating a state machine change.
1685  * This routine single-threads the request and coordinates
1686  * the scheduling of multiple vaps for the purpose of selecting
1687  * an operating channel.  Specifically the following scenarios
1688  * are handled:
1689  * o only one vap can be selecting a channel so on transition to
1690  *   SCAN state if another vap is already scanning then
1691  *   mark the caller for later processing and return without
1692  *   doing anything (XXX? expectations by caller of synchronous operation)
1693  * o only one vap can be doing CAC of a channel so on transition to
1694  *   CAC state if another vap is already scanning for radar then
1695  *   mark the caller for later processing and return without
1696  *   doing anything (XXX? expectations by caller of synchronous operation)
1697  * o if another vap is already running when a request is made
1698  *   to SCAN then an operating channel has been chosen; bypass
1699  *   the scan and just join the channel
1700  *
1701  * Note that the state change call is done through the iv_newstate
1702  * method pointer so any driver routine gets invoked.  The driver
1703  * will normally call back into operating mode-specific
1704  * ieee80211_newstate routines (below) unless it needs to completely
1705  * bypass the state machine (e.g. because the firmware has it's
1706  * own idea how things should work).  Bypassing the net80211 layer
1707  * is usually a mistake and indicates lack of proper integration
1708  * with the net80211 layer.
1709  */
1710 static int
1711 ieee80211_new_state_locked(struct ieee80211vap *vap,
1712         enum ieee80211_state nstate, int arg)
1713 {
1714         struct ieee80211com *ic = vap->iv_ic;
1715         struct ieee80211vap *vp;
1716         enum ieee80211_state ostate;
1717         int nrunning, nscanning;
1718
1719         if (vap->iv_flags_ext & IEEE80211_FEXT_STATEWAIT) {
1720                 if (vap->iv_nstate == IEEE80211_S_INIT) {
1721                         /*
1722                          * XXX The vap is being stopped, do no allow any other
1723                          * state changes until this is completed.
1724                          */
1725                         return -1;
1726                 } else if (vap->iv_state != vap->iv_nstate) {
1727 #if 0
1728                         /* Warn if the previous state hasn't completed. */
1729                         IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1730                             "%s: pending %s -> %s transition lost\n", __func__,
1731                             ieee80211_state_name[vap->iv_state],
1732                             ieee80211_state_name[vap->iv_nstate]);
1733 #else
1734                         /* XXX temporarily enable to identify issues */
1735                         if_printf(vap->iv_ifp,
1736                             "%s: pending %s -> %s transition lost\n",
1737                             __func__, ieee80211_state_name[vap->iv_state],
1738                             ieee80211_state_name[vap->iv_nstate]);
1739 #endif
1740                 }
1741         }
1742
1743         nrunning = nscanning = 0;
1744         /* XXX can track this state instead of calculating */
1745         TAILQ_FOREACH(vp, &ic->ic_vaps, iv_next) {
1746                 if (vp != vap) {
1747                         if (vp->iv_state >= IEEE80211_S_RUN)
1748                                 nrunning++;
1749                         /* XXX doesn't handle bg scan */
1750                         /* NB: CAC+AUTH+ASSOC treated like SCAN */
1751                         else if (vp->iv_state > IEEE80211_S_INIT)
1752                                 nscanning++;
1753                 }
1754         }
1755         ostate = vap->iv_state;
1756         IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1757             "%s: %s -> %s (nrunning %d nscanning %d)\n", __func__,
1758             ieee80211_state_name[ostate], ieee80211_state_name[nstate],
1759             nrunning, nscanning);
1760         switch (nstate) {
1761         case IEEE80211_S_SCAN:
1762                 if (ostate == IEEE80211_S_INIT) {
1763                         /*
1764                          * INIT -> SCAN happens on initial bringup.
1765                          */
1766                         KASSERT(!(nscanning && nrunning),
1767                             ("%d scanning and %d running", nscanning, nrunning));
1768                         if (nscanning) {
1769                                 /*
1770                                  * Someone is scanning, defer our state
1771                                  * change until the work has completed.
1772                                  */
1773                                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1774                                     "%s: defer %s -> %s\n",
1775                                     __func__, ieee80211_state_name[ostate],
1776                                     ieee80211_state_name[nstate]);
1777                                 vap->iv_flags_ext |= IEEE80211_FEXT_SCANWAIT;
1778                                 return 0;
1779                         }
1780                         if (nrunning) {
1781                                 /*
1782                                  * Someone is operating; just join the channel
1783                                  * they have chosen.
1784                                  */
1785                                 /* XXX kill arg? */
1786                                 /* XXX check each opmode, adhoc? */
1787                                 if (vap->iv_opmode == IEEE80211_M_STA)
1788                                         nstate = IEEE80211_S_SCAN;
1789                                 else
1790                                         nstate = IEEE80211_S_RUN;
1791 #ifdef IEEE80211_DEBUG
1792                                 if (nstate != IEEE80211_S_SCAN) {
1793                                         IEEE80211_DPRINTF(vap,
1794                                             IEEE80211_MSG_STATE,
1795                                             "%s: override, now %s -> %s\n",
1796                                             __func__,
1797                                             ieee80211_state_name[ostate],
1798                                             ieee80211_state_name[nstate]);
1799                                 }
1800 #endif
1801                         }
1802                 }
1803                 break;
1804         case IEEE80211_S_RUN:
1805                 if (vap->iv_opmode == IEEE80211_M_WDS &&
1806                     (vap->iv_flags_ext & IEEE80211_FEXT_WDSLEGACY) &&
1807                     nscanning) {
1808                         /*
1809                          * Legacy WDS with someone else scanning; don't
1810                          * go online until that completes as we should
1811                          * follow the other vap to the channel they choose.
1812                          */
1813                         IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1814                              "%s: defer %s -> %s (legacy WDS)\n", __func__,
1815                              ieee80211_state_name[ostate],
1816                              ieee80211_state_name[nstate]);
1817                         vap->iv_flags_ext |= IEEE80211_FEXT_SCANWAIT;
1818                         return 0;
1819                 }
1820                 if (vap->iv_opmode == IEEE80211_M_HOSTAP &&
1821                     IEEE80211_IS_CHAN_DFS(ic->ic_bsschan) &&
1822                     (vap->iv_flags_ext & IEEE80211_FEXT_DFS) &&
1823                     !IEEE80211_IS_CHAN_CACDONE(ic->ic_bsschan)) {
1824                         /*
1825                          * This is a DFS channel, transition to CAC state
1826                          * instead of RUN.  This allows us to initiate
1827                          * Channel Availability Check (CAC) as specified
1828                          * by 11h/DFS.
1829                          */
1830                         nstate = IEEE80211_S_CAC;
1831                         IEEE80211_DPRINTF(vap, IEEE80211_MSG_STATE,
1832                              "%s: override %s -> %s (DFS)\n", __func__,
1833                              ieee80211_state_name[ostate],
1834                              ieee80211_state_name[nstate]);
1835                 }
1836                 break;
1837         case IEEE80211_S_INIT:
1838                 /* cancel any scan in progress */
1839                 ieee80211_cancel_scan(vap);
1840                 if (ostate == IEEE80211_S_INIT ) {
1841                         /* XXX don't believe this */
1842                         /* INIT -> INIT. nothing to do */
1843                         vap->iv_flags_ext &= ~IEEE80211_FEXT_SCANWAIT;
1844                 }
1845                 /* fall thru... */
1846         default:
1847                 break;
1848         }
1849         /* defer the state change to a thread */
1850         vap->iv_nstate = nstate;
1851         vap->iv_nstate_arg = arg;
1852         vap->iv_flags_ext |= IEEE80211_FEXT_STATEWAIT;
1853         ieee80211_runtask(ic, &vap->iv_nstate_task);
1854         return EINPROGRESS;
1855 }
1856
1857 int
1858 ieee80211_new_state(struct ieee80211vap *vap,
1859         enum ieee80211_state nstate, int arg)
1860 {
1861         struct ieee80211com *ic = vap->iv_ic;
1862         int rc;
1863
1864         ic = vap->iv_ic;
1865         rc = ieee80211_new_state_locked(vap, nstate, arg);
1866         return rc;
1867 }