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