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