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