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