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