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