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