xref: /freebsd/sys/net80211/ieee80211_output.c (revision e17f5b1d)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2001 Atsushi Onoe
5  * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include "opt_inet.h"
33 #include "opt_inet6.h"
34 #include "opt_wlan.h"
35 
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/kernel.h>
39 #include <sys/malloc.h>
40 #include <sys/mbuf.h>
41 #include <sys/endian.h>
42 
43 #include <sys/socket.h>
44 
45 #include <net/bpf.h>
46 #include <net/ethernet.h>
47 #include <net/if.h>
48 #include <net/if_var.h>
49 #include <net/if_llc.h>
50 #include <net/if_media.h>
51 #include <net/if_vlan_var.h>
52 
53 #include <net80211/ieee80211_var.h>
54 #include <net80211/ieee80211_regdomain.h>
55 #ifdef IEEE80211_SUPPORT_SUPERG
56 #include <net80211/ieee80211_superg.h>
57 #endif
58 #ifdef IEEE80211_SUPPORT_TDMA
59 #include <net80211/ieee80211_tdma.h>
60 #endif
61 #include <net80211/ieee80211_wds.h>
62 #include <net80211/ieee80211_mesh.h>
63 #include <net80211/ieee80211_vht.h>
64 
65 #if defined(INET) || defined(INET6)
66 #include <netinet/in.h>
67 #endif
68 
69 #ifdef INET
70 #include <netinet/if_ether.h>
71 #include <netinet/in_systm.h>
72 #include <netinet/ip.h>
73 #endif
74 #ifdef INET6
75 #include <netinet/ip6.h>
76 #endif
77 
78 #include <security/mac/mac_framework.h>
79 
80 #define	ETHER_HEADER_COPY(dst, src) \
81 	memcpy(dst, src, sizeof(struct ether_header))
82 
83 static int ieee80211_fragment(struct ieee80211vap *, struct mbuf *,
84 	u_int hdrsize, u_int ciphdrsize, u_int mtu);
85 static	void ieee80211_tx_mgt_cb(struct ieee80211_node *, void *, int);
86 
87 #ifdef IEEE80211_DEBUG
88 /*
89  * Decide if an outbound management frame should be
90  * printed when debugging is enabled.  This filters some
91  * of the less interesting frames that come frequently
92  * (e.g. beacons).
93  */
94 static __inline int
95 doprint(struct ieee80211vap *vap, int subtype)
96 {
97 	switch (subtype) {
98 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
99 		return (vap->iv_opmode == IEEE80211_M_IBSS);
100 	}
101 	return 1;
102 }
103 #endif
104 
105 /*
106  * Transmit a frame to the given destination on the given VAP.
107  *
108  * It's up to the caller to figure out the details of who this
109  * is going to and resolving the node.
110  *
111  * This routine takes care of queuing it for power save,
112  * A-MPDU state stuff, fast-frames state stuff, encapsulation
113  * if required, then passing it up to the driver layer.
114  *
115  * This routine (for now) consumes the mbuf and frees the node
116  * reference; it ideally will return a TX status which reflects
117  * whether the mbuf was consumed or not, so the caller can
118  * free the mbuf (if appropriate) and the node reference (again,
119  * if appropriate.)
120  */
121 int
122 ieee80211_vap_pkt_send_dest(struct ieee80211vap *vap, struct mbuf *m,
123     struct ieee80211_node *ni)
124 {
125 	struct ieee80211com *ic = vap->iv_ic;
126 	struct ifnet *ifp = vap->iv_ifp;
127 	int mcast;
128 	int do_ampdu = 0;
129 	int do_amsdu = 0;
130 	int do_ampdu_amsdu = 0;
131 	int no_ampdu = 1; /* Will be set to 0 if ampdu is active */
132 	int do_ff = 0;
133 
134 	if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
135 	    (m->m_flags & M_PWR_SAV) == 0) {
136 		/*
137 		 * Station in power save mode; pass the frame
138 		 * to the 802.11 layer and continue.  We'll get
139 		 * the frame back when the time is right.
140 		 * XXX lose WDS vap linkage?
141 		 */
142 		if (ieee80211_pwrsave(ni, m) != 0)
143 			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
144 		ieee80211_free_node(ni);
145 
146 		/*
147 		 * We queued it fine, so tell the upper layer
148 		 * that we consumed it.
149 		 */
150 		return (0);
151 	}
152 	/* calculate priority so drivers can find the tx queue */
153 	if (ieee80211_classify(ni, m)) {
154 		IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_OUTPUT,
155 		    ni->ni_macaddr, NULL,
156 		    "%s", "classification failure");
157 		vap->iv_stats.is_tx_classify++;
158 		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
159 		m_freem(m);
160 		ieee80211_free_node(ni);
161 
162 		/* XXX better status? */
163 		return (0);
164 	}
165 	/*
166 	 * Stash the node pointer.  Note that we do this after
167 	 * any call to ieee80211_dwds_mcast because that code
168 	 * uses any existing value for rcvif to identify the
169 	 * interface it (might have been) received on.
170 	 */
171 	MPASS((m->m_pkthdr.csum_flags & CSUM_SND_TAG) == 0);
172 	m->m_pkthdr.rcvif = (void *)ni;
173 	mcast = (m->m_flags & (M_MCAST | M_BCAST)) ? 1: 0;
174 
175 	BPF_MTAP(ifp, m);		/* 802.3 tx */
176 
177 
178 	/*
179 	 * Figure out if we can do A-MPDU, A-MSDU or FF.
180 	 *
181 	 * A-MPDU depends upon vap/node config.
182 	 * A-MSDU depends upon vap/node config.
183 	 * FF depends upon vap config, IE and whether
184 	 *  it's 11abg (and not 11n/11ac/etc.)
185 	 *
186 	 * Note that these flags indiciate whether we can do
187 	 * it at all, rather than the situation (eg traffic type.)
188 	 */
189 	do_ampdu = ((ni->ni_flags & IEEE80211_NODE_AMPDU_TX) &&
190 	    (vap->iv_flags_ht & IEEE80211_FHT_AMPDU_TX));
191 	do_amsdu = ((ni->ni_flags & IEEE80211_NODE_AMSDU_TX) &&
192 	    (vap->iv_flags_ht & IEEE80211_FHT_AMSDU_TX));
193 	do_ff =
194 	    ((ni->ni_flags & IEEE80211_NODE_HT) == 0) &&
195 	    ((ni->ni_flags & IEEE80211_NODE_VHT) == 0) &&
196 	    (IEEE80211_ATH_CAP(vap, ni, IEEE80211_NODE_FF));
197 
198 	/*
199 	 * Check if A-MPDU tx aggregation is setup or if we
200 	 * should try to enable it.  The sta must be associated
201 	 * with HT and A-MPDU enabled for use.  When the policy
202 	 * routine decides we should enable A-MPDU we issue an
203 	 * ADDBA request and wait for a reply.  The frame being
204 	 * encapsulated will go out w/o using A-MPDU, or possibly
205 	 * it might be collected by the driver and held/retransmit.
206 	 * The default ic_ampdu_enable routine handles staggering
207 	 * ADDBA requests in case the receiver NAK's us or we are
208 	 * otherwise unable to establish a BA stream.
209 	 *
210 	 * Don't treat group-addressed frames as candidates for aggregation;
211 	 * net80211 doesn't support 802.11aa-2012 and so group addressed
212 	 * frames will always have sequence numbers allocated from the NON_QOS
213 	 * TID.
214 	 */
215 	if (do_ampdu) {
216 		if ((m->m_flags & M_EAPOL) == 0 && (! mcast)) {
217 			int tid = WME_AC_TO_TID(M_WME_GETAC(m));
218 			struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[tid];
219 
220 			ieee80211_txampdu_count_packet(tap);
221 			if (IEEE80211_AMPDU_RUNNING(tap)) {
222 				/*
223 				 * Operational, mark frame for aggregation.
224 				 *
225 				 * XXX do tx aggregation here
226 				 */
227 				m->m_flags |= M_AMPDU_MPDU;
228 			} else if (!IEEE80211_AMPDU_REQUESTED(tap) &&
229 			    ic->ic_ampdu_enable(ni, tap)) {
230 				/*
231 				 * Not negotiated yet, request service.
232 				 */
233 				ieee80211_ampdu_request(ni, tap);
234 				/* XXX hold frame for reply? */
235 			}
236 			/*
237 			 * Now update the no-ampdu flag.  A-MPDU may have been
238 			 * started or administratively disabled above; so now we
239 			 * know whether we're running yet or not.
240 			 *
241 			 * This will let us know whether we should be doing A-MSDU
242 			 * at this point.  We only do A-MSDU if we're either not
243 			 * doing A-MPDU, or A-MPDU is NACKed, or A-MPDU + A-MSDU
244 			 * is available.
245 			 *
246 			 * Whilst here, update the amsdu-ampdu flag.  The above may
247 			 * have also set or cleared the amsdu-in-ampdu txa_flags
248 			 * combination so we can correctly do A-MPDU + A-MSDU.
249 			 */
250 			no_ampdu = (! IEEE80211_AMPDU_RUNNING(tap)
251 			    || (IEEE80211_AMPDU_NACKED(tap)));
252 			do_ampdu_amsdu = IEEE80211_AMPDU_RUNNING_AMSDU(tap);
253 		}
254 	}
255 
256 #ifdef IEEE80211_SUPPORT_SUPERG
257 	/*
258 	 * Check for AMSDU/FF; queue for aggregation
259 	 *
260 	 * Note: we don't bother trying to do fast frames or
261 	 * A-MSDU encapsulation for 802.3 drivers.  Now, we
262 	 * likely could do it for FF (because it's a magic
263 	 * atheros tunnel LLC type) but I don't think we're going
264 	 * to really need to.  For A-MSDU we'd have to set the
265 	 * A-MSDU QoS bit in the wifi header, so we just plain
266 	 * can't do it.
267 	 */
268 	if (__predict_true((vap->iv_caps & IEEE80211_C_8023ENCAP) == 0)) {
269 		if ((! mcast) &&
270 		    (do_ampdu_amsdu || (no_ampdu && do_amsdu)) &&
271 		    ieee80211_amsdu_tx_ok(ni)) {
272 			m = ieee80211_amsdu_check(ni, m);
273 			if (m == NULL) {
274 				/* NB: any ni ref held on stageq */
275 				IEEE80211_DPRINTF(vap, IEEE80211_MSG_SUPERG,
276 				    "%s: amsdu_check queued frame\n",
277 				    __func__);
278 				return (0);
279 			}
280 		} else if ((! mcast) && do_ff) {
281 			m = ieee80211_ff_check(ni, m);
282 			if (m == NULL) {
283 				/* NB: any ni ref held on stageq */
284 				IEEE80211_DPRINTF(vap, IEEE80211_MSG_SUPERG,
285 				    "%s: ff_check queued frame\n",
286 				    __func__);
287 				return (0);
288 			}
289 		}
290 	}
291 #endif /* IEEE80211_SUPPORT_SUPERG */
292 
293 	/*
294 	 * Grab the TX lock - serialise the TX process from this
295 	 * point (where TX state is being checked/modified)
296 	 * through to driver queue.
297 	 */
298 	IEEE80211_TX_LOCK(ic);
299 
300 	/*
301 	 * XXX make the encap and transmit code a separate function
302 	 * so things like the FF (and later A-MSDU) path can just call
303 	 * it for flushed frames.
304 	 */
305 	if (__predict_true((vap->iv_caps & IEEE80211_C_8023ENCAP) == 0)) {
306 		/*
307 		 * Encapsulate the packet in prep for transmission.
308 		 */
309 		m = ieee80211_encap(vap, ni, m);
310 		if (m == NULL) {
311 			/* NB: stat+msg handled in ieee80211_encap */
312 			IEEE80211_TX_UNLOCK(ic);
313 			ieee80211_free_node(ni);
314 			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
315 			return (ENOBUFS);
316 		}
317 	}
318 	(void) ieee80211_parent_xmitpkt(ic, m);
319 
320 	/*
321 	 * Unlock at this point - no need to hold it across
322 	 * ieee80211_free_node() (ie, the comlock)
323 	 */
324 	IEEE80211_TX_UNLOCK(ic);
325 	ic->ic_lastdata = ticks;
326 
327 	return (0);
328 }
329 
330 
331 
332 /*
333  * Send the given mbuf through the given vap.
334  *
335  * This consumes the mbuf regardless of whether the transmit
336  * was successful or not.
337  *
338  * This does none of the initial checks that ieee80211_start()
339  * does (eg CAC timeout, interface wakeup) - the caller must
340  * do this first.
341  */
342 static int
343 ieee80211_start_pkt(struct ieee80211vap *vap, struct mbuf *m)
344 {
345 #define	IS_DWDS(vap) \
346 	(vap->iv_opmode == IEEE80211_M_WDS && \
347 	 (vap->iv_flags_ext & IEEE80211_FEXT_WDSLEGACY) == 0)
348 	struct ieee80211com *ic = vap->iv_ic;
349 	struct ifnet *ifp = vap->iv_ifp;
350 	struct ieee80211_node *ni;
351 	struct ether_header *eh;
352 
353 	/*
354 	 * Cancel any background scan.
355 	 */
356 	if (ic->ic_flags & IEEE80211_F_SCAN)
357 		ieee80211_cancel_anyscan(vap);
358 	/*
359 	 * Find the node for the destination so we can do
360 	 * things like power save and fast frames aggregation.
361 	 *
362 	 * NB: past this point various code assumes the first
363 	 *     mbuf has the 802.3 header present (and contiguous).
364 	 */
365 	ni = NULL;
366 	if (m->m_len < sizeof(struct ether_header) &&
367 	   (m = m_pullup(m, sizeof(struct ether_header))) == NULL) {
368 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT,
369 		    "discard frame, %s\n", "m_pullup failed");
370 		vap->iv_stats.is_tx_nobuf++;	/* XXX */
371 		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
372 		return (ENOBUFS);
373 	}
374 	eh = mtod(m, struct ether_header *);
375 	if (ETHER_IS_MULTICAST(eh->ether_dhost)) {
376 		if (IS_DWDS(vap)) {
377 			/*
378 			 * Only unicast frames from the above go out
379 			 * DWDS vaps; multicast frames are handled by
380 			 * dispatching the frame as it comes through
381 			 * the AP vap (see below).
382 			 */
383 			IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_WDS,
384 			    eh->ether_dhost, "mcast", "%s", "on DWDS");
385 			vap->iv_stats.is_dwds_mcast++;
386 			m_freem(m);
387 			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
388 			/* XXX better status? */
389 			return (ENOBUFS);
390 		}
391 		if (vap->iv_opmode == IEEE80211_M_HOSTAP) {
392 			/*
393 			 * Spam DWDS vap's w/ multicast traffic.
394 			 */
395 			/* XXX only if dwds in use? */
396 			ieee80211_dwds_mcast(vap, m);
397 		}
398 	}
399 #ifdef IEEE80211_SUPPORT_MESH
400 	if (vap->iv_opmode != IEEE80211_M_MBSS) {
401 #endif
402 		ni = ieee80211_find_txnode(vap, eh->ether_dhost);
403 		if (ni == NULL) {
404 			/* NB: ieee80211_find_txnode does stat+msg */
405 			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
406 			m_freem(m);
407 			/* XXX better status? */
408 			return (ENOBUFS);
409 		}
410 		if (ni->ni_associd == 0 &&
411 		    (ni->ni_flags & IEEE80211_NODE_ASSOCID)) {
412 			IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_OUTPUT,
413 			    eh->ether_dhost, NULL,
414 			    "sta not associated (type 0x%04x)",
415 			    htons(eh->ether_type));
416 			vap->iv_stats.is_tx_notassoc++;
417 			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
418 			m_freem(m);
419 			ieee80211_free_node(ni);
420 			/* XXX better status? */
421 			return (ENOBUFS);
422 		}
423 #ifdef IEEE80211_SUPPORT_MESH
424 	} else {
425 		if (!IEEE80211_ADDR_EQ(eh->ether_shost, vap->iv_myaddr)) {
426 			/*
427 			 * Proxy station only if configured.
428 			 */
429 			if (!ieee80211_mesh_isproxyena(vap)) {
430 				IEEE80211_DISCARD_MAC(vap,
431 				    IEEE80211_MSG_OUTPUT |
432 				    IEEE80211_MSG_MESH,
433 				    eh->ether_dhost, NULL,
434 				    "%s", "proxy not enabled");
435 				vap->iv_stats.is_mesh_notproxy++;
436 				if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
437 				m_freem(m);
438 				/* XXX better status? */
439 				return (ENOBUFS);
440 			}
441 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT,
442 			    "forward frame from DS SA(%6D), DA(%6D)\n",
443 			    eh->ether_shost, ":",
444 			    eh->ether_dhost, ":");
445 			ieee80211_mesh_proxy_check(vap, eh->ether_shost);
446 		}
447 		ni = ieee80211_mesh_discover(vap, eh->ether_dhost, m);
448 		if (ni == NULL) {
449 			/*
450 			 * NB: ieee80211_mesh_discover holds/disposes
451 			 * frame (e.g. queueing on path discovery).
452 			 */
453 			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
454 			/* XXX better status? */
455 			return (ENOBUFS);
456 		}
457 	}
458 #endif
459 
460 	/*
461 	 * We've resolved the sender, so attempt to transmit it.
462 	 */
463 
464 	if (vap->iv_state == IEEE80211_S_SLEEP) {
465 		/*
466 		 * In power save; queue frame and then  wakeup device
467 		 * for transmit.
468 		 */
469 		ic->ic_lastdata = ticks;
470 		if (ieee80211_pwrsave(ni, m) != 0)
471 			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
472 		ieee80211_free_node(ni);
473 		ieee80211_new_state(vap, IEEE80211_S_RUN, 0);
474 		return (0);
475 	}
476 
477 	if (ieee80211_vap_pkt_send_dest(vap, m, ni) != 0)
478 		return (ENOBUFS);
479 	return (0);
480 #undef	IS_DWDS
481 }
482 
483 /*
484  * Start method for vap's.  All packets from the stack come
485  * through here.  We handle common processing of the packets
486  * before dispatching them to the underlying device.
487  *
488  * if_transmit() requires that the mbuf be consumed by this call
489  * regardless of the return condition.
490  */
491 int
492 ieee80211_vap_transmit(struct ifnet *ifp, struct mbuf *m)
493 {
494 	struct ieee80211vap *vap = ifp->if_softc;
495 	struct ieee80211com *ic = vap->iv_ic;
496 
497 	/*
498 	 * No data frames go out unless we're running.
499 	 * Note in particular this covers CAC and CSA
500 	 * states (though maybe we should check muting
501 	 * for CSA).
502 	 */
503 	if (vap->iv_state != IEEE80211_S_RUN &&
504 	    vap->iv_state != IEEE80211_S_SLEEP) {
505 		IEEE80211_LOCK(ic);
506 		/* re-check under the com lock to avoid races */
507 		if (vap->iv_state != IEEE80211_S_RUN &&
508 		    vap->iv_state != IEEE80211_S_SLEEP) {
509 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT,
510 			    "%s: ignore queue, in %s state\n",
511 			    __func__, ieee80211_state_name[vap->iv_state]);
512 			vap->iv_stats.is_tx_badstate++;
513 			IEEE80211_UNLOCK(ic);
514 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
515 			m_freem(m);
516 			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
517 			return (ENETDOWN);
518 		}
519 		IEEE80211_UNLOCK(ic);
520 	}
521 
522 	/*
523 	 * Sanitize mbuf flags for net80211 use.  We cannot
524 	 * clear M_PWR_SAV or M_MORE_DATA because these may
525 	 * be set for frames that are re-submitted from the
526 	 * power save queue.
527 	 *
528 	 * NB: This must be done before ieee80211_classify as
529 	 *     it marks EAPOL in frames with M_EAPOL.
530 	 */
531 	m->m_flags &= ~(M_80211_TX - M_PWR_SAV - M_MORE_DATA);
532 
533 	/*
534 	 * Bump to the packet transmission path.
535 	 * The mbuf will be consumed here.
536 	 */
537 	return (ieee80211_start_pkt(vap, m));
538 }
539 
540 void
541 ieee80211_vap_qflush(struct ifnet *ifp)
542 {
543 
544 	/* Empty for now */
545 }
546 
547 /*
548  * 802.11 raw output routine.
549  *
550  * XXX TODO: this (and other send routines) should correctly
551  * XXX keep the pwr mgmt bit set if it decides to call into the
552  * XXX driver to send a frame whilst the state is SLEEP.
553  *
554  * Otherwise the peer may decide that we're awake and flood us
555  * with traffic we are still too asleep to receive!
556  */
557 int
558 ieee80211_raw_output(struct ieee80211vap *vap, struct ieee80211_node *ni,
559     struct mbuf *m, const struct ieee80211_bpf_params *params)
560 {
561 	struct ieee80211com *ic = vap->iv_ic;
562 	int error;
563 
564 	/*
565 	 * Set node - the caller has taken a reference, so ensure
566 	 * that the mbuf has the same node value that
567 	 * it would if it were going via the normal path.
568 	 */
569 	MPASS((m->m_pkthdr.csum_flags & CSUM_SND_TAG) == 0);
570 	m->m_pkthdr.rcvif = (void *)ni;
571 
572 	/*
573 	 * Attempt to add bpf transmit parameters.
574 	 *
575 	 * For now it's ok to fail; the raw_xmit api still takes
576 	 * them as an option.
577 	 *
578 	 * Later on when ic_raw_xmit() has params removed,
579 	 * they'll have to be added - so fail the transmit if
580 	 * they can't be.
581 	 */
582 	if (params)
583 		(void) ieee80211_add_xmit_params(m, params);
584 
585 	error = ic->ic_raw_xmit(ni, m, params);
586 	if (error) {
587 		if_inc_counter(vap->iv_ifp, IFCOUNTER_OERRORS, 1);
588 		ieee80211_free_node(ni);
589 	}
590 	return (error);
591 }
592 
593 static int
594 ieee80211_validate_frame(struct mbuf *m,
595     const struct ieee80211_bpf_params *params)
596 {
597 	struct ieee80211_frame *wh;
598 	int type;
599 
600 	if (m->m_pkthdr.len < sizeof(struct ieee80211_frame_ack))
601 		return (EINVAL);
602 
603 	wh = mtod(m, struct ieee80211_frame *);
604 	if ((wh->i_fc[0] & IEEE80211_FC0_VERSION_MASK) !=
605 	    IEEE80211_FC0_VERSION_0)
606 		return (EINVAL);
607 
608 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
609 	if (type != IEEE80211_FC0_TYPE_DATA) {
610 		if ((wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) !=
611 		    IEEE80211_FC1_DIR_NODS)
612 			return (EINVAL);
613 
614 		if (type != IEEE80211_FC0_TYPE_MGT &&
615 		    (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG) != 0)
616 			return (EINVAL);
617 
618 		/* XXX skip other field checks? */
619 	}
620 
621 	if ((params && (params->ibp_flags & IEEE80211_BPF_CRYPTO) != 0) ||
622 	    (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) != 0) {
623 		int subtype;
624 
625 		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
626 
627 		/*
628 		 * See IEEE Std 802.11-2012,
629 		 * 8.2.4.1.9 'Protected Frame field'
630 		 */
631 		/* XXX no support for robust management frames yet. */
632 		if (!(type == IEEE80211_FC0_TYPE_DATA ||
633 		    (type == IEEE80211_FC0_TYPE_MGT &&
634 		     subtype == IEEE80211_FC0_SUBTYPE_AUTH)))
635 			return (EINVAL);
636 
637 		wh->i_fc[1] |= IEEE80211_FC1_PROTECTED;
638 	}
639 
640 	if (m->m_pkthdr.len < ieee80211_anyhdrsize(wh))
641 		return (EINVAL);
642 
643 	return (0);
644 }
645 
646 static int
647 ieee80211_validate_rate(struct ieee80211_node *ni, uint8_t rate)
648 {
649 	struct ieee80211com *ic = ni->ni_ic;
650 
651 	if (IEEE80211_IS_HT_RATE(rate)) {
652 		if ((ic->ic_htcaps & IEEE80211_HTC_HT) == 0)
653 			return (EINVAL);
654 
655 		rate = IEEE80211_RV(rate);
656 		if (rate <= 31) {
657 			if (rate > ic->ic_txstream * 8 - 1)
658 				return (EINVAL);
659 
660 			return (0);
661 		}
662 
663 		if (rate == 32) {
664 			if ((ic->ic_htcaps & IEEE80211_HTC_TXMCS32) == 0)
665 				return (EINVAL);
666 
667 			return (0);
668 		}
669 
670 		if ((ic->ic_htcaps & IEEE80211_HTC_TXUNEQUAL) == 0)
671 			return (EINVAL);
672 
673 		switch (ic->ic_txstream) {
674 		case 0:
675 		case 1:
676 			return (EINVAL);
677 		case 2:
678 			if (rate > 38)
679 				return (EINVAL);
680 
681 			return (0);
682 		case 3:
683 			if (rate > 52)
684 				return (EINVAL);
685 
686 			return (0);
687 		case 4:
688 		default:
689 			if (rate > 76)
690 				return (EINVAL);
691 
692 			return (0);
693 		}
694 	}
695 
696 	if (!ieee80211_isratevalid(ic->ic_rt, rate))
697 		return (EINVAL);
698 
699 	return (0);
700 }
701 
702 static int
703 ieee80211_sanitize_rates(struct ieee80211_node *ni, struct mbuf *m,
704     const struct ieee80211_bpf_params *params)
705 {
706 	int error;
707 
708 	if (!params)
709 		return (0);	/* nothing to do */
710 
711 	/* NB: most drivers assume that ibp_rate0 is set (!= 0). */
712 	if (params->ibp_rate0 != 0) {
713 		error = ieee80211_validate_rate(ni, params->ibp_rate0);
714 		if (error != 0)
715 			return (error);
716 	} else {
717 		/* XXX pre-setup some default (e.g., mgmt / mcast) rate */
718 		/* XXX __DECONST? */
719 		(void) m;
720 	}
721 
722 	if (params->ibp_rate1 != 0 &&
723 	    (error = ieee80211_validate_rate(ni, params->ibp_rate1)) != 0)
724 		return (error);
725 
726 	if (params->ibp_rate2 != 0 &&
727 	    (error = ieee80211_validate_rate(ni, params->ibp_rate2)) != 0)
728 		return (error);
729 
730 	if (params->ibp_rate3 != 0 &&
731 	    (error = ieee80211_validate_rate(ni, params->ibp_rate3)) != 0)
732 		return (error);
733 
734 	return (0);
735 }
736 
737 /*
738  * 802.11 output routine. This is (currently) used only to
739  * connect bpf write calls to the 802.11 layer for injecting
740  * raw 802.11 frames.
741  */
742 int
743 ieee80211_output(struct ifnet *ifp, struct mbuf *m,
744 	const struct sockaddr *dst, struct route *ro)
745 {
746 #define senderr(e) do { error = (e); goto bad;} while (0)
747 	const struct ieee80211_bpf_params *params = NULL;
748 	struct ieee80211_node *ni = NULL;
749 	struct ieee80211vap *vap;
750 	struct ieee80211_frame *wh;
751 	struct ieee80211com *ic = NULL;
752 	int error;
753 	int ret;
754 
755 	if (ifp->if_drv_flags & IFF_DRV_OACTIVE) {
756 		/*
757 		 * Short-circuit requests if the vap is marked OACTIVE
758 		 * as this can happen because a packet came down through
759 		 * ieee80211_start before the vap entered RUN state in
760 		 * which case it's ok to just drop the frame.  This
761 		 * should not be necessary but callers of if_output don't
762 		 * check OACTIVE.
763 		 */
764 		senderr(ENETDOWN);
765 	}
766 	vap = ifp->if_softc;
767 	ic = vap->iv_ic;
768 	/*
769 	 * Hand to the 802.3 code if not tagged as
770 	 * a raw 802.11 frame.
771 	 */
772 	if (dst->sa_family != AF_IEEE80211)
773 		return vap->iv_output(ifp, m, dst, ro);
774 #ifdef MAC
775 	error = mac_ifnet_check_transmit(ifp, m);
776 	if (error)
777 		senderr(error);
778 #endif
779 	if (ifp->if_flags & IFF_MONITOR)
780 		senderr(ENETDOWN);
781 	if (!IFNET_IS_UP_RUNNING(ifp))
782 		senderr(ENETDOWN);
783 	if (vap->iv_state == IEEE80211_S_CAC) {
784 		IEEE80211_DPRINTF(vap,
785 		    IEEE80211_MSG_OUTPUT | IEEE80211_MSG_DOTH,
786 		    "block %s frame in CAC state\n", "raw data");
787 		vap->iv_stats.is_tx_badstate++;
788 		senderr(EIO);		/* XXX */
789 	} else if (vap->iv_state == IEEE80211_S_SCAN)
790 		senderr(EIO);
791 	/* XXX bypass bridge, pfil, carp, etc. */
792 
793 	/*
794 	 * NB: DLT_IEEE802_11_RADIO identifies the parameters are
795 	 * present by setting the sa_len field of the sockaddr (yes,
796 	 * this is a hack).
797 	 * NB: we assume sa_data is suitably aligned to cast.
798 	 */
799 	if (dst->sa_len != 0)
800 		params = (const struct ieee80211_bpf_params *)dst->sa_data;
801 
802 	error = ieee80211_validate_frame(m, params);
803 	if (error != 0)
804 		senderr(error);
805 
806 	wh = mtod(m, struct ieee80211_frame *);
807 
808 	/* locate destination node */
809 	switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
810 	case IEEE80211_FC1_DIR_NODS:
811 	case IEEE80211_FC1_DIR_FROMDS:
812 		ni = ieee80211_find_txnode(vap, wh->i_addr1);
813 		break;
814 	case IEEE80211_FC1_DIR_TODS:
815 	case IEEE80211_FC1_DIR_DSTODS:
816 		ni = ieee80211_find_txnode(vap, wh->i_addr3);
817 		break;
818 	default:
819 		senderr(EDOOFUS);
820 	}
821 	if (ni == NULL) {
822 		/*
823 		 * Permit packets w/ bpf params through regardless
824 		 * (see below about sa_len).
825 		 */
826 		if (dst->sa_len == 0)
827 			senderr(EHOSTUNREACH);
828 		ni = ieee80211_ref_node(vap->iv_bss);
829 	}
830 
831 	/*
832 	 * Sanitize mbuf for net80211 flags leaked from above.
833 	 *
834 	 * NB: This must be done before ieee80211_classify as
835 	 *     it marks EAPOL in frames with M_EAPOL.
836 	 */
837 	m->m_flags &= ~M_80211_TX;
838 	m->m_flags |= M_ENCAP;		/* mark encapsulated */
839 
840 	if (IEEE80211_IS_DATA(wh)) {
841 		/* calculate priority so drivers can find the tx queue */
842 		if (ieee80211_classify(ni, m))
843 			senderr(EIO);		/* XXX */
844 
845 		/* NB: ieee80211_encap does not include 802.11 header */
846 		IEEE80211_NODE_STAT_ADD(ni, tx_bytes,
847 		    m->m_pkthdr.len - ieee80211_hdrsize(wh));
848 	} else
849 		M_WME_SETAC(m, WME_AC_BE);
850 
851 	error = ieee80211_sanitize_rates(ni, m, params);
852 	if (error != 0)
853 		senderr(error);
854 
855 	IEEE80211_NODE_STAT(ni, tx_data);
856 	if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
857 		IEEE80211_NODE_STAT(ni, tx_mcast);
858 		m->m_flags |= M_MCAST;
859 	} else
860 		IEEE80211_NODE_STAT(ni, tx_ucast);
861 
862 	IEEE80211_TX_LOCK(ic);
863 	ret = ieee80211_raw_output(vap, ni, m, params);
864 	IEEE80211_TX_UNLOCK(ic);
865 	return (ret);
866 bad:
867 	if (m != NULL)
868 		m_freem(m);
869 	if (ni != NULL)
870 		ieee80211_free_node(ni);
871 	if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
872 	return error;
873 #undef senderr
874 }
875 
876 /*
877  * Set the direction field and address fields of an outgoing
878  * frame.  Note this should be called early on in constructing
879  * a frame as it sets i_fc[1]; other bits can then be or'd in.
880  */
881 void
882 ieee80211_send_setup(
883 	struct ieee80211_node *ni,
884 	struct mbuf *m,
885 	int type, int tid,
886 	const uint8_t sa[IEEE80211_ADDR_LEN],
887 	const uint8_t da[IEEE80211_ADDR_LEN],
888 	const uint8_t bssid[IEEE80211_ADDR_LEN])
889 {
890 #define	WH4(wh)	((struct ieee80211_frame_addr4 *)wh)
891 	struct ieee80211vap *vap = ni->ni_vap;
892 	struct ieee80211_tx_ampdu *tap;
893 	struct ieee80211_frame *wh = mtod(m, struct ieee80211_frame *);
894 	ieee80211_seq seqno;
895 
896 	IEEE80211_TX_LOCK_ASSERT(ni->ni_ic);
897 
898 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | type;
899 	if ((type & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_DATA) {
900 		switch (vap->iv_opmode) {
901 		case IEEE80211_M_STA:
902 			wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
903 			IEEE80211_ADDR_COPY(wh->i_addr1, bssid);
904 			IEEE80211_ADDR_COPY(wh->i_addr2, sa);
905 			IEEE80211_ADDR_COPY(wh->i_addr3, da);
906 			break;
907 		case IEEE80211_M_IBSS:
908 		case IEEE80211_M_AHDEMO:
909 			wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
910 			IEEE80211_ADDR_COPY(wh->i_addr1, da);
911 			IEEE80211_ADDR_COPY(wh->i_addr2, sa);
912 			IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
913 			break;
914 		case IEEE80211_M_HOSTAP:
915 			wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
916 			IEEE80211_ADDR_COPY(wh->i_addr1, da);
917 			IEEE80211_ADDR_COPY(wh->i_addr2, bssid);
918 			IEEE80211_ADDR_COPY(wh->i_addr3, sa);
919 			break;
920 		case IEEE80211_M_WDS:
921 			wh->i_fc[1] = IEEE80211_FC1_DIR_DSTODS;
922 			IEEE80211_ADDR_COPY(wh->i_addr1, da);
923 			IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
924 			IEEE80211_ADDR_COPY(wh->i_addr3, da);
925 			IEEE80211_ADDR_COPY(WH4(wh)->i_addr4, sa);
926 			break;
927 		case IEEE80211_M_MBSS:
928 #ifdef IEEE80211_SUPPORT_MESH
929 			if (IEEE80211_IS_MULTICAST(da)) {
930 				wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
931 				/* XXX next hop */
932 				IEEE80211_ADDR_COPY(wh->i_addr1, da);
933 				IEEE80211_ADDR_COPY(wh->i_addr2,
934 				    vap->iv_myaddr);
935 			} else {
936 				wh->i_fc[1] = IEEE80211_FC1_DIR_DSTODS;
937 				IEEE80211_ADDR_COPY(wh->i_addr1, da);
938 				IEEE80211_ADDR_COPY(wh->i_addr2,
939 				    vap->iv_myaddr);
940 				IEEE80211_ADDR_COPY(wh->i_addr3, da);
941 				IEEE80211_ADDR_COPY(WH4(wh)->i_addr4, sa);
942 			}
943 #endif
944 			break;
945 		case IEEE80211_M_MONITOR:	/* NB: to quiet compiler */
946 			break;
947 		}
948 	} else {
949 		wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
950 		IEEE80211_ADDR_COPY(wh->i_addr1, da);
951 		IEEE80211_ADDR_COPY(wh->i_addr2, sa);
952 #ifdef IEEE80211_SUPPORT_MESH
953 		if (vap->iv_opmode == IEEE80211_M_MBSS)
954 			IEEE80211_ADDR_COPY(wh->i_addr3, sa);
955 		else
956 #endif
957 			IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
958 	}
959 	*(uint16_t *)&wh->i_dur[0] = 0;
960 
961 	/*
962 	 * XXX TODO: this is what the TX lock is for.
963 	 * Here we're incrementing sequence numbers, and they
964 	 * need to be in lock-step with what the driver is doing
965 	 * both in TX ordering and crypto encap (IV increment.)
966 	 *
967 	 * If the driver does seqno itself, then we can skip
968 	 * assigning sequence numbers here, and we can avoid
969 	 * requiring the TX lock.
970 	 */
971 	tap = &ni->ni_tx_ampdu[tid];
972 	if (tid != IEEE80211_NONQOS_TID && IEEE80211_AMPDU_RUNNING(tap)) {
973 		m->m_flags |= M_AMPDU_MPDU;
974 
975 		/* NB: zero out i_seq field (for s/w encryption etc) */
976 		*(uint16_t *)&wh->i_seq[0] = 0;
977 	} else {
978 		if (IEEE80211_HAS_SEQ(type & IEEE80211_FC0_TYPE_MASK,
979 				      type & IEEE80211_FC0_SUBTYPE_MASK))
980 			/*
981 			 * 802.11-2012 9.3.2.10 - QoS multicast frames
982 			 * come out of a different seqno space.
983 			 */
984 			if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
985 				seqno = ni->ni_txseqs[IEEE80211_NONQOS_TID]++;
986 			} else {
987 				seqno = ni->ni_txseqs[tid]++;
988 			}
989 		else
990 			seqno = 0;
991 
992 		*(uint16_t *)&wh->i_seq[0] =
993 		    htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT);
994 		M_SEQNO_SET(m, seqno);
995 	}
996 
997 	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
998 		m->m_flags |= M_MCAST;
999 #undef WH4
1000 }
1001 
1002 /*
1003  * Send a management frame to the specified node.  The node pointer
1004  * must have a reference as the pointer will be passed to the driver
1005  * and potentially held for a long time.  If the frame is successfully
1006  * dispatched to the driver, then it is responsible for freeing the
1007  * reference (and potentially free'ing up any associated storage);
1008  * otherwise deal with reclaiming any reference (on error).
1009  */
1010 int
1011 ieee80211_mgmt_output(struct ieee80211_node *ni, struct mbuf *m, int type,
1012 	struct ieee80211_bpf_params *params)
1013 {
1014 	struct ieee80211vap *vap = ni->ni_vap;
1015 	struct ieee80211com *ic = ni->ni_ic;
1016 	struct ieee80211_frame *wh;
1017 	int ret;
1018 
1019 	KASSERT(ni != NULL, ("null node"));
1020 
1021 	if (vap->iv_state == IEEE80211_S_CAC) {
1022 		IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT | IEEE80211_MSG_DOTH,
1023 		    ni, "block %s frame in CAC state",
1024 			ieee80211_mgt_subtype_name(type));
1025 		vap->iv_stats.is_tx_badstate++;
1026 		ieee80211_free_node(ni);
1027 		m_freem(m);
1028 		return EIO;		/* XXX */
1029 	}
1030 
1031 	M_PREPEND(m, sizeof(struct ieee80211_frame), M_NOWAIT);
1032 	if (m == NULL) {
1033 		ieee80211_free_node(ni);
1034 		return ENOMEM;
1035 	}
1036 
1037 	IEEE80211_TX_LOCK(ic);
1038 
1039 	wh = mtod(m, struct ieee80211_frame *);
1040 	ieee80211_send_setup(ni, m,
1041 	     IEEE80211_FC0_TYPE_MGT | type, IEEE80211_NONQOS_TID,
1042 	     vap->iv_myaddr, ni->ni_macaddr, ni->ni_bssid);
1043 	if (params->ibp_flags & IEEE80211_BPF_CRYPTO) {
1044 		IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_AUTH, wh->i_addr1,
1045 		    "encrypting frame (%s)", __func__);
1046 		wh->i_fc[1] |= IEEE80211_FC1_PROTECTED;
1047 	}
1048 	m->m_flags |= M_ENCAP;		/* mark encapsulated */
1049 
1050 	KASSERT(type != IEEE80211_FC0_SUBTYPE_PROBE_RESP, ("probe response?"));
1051 	M_WME_SETAC(m, params->ibp_pri);
1052 
1053 #ifdef IEEE80211_DEBUG
1054 	/* avoid printing too many frames */
1055 	if ((ieee80211_msg_debug(vap) && doprint(vap, type)) ||
1056 	    ieee80211_msg_dumppkts(vap)) {
1057 		printf("[%s] send %s on channel %u\n",
1058 		    ether_sprintf(wh->i_addr1),
1059 		    ieee80211_mgt_subtype_name(type),
1060 		    ieee80211_chan2ieee(ic, ic->ic_curchan));
1061 	}
1062 #endif
1063 	IEEE80211_NODE_STAT(ni, tx_mgmt);
1064 
1065 	ret = ieee80211_raw_output(vap, ni, m, params);
1066 	IEEE80211_TX_UNLOCK(ic);
1067 	return (ret);
1068 }
1069 
1070 static void
1071 ieee80211_nulldata_transmitted(struct ieee80211_node *ni, void *arg,
1072     int status)
1073 {
1074 	struct ieee80211vap *vap = ni->ni_vap;
1075 
1076 	wakeup(vap);
1077 }
1078 
1079 /*
1080  * Send a null data frame to the specified node.  If the station
1081  * is setup for QoS then a QoS Null Data frame is constructed.
1082  * If this is a WDS station then a 4-address frame is constructed.
1083  *
1084  * NB: the caller is assumed to have setup a node reference
1085  *     for use; this is necessary to deal with a race condition
1086  *     when probing for inactive stations.  Like ieee80211_mgmt_output
1087  *     we must cleanup any node reference on error;  however we
1088  *     can safely just unref it as we know it will never be the
1089  *     last reference to the node.
1090  */
1091 int
1092 ieee80211_send_nulldata(struct ieee80211_node *ni)
1093 {
1094 	struct ieee80211vap *vap = ni->ni_vap;
1095 	struct ieee80211com *ic = ni->ni_ic;
1096 	struct mbuf *m;
1097 	struct ieee80211_frame *wh;
1098 	int hdrlen;
1099 	uint8_t *frm;
1100 	int ret;
1101 
1102 	if (vap->iv_state == IEEE80211_S_CAC) {
1103 		IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT | IEEE80211_MSG_DOTH,
1104 		    ni, "block %s frame in CAC state", "null data");
1105 		ieee80211_unref_node(&ni);
1106 		vap->iv_stats.is_tx_badstate++;
1107 		return EIO;		/* XXX */
1108 	}
1109 
1110 	if (ni->ni_flags & (IEEE80211_NODE_QOS|IEEE80211_NODE_HT))
1111 		hdrlen = sizeof(struct ieee80211_qosframe);
1112 	else
1113 		hdrlen = sizeof(struct ieee80211_frame);
1114 	/* NB: only WDS vap's get 4-address frames */
1115 	if (vap->iv_opmode == IEEE80211_M_WDS)
1116 		hdrlen += IEEE80211_ADDR_LEN;
1117 	if (ic->ic_flags & IEEE80211_F_DATAPAD)
1118 		hdrlen = roundup(hdrlen, sizeof(uint32_t));
1119 
1120 	m = ieee80211_getmgtframe(&frm, ic->ic_headroom + hdrlen, 0);
1121 	if (m == NULL) {
1122 		/* XXX debug msg */
1123 		ieee80211_unref_node(&ni);
1124 		vap->iv_stats.is_tx_nobuf++;
1125 		return ENOMEM;
1126 	}
1127 	KASSERT(M_LEADINGSPACE(m) >= hdrlen,
1128 	    ("leading space %zd", M_LEADINGSPACE(m)));
1129 	M_PREPEND(m, hdrlen, M_NOWAIT);
1130 	if (m == NULL) {
1131 		/* NB: cannot happen */
1132 		ieee80211_free_node(ni);
1133 		return ENOMEM;
1134 	}
1135 
1136 	IEEE80211_TX_LOCK(ic);
1137 
1138 	wh = mtod(m, struct ieee80211_frame *);		/* NB: a little lie */
1139 	if (ni->ni_flags & IEEE80211_NODE_QOS) {
1140 		const int tid = WME_AC_TO_TID(WME_AC_BE);
1141 		uint8_t *qos;
1142 
1143 		ieee80211_send_setup(ni, m,
1144 		    IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_QOS_NULL,
1145 		    tid, vap->iv_myaddr, ni->ni_macaddr, ni->ni_bssid);
1146 
1147 		if (vap->iv_opmode == IEEE80211_M_WDS)
1148 			qos = ((struct ieee80211_qosframe_addr4 *) wh)->i_qos;
1149 		else
1150 			qos = ((struct ieee80211_qosframe *) wh)->i_qos;
1151 		qos[0] = tid & IEEE80211_QOS_TID;
1152 		if (ic->ic_wme.wme_wmeChanParams.cap_wmeParams[WME_AC_BE].wmep_noackPolicy)
1153 			qos[0] |= IEEE80211_QOS_ACKPOLICY_NOACK;
1154 		qos[1] = 0;
1155 	} else {
1156 		ieee80211_send_setup(ni, m,
1157 		    IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_NODATA,
1158 		    IEEE80211_NONQOS_TID,
1159 		    vap->iv_myaddr, ni->ni_macaddr, ni->ni_bssid);
1160 	}
1161 	if (vap->iv_opmode != IEEE80211_M_WDS) {
1162 		/* NB: power management bit is never sent by an AP */
1163 		if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
1164 		    vap->iv_opmode != IEEE80211_M_HOSTAP)
1165 			wh->i_fc[1] |= IEEE80211_FC1_PWR_MGT;
1166 	}
1167 	if ((ic->ic_flags & IEEE80211_F_SCAN) &&
1168 	    (ni->ni_flags & IEEE80211_NODE_PWR_MGT)) {
1169 		ieee80211_add_callback(m, ieee80211_nulldata_transmitted,
1170 		    NULL);
1171 	}
1172 	m->m_len = m->m_pkthdr.len = hdrlen;
1173 	m->m_flags |= M_ENCAP;		/* mark encapsulated */
1174 
1175 	M_WME_SETAC(m, WME_AC_BE);
1176 
1177 	IEEE80211_NODE_STAT(ni, tx_data);
1178 
1179 	IEEE80211_NOTE(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS, ni,
1180 	    "send %snull data frame on channel %u, pwr mgt %s",
1181 	    ni->ni_flags & IEEE80211_NODE_QOS ? "QoS " : "",
1182 	    ieee80211_chan2ieee(ic, ic->ic_curchan),
1183 	    wh->i_fc[1] & IEEE80211_FC1_PWR_MGT ? "ena" : "dis");
1184 
1185 	ret = ieee80211_raw_output(vap, ni, m, NULL);
1186 	IEEE80211_TX_UNLOCK(ic);
1187 	return (ret);
1188 }
1189 
1190 /*
1191  * Assign priority to a frame based on any vlan tag assigned
1192  * to the station and/or any Diffserv setting in an IP header.
1193  * Finally, if an ACM policy is setup (in station mode) it's
1194  * applied.
1195  */
1196 int
1197 ieee80211_classify(struct ieee80211_node *ni, struct mbuf *m)
1198 {
1199 	const struct ether_header *eh = NULL;
1200 	uint16_t ether_type;
1201 	int v_wme_ac, d_wme_ac, ac;
1202 
1203 	if (__predict_false(m->m_flags & M_ENCAP)) {
1204 		struct ieee80211_frame *wh = mtod(m, struct ieee80211_frame *);
1205 		struct llc *llc;
1206 		int hdrlen, subtype;
1207 
1208 		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
1209 		if (subtype & IEEE80211_FC0_SUBTYPE_NODATA) {
1210 			ac = WME_AC_BE;
1211 			goto done;
1212 		}
1213 
1214 		hdrlen = ieee80211_hdrsize(wh);
1215 		if (m->m_pkthdr.len < hdrlen + sizeof(*llc))
1216 			return 1;
1217 
1218 		llc = (struct llc *)mtodo(m, hdrlen);
1219 		if (llc->llc_dsap != LLC_SNAP_LSAP ||
1220 		    llc->llc_ssap != LLC_SNAP_LSAP ||
1221 		    llc->llc_control != LLC_UI ||
1222 		    llc->llc_snap.org_code[0] != 0 ||
1223 		    llc->llc_snap.org_code[1] != 0 ||
1224 		    llc->llc_snap.org_code[2] != 0)
1225 			return 1;
1226 
1227 		ether_type = llc->llc_snap.ether_type;
1228 	} else {
1229 		eh = mtod(m, struct ether_header *);
1230 		ether_type = eh->ether_type;
1231 	}
1232 
1233 	/*
1234 	 * Always promote PAE/EAPOL frames to high priority.
1235 	 */
1236 	if (ether_type == htons(ETHERTYPE_PAE)) {
1237 		/* NB: mark so others don't need to check header */
1238 		m->m_flags |= M_EAPOL;
1239 		ac = WME_AC_VO;
1240 		goto done;
1241 	}
1242 	/*
1243 	 * Non-qos traffic goes to BE.
1244 	 */
1245 	if ((ni->ni_flags & IEEE80211_NODE_QOS) == 0) {
1246 		ac = WME_AC_BE;
1247 		goto done;
1248 	}
1249 
1250 	/*
1251 	 * If node has a vlan tag then all traffic
1252 	 * to it must have a matching tag.
1253 	 */
1254 	v_wme_ac = 0;
1255 	if (ni->ni_vlan != 0) {
1256 		 if ((m->m_flags & M_VLANTAG) == 0) {
1257 			IEEE80211_NODE_STAT(ni, tx_novlantag);
1258 			return 1;
1259 		}
1260 		if (EVL_VLANOFTAG(m->m_pkthdr.ether_vtag) !=
1261 		    EVL_VLANOFTAG(ni->ni_vlan)) {
1262 			IEEE80211_NODE_STAT(ni, tx_vlanmismatch);
1263 			return 1;
1264 		}
1265 		/* map vlan priority to AC */
1266 		v_wme_ac = TID_TO_WME_AC(EVL_PRIOFTAG(ni->ni_vlan));
1267 	}
1268 
1269 	/* XXX m_copydata may be too slow for fast path */
1270 #ifdef INET
1271 	if (eh && eh->ether_type == htons(ETHERTYPE_IP)) {
1272 		uint8_t tos;
1273 		/*
1274 		 * IP frame, map the DSCP bits from the TOS field.
1275 		 */
1276 		/* NB: ip header may not be in first mbuf */
1277 		m_copydata(m, sizeof(struct ether_header) +
1278 		    offsetof(struct ip, ip_tos), sizeof(tos), &tos);
1279 		tos >>= 5;		/* NB: ECN + low 3 bits of DSCP */
1280 		d_wme_ac = TID_TO_WME_AC(tos);
1281 	} else {
1282 #endif /* INET */
1283 #ifdef INET6
1284 	if (eh && eh->ether_type == htons(ETHERTYPE_IPV6)) {
1285 		uint32_t flow;
1286 		uint8_t tos;
1287 		/*
1288 		 * IPv6 frame, map the DSCP bits from the traffic class field.
1289 		 */
1290 		m_copydata(m, sizeof(struct ether_header) +
1291 		    offsetof(struct ip6_hdr, ip6_flow), sizeof(flow),
1292 		    (caddr_t) &flow);
1293 		tos = (uint8_t)(ntohl(flow) >> 20);
1294 		tos >>= 5;		/* NB: ECN + low 3 bits of DSCP */
1295 		d_wme_ac = TID_TO_WME_AC(tos);
1296 	} else {
1297 #endif /* INET6 */
1298 		d_wme_ac = WME_AC_BE;
1299 #ifdef INET6
1300 	}
1301 #endif
1302 #ifdef INET
1303 	}
1304 #endif
1305 	/*
1306 	 * Use highest priority AC.
1307 	 */
1308 	if (v_wme_ac > d_wme_ac)
1309 		ac = v_wme_ac;
1310 	else
1311 		ac = d_wme_ac;
1312 
1313 	/*
1314 	 * Apply ACM policy.
1315 	 */
1316 	if (ni->ni_vap->iv_opmode == IEEE80211_M_STA) {
1317 		static const int acmap[4] = {
1318 			WME_AC_BK,	/* WME_AC_BE */
1319 			WME_AC_BK,	/* WME_AC_BK */
1320 			WME_AC_BE,	/* WME_AC_VI */
1321 			WME_AC_VI,	/* WME_AC_VO */
1322 		};
1323 		struct ieee80211com *ic = ni->ni_ic;
1324 
1325 		while (ac != WME_AC_BK &&
1326 		    ic->ic_wme.wme_wmeBssChanParams.cap_wmeParams[ac].wmep_acm)
1327 			ac = acmap[ac];
1328 	}
1329 done:
1330 	M_WME_SETAC(m, ac);
1331 	return 0;
1332 }
1333 
1334 /*
1335  * Insure there is sufficient contiguous space to encapsulate the
1336  * 802.11 data frame.  If room isn't already there, arrange for it.
1337  * Drivers and cipher modules assume we have done the necessary work
1338  * and fail rudely if they don't find the space they need.
1339  */
1340 struct mbuf *
1341 ieee80211_mbuf_adjust(struct ieee80211vap *vap, int hdrsize,
1342 	struct ieee80211_key *key, struct mbuf *m)
1343 {
1344 #define	TO_BE_RECLAIMED	(sizeof(struct ether_header) - sizeof(struct llc))
1345 	int needed_space = vap->iv_ic->ic_headroom + hdrsize;
1346 
1347 	if (key != NULL) {
1348 		/* XXX belongs in crypto code? */
1349 		needed_space += key->wk_cipher->ic_header;
1350 		/* XXX frags */
1351 		/*
1352 		 * When crypto is being done in the host we must insure
1353 		 * the data are writable for the cipher routines; clone
1354 		 * a writable mbuf chain.
1355 		 * XXX handle SWMIC specially
1356 		 */
1357 		if (key->wk_flags & (IEEE80211_KEY_SWENCRYPT|IEEE80211_KEY_SWENMIC)) {
1358 			m = m_unshare(m, M_NOWAIT);
1359 			if (m == NULL) {
1360 				IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT,
1361 				    "%s: cannot get writable mbuf\n", __func__);
1362 				vap->iv_stats.is_tx_nobuf++; /* XXX new stat */
1363 				return NULL;
1364 			}
1365 		}
1366 	}
1367 	/*
1368 	 * We know we are called just before stripping an Ethernet
1369 	 * header and prepending an LLC header.  This means we know
1370 	 * there will be
1371 	 *	sizeof(struct ether_header) - sizeof(struct llc)
1372 	 * bytes recovered to which we need additional space for the
1373 	 * 802.11 header and any crypto header.
1374 	 */
1375 	/* XXX check trailing space and copy instead? */
1376 	if (M_LEADINGSPACE(m) < needed_space - TO_BE_RECLAIMED) {
1377 		struct mbuf *n = m_gethdr(M_NOWAIT, m->m_type);
1378 		if (n == NULL) {
1379 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT,
1380 			    "%s: cannot expand storage\n", __func__);
1381 			vap->iv_stats.is_tx_nobuf++;
1382 			m_freem(m);
1383 			return NULL;
1384 		}
1385 		KASSERT(needed_space <= MHLEN,
1386 		    ("not enough room, need %u got %d\n", needed_space, MHLEN));
1387 		/*
1388 		 * Setup new mbuf to have leading space to prepend the
1389 		 * 802.11 header and any crypto header bits that are
1390 		 * required (the latter are added when the driver calls
1391 		 * back to ieee80211_crypto_encap to do crypto encapsulation).
1392 		 */
1393 		/* NB: must be first 'cuz it clobbers m_data */
1394 		m_move_pkthdr(n, m);
1395 		n->m_len = 0;			/* NB: m_gethdr does not set */
1396 		n->m_data += needed_space;
1397 		/*
1398 		 * Pull up Ethernet header to create the expected layout.
1399 		 * We could use m_pullup but that's overkill (i.e. we don't
1400 		 * need the actual data) and it cannot fail so do it inline
1401 		 * for speed.
1402 		 */
1403 		/* NB: struct ether_header is known to be contiguous */
1404 		n->m_len += sizeof(struct ether_header);
1405 		m->m_len -= sizeof(struct ether_header);
1406 		m->m_data += sizeof(struct ether_header);
1407 		/*
1408 		 * Replace the head of the chain.
1409 		 */
1410 		n->m_next = m;
1411 		m = n;
1412 	}
1413 	return m;
1414 #undef TO_BE_RECLAIMED
1415 }
1416 
1417 /*
1418  * Return the transmit key to use in sending a unicast frame.
1419  * If a unicast key is set we use that.  When no unicast key is set
1420  * we fall back to the default transmit key.
1421  */
1422 static __inline struct ieee80211_key *
1423 ieee80211_crypto_getucastkey(struct ieee80211vap *vap,
1424 	struct ieee80211_node *ni)
1425 {
1426 	if (IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey)) {
1427 		if (vap->iv_def_txkey == IEEE80211_KEYIX_NONE ||
1428 		    IEEE80211_KEY_UNDEFINED(&vap->iv_nw_keys[vap->iv_def_txkey]))
1429 			return NULL;
1430 		return &vap->iv_nw_keys[vap->iv_def_txkey];
1431 	} else {
1432 		return &ni->ni_ucastkey;
1433 	}
1434 }
1435 
1436 /*
1437  * Return the transmit key to use in sending a multicast frame.
1438  * Multicast traffic always uses the group key which is installed as
1439  * the default tx key.
1440  */
1441 static __inline struct ieee80211_key *
1442 ieee80211_crypto_getmcastkey(struct ieee80211vap *vap,
1443 	struct ieee80211_node *ni)
1444 {
1445 	if (vap->iv_def_txkey == IEEE80211_KEYIX_NONE ||
1446 	    IEEE80211_KEY_UNDEFINED(&vap->iv_nw_keys[vap->iv_def_txkey]))
1447 		return NULL;
1448 	return &vap->iv_nw_keys[vap->iv_def_txkey];
1449 }
1450 
1451 /*
1452  * Encapsulate an outbound data frame.  The mbuf chain is updated.
1453  * If an error is encountered NULL is returned.  The caller is required
1454  * to provide a node reference and pullup the ethernet header in the
1455  * first mbuf.
1456  *
1457  * NB: Packet is assumed to be processed by ieee80211_classify which
1458  *     marked EAPOL frames w/ M_EAPOL.
1459  */
1460 struct mbuf *
1461 ieee80211_encap(struct ieee80211vap *vap, struct ieee80211_node *ni,
1462     struct mbuf *m)
1463 {
1464 #define	WH4(wh)	((struct ieee80211_frame_addr4 *)(wh))
1465 #define MC01(mc)	((struct ieee80211_meshcntl_ae01 *)mc)
1466 	struct ieee80211com *ic = ni->ni_ic;
1467 #ifdef IEEE80211_SUPPORT_MESH
1468 	struct ieee80211_mesh_state *ms = vap->iv_mesh;
1469 	struct ieee80211_meshcntl_ae10 *mc;
1470 	struct ieee80211_mesh_route *rt = NULL;
1471 	int dir = -1;
1472 #endif
1473 	struct ether_header eh;
1474 	struct ieee80211_frame *wh;
1475 	struct ieee80211_key *key;
1476 	struct llc *llc;
1477 	int hdrsize, hdrspace, datalen, addqos, txfrag, is4addr, is_mcast;
1478 	ieee80211_seq seqno;
1479 	int meshhdrsize, meshae;
1480 	uint8_t *qos;
1481 	int is_amsdu = 0;
1482 
1483 	IEEE80211_TX_LOCK_ASSERT(ic);
1484 
1485 	is_mcast = !! (m->m_flags & (M_MCAST | M_BCAST));
1486 
1487 	/*
1488 	 * Copy existing Ethernet header to a safe place.  The
1489 	 * rest of the code assumes it's ok to strip it when
1490 	 * reorganizing state for the final encapsulation.
1491 	 */
1492 	KASSERT(m->m_len >= sizeof(eh), ("no ethernet header!"));
1493 	ETHER_HEADER_COPY(&eh, mtod(m, caddr_t));
1494 
1495 	/*
1496 	 * Insure space for additional headers.  First identify
1497 	 * transmit key to use in calculating any buffer adjustments
1498 	 * required.  This is also used below to do privacy
1499 	 * encapsulation work.  Then calculate the 802.11 header
1500 	 * size and any padding required by the driver.
1501 	 *
1502 	 * Note key may be NULL if we fall back to the default
1503 	 * transmit key and that is not set.  In that case the
1504 	 * buffer may not be expanded as needed by the cipher
1505 	 * routines, but they will/should discard it.
1506 	 */
1507 	if (vap->iv_flags & IEEE80211_F_PRIVACY) {
1508 		if (vap->iv_opmode == IEEE80211_M_STA ||
1509 		    !IEEE80211_IS_MULTICAST(eh.ether_dhost) ||
1510 		    (vap->iv_opmode == IEEE80211_M_WDS &&
1511 		     (vap->iv_flags_ext & IEEE80211_FEXT_WDSLEGACY))) {
1512 			key = ieee80211_crypto_getucastkey(vap, ni);
1513 		} else if ((vap->iv_opmode == IEEE80211_M_WDS) &&
1514 		    (! (vap->iv_flags_ext & IEEE80211_FEXT_WDSLEGACY))) {
1515 			/*
1516 			 * Use ucastkey for DWDS transmit nodes, multicast
1517 			 * or otherwise.
1518 			 *
1519 			 * This is required to ensure that multicast frames
1520 			 * from a DWDS AP to a DWDS STA is encrypted with
1521 			 * a key that can actually work.
1522 			 *
1523 			 * There's no default key for multicast traffic
1524 			 * on a DWDS WDS VAP node (note NOT the DWDS enabled
1525 			 * AP VAP, the dynamically created per-STA WDS node)
1526 			 * so encap fails and transmit fails.
1527 			 */
1528 			key = ieee80211_crypto_getucastkey(vap, ni);
1529 		} else {
1530 			key = ieee80211_crypto_getmcastkey(vap, ni);
1531 		}
1532 		if (key == NULL && (m->m_flags & M_EAPOL) == 0) {
1533 			IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_CRYPTO,
1534 			    eh.ether_dhost,
1535 			    "no default transmit key (%s) deftxkey %u",
1536 			    __func__, vap->iv_def_txkey);
1537 			vap->iv_stats.is_tx_nodefkey++;
1538 			goto bad;
1539 		}
1540 	} else
1541 		key = NULL;
1542 	/*
1543 	 * XXX Some ap's don't handle QoS-encapsulated EAPOL
1544 	 * frames so suppress use.  This may be an issue if other
1545 	 * ap's require all data frames to be QoS-encapsulated
1546 	 * once negotiated in which case we'll need to make this
1547 	 * configurable.
1548 	 *
1549 	 * Don't send multicast QoS frames.
1550 	 * Technically multicast frames can be QoS if all stations in the
1551 	 * BSS are also QoS.
1552 	 *
1553 	 * NB: mesh data frames are QoS, including multicast frames.
1554 	 */
1555 	addqos =
1556 	    (((is_mcast == 0) && (ni->ni_flags &
1557 	     (IEEE80211_NODE_QOS|IEEE80211_NODE_HT))) ||
1558 	    (vap->iv_opmode == IEEE80211_M_MBSS)) &&
1559 	    (m->m_flags & M_EAPOL) == 0;
1560 
1561 	if (addqos)
1562 		hdrsize = sizeof(struct ieee80211_qosframe);
1563 	else
1564 		hdrsize = sizeof(struct ieee80211_frame);
1565 #ifdef IEEE80211_SUPPORT_MESH
1566 	if (vap->iv_opmode == IEEE80211_M_MBSS) {
1567 		/*
1568 		 * Mesh data frames are encapsulated according to the
1569 		 * rules of Section 11B.8.5 (p.139 of D3.0 spec).
1570 		 * o Group Addressed data (aka multicast) originating
1571 		 *   at the local sta are sent w/ 3-address format and
1572 		 *   address extension mode 00
1573 		 * o Individually Addressed data (aka unicast) originating
1574 		 *   at the local sta are sent w/ 4-address format and
1575 		 *   address extension mode 00
1576 		 * o Group Addressed data forwarded from a non-mesh sta are
1577 		 *   sent w/ 3-address format and address extension mode 01
1578 		 * o Individually Address data from another sta are sent
1579 		 *   w/ 4-address format and address extension mode 10
1580 		 */
1581 		is4addr = 0;		/* NB: don't use, disable */
1582 		if (!IEEE80211_IS_MULTICAST(eh.ether_dhost)) {
1583 			rt = ieee80211_mesh_rt_find(vap, eh.ether_dhost);
1584 			KASSERT(rt != NULL, ("route is NULL"));
1585 			dir = IEEE80211_FC1_DIR_DSTODS;
1586 			hdrsize += IEEE80211_ADDR_LEN;
1587 			if (rt->rt_flags & IEEE80211_MESHRT_FLAGS_PROXY) {
1588 				if (IEEE80211_ADDR_EQ(rt->rt_mesh_gate,
1589 				    vap->iv_myaddr)) {
1590 					IEEE80211_NOTE_MAC(vap,
1591 					    IEEE80211_MSG_MESH,
1592 					    eh.ether_dhost,
1593 					    "%s", "trying to send to ourself");
1594 					goto bad;
1595 				}
1596 				meshae = IEEE80211_MESH_AE_10;
1597 				meshhdrsize =
1598 				    sizeof(struct ieee80211_meshcntl_ae10);
1599 			} else {
1600 				meshae = IEEE80211_MESH_AE_00;
1601 				meshhdrsize =
1602 				    sizeof(struct ieee80211_meshcntl);
1603 			}
1604 		} else {
1605 			dir = IEEE80211_FC1_DIR_FROMDS;
1606 			if (!IEEE80211_ADDR_EQ(eh.ether_shost, vap->iv_myaddr)) {
1607 				/* proxy group */
1608 				meshae = IEEE80211_MESH_AE_01;
1609 				meshhdrsize =
1610 				    sizeof(struct ieee80211_meshcntl_ae01);
1611 			} else {
1612 				/* group */
1613 				meshae = IEEE80211_MESH_AE_00;
1614 				meshhdrsize = sizeof(struct ieee80211_meshcntl);
1615 			}
1616 		}
1617 	} else {
1618 #endif
1619 		/*
1620 		 * 4-address frames need to be generated for:
1621 		 * o packets sent through a WDS vap (IEEE80211_M_WDS)
1622 		 * o packets sent through a vap marked for relaying
1623 		 *   (e.g. a station operating with dynamic WDS)
1624 		 */
1625 		is4addr = vap->iv_opmode == IEEE80211_M_WDS ||
1626 		    ((vap->iv_flags_ext & IEEE80211_FEXT_4ADDR) &&
1627 		     !IEEE80211_ADDR_EQ(eh.ether_shost, vap->iv_myaddr));
1628 		if (is4addr)
1629 			hdrsize += IEEE80211_ADDR_LEN;
1630 		meshhdrsize = meshae = 0;
1631 #ifdef IEEE80211_SUPPORT_MESH
1632 	}
1633 #endif
1634 	/*
1635 	 * Honor driver DATAPAD requirement.
1636 	 */
1637 	if (ic->ic_flags & IEEE80211_F_DATAPAD)
1638 		hdrspace = roundup(hdrsize, sizeof(uint32_t));
1639 	else
1640 		hdrspace = hdrsize;
1641 
1642 	if (__predict_true((m->m_flags & M_FF) == 0)) {
1643 		/*
1644 		 * Normal frame.
1645 		 */
1646 		m = ieee80211_mbuf_adjust(vap, hdrspace + meshhdrsize, key, m);
1647 		if (m == NULL) {
1648 			/* NB: ieee80211_mbuf_adjust handles msgs+statistics */
1649 			goto bad;
1650 		}
1651 		/* NB: this could be optimized 'cuz of ieee80211_mbuf_adjust */
1652 		m_adj(m, sizeof(struct ether_header) - sizeof(struct llc));
1653 		llc = mtod(m, struct llc *);
1654 		llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
1655 		llc->llc_control = LLC_UI;
1656 		llc->llc_snap.org_code[0] = 0;
1657 		llc->llc_snap.org_code[1] = 0;
1658 		llc->llc_snap.org_code[2] = 0;
1659 		llc->llc_snap.ether_type = eh.ether_type;
1660 	} else {
1661 #ifdef IEEE80211_SUPPORT_SUPERG
1662 		/*
1663 		 * Aggregated frame.  Check if it's for AMSDU or FF.
1664 		 *
1665 		 * XXX TODO: IEEE80211_NODE_AMSDU* isn't implemented
1666 		 * anywhere for some reason.  But, since 11n requires
1667 		 * AMSDU RX, we can just assume "11n" == "AMSDU".
1668 		 */
1669 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SUPERG, "%s: called; M_FF\n", __func__);
1670 		if (ieee80211_amsdu_tx_ok(ni)) {
1671 			m = ieee80211_amsdu_encap(vap, m, hdrspace + meshhdrsize, key);
1672 			is_amsdu = 1;
1673 		} else {
1674 			m = ieee80211_ff_encap(vap, m, hdrspace + meshhdrsize, key);
1675 		}
1676 		if (m == NULL)
1677 #endif
1678 			goto bad;
1679 	}
1680 	datalen = m->m_pkthdr.len;		/* NB: w/o 802.11 header */
1681 
1682 	M_PREPEND(m, hdrspace + meshhdrsize, M_NOWAIT);
1683 	if (m == NULL) {
1684 		vap->iv_stats.is_tx_nobuf++;
1685 		goto bad;
1686 	}
1687 	wh = mtod(m, struct ieee80211_frame *);
1688 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_DATA;
1689 	*(uint16_t *)wh->i_dur = 0;
1690 	qos = NULL;	/* NB: quiet compiler */
1691 	if (is4addr) {
1692 		wh->i_fc[1] = IEEE80211_FC1_DIR_DSTODS;
1693 		IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_macaddr);
1694 		IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
1695 		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost);
1696 		IEEE80211_ADDR_COPY(WH4(wh)->i_addr4, eh.ether_shost);
1697 	} else switch (vap->iv_opmode) {
1698 	case IEEE80211_M_STA:
1699 		wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
1700 		IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_bssid);
1701 		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
1702 		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost);
1703 		break;
1704 	case IEEE80211_M_IBSS:
1705 	case IEEE80211_M_AHDEMO:
1706 		wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1707 		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
1708 		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
1709 		/*
1710 		 * NB: always use the bssid from iv_bss as the
1711 		 *     neighbor's may be stale after an ibss merge
1712 		 */
1713 		IEEE80211_ADDR_COPY(wh->i_addr3, vap->iv_bss->ni_bssid);
1714 		break;
1715 	case IEEE80211_M_HOSTAP:
1716 		wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
1717 		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
1718 		IEEE80211_ADDR_COPY(wh->i_addr2, ni->ni_bssid);
1719 		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_shost);
1720 		break;
1721 #ifdef IEEE80211_SUPPORT_MESH
1722 	case IEEE80211_M_MBSS:
1723 		/* NB: offset by hdrspace to deal with DATAPAD */
1724 		mc = (struct ieee80211_meshcntl_ae10 *)
1725 		     (mtod(m, uint8_t *) + hdrspace);
1726 		wh->i_fc[1] = dir;
1727 		switch (meshae) {
1728 		case IEEE80211_MESH_AE_00:	/* no proxy */
1729 			mc->mc_flags = 0;
1730 			if (dir == IEEE80211_FC1_DIR_DSTODS) { /* ucast */
1731 				IEEE80211_ADDR_COPY(wh->i_addr1,
1732 				    ni->ni_macaddr);
1733 				IEEE80211_ADDR_COPY(wh->i_addr2,
1734 				    vap->iv_myaddr);
1735 				IEEE80211_ADDR_COPY(wh->i_addr3,
1736 				    eh.ether_dhost);
1737 				IEEE80211_ADDR_COPY(WH4(wh)->i_addr4,
1738 				    eh.ether_shost);
1739 				qos =((struct ieee80211_qosframe_addr4 *)
1740 				    wh)->i_qos;
1741 			} else if (dir == IEEE80211_FC1_DIR_FROMDS) {
1742 				 /* mcast */
1743 				IEEE80211_ADDR_COPY(wh->i_addr1,
1744 				    eh.ether_dhost);
1745 				IEEE80211_ADDR_COPY(wh->i_addr2,
1746 				    vap->iv_myaddr);
1747 				IEEE80211_ADDR_COPY(wh->i_addr3,
1748 				    eh.ether_shost);
1749 				qos = ((struct ieee80211_qosframe *)
1750 				    wh)->i_qos;
1751 			}
1752 			break;
1753 		case IEEE80211_MESH_AE_01:	/* mcast, proxy */
1754 			wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
1755 			IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
1756 			IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
1757 			IEEE80211_ADDR_COPY(wh->i_addr3, vap->iv_myaddr);
1758 			mc->mc_flags = 1;
1759 			IEEE80211_ADDR_COPY(MC01(mc)->mc_addr4,
1760 			    eh.ether_shost);
1761 			qos = ((struct ieee80211_qosframe *) wh)->i_qos;
1762 			break;
1763 		case IEEE80211_MESH_AE_10:	/* ucast, proxy */
1764 			KASSERT(rt != NULL, ("route is NULL"));
1765 			IEEE80211_ADDR_COPY(wh->i_addr1, rt->rt_nexthop);
1766 			IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
1767 			IEEE80211_ADDR_COPY(wh->i_addr3, rt->rt_mesh_gate);
1768 			IEEE80211_ADDR_COPY(WH4(wh)->i_addr4, vap->iv_myaddr);
1769 			mc->mc_flags = IEEE80211_MESH_AE_10;
1770 			IEEE80211_ADDR_COPY(mc->mc_addr5, eh.ether_dhost);
1771 			IEEE80211_ADDR_COPY(mc->mc_addr6, eh.ether_shost);
1772 			qos = ((struct ieee80211_qosframe_addr4 *) wh)->i_qos;
1773 			break;
1774 		default:
1775 			KASSERT(0, ("meshae %d", meshae));
1776 			break;
1777 		}
1778 		mc->mc_ttl = ms->ms_ttl;
1779 		ms->ms_seq++;
1780 		le32enc(mc->mc_seq, ms->ms_seq);
1781 		break;
1782 #endif
1783 	case IEEE80211_M_WDS:		/* NB: is4addr should always be true */
1784 	default:
1785 		goto bad;
1786 	}
1787 	if (m->m_flags & M_MORE_DATA)
1788 		wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
1789 	if (addqos) {
1790 		int ac, tid;
1791 
1792 		if (is4addr) {
1793 			qos = ((struct ieee80211_qosframe_addr4 *) wh)->i_qos;
1794 		/* NB: mesh case handled earlier */
1795 		} else if (vap->iv_opmode != IEEE80211_M_MBSS)
1796 			qos = ((struct ieee80211_qosframe *) wh)->i_qos;
1797 		ac = M_WME_GETAC(m);
1798 		/* map from access class/queue to 11e header priorty value */
1799 		tid = WME_AC_TO_TID(ac);
1800 		qos[0] = tid & IEEE80211_QOS_TID;
1801 		if (ic->ic_wme.wme_wmeChanParams.cap_wmeParams[ac].wmep_noackPolicy)
1802 			qos[0] |= IEEE80211_QOS_ACKPOLICY_NOACK;
1803 #ifdef IEEE80211_SUPPORT_MESH
1804 		if (vap->iv_opmode == IEEE80211_M_MBSS)
1805 			qos[1] = IEEE80211_QOS_MC;
1806 		else
1807 #endif
1808 			qos[1] = 0;
1809 		wh->i_fc[0] |= IEEE80211_FC0_SUBTYPE_QOS;
1810 
1811 		/*
1812 		 * If this is an A-MSDU then ensure we set the
1813 		 * relevant field.
1814 		 */
1815 		if (is_amsdu)
1816 			qos[0] |= IEEE80211_QOS_AMSDU;
1817 
1818 		/*
1819 		 * XXX TODO TX lock is needed for atomic updates of sequence
1820 		 * numbers.  If the driver does it, then don't do it here;
1821 		 * and we don't need the TX lock held.
1822 		 */
1823 		if ((m->m_flags & M_AMPDU_MPDU) == 0) {
1824 			/*
1825 			 * 802.11-2012 9.3.2.10 -
1826 			 *
1827 			 * If this is a multicast frame then we need
1828 			 * to ensure that the sequence number comes from
1829 			 * a separate seqno space and not the TID space.
1830 			 *
1831 			 * Otherwise multicast frames may actually cause
1832 			 * holes in the TX blockack window space and
1833 			 * upset various things.
1834 			 */
1835 			if (IEEE80211_IS_MULTICAST(wh->i_addr1))
1836 				seqno = ni->ni_txseqs[IEEE80211_NONQOS_TID]++;
1837 			else
1838 				seqno = ni->ni_txseqs[tid]++;
1839 
1840 			/*
1841 			 * NB: don't assign a sequence # to potential
1842 			 * aggregates; we expect this happens at the
1843 			 * point the frame comes off any aggregation q
1844 			 * as otherwise we may introduce holes in the
1845 			 * BA sequence space and/or make window accouting
1846 			 * more difficult.
1847 			 *
1848 			 * XXX may want to control this with a driver
1849 			 * capability; this may also change when we pull
1850 			 * aggregation up into net80211
1851 			 */
1852 			*(uint16_t *)wh->i_seq =
1853 			    htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT);
1854 			M_SEQNO_SET(m, seqno);
1855 		} else {
1856 			/* NB: zero out i_seq field (for s/w encryption etc) */
1857 			*(uint16_t *)wh->i_seq = 0;
1858 		}
1859 	} else {
1860 		/*
1861 		 * XXX TODO TX lock is needed for atomic updates of sequence
1862 		 * numbers.  If the driver does it, then don't do it here;
1863 		 * and we don't need the TX lock held.
1864 		 */
1865 		seqno = ni->ni_txseqs[IEEE80211_NONQOS_TID]++;
1866 		*(uint16_t *)wh->i_seq =
1867 		    htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT);
1868 		M_SEQNO_SET(m, seqno);
1869 
1870 		/*
1871 		 * XXX TODO: we shouldn't allow EAPOL, etc that would
1872 		 * be forced to be non-QoS traffic to be A-MSDU encapsulated.
1873 		 */
1874 		if (is_amsdu)
1875 			printf("%s: XXX ERROR: is_amsdu set; not QoS!\n",
1876 			    __func__);
1877 	}
1878 
1879 	/*
1880 	 * Check if xmit fragmentation is required.
1881 	 *
1882 	 * If the hardware does fragmentation offload, then don't bother
1883 	 * doing it here.
1884 	 */
1885 	if (IEEE80211_CONF_FRAG_OFFLOAD(ic))
1886 		txfrag = 0;
1887 	else
1888 		txfrag = (m->m_pkthdr.len > vap->iv_fragthreshold &&
1889 		    !IEEE80211_IS_MULTICAST(wh->i_addr1) &&
1890 		    (vap->iv_caps & IEEE80211_C_TXFRAG) &&
1891 		    (m->m_flags & (M_FF | M_AMPDU_MPDU)) == 0);
1892 
1893 	if (key != NULL) {
1894 		/*
1895 		 * IEEE 802.1X: send EAPOL frames always in the clear.
1896 		 * WPA/WPA2: encrypt EAPOL keys when pairwise keys are set.
1897 		 */
1898 		if ((m->m_flags & M_EAPOL) == 0 ||
1899 		    ((vap->iv_flags & IEEE80211_F_WPA) &&
1900 		     (vap->iv_opmode == IEEE80211_M_STA ?
1901 		      !IEEE80211_KEY_UNDEFINED(key) :
1902 		      !IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey)))) {
1903 			wh->i_fc[1] |= IEEE80211_FC1_PROTECTED;
1904 			if (!ieee80211_crypto_enmic(vap, key, m, txfrag)) {
1905 				IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_OUTPUT,
1906 				    eh.ether_dhost,
1907 				    "%s", "enmic failed, discard frame");
1908 				vap->iv_stats.is_crypto_enmicfail++;
1909 				goto bad;
1910 			}
1911 		}
1912 	}
1913 	if (txfrag && !ieee80211_fragment(vap, m, hdrsize,
1914 	    key != NULL ? key->wk_cipher->ic_header : 0, vap->iv_fragthreshold))
1915 		goto bad;
1916 
1917 	m->m_flags |= M_ENCAP;		/* mark encapsulated */
1918 
1919 	IEEE80211_NODE_STAT(ni, tx_data);
1920 	if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1921 		IEEE80211_NODE_STAT(ni, tx_mcast);
1922 		m->m_flags |= M_MCAST;
1923 	} else
1924 		IEEE80211_NODE_STAT(ni, tx_ucast);
1925 	IEEE80211_NODE_STAT_ADD(ni, tx_bytes, datalen);
1926 
1927 	return m;
1928 bad:
1929 	if (m != NULL)
1930 		m_freem(m);
1931 	return NULL;
1932 #undef WH4
1933 #undef MC01
1934 }
1935 
1936 void
1937 ieee80211_free_mbuf(struct mbuf *m)
1938 {
1939 	struct mbuf *next;
1940 
1941 	if (m == NULL)
1942 		return;
1943 
1944 	do {
1945 		next = m->m_nextpkt;
1946 		m->m_nextpkt = NULL;
1947 		m_freem(m);
1948 	} while ((m = next) != NULL);
1949 }
1950 
1951 /*
1952  * Fragment the frame according to the specified mtu.
1953  * The size of the 802.11 header (w/o padding) is provided
1954  * so we don't need to recalculate it.  We create a new
1955  * mbuf for each fragment and chain it through m_nextpkt;
1956  * we might be able to optimize this by reusing the original
1957  * packet's mbufs but that is significantly more complicated.
1958  */
1959 static int
1960 ieee80211_fragment(struct ieee80211vap *vap, struct mbuf *m0,
1961 	u_int hdrsize, u_int ciphdrsize, u_int mtu)
1962 {
1963 	struct ieee80211com *ic = vap->iv_ic;
1964 	struct ieee80211_frame *wh, *whf;
1965 	struct mbuf *m, *prev;
1966 	u_int totalhdrsize, fragno, fragsize, off, remainder, payload;
1967 	u_int hdrspace;
1968 
1969 	KASSERT(m0->m_nextpkt == NULL, ("mbuf already chained?"));
1970 	KASSERT(m0->m_pkthdr.len > mtu,
1971 		("pktlen %u mtu %u", m0->m_pkthdr.len, mtu));
1972 
1973 	/*
1974 	 * Honor driver DATAPAD requirement.
1975 	 */
1976 	if (ic->ic_flags & IEEE80211_F_DATAPAD)
1977 		hdrspace = roundup(hdrsize, sizeof(uint32_t));
1978 	else
1979 		hdrspace = hdrsize;
1980 
1981 	wh = mtod(m0, struct ieee80211_frame *);
1982 	/* NB: mark the first frag; it will be propagated below */
1983 	wh->i_fc[1] |= IEEE80211_FC1_MORE_FRAG;
1984 	totalhdrsize = hdrspace + ciphdrsize;
1985 	fragno = 1;
1986 	off = mtu - ciphdrsize;
1987 	remainder = m0->m_pkthdr.len - off;
1988 	prev = m0;
1989 	do {
1990 		fragsize = MIN(totalhdrsize + remainder, mtu);
1991 		m = m_get2(fragsize, M_NOWAIT, MT_DATA, M_PKTHDR);
1992 		if (m == NULL)
1993 			goto bad;
1994 		/* leave room to prepend any cipher header */
1995 		m_align(m, fragsize - ciphdrsize);
1996 
1997 		/*
1998 		 * Form the header in the fragment.  Note that since
1999 		 * we mark the first fragment with the MORE_FRAG bit
2000 		 * it automatically is propagated to each fragment; we
2001 		 * need only clear it on the last fragment (done below).
2002 		 * NB: frag 1+ dont have Mesh Control field present.
2003 		 */
2004 		whf = mtod(m, struct ieee80211_frame *);
2005 		memcpy(whf, wh, hdrsize);
2006 #ifdef IEEE80211_SUPPORT_MESH
2007 		if (vap->iv_opmode == IEEE80211_M_MBSS)
2008 			ieee80211_getqos(wh)[1] &= ~IEEE80211_QOS_MC;
2009 #endif
2010 		*(uint16_t *)&whf->i_seq[0] |= htole16(
2011 			(fragno & IEEE80211_SEQ_FRAG_MASK) <<
2012 				IEEE80211_SEQ_FRAG_SHIFT);
2013 		fragno++;
2014 
2015 		payload = fragsize - totalhdrsize;
2016 		/* NB: destination is known to be contiguous */
2017 
2018 		m_copydata(m0, off, payload, mtod(m, uint8_t *) + hdrspace);
2019 		m->m_len = hdrspace + payload;
2020 		m->m_pkthdr.len = hdrspace + payload;
2021 		m->m_flags |= M_FRAG;
2022 
2023 		/* chain up the fragment */
2024 		prev->m_nextpkt = m;
2025 		prev = m;
2026 
2027 		/* deduct fragment just formed */
2028 		remainder -= payload;
2029 		off += payload;
2030 	} while (remainder != 0);
2031 
2032 	/* set the last fragment */
2033 	m->m_flags |= M_LASTFRAG;
2034 	whf->i_fc[1] &= ~IEEE80211_FC1_MORE_FRAG;
2035 
2036 	/* strip first mbuf now that everything has been copied */
2037 	m_adj(m0, -(m0->m_pkthdr.len - (mtu - ciphdrsize)));
2038 	m0->m_flags |= M_FIRSTFRAG | M_FRAG;
2039 
2040 	vap->iv_stats.is_tx_fragframes++;
2041 	vap->iv_stats.is_tx_frags += fragno-1;
2042 
2043 	return 1;
2044 bad:
2045 	/* reclaim fragments but leave original frame for caller to free */
2046 	ieee80211_free_mbuf(m0->m_nextpkt);
2047 	m0->m_nextpkt = NULL;
2048 	return 0;
2049 }
2050 
2051 /*
2052  * Add a supported rates element id to a frame.
2053  */
2054 uint8_t *
2055 ieee80211_add_rates(uint8_t *frm, const struct ieee80211_rateset *rs)
2056 {
2057 	int nrates;
2058 
2059 	*frm++ = IEEE80211_ELEMID_RATES;
2060 	nrates = rs->rs_nrates;
2061 	if (nrates > IEEE80211_RATE_SIZE)
2062 		nrates = IEEE80211_RATE_SIZE;
2063 	*frm++ = nrates;
2064 	memcpy(frm, rs->rs_rates, nrates);
2065 	return frm + nrates;
2066 }
2067 
2068 /*
2069  * Add an extended supported rates element id to a frame.
2070  */
2071 uint8_t *
2072 ieee80211_add_xrates(uint8_t *frm, const struct ieee80211_rateset *rs)
2073 {
2074 	/*
2075 	 * Add an extended supported rates element if operating in 11g mode.
2076 	 */
2077 	if (rs->rs_nrates > IEEE80211_RATE_SIZE) {
2078 		int nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
2079 		*frm++ = IEEE80211_ELEMID_XRATES;
2080 		*frm++ = nrates;
2081 		memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
2082 		frm += nrates;
2083 	}
2084 	return frm;
2085 }
2086 
2087 /*
2088  * Add an ssid element to a frame.
2089  */
2090 uint8_t *
2091 ieee80211_add_ssid(uint8_t *frm, const uint8_t *ssid, u_int len)
2092 {
2093 	*frm++ = IEEE80211_ELEMID_SSID;
2094 	*frm++ = len;
2095 	memcpy(frm, ssid, len);
2096 	return frm + len;
2097 }
2098 
2099 /*
2100  * Add an erp element to a frame.
2101  */
2102 static uint8_t *
2103 ieee80211_add_erp(uint8_t *frm, struct ieee80211vap *vap)
2104 {
2105 	struct ieee80211com *ic = vap->iv_ic;
2106 	uint8_t erp;
2107 
2108 	*frm++ = IEEE80211_ELEMID_ERP;
2109 	*frm++ = 1;
2110 	erp = 0;
2111 
2112 	/*
2113 	 * TODO:  This uses the global flags for now because
2114 	 * the per-VAP flags are fine for per-VAP, but don't
2115 	 * take into account which VAPs share the same channel
2116 	 * and which are on different channels.
2117 	 *
2118 	 * ERP and HT/VHT protection mode is a function of
2119 	 * how many stations are on a channel, not specifically
2120 	 * the VAP or global.  But, until we grow that status,
2121 	 * the global flag will have to do.
2122 	 */
2123 	if (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR)
2124 		erp |= IEEE80211_ERP_NON_ERP_PRESENT;
2125 
2126 	/*
2127 	 * TODO: same as above; these should be based not
2128 	 * on the vap or ic flags, but instead on a combination
2129 	 * of per-VAP and channels.
2130 	 */
2131 	if (ic->ic_flags & IEEE80211_F_USEPROT)
2132 		erp |= IEEE80211_ERP_USE_PROTECTION;
2133 	if (ic->ic_flags & IEEE80211_F_USEBARKER)
2134 		erp |= IEEE80211_ERP_LONG_PREAMBLE;
2135 	*frm++ = erp;
2136 	return frm;
2137 }
2138 
2139 /*
2140  * Add a CFParams element to a frame.
2141  */
2142 static uint8_t *
2143 ieee80211_add_cfparms(uint8_t *frm, struct ieee80211com *ic)
2144 {
2145 #define	ADDSHORT(frm, v) do {	\
2146 	le16enc(frm, v);	\
2147 	frm += 2;		\
2148 } while (0)
2149 	*frm++ = IEEE80211_ELEMID_CFPARMS;
2150 	*frm++ = 6;
2151 	*frm++ = 0;		/* CFP count */
2152 	*frm++ = 2;		/* CFP period */
2153 	ADDSHORT(frm, 0);	/* CFP MaxDuration (TU) */
2154 	ADDSHORT(frm, 0);	/* CFP CurRemaining (TU) */
2155 	return frm;
2156 #undef ADDSHORT
2157 }
2158 
2159 static __inline uint8_t *
2160 add_appie(uint8_t *frm, const struct ieee80211_appie *ie)
2161 {
2162 	memcpy(frm, ie->ie_data, ie->ie_len);
2163 	return frm + ie->ie_len;
2164 }
2165 
2166 static __inline uint8_t *
2167 add_ie(uint8_t *frm, const uint8_t *ie)
2168 {
2169 	memcpy(frm, ie, 2 + ie[1]);
2170 	return frm + 2 + ie[1];
2171 }
2172 
2173 #define	WME_OUI_BYTES		0x00, 0x50, 0xf2
2174 /*
2175  * Add a WME information element to a frame.
2176  */
2177 uint8_t *
2178 ieee80211_add_wme_info(uint8_t *frm, struct ieee80211_wme_state *wme,
2179     struct ieee80211_node *ni)
2180 {
2181 	static const uint8_t oui[4] = { WME_OUI_BYTES, WME_OUI_TYPE };
2182 	struct ieee80211vap *vap = ni->ni_vap;
2183 
2184 	*frm++ = IEEE80211_ELEMID_VENDOR;
2185 	*frm++ = sizeof(struct ieee80211_wme_info) - 2;
2186 	memcpy(frm, oui, sizeof(oui));
2187 	frm += sizeof(oui);
2188 	*frm++ = WME_INFO_OUI_SUBTYPE;
2189 	*frm++ = WME_VERSION;
2190 
2191 	/* QoS info field depends upon operating mode */
2192 	switch (vap->iv_opmode) {
2193 	case IEEE80211_M_HOSTAP:
2194 		*frm = wme->wme_bssChanParams.cap_info;
2195 		if (vap->iv_flags_ext & IEEE80211_FEXT_UAPSD)
2196 			*frm |= WME_CAPINFO_UAPSD_EN;
2197 		frm++;
2198 		break;
2199 	case IEEE80211_M_STA:
2200 		/*
2201 		 * NB: UAPSD drivers must set this up in their
2202 		 * VAP creation method.
2203 		 */
2204 		*frm++ = vap->iv_uapsdinfo;
2205 		break;
2206 	default:
2207 		*frm++ = 0;
2208 		break;
2209 	}
2210 
2211 	return frm;
2212 }
2213 
2214 /*
2215  * Add a WME parameters element to a frame.
2216  */
2217 static uint8_t *
2218 ieee80211_add_wme_param(uint8_t *frm, struct ieee80211_wme_state *wme,
2219     int uapsd_enable)
2220 {
2221 #define	SM(_v, _f)	(((_v) << _f##_S) & _f)
2222 #define	ADDSHORT(frm, v) do {	\
2223 	le16enc(frm, v);	\
2224 	frm += 2;		\
2225 } while (0)
2226 	/* NB: this works 'cuz a param has an info at the front */
2227 	static const struct ieee80211_wme_info param = {
2228 		.wme_id		= IEEE80211_ELEMID_VENDOR,
2229 		.wme_len	= sizeof(struct ieee80211_wme_param) - 2,
2230 		.wme_oui	= { WME_OUI_BYTES },
2231 		.wme_type	= WME_OUI_TYPE,
2232 		.wme_subtype	= WME_PARAM_OUI_SUBTYPE,
2233 		.wme_version	= WME_VERSION,
2234 	};
2235 	int i;
2236 
2237 	memcpy(frm, &param, sizeof(param));
2238 	frm += __offsetof(struct ieee80211_wme_info, wme_info);
2239 	*frm = wme->wme_bssChanParams.cap_info;	/* AC info */
2240 	if (uapsd_enable)
2241 		*frm |= WME_CAPINFO_UAPSD_EN;
2242 	frm++;
2243 	*frm++ = 0;					/* reserved field */
2244 	/* XXX TODO - U-APSD bits - SP, flags below */
2245 	for (i = 0; i < WME_NUM_AC; i++) {
2246 		const struct wmeParams *ac =
2247 		       &wme->wme_bssChanParams.cap_wmeParams[i];
2248 		*frm++ = SM(i, WME_PARAM_ACI)
2249 		       | SM(ac->wmep_acm, WME_PARAM_ACM)
2250 		       | SM(ac->wmep_aifsn, WME_PARAM_AIFSN)
2251 		       ;
2252 		*frm++ = SM(ac->wmep_logcwmax, WME_PARAM_LOGCWMAX)
2253 		       | SM(ac->wmep_logcwmin, WME_PARAM_LOGCWMIN)
2254 		       ;
2255 		ADDSHORT(frm, ac->wmep_txopLimit);
2256 	}
2257 	return frm;
2258 #undef SM
2259 #undef ADDSHORT
2260 }
2261 #undef WME_OUI_BYTES
2262 
2263 /*
2264  * Add an 11h Power Constraint element to a frame.
2265  */
2266 static uint8_t *
2267 ieee80211_add_powerconstraint(uint8_t *frm, struct ieee80211vap *vap)
2268 {
2269 	const struct ieee80211_channel *c = vap->iv_bss->ni_chan;
2270 	/* XXX per-vap tx power limit? */
2271 	int8_t limit = vap->iv_ic->ic_txpowlimit / 2;
2272 
2273 	frm[0] = IEEE80211_ELEMID_PWRCNSTR;
2274 	frm[1] = 1;
2275 	frm[2] = c->ic_maxregpower > limit ?  c->ic_maxregpower - limit : 0;
2276 	return frm + 3;
2277 }
2278 
2279 /*
2280  * Add an 11h Power Capability element to a frame.
2281  */
2282 static uint8_t *
2283 ieee80211_add_powercapability(uint8_t *frm, const struct ieee80211_channel *c)
2284 {
2285 	frm[0] = IEEE80211_ELEMID_PWRCAP;
2286 	frm[1] = 2;
2287 	frm[2] = c->ic_minpower;
2288 	frm[3] = c->ic_maxpower;
2289 	return frm + 4;
2290 }
2291 
2292 /*
2293  * Add an 11h Supported Channels element to a frame.
2294  */
2295 static uint8_t *
2296 ieee80211_add_supportedchannels(uint8_t *frm, struct ieee80211com *ic)
2297 {
2298 	static const int ielen = 26;
2299 
2300 	frm[0] = IEEE80211_ELEMID_SUPPCHAN;
2301 	frm[1] = ielen;
2302 	/* XXX not correct */
2303 	memcpy(frm+2, ic->ic_chan_avail, ielen);
2304 	return frm + 2 + ielen;
2305 }
2306 
2307 /*
2308  * Add an 11h Quiet time element to a frame.
2309  */
2310 static uint8_t *
2311 ieee80211_add_quiet(uint8_t *frm, struct ieee80211vap *vap, int update)
2312 {
2313 	struct ieee80211_quiet_ie *quiet = (struct ieee80211_quiet_ie *) frm;
2314 
2315 	quiet->quiet_ie = IEEE80211_ELEMID_QUIET;
2316 	quiet->len = 6;
2317 
2318 	/*
2319 	 * Only update every beacon interval - otherwise probe responses
2320 	 * would update the quiet count value.
2321 	 */
2322 	if (update) {
2323 		if (vap->iv_quiet_count_value == 1)
2324 			vap->iv_quiet_count_value = vap->iv_quiet_count;
2325 		else if (vap->iv_quiet_count_value > 1)
2326 			vap->iv_quiet_count_value--;
2327 	}
2328 
2329 	if (vap->iv_quiet_count_value == 0) {
2330 		/* value 0 is reserved as per 802.11h standerd */
2331 		vap->iv_quiet_count_value = 1;
2332 	}
2333 
2334 	quiet->tbttcount = vap->iv_quiet_count_value;
2335 	quiet->period = vap->iv_quiet_period;
2336 	quiet->duration = htole16(vap->iv_quiet_duration);
2337 	quiet->offset = htole16(vap->iv_quiet_offset);
2338 	return frm + sizeof(*quiet);
2339 }
2340 
2341 /*
2342  * Add an 11h Channel Switch Announcement element to a frame.
2343  * Note that we use the per-vap CSA count to adjust the global
2344  * counter so we can use this routine to form probe response
2345  * frames and get the current count.
2346  */
2347 static uint8_t *
2348 ieee80211_add_csa(uint8_t *frm, struct ieee80211vap *vap)
2349 {
2350 	struct ieee80211com *ic = vap->iv_ic;
2351 	struct ieee80211_csa_ie *csa = (struct ieee80211_csa_ie *) frm;
2352 
2353 	csa->csa_ie = IEEE80211_ELEMID_CSA;
2354 	csa->csa_len = 3;
2355 	csa->csa_mode = 1;		/* XXX force quiet on channel */
2356 	csa->csa_newchan = ieee80211_chan2ieee(ic, ic->ic_csa_newchan);
2357 	csa->csa_count = ic->ic_csa_count - vap->iv_csa_count;
2358 	return frm + sizeof(*csa);
2359 }
2360 
2361 /*
2362  * Add an 11h country information element to a frame.
2363  */
2364 static uint8_t *
2365 ieee80211_add_countryie(uint8_t *frm, struct ieee80211com *ic)
2366 {
2367 
2368 	if (ic->ic_countryie == NULL ||
2369 	    ic->ic_countryie_chan != ic->ic_bsschan) {
2370 		/*
2371 		 * Handle lazy construction of ie.  This is done on
2372 		 * first use and after a channel change that requires
2373 		 * re-calculation.
2374 		 */
2375 		if (ic->ic_countryie != NULL)
2376 			IEEE80211_FREE(ic->ic_countryie, M_80211_NODE_IE);
2377 		ic->ic_countryie = ieee80211_alloc_countryie(ic);
2378 		if (ic->ic_countryie == NULL)
2379 			return frm;
2380 		ic->ic_countryie_chan = ic->ic_bsschan;
2381 	}
2382 	return add_appie(frm, ic->ic_countryie);
2383 }
2384 
2385 uint8_t *
2386 ieee80211_add_wpa(uint8_t *frm, const struct ieee80211vap *vap)
2387 {
2388 	if (vap->iv_flags & IEEE80211_F_WPA1 && vap->iv_wpa_ie != NULL)
2389 		return (add_ie(frm, vap->iv_wpa_ie));
2390 	else {
2391 		/* XXX else complain? */
2392 		return (frm);
2393 	}
2394 }
2395 
2396 uint8_t *
2397 ieee80211_add_rsn(uint8_t *frm, const struct ieee80211vap *vap)
2398 {
2399 	if (vap->iv_flags & IEEE80211_F_WPA2 && vap->iv_rsn_ie != NULL)
2400 		return (add_ie(frm, vap->iv_rsn_ie));
2401 	else {
2402 		/* XXX else complain? */
2403 		return (frm);
2404 	}
2405 }
2406 
2407 uint8_t *
2408 ieee80211_add_qos(uint8_t *frm, const struct ieee80211_node *ni)
2409 {
2410 	if (ni->ni_flags & IEEE80211_NODE_QOS) {
2411 		*frm++ = IEEE80211_ELEMID_QOS;
2412 		*frm++ = 1;
2413 		*frm++ = 0;
2414 	}
2415 
2416 	return (frm);
2417 }
2418 
2419 /*
2420  * Send a probe request frame with the specified ssid
2421  * and any optional information element data.
2422  */
2423 int
2424 ieee80211_send_probereq(struct ieee80211_node *ni,
2425 	const uint8_t sa[IEEE80211_ADDR_LEN],
2426 	const uint8_t da[IEEE80211_ADDR_LEN],
2427 	const uint8_t bssid[IEEE80211_ADDR_LEN],
2428 	const uint8_t *ssid, size_t ssidlen)
2429 {
2430 	struct ieee80211vap *vap = ni->ni_vap;
2431 	struct ieee80211com *ic = ni->ni_ic;
2432 	struct ieee80211_node *bss;
2433 	const struct ieee80211_txparam *tp;
2434 	struct ieee80211_bpf_params params;
2435 	const struct ieee80211_rateset *rs;
2436 	struct mbuf *m;
2437 	uint8_t *frm;
2438 	int ret;
2439 
2440 	bss = ieee80211_ref_node(vap->iv_bss);
2441 
2442 	if (vap->iv_state == IEEE80211_S_CAC) {
2443 		IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT, ni,
2444 		    "block %s frame in CAC state", "probe request");
2445 		vap->iv_stats.is_tx_badstate++;
2446 		ieee80211_free_node(bss);
2447 		return EIO;		/* XXX */
2448 	}
2449 
2450 	/*
2451 	 * Hold a reference on the node so it doesn't go away until after
2452 	 * the xmit is complete all the way in the driver.  On error we
2453 	 * will remove our reference.
2454 	 */
2455 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2456 		"ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
2457 		__func__, __LINE__,
2458 		ni, ether_sprintf(ni->ni_macaddr),
2459 		ieee80211_node_refcnt(ni)+1);
2460 	ieee80211_ref_node(ni);
2461 
2462 	/*
2463 	 * prreq frame format
2464 	 *	[tlv] ssid
2465 	 *	[tlv] supported rates
2466 	 *	[tlv] RSN (optional)
2467 	 *	[tlv] extended supported rates
2468 	 *	[tlv] HT cap (optional)
2469 	 *	[tlv] VHT cap (optional)
2470 	 *	[tlv] WPA (optional)
2471 	 *	[tlv] user-specified ie's
2472 	 */
2473 	m = ieee80211_getmgtframe(&frm,
2474 		 ic->ic_headroom + sizeof(struct ieee80211_frame),
2475 	       	 2 + IEEE80211_NWID_LEN
2476 	       + 2 + IEEE80211_RATE_SIZE
2477 	       + sizeof(struct ieee80211_ie_htcap)
2478 	       + sizeof(struct ieee80211_ie_vhtcap)
2479 	       + sizeof(struct ieee80211_ie_htinfo)	/* XXX not needed? */
2480 	       + sizeof(struct ieee80211_ie_wpa)
2481 	       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
2482 	       + sizeof(struct ieee80211_ie_wpa)
2483 	       + (vap->iv_appie_probereq != NULL ?
2484 		   vap->iv_appie_probereq->ie_len : 0)
2485 	);
2486 	if (m == NULL) {
2487 		vap->iv_stats.is_tx_nobuf++;
2488 		ieee80211_free_node(ni);
2489 		ieee80211_free_node(bss);
2490 		return ENOMEM;
2491 	}
2492 
2493 	frm = ieee80211_add_ssid(frm, ssid, ssidlen);
2494 	rs = ieee80211_get_suprates(ic, ic->ic_curchan);
2495 	frm = ieee80211_add_rates(frm, rs);
2496 	frm = ieee80211_add_rsn(frm, vap);
2497 	frm = ieee80211_add_xrates(frm, rs);
2498 
2499 	/*
2500 	 * Note: we can't use bss; we don't have one yet.
2501 	 *
2502 	 * So, we should announce our capabilities
2503 	 * in this channel mode (2g/5g), not the
2504 	 * channel details itself.
2505 	 */
2506 	if ((vap->iv_opmode == IEEE80211_M_IBSS) &&
2507 	    (vap->iv_flags_ht & IEEE80211_FHT_HT)) {
2508 		struct ieee80211_channel *c;
2509 
2510 		/*
2511 		 * Get the HT channel that we should try upgrading to.
2512 		 * If we can do 40MHz then this'll upgrade it appropriately.
2513 		 */
2514 		c = ieee80211_ht_adjust_channel(ic, ic->ic_curchan,
2515 		    vap->iv_flags_ht);
2516 		frm = ieee80211_add_htcap_ch(frm, vap, c);
2517 	}
2518 
2519 	/*
2520 	 * XXX TODO: need to figure out what/how to update the
2521 	 * VHT channel.
2522 	 */
2523 #if 0
2524 	(vap->iv_flags_vht & IEEE80211_FVHT_VHT) {
2525 		struct ieee80211_channel *c;
2526 
2527 		c = ieee80211_ht_adjust_channel(ic, ic->ic_curchan,
2528 		    vap->iv_flags_ht);
2529 		c = ieee80211_vht_adjust_channel(ic, c, vap->iv_flags_vht);
2530 		frm = ieee80211_add_vhtcap_ch(frm, vap, c);
2531 	}
2532 #endif
2533 
2534 	frm = ieee80211_add_wpa(frm, vap);
2535 	if (vap->iv_appie_probereq != NULL)
2536 		frm = add_appie(frm, vap->iv_appie_probereq);
2537 	m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2538 
2539 	KASSERT(M_LEADINGSPACE(m) >= sizeof(struct ieee80211_frame),
2540 	    ("leading space %zd", M_LEADINGSPACE(m)));
2541 	M_PREPEND(m, sizeof(struct ieee80211_frame), M_NOWAIT);
2542 	if (m == NULL) {
2543 		/* NB: cannot happen */
2544 		ieee80211_free_node(ni);
2545 		ieee80211_free_node(bss);
2546 		return ENOMEM;
2547 	}
2548 
2549 	IEEE80211_TX_LOCK(ic);
2550 	ieee80211_send_setup(ni, m,
2551 	     IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_REQ,
2552 	     IEEE80211_NONQOS_TID, sa, da, bssid);
2553 	/* XXX power management? */
2554 	m->m_flags |= M_ENCAP;		/* mark encapsulated */
2555 
2556 	M_WME_SETAC(m, WME_AC_BE);
2557 
2558 	IEEE80211_NODE_STAT(ni, tx_probereq);
2559 	IEEE80211_NODE_STAT(ni, tx_mgmt);
2560 
2561 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
2562 	    "send probe req on channel %u bssid %s sa %6D da %6D ssid \"%.*s\"\n",
2563 	    ieee80211_chan2ieee(ic, ic->ic_curchan),
2564 	    ether_sprintf(bssid),
2565 	    sa, ":",
2566 	    da, ":",
2567 	    ssidlen, ssid);
2568 
2569 	memset(&params, 0, sizeof(params));
2570 	params.ibp_pri = M_WME_GETAC(m);
2571 	tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
2572 	params.ibp_rate0 = tp->mgmtrate;
2573 	if (IEEE80211_IS_MULTICAST(da)) {
2574 		params.ibp_flags |= IEEE80211_BPF_NOACK;
2575 		params.ibp_try0 = 1;
2576 	} else
2577 		params.ibp_try0 = tp->maxretry;
2578 	params.ibp_power = ni->ni_txpower;
2579 	ret = ieee80211_raw_output(vap, ni, m, &params);
2580 	IEEE80211_TX_UNLOCK(ic);
2581 	ieee80211_free_node(bss);
2582 	return (ret);
2583 }
2584 
2585 /*
2586  * Calculate capability information for mgt frames.
2587  */
2588 uint16_t
2589 ieee80211_getcapinfo(struct ieee80211vap *vap, struct ieee80211_channel *chan)
2590 {
2591 	uint16_t capinfo;
2592 
2593 	KASSERT(vap->iv_opmode != IEEE80211_M_STA, ("station mode"));
2594 
2595 	if (vap->iv_opmode == IEEE80211_M_HOSTAP)
2596 		capinfo = IEEE80211_CAPINFO_ESS;
2597 	else if (vap->iv_opmode == IEEE80211_M_IBSS)
2598 		capinfo = IEEE80211_CAPINFO_IBSS;
2599 	else
2600 		capinfo = 0;
2601 	if (vap->iv_flags & IEEE80211_F_PRIVACY)
2602 		capinfo |= IEEE80211_CAPINFO_PRIVACY;
2603 	if ((vap->iv_flags & IEEE80211_F_SHPREAMBLE) &&
2604 	    IEEE80211_IS_CHAN_2GHZ(chan))
2605 		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
2606 	if (vap->iv_flags & IEEE80211_F_SHSLOT)
2607 		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
2608 	if (IEEE80211_IS_CHAN_5GHZ(chan) && (vap->iv_flags & IEEE80211_F_DOTH))
2609 		capinfo |= IEEE80211_CAPINFO_SPECTRUM_MGMT;
2610 	return capinfo;
2611 }
2612 
2613 /*
2614  * Send a management frame.  The node is for the destination (or ic_bss
2615  * when in station mode).  Nodes other than ic_bss have their reference
2616  * count bumped to reflect our use for an indeterminant time.
2617  */
2618 int
2619 ieee80211_send_mgmt(struct ieee80211_node *ni, int type, int arg)
2620 {
2621 #define	HTFLAGS (IEEE80211_NODE_HT | IEEE80211_NODE_HTCOMPAT)
2622 #define	senderr(_x, _v)	do { vap->iv_stats._v++; ret = _x; goto bad; } while (0)
2623 	struct ieee80211vap *vap = ni->ni_vap;
2624 	struct ieee80211com *ic = ni->ni_ic;
2625 	struct ieee80211_node *bss = vap->iv_bss;
2626 	struct ieee80211_bpf_params params;
2627 	struct mbuf *m;
2628 	uint8_t *frm;
2629 	uint16_t capinfo;
2630 	int has_challenge, is_shared_key, ret, status;
2631 
2632 	KASSERT(ni != NULL, ("null node"));
2633 
2634 	/*
2635 	 * Hold a reference on the node so it doesn't go away until after
2636 	 * the xmit is complete all the way in the driver.  On error we
2637 	 * will remove our reference.
2638 	 */
2639 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
2640 		"ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
2641 		__func__, __LINE__,
2642 		ni, ether_sprintf(ni->ni_macaddr),
2643 		ieee80211_node_refcnt(ni)+1);
2644 	ieee80211_ref_node(ni);
2645 
2646 	memset(&params, 0, sizeof(params));
2647 	switch (type) {
2648 
2649 	case IEEE80211_FC0_SUBTYPE_AUTH:
2650 		status = arg >> 16;
2651 		arg &= 0xffff;
2652 		has_challenge = ((arg == IEEE80211_AUTH_SHARED_CHALLENGE ||
2653 		    arg == IEEE80211_AUTH_SHARED_RESPONSE) &&
2654 		    ni->ni_challenge != NULL);
2655 
2656 		/*
2657 		 * Deduce whether we're doing open authentication or
2658 		 * shared key authentication.  We do the latter if
2659 		 * we're in the middle of a shared key authentication
2660 		 * handshake or if we're initiating an authentication
2661 		 * request and configured to use shared key.
2662 		 */
2663 		is_shared_key = has_challenge ||
2664 		     arg >= IEEE80211_AUTH_SHARED_RESPONSE ||
2665 		     (arg == IEEE80211_AUTH_SHARED_REQUEST &&
2666 		      bss->ni_authmode == IEEE80211_AUTH_SHARED);
2667 
2668 		m = ieee80211_getmgtframe(&frm,
2669 			  ic->ic_headroom + sizeof(struct ieee80211_frame),
2670 			  3 * sizeof(uint16_t)
2671 			+ (has_challenge && status == IEEE80211_STATUS_SUCCESS ?
2672 				sizeof(uint16_t)+IEEE80211_CHALLENGE_LEN : 0)
2673 		);
2674 		if (m == NULL)
2675 			senderr(ENOMEM, is_tx_nobuf);
2676 
2677 		((uint16_t *)frm)[0] =
2678 		    (is_shared_key) ? htole16(IEEE80211_AUTH_ALG_SHARED)
2679 		                    : htole16(IEEE80211_AUTH_ALG_OPEN);
2680 		((uint16_t *)frm)[1] = htole16(arg);	/* sequence number */
2681 		((uint16_t *)frm)[2] = htole16(status);/* status */
2682 
2683 		if (has_challenge && status == IEEE80211_STATUS_SUCCESS) {
2684 			((uint16_t *)frm)[3] =
2685 			    htole16((IEEE80211_CHALLENGE_LEN << 8) |
2686 			    IEEE80211_ELEMID_CHALLENGE);
2687 			memcpy(&((uint16_t *)frm)[4], ni->ni_challenge,
2688 			    IEEE80211_CHALLENGE_LEN);
2689 			m->m_pkthdr.len = m->m_len =
2690 				4 * sizeof(uint16_t) + IEEE80211_CHALLENGE_LEN;
2691 			if (arg == IEEE80211_AUTH_SHARED_RESPONSE) {
2692 				IEEE80211_NOTE(vap, IEEE80211_MSG_AUTH, ni,
2693 				    "request encrypt frame (%s)", __func__);
2694 				/* mark frame for encryption */
2695 				params.ibp_flags |= IEEE80211_BPF_CRYPTO;
2696 			}
2697 		} else
2698 			m->m_pkthdr.len = m->m_len = 3 * sizeof(uint16_t);
2699 
2700 		/* XXX not right for shared key */
2701 		if (status == IEEE80211_STATUS_SUCCESS)
2702 			IEEE80211_NODE_STAT(ni, tx_auth);
2703 		else
2704 			IEEE80211_NODE_STAT(ni, tx_auth_fail);
2705 
2706 		if (vap->iv_opmode == IEEE80211_M_STA)
2707 			ieee80211_add_callback(m, ieee80211_tx_mgt_cb,
2708 				(void *) vap->iv_state);
2709 		break;
2710 
2711 	case IEEE80211_FC0_SUBTYPE_DEAUTH:
2712 		IEEE80211_NOTE(vap, IEEE80211_MSG_AUTH, ni,
2713 		    "send station deauthenticate (reason: %d (%s))", arg,
2714 		    ieee80211_reason_to_string(arg));
2715 		m = ieee80211_getmgtframe(&frm,
2716 			ic->ic_headroom + sizeof(struct ieee80211_frame),
2717 			sizeof(uint16_t));
2718 		if (m == NULL)
2719 			senderr(ENOMEM, is_tx_nobuf);
2720 		*(uint16_t *)frm = htole16(arg);	/* reason */
2721 		m->m_pkthdr.len = m->m_len = sizeof(uint16_t);
2722 
2723 		IEEE80211_NODE_STAT(ni, tx_deauth);
2724 		IEEE80211_NODE_STAT_SET(ni, tx_deauth_code, arg);
2725 
2726 		ieee80211_node_unauthorize(ni);		/* port closed */
2727 		break;
2728 
2729 	case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
2730 	case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
2731 		/*
2732 		 * asreq frame format
2733 		 *	[2] capability information
2734 		 *	[2] listen interval
2735 		 *	[6*] current AP address (reassoc only)
2736 		 *	[tlv] ssid
2737 		 *	[tlv] supported rates
2738 		 *	[tlv] extended supported rates
2739 		 *	[4] power capability (optional)
2740 		 *	[28] supported channels (optional)
2741 		 *	[tlv] HT capabilities
2742 		 *	[tlv] VHT capabilities
2743 		 *	[tlv] WME (optional)
2744 		 *	[tlv] Vendor OUI HT capabilities (optional)
2745 		 *	[tlv] Atheros capabilities (if negotiated)
2746 		 *	[tlv] AppIE's (optional)
2747 		 */
2748 		m = ieee80211_getmgtframe(&frm,
2749 			 ic->ic_headroom + sizeof(struct ieee80211_frame),
2750 			 sizeof(uint16_t)
2751 		       + sizeof(uint16_t)
2752 		       + IEEE80211_ADDR_LEN
2753 		       + 2 + IEEE80211_NWID_LEN
2754 		       + 2 + IEEE80211_RATE_SIZE
2755 		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
2756 		       + 4
2757 		       + 2 + 26
2758 		       + sizeof(struct ieee80211_wme_info)
2759 		       + sizeof(struct ieee80211_ie_htcap)
2760 		       + sizeof(struct ieee80211_ie_vhtcap)
2761 		       + 4 + sizeof(struct ieee80211_ie_htcap)
2762 #ifdef IEEE80211_SUPPORT_SUPERG
2763 		       + sizeof(struct ieee80211_ath_ie)
2764 #endif
2765 		       + (vap->iv_appie_wpa != NULL ?
2766 				vap->iv_appie_wpa->ie_len : 0)
2767 		       + (vap->iv_appie_assocreq != NULL ?
2768 				vap->iv_appie_assocreq->ie_len : 0)
2769 		);
2770 		if (m == NULL)
2771 			senderr(ENOMEM, is_tx_nobuf);
2772 
2773 		KASSERT(vap->iv_opmode == IEEE80211_M_STA,
2774 		    ("wrong mode %u", vap->iv_opmode));
2775 		capinfo = IEEE80211_CAPINFO_ESS;
2776 		if (vap->iv_flags & IEEE80211_F_PRIVACY)
2777 			capinfo |= IEEE80211_CAPINFO_PRIVACY;
2778 		/*
2779 		 * NB: Some 11a AP's reject the request when
2780 		 *     short preamble is set.
2781 		 */
2782 		if ((vap->iv_flags & IEEE80211_F_SHPREAMBLE) &&
2783 		    IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
2784 			capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
2785 		if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan) &&
2786 		    (ic->ic_caps & IEEE80211_C_SHSLOT))
2787 			capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
2788 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SPECTRUM_MGMT) &&
2789 		    (vap->iv_flags & IEEE80211_F_DOTH))
2790 			capinfo |= IEEE80211_CAPINFO_SPECTRUM_MGMT;
2791 		*(uint16_t *)frm = htole16(capinfo);
2792 		frm += 2;
2793 
2794 		KASSERT(bss->ni_intval != 0, ("beacon interval is zero!"));
2795 		*(uint16_t *)frm = htole16(howmany(ic->ic_lintval,
2796 						    bss->ni_intval));
2797 		frm += 2;
2798 
2799 		if (type == IEEE80211_FC0_SUBTYPE_REASSOC_REQ) {
2800 			IEEE80211_ADDR_COPY(frm, bss->ni_bssid);
2801 			frm += IEEE80211_ADDR_LEN;
2802 		}
2803 
2804 		frm = ieee80211_add_ssid(frm, ni->ni_essid, ni->ni_esslen);
2805 		frm = ieee80211_add_rates(frm, &ni->ni_rates);
2806 		frm = ieee80211_add_rsn(frm, vap);
2807 		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
2808 		if (capinfo & IEEE80211_CAPINFO_SPECTRUM_MGMT) {
2809 			frm = ieee80211_add_powercapability(frm,
2810 			    ic->ic_curchan);
2811 			frm = ieee80211_add_supportedchannels(frm, ic);
2812 		}
2813 
2814 		/*
2815 		 * Check the channel - we may be using an 11n NIC with an
2816 		 * 11n capable station, but we're configured to be an 11b
2817 		 * channel.
2818 		 */
2819 		if ((vap->iv_flags_ht & IEEE80211_FHT_HT) &&
2820 		    IEEE80211_IS_CHAN_HT(ni->ni_chan) &&
2821 		    ni->ni_ies.htcap_ie != NULL &&
2822 		    ni->ni_ies.htcap_ie[0] == IEEE80211_ELEMID_HTCAP) {
2823 			frm = ieee80211_add_htcap(frm, ni);
2824 		}
2825 
2826 		if ((vap->iv_flags_vht & IEEE80211_FVHT_VHT) &&
2827 		    IEEE80211_IS_CHAN_VHT(ni->ni_chan) &&
2828 		    ni->ni_ies.vhtcap_ie != NULL &&
2829 		    ni->ni_ies.vhtcap_ie[0] == IEEE80211_ELEMID_VHT_CAP) {
2830 			frm = ieee80211_add_vhtcap(frm, ni);
2831 		}
2832 
2833 		frm = ieee80211_add_wpa(frm, vap);
2834 		if ((ic->ic_flags & IEEE80211_F_WME) &&
2835 		    ni->ni_ies.wme_ie != NULL)
2836 			frm = ieee80211_add_wme_info(frm, &ic->ic_wme, ni);
2837 
2838 		/*
2839 		 * Same deal - only send HT info if we're on an 11n
2840 		 * capable channel.
2841 		 */
2842 		if ((vap->iv_flags_ht & IEEE80211_FHT_HT) &&
2843 		    IEEE80211_IS_CHAN_HT(ni->ni_chan) &&
2844 		    ni->ni_ies.htcap_ie != NULL &&
2845 		    ni->ni_ies.htcap_ie[0] == IEEE80211_ELEMID_VENDOR) {
2846 			frm = ieee80211_add_htcap_vendor(frm, ni);
2847 		}
2848 #ifdef IEEE80211_SUPPORT_SUPERG
2849 		if (IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS)) {
2850 			frm = ieee80211_add_ath(frm,
2851 				IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS),
2852 				((vap->iv_flags & IEEE80211_F_WPA) == 0 &&
2853 				 ni->ni_authmode != IEEE80211_AUTH_8021X) ?
2854 				vap->iv_def_txkey : IEEE80211_KEYIX_NONE);
2855 		}
2856 #endif /* IEEE80211_SUPPORT_SUPERG */
2857 		if (vap->iv_appie_assocreq != NULL)
2858 			frm = add_appie(frm, vap->iv_appie_assocreq);
2859 		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2860 
2861 		ieee80211_add_callback(m, ieee80211_tx_mgt_cb,
2862 			(void *) vap->iv_state);
2863 		break;
2864 
2865 	case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
2866 	case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
2867 		/*
2868 		 * asresp frame format
2869 		 *	[2] capability information
2870 		 *	[2] status
2871 		 *	[2] association ID
2872 		 *	[tlv] supported rates
2873 		 *	[tlv] extended supported rates
2874 		 *	[tlv] HT capabilities (standard, if STA enabled)
2875 		 *	[tlv] HT information (standard, if STA enabled)
2876 		 *	[tlv] VHT capabilities (standard, if STA enabled)
2877 		 *	[tlv] VHT information (standard, if STA enabled)
2878 		 *	[tlv] WME (if configured and STA enabled)
2879 		 *	[tlv] HT capabilities (vendor OUI, if STA enabled)
2880 		 *	[tlv] HT information (vendor OUI, if STA enabled)
2881 		 *	[tlv] Atheros capabilities (if STA enabled)
2882 		 *	[tlv] AppIE's (optional)
2883 		 */
2884 		m = ieee80211_getmgtframe(&frm,
2885 			 ic->ic_headroom + sizeof(struct ieee80211_frame),
2886 			 sizeof(uint16_t)
2887 		       + sizeof(uint16_t)
2888 		       + sizeof(uint16_t)
2889 		       + 2 + IEEE80211_RATE_SIZE
2890 		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
2891 		       + sizeof(struct ieee80211_ie_htcap) + 4
2892 		       + sizeof(struct ieee80211_ie_htinfo) + 4
2893 		       + sizeof(struct ieee80211_ie_vhtcap)
2894 		       + sizeof(struct ieee80211_ie_vht_operation)
2895 		       + sizeof(struct ieee80211_wme_param)
2896 #ifdef IEEE80211_SUPPORT_SUPERG
2897 		       + sizeof(struct ieee80211_ath_ie)
2898 #endif
2899 		       + (vap->iv_appie_assocresp != NULL ?
2900 				vap->iv_appie_assocresp->ie_len : 0)
2901 		);
2902 		if (m == NULL)
2903 			senderr(ENOMEM, is_tx_nobuf);
2904 
2905 		capinfo = ieee80211_getcapinfo(vap, bss->ni_chan);
2906 		*(uint16_t *)frm = htole16(capinfo);
2907 		frm += 2;
2908 
2909 		*(uint16_t *)frm = htole16(arg);	/* status */
2910 		frm += 2;
2911 
2912 		if (arg == IEEE80211_STATUS_SUCCESS) {
2913 			*(uint16_t *)frm = htole16(ni->ni_associd);
2914 			IEEE80211_NODE_STAT(ni, tx_assoc);
2915 		} else
2916 			IEEE80211_NODE_STAT(ni, tx_assoc_fail);
2917 		frm += 2;
2918 
2919 		frm = ieee80211_add_rates(frm, &ni->ni_rates);
2920 		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
2921 		/* NB: respond according to what we received */
2922 		if ((ni->ni_flags & HTFLAGS) == IEEE80211_NODE_HT) {
2923 			frm = ieee80211_add_htcap(frm, ni);
2924 			frm = ieee80211_add_htinfo(frm, ni);
2925 		}
2926 		if ((vap->iv_flags & IEEE80211_F_WME) &&
2927 		    ni->ni_ies.wme_ie != NULL)
2928 			frm = ieee80211_add_wme_param(frm, &ic->ic_wme,
2929 			    !! (vap->iv_flags_ext & IEEE80211_FEXT_UAPSD));
2930 		if ((ni->ni_flags & HTFLAGS) == HTFLAGS) {
2931 			frm = ieee80211_add_htcap_vendor(frm, ni);
2932 			frm = ieee80211_add_htinfo_vendor(frm, ni);
2933 		}
2934 		if (ni->ni_flags & IEEE80211_NODE_VHT) {
2935 			frm = ieee80211_add_vhtcap(frm, ni);
2936 			frm = ieee80211_add_vhtinfo(frm, ni);
2937 		}
2938 #ifdef IEEE80211_SUPPORT_SUPERG
2939 		if (IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS))
2940 			frm = ieee80211_add_ath(frm,
2941 				IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS),
2942 				((vap->iv_flags & IEEE80211_F_WPA) == 0 &&
2943 				 ni->ni_authmode != IEEE80211_AUTH_8021X) ?
2944 				vap->iv_def_txkey : IEEE80211_KEYIX_NONE);
2945 #endif /* IEEE80211_SUPPORT_SUPERG */
2946 		if (vap->iv_appie_assocresp != NULL)
2947 			frm = add_appie(frm, vap->iv_appie_assocresp);
2948 		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
2949 		break;
2950 
2951 	case IEEE80211_FC0_SUBTYPE_DISASSOC:
2952 		IEEE80211_NOTE(vap, IEEE80211_MSG_ASSOC, ni,
2953 		    "send station disassociate (reason: %d (%s))", arg,
2954 		    ieee80211_reason_to_string(arg));
2955 		m = ieee80211_getmgtframe(&frm,
2956 			ic->ic_headroom + sizeof(struct ieee80211_frame),
2957 			sizeof(uint16_t));
2958 		if (m == NULL)
2959 			senderr(ENOMEM, is_tx_nobuf);
2960 		*(uint16_t *)frm = htole16(arg);	/* reason */
2961 		m->m_pkthdr.len = m->m_len = sizeof(uint16_t);
2962 
2963 		IEEE80211_NODE_STAT(ni, tx_disassoc);
2964 		IEEE80211_NODE_STAT_SET(ni, tx_disassoc_code, arg);
2965 		break;
2966 
2967 	default:
2968 		IEEE80211_NOTE(vap, IEEE80211_MSG_ANY, ni,
2969 		    "invalid mgmt frame type %u", type);
2970 		senderr(EINVAL, is_tx_unknownmgt);
2971 		/* NOTREACHED */
2972 	}
2973 
2974 	/* NB: force non-ProbeResp frames to the highest queue */
2975 	params.ibp_pri = WME_AC_VO;
2976 	params.ibp_rate0 = bss->ni_txparms->mgmtrate;
2977 	/* NB: we know all frames are unicast */
2978 	params.ibp_try0 = bss->ni_txparms->maxretry;
2979 	params.ibp_power = bss->ni_txpower;
2980 	return ieee80211_mgmt_output(ni, m, type, &params);
2981 bad:
2982 	ieee80211_free_node(ni);
2983 	return ret;
2984 #undef senderr
2985 #undef HTFLAGS
2986 }
2987 
2988 /*
2989  * Return an mbuf with a probe response frame in it.
2990  * Space is left to prepend and 802.11 header at the
2991  * front but it's left to the caller to fill in.
2992  */
2993 struct mbuf *
2994 ieee80211_alloc_proberesp(struct ieee80211_node *bss, int legacy)
2995 {
2996 	struct ieee80211vap *vap = bss->ni_vap;
2997 	struct ieee80211com *ic = bss->ni_ic;
2998 	const struct ieee80211_rateset *rs;
2999 	struct mbuf *m;
3000 	uint16_t capinfo;
3001 	uint8_t *frm;
3002 
3003 	/*
3004 	 * probe response frame format
3005 	 *	[8] time stamp
3006 	 *	[2] beacon interval
3007 	 *	[2] cabability information
3008 	 *	[tlv] ssid
3009 	 *	[tlv] supported rates
3010 	 *	[tlv] parameter set (FH/DS)
3011 	 *	[tlv] parameter set (IBSS)
3012 	 *	[tlv] country (optional)
3013 	 *	[3] power control (optional)
3014 	 *	[5] channel switch announcement (CSA) (optional)
3015 	 *	[tlv] extended rate phy (ERP)
3016 	 *	[tlv] extended supported rates
3017 	 *	[tlv] RSN (optional)
3018 	 *	[tlv] HT capabilities
3019 	 *	[tlv] HT information
3020 	 *	[tlv] VHT capabilities
3021 	 *	[tlv] VHT information
3022 	 *	[tlv] WPA (optional)
3023 	 *	[tlv] WME (optional)
3024 	 *	[tlv] Vendor OUI HT capabilities (optional)
3025 	 *	[tlv] Vendor OUI HT information (optional)
3026 	 *	[tlv] Atheros capabilities
3027 	 *	[tlv] AppIE's (optional)
3028 	 *	[tlv] Mesh ID (MBSS)
3029 	 *	[tlv] Mesh Conf (MBSS)
3030 	 */
3031 	m = ieee80211_getmgtframe(&frm,
3032 		 ic->ic_headroom + sizeof(struct ieee80211_frame),
3033 		 8
3034 	       + sizeof(uint16_t)
3035 	       + sizeof(uint16_t)
3036 	       + 2 + IEEE80211_NWID_LEN
3037 	       + 2 + IEEE80211_RATE_SIZE
3038 	       + 7	/* max(7,3) */
3039 	       + IEEE80211_COUNTRY_MAX_SIZE
3040 	       + 3
3041 	       + sizeof(struct ieee80211_csa_ie)
3042 	       + sizeof(struct ieee80211_quiet_ie)
3043 	       + 3
3044 	       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
3045 	       + sizeof(struct ieee80211_ie_wpa)
3046 	       + sizeof(struct ieee80211_ie_htcap)
3047 	       + sizeof(struct ieee80211_ie_htinfo)
3048 	       + sizeof(struct ieee80211_ie_wpa)
3049 	       + sizeof(struct ieee80211_wme_param)
3050 	       + 4 + sizeof(struct ieee80211_ie_htcap)
3051 	       + 4 + sizeof(struct ieee80211_ie_htinfo)
3052 	       +  sizeof(struct ieee80211_ie_vhtcap)
3053 	       +  sizeof(struct ieee80211_ie_vht_operation)
3054 #ifdef IEEE80211_SUPPORT_SUPERG
3055 	       + sizeof(struct ieee80211_ath_ie)
3056 #endif
3057 #ifdef IEEE80211_SUPPORT_MESH
3058 	       + 2 + IEEE80211_MESHID_LEN
3059 	       + sizeof(struct ieee80211_meshconf_ie)
3060 #endif
3061 	       + (vap->iv_appie_proberesp != NULL ?
3062 			vap->iv_appie_proberesp->ie_len : 0)
3063 	);
3064 	if (m == NULL) {
3065 		vap->iv_stats.is_tx_nobuf++;
3066 		return NULL;
3067 	}
3068 
3069 	memset(frm, 0, 8);	/* timestamp should be filled later */
3070 	frm += 8;
3071 	*(uint16_t *)frm = htole16(bss->ni_intval);
3072 	frm += 2;
3073 	capinfo = ieee80211_getcapinfo(vap, bss->ni_chan);
3074 	*(uint16_t *)frm = htole16(capinfo);
3075 	frm += 2;
3076 
3077 	frm = ieee80211_add_ssid(frm, bss->ni_essid, bss->ni_esslen);
3078 	rs = ieee80211_get_suprates(ic, bss->ni_chan);
3079 	frm = ieee80211_add_rates(frm, rs);
3080 
3081 	if (IEEE80211_IS_CHAN_FHSS(bss->ni_chan)) {
3082 		*frm++ = IEEE80211_ELEMID_FHPARMS;
3083 		*frm++ = 5;
3084 		*frm++ = bss->ni_fhdwell & 0x00ff;
3085 		*frm++ = (bss->ni_fhdwell >> 8) & 0x00ff;
3086 		*frm++ = IEEE80211_FH_CHANSET(
3087 		    ieee80211_chan2ieee(ic, bss->ni_chan));
3088 		*frm++ = IEEE80211_FH_CHANPAT(
3089 		    ieee80211_chan2ieee(ic, bss->ni_chan));
3090 		*frm++ = bss->ni_fhindex;
3091 	} else {
3092 		*frm++ = IEEE80211_ELEMID_DSPARMS;
3093 		*frm++ = 1;
3094 		*frm++ = ieee80211_chan2ieee(ic, bss->ni_chan);
3095 	}
3096 
3097 	if (vap->iv_opmode == IEEE80211_M_IBSS) {
3098 		*frm++ = IEEE80211_ELEMID_IBSSPARMS;
3099 		*frm++ = 2;
3100 		*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
3101 	}
3102 	if ((vap->iv_flags & IEEE80211_F_DOTH) ||
3103 	    (vap->iv_flags_ext & IEEE80211_FEXT_DOTD))
3104 		frm = ieee80211_add_countryie(frm, ic);
3105 	if (vap->iv_flags & IEEE80211_F_DOTH) {
3106 		if (IEEE80211_IS_CHAN_5GHZ(bss->ni_chan))
3107 			frm = ieee80211_add_powerconstraint(frm, vap);
3108 		if (ic->ic_flags & IEEE80211_F_CSAPENDING)
3109 			frm = ieee80211_add_csa(frm, vap);
3110 	}
3111 	if (vap->iv_flags & IEEE80211_F_DOTH) {
3112 		if (IEEE80211_IS_CHAN_DFS(ic->ic_bsschan) &&
3113 		    (vap->iv_flags_ext & IEEE80211_FEXT_DFS)) {
3114 			if (vap->iv_quiet)
3115 				frm = ieee80211_add_quiet(frm, vap, 0);
3116 		}
3117 	}
3118 	if (IEEE80211_IS_CHAN_ANYG(bss->ni_chan))
3119 		frm = ieee80211_add_erp(frm, vap);
3120 	frm = ieee80211_add_xrates(frm, rs);
3121 	frm = ieee80211_add_rsn(frm, vap);
3122 	/*
3123 	 * NB: legacy 11b clients do not get certain ie's.
3124 	 *     The caller identifies such clients by passing
3125 	 *     a token in legacy to us.  Could expand this to be
3126 	 *     any legacy client for stuff like HT ie's.
3127 	 */
3128 	if (IEEE80211_IS_CHAN_HT(bss->ni_chan) &&
3129 	    legacy != IEEE80211_SEND_LEGACY_11B) {
3130 		frm = ieee80211_add_htcap(frm, bss);
3131 		frm = ieee80211_add_htinfo(frm, bss);
3132 	}
3133 	if (IEEE80211_IS_CHAN_VHT(bss->ni_chan) &&
3134 	    legacy != IEEE80211_SEND_LEGACY_11B) {
3135 		frm = ieee80211_add_vhtcap(frm, bss);
3136 		frm = ieee80211_add_vhtinfo(frm, bss);
3137 	}
3138 	frm = ieee80211_add_wpa(frm, vap);
3139 	if (vap->iv_flags & IEEE80211_F_WME)
3140 		frm = ieee80211_add_wme_param(frm, &ic->ic_wme,
3141 		    !! (vap->iv_flags_ext & IEEE80211_FEXT_UAPSD));
3142 	if (IEEE80211_IS_CHAN_HT(bss->ni_chan) &&
3143 	    (vap->iv_flags_ht & IEEE80211_FHT_HTCOMPAT) &&
3144 	    legacy != IEEE80211_SEND_LEGACY_11B) {
3145 		frm = ieee80211_add_htcap_vendor(frm, bss);
3146 		frm = ieee80211_add_htinfo_vendor(frm, bss);
3147 	}
3148 #ifdef IEEE80211_SUPPORT_SUPERG
3149 	if ((vap->iv_flags & IEEE80211_F_ATHEROS) &&
3150 	    legacy != IEEE80211_SEND_LEGACY_11B)
3151 		frm = ieee80211_add_athcaps(frm, bss);
3152 #endif
3153 	if (vap->iv_appie_proberesp != NULL)
3154 		frm = add_appie(frm, vap->iv_appie_proberesp);
3155 #ifdef IEEE80211_SUPPORT_MESH
3156 	if (vap->iv_opmode == IEEE80211_M_MBSS) {
3157 		frm = ieee80211_add_meshid(frm, vap);
3158 		frm = ieee80211_add_meshconf(frm, vap);
3159 	}
3160 #endif
3161 	m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
3162 
3163 	return m;
3164 }
3165 
3166 /*
3167  * Send a probe response frame to the specified mac address.
3168  * This does not go through the normal mgt frame api so we
3169  * can specify the destination address and re-use the bss node
3170  * for the sta reference.
3171  */
3172 int
3173 ieee80211_send_proberesp(struct ieee80211vap *vap,
3174 	const uint8_t da[IEEE80211_ADDR_LEN], int legacy)
3175 {
3176 	struct ieee80211_node *bss = vap->iv_bss;
3177 	struct ieee80211com *ic = vap->iv_ic;
3178 	struct mbuf *m;
3179 	int ret;
3180 
3181 	if (vap->iv_state == IEEE80211_S_CAC) {
3182 		IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT, bss,
3183 		    "block %s frame in CAC state", "probe response");
3184 		vap->iv_stats.is_tx_badstate++;
3185 		return EIO;		/* XXX */
3186 	}
3187 
3188 	/*
3189 	 * Hold a reference on the node so it doesn't go away until after
3190 	 * the xmit is complete all the way in the driver.  On error we
3191 	 * will remove our reference.
3192 	 */
3193 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
3194 	    "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
3195 	    __func__, __LINE__, bss, ether_sprintf(bss->ni_macaddr),
3196 	    ieee80211_node_refcnt(bss)+1);
3197 	ieee80211_ref_node(bss);
3198 
3199 	m = ieee80211_alloc_proberesp(bss, legacy);
3200 	if (m == NULL) {
3201 		ieee80211_free_node(bss);
3202 		return ENOMEM;
3203 	}
3204 
3205 	M_PREPEND(m, sizeof(struct ieee80211_frame), M_NOWAIT);
3206 	KASSERT(m != NULL, ("no room for header"));
3207 
3208 	IEEE80211_TX_LOCK(ic);
3209 	ieee80211_send_setup(bss, m,
3210 	     IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP,
3211 	     IEEE80211_NONQOS_TID, vap->iv_myaddr, da, bss->ni_bssid);
3212 	/* XXX power management? */
3213 	m->m_flags |= M_ENCAP;		/* mark encapsulated */
3214 
3215 	M_WME_SETAC(m, WME_AC_BE);
3216 
3217 	IEEE80211_DPRINTF(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
3218 	    "send probe resp on channel %u to %s%s\n",
3219 	    ieee80211_chan2ieee(ic, ic->ic_curchan), ether_sprintf(da),
3220 	    legacy ? " <legacy>" : "");
3221 	IEEE80211_NODE_STAT(bss, tx_mgmt);
3222 
3223 	ret = ieee80211_raw_output(vap, bss, m, NULL);
3224 	IEEE80211_TX_UNLOCK(ic);
3225 	return (ret);
3226 }
3227 
3228 /*
3229  * Allocate and build a RTS (Request To Send) control frame.
3230  */
3231 struct mbuf *
3232 ieee80211_alloc_rts(struct ieee80211com *ic,
3233 	const uint8_t ra[IEEE80211_ADDR_LEN],
3234 	const uint8_t ta[IEEE80211_ADDR_LEN],
3235 	uint16_t dur)
3236 {
3237 	struct ieee80211_frame_rts *rts;
3238 	struct mbuf *m;
3239 
3240 	/* XXX honor ic_headroom */
3241 	m = m_gethdr(M_NOWAIT, MT_DATA);
3242 	if (m != NULL) {
3243 		rts = mtod(m, struct ieee80211_frame_rts *);
3244 		rts->i_fc[0] = IEEE80211_FC0_VERSION_0 |
3245 			IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_RTS;
3246 		rts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
3247 		*(u_int16_t *)rts->i_dur = htole16(dur);
3248 		IEEE80211_ADDR_COPY(rts->i_ra, ra);
3249 		IEEE80211_ADDR_COPY(rts->i_ta, ta);
3250 
3251 		m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame_rts);
3252 	}
3253 	return m;
3254 }
3255 
3256 /*
3257  * Allocate and build a CTS (Clear To Send) control frame.
3258  */
3259 struct mbuf *
3260 ieee80211_alloc_cts(struct ieee80211com *ic,
3261 	const uint8_t ra[IEEE80211_ADDR_LEN], uint16_t dur)
3262 {
3263 	struct ieee80211_frame_cts *cts;
3264 	struct mbuf *m;
3265 
3266 	/* XXX honor ic_headroom */
3267 	m = m_gethdr(M_NOWAIT, MT_DATA);
3268 	if (m != NULL) {
3269 		cts = mtod(m, struct ieee80211_frame_cts *);
3270 		cts->i_fc[0] = IEEE80211_FC0_VERSION_0 |
3271 			IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_CTS;
3272 		cts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
3273 		*(u_int16_t *)cts->i_dur = htole16(dur);
3274 		IEEE80211_ADDR_COPY(cts->i_ra, ra);
3275 
3276 		m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame_cts);
3277 	}
3278 	return m;
3279 }
3280 
3281 /*
3282  * Wrapper for CTS/RTS frame allocation.
3283  */
3284 struct mbuf *
3285 ieee80211_alloc_prot(struct ieee80211_node *ni, const struct mbuf *m,
3286     uint8_t rate, int prot)
3287 {
3288 	struct ieee80211com *ic = ni->ni_ic;
3289 	struct ieee80211vap *vap = ni->ni_vap;
3290 	const struct ieee80211_frame *wh;
3291 	struct mbuf *mprot;
3292 	uint16_t dur;
3293 	int pktlen, isshort;
3294 
3295 	KASSERT(prot == IEEE80211_PROT_RTSCTS ||
3296 	    prot == IEEE80211_PROT_CTSONLY,
3297 	    ("wrong protection type %d", prot));
3298 
3299 	wh = mtod(m, const struct ieee80211_frame *);
3300 	pktlen = m->m_pkthdr.len + IEEE80211_CRC_LEN;
3301 	isshort = (vap->iv_flags & IEEE80211_F_SHPREAMBLE) != 0;
3302 	dur = ieee80211_compute_duration(ic->ic_rt, pktlen, rate, isshort)
3303 	    + ieee80211_ack_duration(ic->ic_rt, rate, isshort);
3304 
3305 	if (prot == IEEE80211_PROT_RTSCTS) {
3306 		/* NB: CTS is the same size as an ACK */
3307 		dur += ieee80211_ack_duration(ic->ic_rt, rate, isshort);
3308 		mprot = ieee80211_alloc_rts(ic, wh->i_addr1, wh->i_addr2, dur);
3309 	} else
3310 		mprot = ieee80211_alloc_cts(ic, vap->iv_myaddr, dur);
3311 
3312 	return (mprot);
3313 }
3314 
3315 static void
3316 ieee80211_tx_mgt_timeout(void *arg)
3317 {
3318 	struct ieee80211vap *vap = arg;
3319 
3320 	IEEE80211_LOCK(vap->iv_ic);
3321 	if (vap->iv_state != IEEE80211_S_INIT &&
3322 	    (vap->iv_ic->ic_flags & IEEE80211_F_SCAN) == 0) {
3323 		/*
3324 		 * NB: it's safe to specify a timeout as the reason here;
3325 		 *     it'll only be used in the right state.
3326 		 */
3327 		ieee80211_new_state_locked(vap, IEEE80211_S_SCAN,
3328 			IEEE80211_SCAN_FAIL_TIMEOUT);
3329 	}
3330 	IEEE80211_UNLOCK(vap->iv_ic);
3331 }
3332 
3333 /*
3334  * This is the callback set on net80211-sourced transmitted
3335  * authentication request frames.
3336  *
3337  * This does a couple of things:
3338  *
3339  * + If the frame transmitted was a success, it schedules a future
3340  *   event which will transition the interface to scan.
3341  *   If a state transition _then_ occurs before that event occurs,
3342  *   said state transition will cancel this callout.
3343  *
3344  * + If the frame transmit was a failure, it immediately schedules
3345  *   the transition back to scan.
3346  */
3347 static void
3348 ieee80211_tx_mgt_cb(struct ieee80211_node *ni, void *arg, int status)
3349 {
3350 	struct ieee80211vap *vap = ni->ni_vap;
3351 	enum ieee80211_state ostate = (enum ieee80211_state)(uintptr_t)arg;
3352 
3353 	/*
3354 	 * Frame transmit completed; arrange timer callback.  If
3355 	 * transmit was successfully we wait for response.  Otherwise
3356 	 * we arrange an immediate callback instead of doing the
3357 	 * callback directly since we don't know what state the driver
3358 	 * is in (e.g. what locks it is holding).  This work should
3359 	 * not be too time-critical and not happen too often so the
3360 	 * added overhead is acceptable.
3361 	 *
3362 	 * XXX what happens if !acked but response shows up before callback?
3363 	 */
3364 	if (vap->iv_state == ostate) {
3365 		callout_reset(&vap->iv_mgtsend,
3366 			status == 0 ? IEEE80211_TRANS_WAIT*hz : 0,
3367 			ieee80211_tx_mgt_timeout, vap);
3368 	}
3369 }
3370 
3371 static void
3372 ieee80211_beacon_construct(struct mbuf *m, uint8_t *frm,
3373 	struct ieee80211_node *ni)
3374 {
3375 	struct ieee80211vap *vap = ni->ni_vap;
3376 	struct ieee80211_beacon_offsets *bo = &vap->iv_bcn_off;
3377 	struct ieee80211com *ic = ni->ni_ic;
3378 	struct ieee80211_rateset *rs = &ni->ni_rates;
3379 	uint16_t capinfo;
3380 
3381 	/*
3382 	 * beacon frame format
3383 	 *
3384 	 * TODO: update to 802.11-2012; a lot of stuff has changed;
3385 	 * vendor extensions should be at the end, etc.
3386 	 *
3387 	 *	[8] time stamp
3388 	 *	[2] beacon interval
3389 	 *	[2] cabability information
3390 	 *	[tlv] ssid
3391 	 *	[tlv] supported rates
3392 	 *	[3] parameter set (DS)
3393 	 *	[8] CF parameter set (optional)
3394 	 *	[tlv] parameter set (IBSS/TIM)
3395 	 *	[tlv] country (optional)
3396 	 *	[3] power control (optional)
3397 	 *	[5] channel switch announcement (CSA) (optional)
3398 	 * XXX TODO: Quiet
3399 	 * XXX TODO: IBSS DFS
3400 	 * XXX TODO: TPC report
3401 	 *	[tlv] extended rate phy (ERP)
3402 	 *	[tlv] extended supported rates
3403 	 *	[tlv] RSN parameters
3404 	 * XXX TODO: BSSLOAD
3405 	 * (XXX EDCA parameter set, QoS capability?)
3406 	 * XXX TODO: AP channel report
3407 	 *
3408 	 *	[tlv] HT capabilities
3409 	 *	[tlv] HT information
3410 	 *	XXX TODO: 20/40 BSS coexistence
3411 	 * Mesh:
3412 	 * XXX TODO: Meshid
3413 	 * XXX TODO: mesh config
3414 	 * XXX TODO: mesh awake window
3415 	 * XXX TODO: beacon timing (mesh, etc)
3416 	 * XXX TODO: MCCAOP Advertisement Overview
3417 	 * XXX TODO: MCCAOP Advertisement
3418 	 * XXX TODO: Mesh channel switch parameters
3419 	 * VHT:
3420 	 * XXX TODO: VHT capabilities
3421 	 * XXX TODO: VHT operation
3422 	 * XXX TODO: VHT transmit power envelope
3423 	 * XXX TODO: channel switch wrapper element
3424 	 * XXX TODO: extended BSS load element
3425 	 *
3426 	 * XXX Vendor-specific OIDs (e.g. Atheros)
3427 	 *	[tlv] WPA parameters
3428 	 *	[tlv] WME parameters
3429 	 *	[tlv] Vendor OUI HT capabilities (optional)
3430 	 *	[tlv] Vendor OUI HT information (optional)
3431 	 *	[tlv] Atheros capabilities (optional)
3432 	 *	[tlv] TDMA parameters (optional)
3433 	 *	[tlv] Mesh ID (MBSS)
3434 	 *	[tlv] Mesh Conf (MBSS)
3435 	 *	[tlv] application data (optional)
3436 	 */
3437 
3438 	memset(bo, 0, sizeof(*bo));
3439 
3440 	memset(frm, 0, 8);	/* XXX timestamp is set by hardware/driver */
3441 	frm += 8;
3442 	*(uint16_t *)frm = htole16(ni->ni_intval);
3443 	frm += 2;
3444 	capinfo = ieee80211_getcapinfo(vap, ni->ni_chan);
3445 	bo->bo_caps = (uint16_t *)frm;
3446 	*(uint16_t *)frm = htole16(capinfo);
3447 	frm += 2;
3448 	*frm++ = IEEE80211_ELEMID_SSID;
3449 	if ((vap->iv_flags & IEEE80211_F_HIDESSID) == 0) {
3450 		*frm++ = ni->ni_esslen;
3451 		memcpy(frm, ni->ni_essid, ni->ni_esslen);
3452 		frm += ni->ni_esslen;
3453 	} else
3454 		*frm++ = 0;
3455 	frm = ieee80211_add_rates(frm, rs);
3456 	if (!IEEE80211_IS_CHAN_FHSS(ni->ni_chan)) {
3457 		*frm++ = IEEE80211_ELEMID_DSPARMS;
3458 		*frm++ = 1;
3459 		*frm++ = ieee80211_chan2ieee(ic, ni->ni_chan);
3460 	}
3461 	if (ic->ic_flags & IEEE80211_F_PCF) {
3462 		bo->bo_cfp = frm;
3463 		frm = ieee80211_add_cfparms(frm, ic);
3464 	}
3465 	bo->bo_tim = frm;
3466 	if (vap->iv_opmode == IEEE80211_M_IBSS) {
3467 		*frm++ = IEEE80211_ELEMID_IBSSPARMS;
3468 		*frm++ = 2;
3469 		*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
3470 		bo->bo_tim_len = 0;
3471 	} else if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
3472 	    vap->iv_opmode == IEEE80211_M_MBSS) {
3473 		/* TIM IE is the same for Mesh and Hostap */
3474 		struct ieee80211_tim_ie *tie = (struct ieee80211_tim_ie *) frm;
3475 
3476 		tie->tim_ie = IEEE80211_ELEMID_TIM;
3477 		tie->tim_len = 4;	/* length */
3478 		tie->tim_count = 0;	/* DTIM count */
3479 		tie->tim_period = vap->iv_dtim_period;	/* DTIM period */
3480 		tie->tim_bitctl = 0;	/* bitmap control */
3481 		tie->tim_bitmap[0] = 0;	/* Partial Virtual Bitmap */
3482 		frm += sizeof(struct ieee80211_tim_ie);
3483 		bo->bo_tim_len = 1;
3484 	}
3485 	bo->bo_tim_trailer = frm;
3486 	if ((vap->iv_flags & IEEE80211_F_DOTH) ||
3487 	    (vap->iv_flags_ext & IEEE80211_FEXT_DOTD))
3488 		frm = ieee80211_add_countryie(frm, ic);
3489 	if (vap->iv_flags & IEEE80211_F_DOTH) {
3490 		if (IEEE80211_IS_CHAN_5GHZ(ni->ni_chan))
3491 			frm = ieee80211_add_powerconstraint(frm, vap);
3492 		bo->bo_csa = frm;
3493 		if (ic->ic_flags & IEEE80211_F_CSAPENDING)
3494 			frm = ieee80211_add_csa(frm, vap);
3495 	} else
3496 		bo->bo_csa = frm;
3497 
3498 	bo->bo_quiet = NULL;
3499 	if (vap->iv_flags & IEEE80211_F_DOTH) {
3500 		if (IEEE80211_IS_CHAN_DFS(ic->ic_bsschan) &&
3501 		    (vap->iv_flags_ext & IEEE80211_FEXT_DFS) &&
3502 		    (vap->iv_quiet == 1)) {
3503 			/*
3504 			 * We only insert the quiet IE offset if
3505 			 * the quiet IE is enabled.  Otherwise don't
3506 			 * put it here or we'll just overwrite
3507 			 * some other beacon contents.
3508 			 */
3509 			if (vap->iv_quiet) {
3510 				bo->bo_quiet = frm;
3511 				frm = ieee80211_add_quiet(frm,vap, 0);
3512 			}
3513 		}
3514 	}
3515 
3516 	if (IEEE80211_IS_CHAN_ANYG(ni->ni_chan)) {
3517 		bo->bo_erp = frm;
3518 		frm = ieee80211_add_erp(frm, vap);
3519 	}
3520 	frm = ieee80211_add_xrates(frm, rs);
3521 	frm = ieee80211_add_rsn(frm, vap);
3522 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) {
3523 		frm = ieee80211_add_htcap(frm, ni);
3524 		bo->bo_htinfo = frm;
3525 		frm = ieee80211_add_htinfo(frm, ni);
3526 	}
3527 
3528 	if (IEEE80211_IS_CHAN_VHT(ni->ni_chan)) {
3529 		frm = ieee80211_add_vhtcap(frm, ni);
3530 		bo->bo_vhtinfo = frm;
3531 		frm = ieee80211_add_vhtinfo(frm, ni);
3532 		/* Transmit power envelope */
3533 		/* Channel switch wrapper element */
3534 		/* Extended bss load element */
3535 	}
3536 
3537 	frm = ieee80211_add_wpa(frm, vap);
3538 	if (vap->iv_flags & IEEE80211_F_WME) {
3539 		bo->bo_wme = frm;
3540 		frm = ieee80211_add_wme_param(frm, &ic->ic_wme,
3541 		    !! (vap->iv_flags_ext & IEEE80211_FEXT_UAPSD));
3542 	}
3543 	if (IEEE80211_IS_CHAN_HT(ni->ni_chan) &&
3544 	    (vap->iv_flags_ht & IEEE80211_FHT_HTCOMPAT)) {
3545 		frm = ieee80211_add_htcap_vendor(frm, ni);
3546 		frm = ieee80211_add_htinfo_vendor(frm, ni);
3547 	}
3548 
3549 #ifdef IEEE80211_SUPPORT_SUPERG
3550 	if (vap->iv_flags & IEEE80211_F_ATHEROS) {
3551 		bo->bo_ath = frm;
3552 		frm = ieee80211_add_athcaps(frm, ni);
3553 	}
3554 #endif
3555 #ifdef IEEE80211_SUPPORT_TDMA
3556 	if (vap->iv_caps & IEEE80211_C_TDMA) {
3557 		bo->bo_tdma = frm;
3558 		frm = ieee80211_add_tdma(frm, vap);
3559 	}
3560 #endif
3561 	if (vap->iv_appie_beacon != NULL) {
3562 		bo->bo_appie = frm;
3563 		bo->bo_appie_len = vap->iv_appie_beacon->ie_len;
3564 		frm = add_appie(frm, vap->iv_appie_beacon);
3565 	}
3566 
3567 	/* XXX TODO: move meshid/meshconf up to before vendor extensions? */
3568 #ifdef IEEE80211_SUPPORT_MESH
3569 	if (vap->iv_opmode == IEEE80211_M_MBSS) {
3570 		frm = ieee80211_add_meshid(frm, vap);
3571 		bo->bo_meshconf = frm;
3572 		frm = ieee80211_add_meshconf(frm, vap);
3573 	}
3574 #endif
3575 	bo->bo_tim_trailer_len = frm - bo->bo_tim_trailer;
3576 	bo->bo_csa_trailer_len = frm - bo->bo_csa;
3577 	m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
3578 }
3579 
3580 /*
3581  * Allocate a beacon frame and fillin the appropriate bits.
3582  */
3583 struct mbuf *
3584 ieee80211_beacon_alloc(struct ieee80211_node *ni)
3585 {
3586 	struct ieee80211vap *vap = ni->ni_vap;
3587 	struct ieee80211com *ic = ni->ni_ic;
3588 	struct ifnet *ifp = vap->iv_ifp;
3589 	struct ieee80211_frame *wh;
3590 	struct mbuf *m;
3591 	int pktlen;
3592 	uint8_t *frm;
3593 
3594 	/*
3595 	 * Update the "We're putting the quiet IE in the beacon" state.
3596 	 */
3597 	if (vap->iv_quiet == 1)
3598 		vap->iv_flags_ext |= IEEE80211_FEXT_QUIET_IE;
3599 	else if (vap->iv_quiet == 0)
3600 		vap->iv_flags_ext &= ~IEEE80211_FEXT_QUIET_IE;
3601 
3602 	/*
3603 	 * beacon frame format
3604 	 *
3605 	 * Note: This needs updating for 802.11-2012.
3606 	 *
3607 	 *	[8] time stamp
3608 	 *	[2] beacon interval
3609 	 *	[2] cabability information
3610 	 *	[tlv] ssid
3611 	 *	[tlv] supported rates
3612 	 *	[3] parameter set (DS)
3613 	 *	[8] CF parameter set (optional)
3614 	 *	[tlv] parameter set (IBSS/TIM)
3615 	 *	[tlv] country (optional)
3616 	 *	[3] power control (optional)
3617 	 *	[5] channel switch announcement (CSA) (optional)
3618 	 *	[tlv] extended rate phy (ERP)
3619 	 *	[tlv] extended supported rates
3620 	 *	[tlv] RSN parameters
3621 	 *	[tlv] HT capabilities
3622 	 *	[tlv] HT information
3623 	 *	[tlv] VHT capabilities
3624 	 *	[tlv] VHT operation
3625 	 *	[tlv] Vendor OUI HT capabilities (optional)
3626 	 *	[tlv] Vendor OUI HT information (optional)
3627 	 * XXX Vendor-specific OIDs (e.g. Atheros)
3628 	 *	[tlv] WPA parameters
3629 	 *	[tlv] WME parameters
3630 	 *	[tlv] TDMA parameters (optional)
3631 	 *	[tlv] Mesh ID (MBSS)
3632 	 *	[tlv] Mesh Conf (MBSS)
3633 	 *	[tlv] application data (optional)
3634 	 * NB: we allocate the max space required for the TIM bitmap.
3635 	 * XXX how big is this?
3636 	 */
3637 	pktlen =   8					/* time stamp */
3638 		 + sizeof(uint16_t)			/* beacon interval */
3639 		 + sizeof(uint16_t)			/* capabilities */
3640 		 + 2 + ni->ni_esslen			/* ssid */
3641 	         + 2 + IEEE80211_RATE_SIZE		/* supported rates */
3642 	         + 2 + 1				/* DS parameters */
3643 		 + 2 + 6				/* CF parameters */
3644 		 + 2 + 4 + vap->iv_tim_len		/* DTIM/IBSSPARMS */
3645 		 + IEEE80211_COUNTRY_MAX_SIZE		/* country */
3646 		 + 2 + 1				/* power control */
3647 		 + sizeof(struct ieee80211_csa_ie)	/* CSA */
3648 		 + sizeof(struct ieee80211_quiet_ie)	/* Quiet */
3649 		 + 2 + 1				/* ERP */
3650 	         + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
3651 		 + (vap->iv_caps & IEEE80211_C_WPA ?	/* WPA 1+2 */
3652 			2*sizeof(struct ieee80211_ie_wpa) : 0)
3653 		 /* XXX conditional? */
3654 		 + 4+2*sizeof(struct ieee80211_ie_htcap)/* HT caps */
3655 		 + 4+2*sizeof(struct ieee80211_ie_htinfo)/* HT info */
3656 		 + sizeof(struct ieee80211_ie_vhtcap)/* VHT caps */
3657 		 + sizeof(struct ieee80211_ie_vht_operation)/* VHT info */
3658 		 + (vap->iv_caps & IEEE80211_C_WME ?	/* WME */
3659 			sizeof(struct ieee80211_wme_param) : 0)
3660 #ifdef IEEE80211_SUPPORT_SUPERG
3661 		 + sizeof(struct ieee80211_ath_ie)	/* ATH */
3662 #endif
3663 #ifdef IEEE80211_SUPPORT_TDMA
3664 		 + (vap->iv_caps & IEEE80211_C_TDMA ?	/* TDMA */
3665 			sizeof(struct ieee80211_tdma_param) : 0)
3666 #endif
3667 #ifdef IEEE80211_SUPPORT_MESH
3668 		 + 2 + ni->ni_meshidlen
3669 		 + sizeof(struct ieee80211_meshconf_ie)
3670 #endif
3671 		 + IEEE80211_MAX_APPIE
3672 		 ;
3673 	m = ieee80211_getmgtframe(&frm,
3674 		ic->ic_headroom + sizeof(struct ieee80211_frame), pktlen);
3675 	if (m == NULL) {
3676 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_ANY,
3677 			"%s: cannot get buf; size %u\n", __func__, pktlen);
3678 		vap->iv_stats.is_tx_nobuf++;
3679 		return NULL;
3680 	}
3681 	ieee80211_beacon_construct(m, frm, ni);
3682 
3683 	M_PREPEND(m, sizeof(struct ieee80211_frame), M_NOWAIT);
3684 	KASSERT(m != NULL, ("no space for 802.11 header?"));
3685 	wh = mtod(m, struct ieee80211_frame *);
3686 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
3687 	    IEEE80211_FC0_SUBTYPE_BEACON;
3688 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
3689 	*(uint16_t *)wh->i_dur = 0;
3690 	IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
3691 	IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
3692 	IEEE80211_ADDR_COPY(wh->i_addr3, ni->ni_bssid);
3693 	*(uint16_t *)wh->i_seq = 0;
3694 
3695 	return m;
3696 }
3697 
3698 /*
3699  * Update the dynamic parts of a beacon frame based on the current state.
3700  */
3701 int
3702 ieee80211_beacon_update(struct ieee80211_node *ni, struct mbuf *m, int mcast)
3703 {
3704 	struct ieee80211vap *vap = ni->ni_vap;
3705 	struct ieee80211_beacon_offsets *bo = &vap->iv_bcn_off;
3706 	struct ieee80211com *ic = ni->ni_ic;
3707 	int len_changed = 0;
3708 	uint16_t capinfo;
3709 	struct ieee80211_frame *wh;
3710 	ieee80211_seq seqno;
3711 
3712 	IEEE80211_LOCK(ic);
3713 	/*
3714 	 * Handle 11h channel change when we've reached the count.
3715 	 * We must recalculate the beacon frame contents to account
3716 	 * for the new channel.  Note we do this only for the first
3717 	 * vap that reaches this point; subsequent vaps just update
3718 	 * their beacon state to reflect the recalculated channel.
3719 	 */
3720 	if (isset(bo->bo_flags, IEEE80211_BEACON_CSA) &&
3721 	    vap->iv_csa_count == ic->ic_csa_count) {
3722 		vap->iv_csa_count = 0;
3723 		/*
3724 		 * Effect channel change before reconstructing the beacon
3725 		 * frame contents as many places reference ni_chan.
3726 		 */
3727 		if (ic->ic_csa_newchan != NULL)
3728 			ieee80211_csa_completeswitch(ic);
3729 		/*
3730 		 * NB: ieee80211_beacon_construct clears all pending
3731 		 * updates in bo_flags so we don't need to explicitly
3732 		 * clear IEEE80211_BEACON_CSA.
3733 		 */
3734 		ieee80211_beacon_construct(m,
3735 		    mtod(m, uint8_t*) + sizeof(struct ieee80211_frame), ni);
3736 
3737 		/* XXX do WME aggressive mode processing? */
3738 		IEEE80211_UNLOCK(ic);
3739 		return 1;		/* just assume length changed */
3740 	}
3741 
3742 	/*
3743 	 * Handle the quiet time element being added and removed.
3744 	 * Again, for now we just cheat and reconstruct the whole
3745 	 * beacon - that way the gap is provided as appropriate.
3746 	 *
3747 	 * So, track whether we have already added the IE versus
3748 	 * whether we want to be adding the IE.
3749 	 */
3750 	if ((vap->iv_flags_ext & IEEE80211_FEXT_QUIET_IE) &&
3751 	    (vap->iv_quiet == 0)) {
3752 		/*
3753 		 * Quiet time beacon IE enabled, but it's disabled;
3754 		 * recalc
3755 		 */
3756 		vap->iv_flags_ext &= ~IEEE80211_FEXT_QUIET_IE;
3757 		ieee80211_beacon_construct(m,
3758 		    mtod(m, uint8_t*) + sizeof(struct ieee80211_frame), ni);
3759 		/* XXX do WME aggressive mode processing? */
3760 		IEEE80211_UNLOCK(ic);
3761 		return 1;		/* just assume length changed */
3762 	}
3763 
3764 	if (((vap->iv_flags_ext & IEEE80211_FEXT_QUIET_IE) == 0) &&
3765 	    (vap->iv_quiet == 1)) {
3766 		/*
3767 		 * Quiet time beacon IE disabled, but it's now enabled;
3768 		 * recalc
3769 		 */
3770 		vap->iv_flags_ext |= IEEE80211_FEXT_QUIET_IE;
3771 		ieee80211_beacon_construct(m,
3772 		    mtod(m, uint8_t*) + sizeof(struct ieee80211_frame), ni);
3773 		/* XXX do WME aggressive mode processing? */
3774 		IEEE80211_UNLOCK(ic);
3775 		return 1;		/* just assume length changed */
3776 	}
3777 
3778 	wh = mtod(m, struct ieee80211_frame *);
3779 
3780 	/*
3781 	 * XXX TODO Strictly speaking this should be incremented with the TX
3782 	 * lock held so as to serialise access to the non-qos TID sequence
3783 	 * number space.
3784 	 *
3785 	 * If the driver identifies it does its own TX seqno management then
3786 	 * we can skip this (and still not do the TX seqno.)
3787 	 */
3788 	seqno = ni->ni_txseqs[IEEE80211_NONQOS_TID]++;
3789 	*(uint16_t *)&wh->i_seq[0] =
3790 		htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT);
3791 	M_SEQNO_SET(m, seqno);
3792 
3793 	/* XXX faster to recalculate entirely or just changes? */
3794 	capinfo = ieee80211_getcapinfo(vap, ni->ni_chan);
3795 	*bo->bo_caps = htole16(capinfo);
3796 
3797 	if (vap->iv_flags & IEEE80211_F_WME) {
3798 		struct ieee80211_wme_state *wme = &ic->ic_wme;
3799 
3800 		/*
3801 		 * Check for aggressive mode change.  When there is
3802 		 * significant high priority traffic in the BSS
3803 		 * throttle back BE traffic by using conservative
3804 		 * parameters.  Otherwise BE uses aggressive params
3805 		 * to optimize performance of legacy/non-QoS traffic.
3806 		 */
3807 		if (wme->wme_flags & WME_F_AGGRMODE) {
3808 			if (wme->wme_hipri_traffic >
3809 			    wme->wme_hipri_switch_thresh) {
3810 				IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
3811 				    "%s: traffic %u, disable aggressive mode\n",
3812 				    __func__, wme->wme_hipri_traffic);
3813 				wme->wme_flags &= ~WME_F_AGGRMODE;
3814 				ieee80211_wme_updateparams_locked(vap);
3815 				wme->wme_hipri_traffic =
3816 					wme->wme_hipri_switch_hysteresis;
3817 			} else
3818 				wme->wme_hipri_traffic = 0;
3819 		} else {
3820 			if (wme->wme_hipri_traffic <=
3821 			    wme->wme_hipri_switch_thresh) {
3822 				IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME,
3823 				    "%s: traffic %u, enable aggressive mode\n",
3824 				    __func__, wme->wme_hipri_traffic);
3825 				wme->wme_flags |= WME_F_AGGRMODE;
3826 				ieee80211_wme_updateparams_locked(vap);
3827 				wme->wme_hipri_traffic = 0;
3828 			} else
3829 				wme->wme_hipri_traffic =
3830 					wme->wme_hipri_switch_hysteresis;
3831 		}
3832 		if (isset(bo->bo_flags, IEEE80211_BEACON_WME)) {
3833 			(void) ieee80211_add_wme_param(bo->bo_wme, wme,
3834 			  vap->iv_flags_ext & IEEE80211_FEXT_UAPSD);
3835 			clrbit(bo->bo_flags, IEEE80211_BEACON_WME);
3836 		}
3837 	}
3838 
3839 	if (isset(bo->bo_flags,  IEEE80211_BEACON_HTINFO)) {
3840 		ieee80211_ht_update_beacon(vap, bo);
3841 		clrbit(bo->bo_flags, IEEE80211_BEACON_HTINFO);
3842 	}
3843 #ifdef IEEE80211_SUPPORT_TDMA
3844 	if (vap->iv_caps & IEEE80211_C_TDMA) {
3845 		/*
3846 		 * NB: the beacon is potentially updated every TBTT.
3847 		 */
3848 		ieee80211_tdma_update_beacon(vap, bo);
3849 	}
3850 #endif
3851 #ifdef IEEE80211_SUPPORT_MESH
3852 	if (vap->iv_opmode == IEEE80211_M_MBSS)
3853 		ieee80211_mesh_update_beacon(vap, bo);
3854 #endif
3855 
3856 	if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
3857 	    vap->iv_opmode == IEEE80211_M_MBSS) {	/* NB: no IBSS support*/
3858 		struct ieee80211_tim_ie *tie =
3859 			(struct ieee80211_tim_ie *) bo->bo_tim;
3860 		if (isset(bo->bo_flags, IEEE80211_BEACON_TIM)) {
3861 			u_int timlen, timoff, i;
3862 			/*
3863 			 * ATIM/DTIM needs updating.  If it fits in the
3864 			 * current space allocated then just copy in the
3865 			 * new bits.  Otherwise we need to move any trailing
3866 			 * data to make room.  Note that we know there is
3867 			 * contiguous space because ieee80211_beacon_allocate
3868 			 * insures there is space in the mbuf to write a
3869 			 * maximal-size virtual bitmap (based on iv_max_aid).
3870 			 */
3871 			/*
3872 			 * Calculate the bitmap size and offset, copy any
3873 			 * trailer out of the way, and then copy in the
3874 			 * new bitmap and update the information element.
3875 			 * Note that the tim bitmap must contain at least
3876 			 * one byte and any offset must be even.
3877 			 */
3878 			if (vap->iv_ps_pending != 0) {
3879 				timoff = 128;		/* impossibly large */
3880 				for (i = 0; i < vap->iv_tim_len; i++)
3881 					if (vap->iv_tim_bitmap[i]) {
3882 						timoff = i &~ 1;
3883 						break;
3884 					}
3885 				KASSERT(timoff != 128, ("tim bitmap empty!"));
3886 				for (i = vap->iv_tim_len-1; i >= timoff; i--)
3887 					if (vap->iv_tim_bitmap[i])
3888 						break;
3889 				timlen = 1 + (i - timoff);
3890 			} else {
3891 				timoff = 0;
3892 				timlen = 1;
3893 			}
3894 
3895 			/*
3896 			 * TODO: validate this!
3897 			 */
3898 			if (timlen != bo->bo_tim_len) {
3899 				/* copy up/down trailer */
3900 				int adjust = tie->tim_bitmap+timlen
3901 					   - bo->bo_tim_trailer;
3902 				ovbcopy(bo->bo_tim_trailer,
3903 				    bo->bo_tim_trailer+adjust,
3904 				    bo->bo_tim_trailer_len);
3905 				bo->bo_tim_trailer += adjust;
3906 				bo->bo_erp += adjust;
3907 				bo->bo_htinfo += adjust;
3908 				bo->bo_vhtinfo += adjust;
3909 #ifdef IEEE80211_SUPPORT_SUPERG
3910 				bo->bo_ath += adjust;
3911 #endif
3912 #ifdef IEEE80211_SUPPORT_TDMA
3913 				bo->bo_tdma += adjust;
3914 #endif
3915 #ifdef IEEE80211_SUPPORT_MESH
3916 				bo->bo_meshconf += adjust;
3917 #endif
3918 				bo->bo_appie += adjust;
3919 				bo->bo_wme += adjust;
3920 				bo->bo_csa += adjust;
3921 				bo->bo_quiet += adjust;
3922 				bo->bo_tim_len = timlen;
3923 
3924 				/* update information element */
3925 				tie->tim_len = 3 + timlen;
3926 				tie->tim_bitctl = timoff;
3927 				len_changed = 1;
3928 			}
3929 			memcpy(tie->tim_bitmap, vap->iv_tim_bitmap + timoff,
3930 				bo->bo_tim_len);
3931 
3932 			clrbit(bo->bo_flags, IEEE80211_BEACON_TIM);
3933 
3934 			IEEE80211_DPRINTF(vap, IEEE80211_MSG_POWER,
3935 				"%s: TIM updated, pending %u, off %u, len %u\n",
3936 				__func__, vap->iv_ps_pending, timoff, timlen);
3937 		}
3938 		/* count down DTIM period */
3939 		if (tie->tim_count == 0)
3940 			tie->tim_count = tie->tim_period - 1;
3941 		else
3942 			tie->tim_count--;
3943 		/* update state for buffered multicast frames on DTIM */
3944 		if (mcast && tie->tim_count == 0)
3945 			tie->tim_bitctl |= 1;
3946 		else
3947 			tie->tim_bitctl &= ~1;
3948 		if (isset(bo->bo_flags, IEEE80211_BEACON_CSA)) {
3949 			struct ieee80211_csa_ie *csa =
3950 			    (struct ieee80211_csa_ie *) bo->bo_csa;
3951 
3952 			/*
3953 			 * Insert or update CSA ie.  If we're just starting
3954 			 * to count down to the channel switch then we need
3955 			 * to insert the CSA ie.  Otherwise we just need to
3956 			 * drop the count.  The actual change happens above
3957 			 * when the vap's count reaches the target count.
3958 			 */
3959 			if (vap->iv_csa_count == 0) {
3960 				memmove(&csa[1], csa, bo->bo_csa_trailer_len);
3961 				bo->bo_erp += sizeof(*csa);
3962 				bo->bo_htinfo += sizeof(*csa);
3963 				bo->bo_vhtinfo += sizeof(*csa);
3964 				bo->bo_wme += sizeof(*csa);
3965 #ifdef IEEE80211_SUPPORT_SUPERG
3966 				bo->bo_ath += sizeof(*csa);
3967 #endif
3968 #ifdef IEEE80211_SUPPORT_TDMA
3969 				bo->bo_tdma += sizeof(*csa);
3970 #endif
3971 #ifdef IEEE80211_SUPPORT_MESH
3972 				bo->bo_meshconf += sizeof(*csa);
3973 #endif
3974 				bo->bo_appie += sizeof(*csa);
3975 				bo->bo_csa_trailer_len += sizeof(*csa);
3976 				bo->bo_quiet += sizeof(*csa);
3977 				bo->bo_tim_trailer_len += sizeof(*csa);
3978 				m->m_len += sizeof(*csa);
3979 				m->m_pkthdr.len += sizeof(*csa);
3980 
3981 				ieee80211_add_csa(bo->bo_csa, vap);
3982 			} else
3983 				csa->csa_count--;
3984 			vap->iv_csa_count++;
3985 			/* NB: don't clear IEEE80211_BEACON_CSA */
3986 		}
3987 
3988 		/*
3989 		 * Only add the quiet time IE if we've enabled it
3990 		 * as appropriate.
3991 		 */
3992 		if (IEEE80211_IS_CHAN_DFS(ic->ic_bsschan) &&
3993 		    (vap->iv_flags_ext & IEEE80211_FEXT_DFS)) {
3994 			if (vap->iv_quiet &&
3995 			    (vap->iv_flags_ext & IEEE80211_FEXT_QUIET_IE)) {
3996 				ieee80211_add_quiet(bo->bo_quiet, vap, 1);
3997 			}
3998 		}
3999 		if (isset(bo->bo_flags, IEEE80211_BEACON_ERP)) {
4000 			/*
4001 			 * ERP element needs updating.
4002 			 */
4003 			(void) ieee80211_add_erp(bo->bo_erp, vap);
4004 			clrbit(bo->bo_flags, IEEE80211_BEACON_ERP);
4005 		}
4006 #ifdef IEEE80211_SUPPORT_SUPERG
4007 		if (isset(bo->bo_flags,  IEEE80211_BEACON_ATH)) {
4008 			ieee80211_add_athcaps(bo->bo_ath, ni);
4009 			clrbit(bo->bo_flags, IEEE80211_BEACON_ATH);
4010 		}
4011 #endif
4012 	}
4013 	if (isset(bo->bo_flags, IEEE80211_BEACON_APPIE)) {
4014 		const struct ieee80211_appie *aie = vap->iv_appie_beacon;
4015 		int aielen;
4016 		uint8_t *frm;
4017 
4018 		aielen = 0;
4019 		if (aie != NULL)
4020 			aielen += aie->ie_len;
4021 		if (aielen != bo->bo_appie_len) {
4022 			/* copy up/down trailer */
4023 			int adjust = aielen - bo->bo_appie_len;
4024 			ovbcopy(bo->bo_tim_trailer, bo->bo_tim_trailer+adjust,
4025 				bo->bo_tim_trailer_len);
4026 			bo->bo_tim_trailer += adjust;
4027 			bo->bo_appie += adjust;
4028 			bo->bo_appie_len = aielen;
4029 
4030 			len_changed = 1;
4031 		}
4032 		frm = bo->bo_appie;
4033 		if (aie != NULL)
4034 			frm  = add_appie(frm, aie);
4035 		clrbit(bo->bo_flags, IEEE80211_BEACON_APPIE);
4036 	}
4037 	IEEE80211_UNLOCK(ic);
4038 
4039 	return len_changed;
4040 }
4041 
4042 /*
4043  * Do Ethernet-LLC encapsulation for each payload in a fast frame
4044  * tunnel encapsulation.  The frame is assumed to have an Ethernet
4045  * header at the front that must be stripped before prepending the
4046  * LLC followed by the Ethernet header passed in (with an Ethernet
4047  * type that specifies the payload size).
4048  */
4049 struct mbuf *
4050 ieee80211_ff_encap1(struct ieee80211vap *vap, struct mbuf *m,
4051 	const struct ether_header *eh)
4052 {
4053 	struct llc *llc;
4054 	uint16_t payload;
4055 
4056 	/* XXX optimize by combining m_adj+M_PREPEND */
4057 	m_adj(m, sizeof(struct ether_header) - sizeof(struct llc));
4058 	llc = mtod(m, struct llc *);
4059 	llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
4060 	llc->llc_control = LLC_UI;
4061 	llc->llc_snap.org_code[0] = 0;
4062 	llc->llc_snap.org_code[1] = 0;
4063 	llc->llc_snap.org_code[2] = 0;
4064 	llc->llc_snap.ether_type = eh->ether_type;
4065 	payload = m->m_pkthdr.len;		/* NB: w/o Ethernet header */
4066 
4067 	M_PREPEND(m, sizeof(struct ether_header), M_NOWAIT);
4068 	if (m == NULL) {		/* XXX cannot happen */
4069 		IEEE80211_DPRINTF(vap, IEEE80211_MSG_SUPERG,
4070 			"%s: no space for ether_header\n", __func__);
4071 		vap->iv_stats.is_tx_nobuf++;
4072 		return NULL;
4073 	}
4074 	ETHER_HEADER_COPY(mtod(m, void *), eh);
4075 	mtod(m, struct ether_header *)->ether_type = htons(payload);
4076 	return m;
4077 }
4078 
4079 /*
4080  * Complete an mbuf transmission.
4081  *
4082  * For now, this simply processes a completed frame after the
4083  * driver has completed it's transmission and/or retransmission.
4084  * It assumes the frame is an 802.11 encapsulated frame.
4085  *
4086  * Later on it will grow to become the exit path for a given frame
4087  * from the driver and, depending upon how it's been encapsulated
4088  * and already transmitted, it may end up doing A-MPDU retransmission,
4089  * power save requeuing, etc.
4090  *
4091  * In order for the above to work, the driver entry point to this
4092  * must not hold any driver locks.  Thus, the driver needs to delay
4093  * any actual mbuf completion until it can release said locks.
4094  *
4095  * This frees the mbuf and if the mbuf has a node reference,
4096  * the node reference will be freed.
4097  */
4098 void
4099 ieee80211_tx_complete(struct ieee80211_node *ni, struct mbuf *m, int status)
4100 {
4101 
4102 	if (ni != NULL) {
4103 		struct ifnet *ifp = ni->ni_vap->iv_ifp;
4104 
4105 		if (status == 0) {
4106 			if_inc_counter(ifp, IFCOUNTER_OBYTES, m->m_pkthdr.len);
4107 			if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
4108 			if (m->m_flags & M_MCAST)
4109 				if_inc_counter(ifp, IFCOUNTER_OMCASTS, 1);
4110 		} else
4111 			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
4112 		if (m->m_flags & M_TXCB)
4113 			ieee80211_process_callback(ni, m, status);
4114 		ieee80211_free_node(ni);
4115 	}
4116 	m_freem(m);
4117 }
4118