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