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