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