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