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