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