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