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