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