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