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