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