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