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