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