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