Home | History | Annotate | Line # | Download | only in net80211
ieee80211_output.c revision 1.47.34.1
      1 /*	$NetBSD: ieee80211_output.c,v 1.47.34.1 2008/02/22 16:50:25 skrll Exp $	*/
      2 /*-
      3  * Copyright (c) 2001 Atsushi Onoe
      4  * Copyright (c) 2002-2007 Sam Leffler, Errno Consulting
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     26  */
     27 
     28 #include <sys/cdefs.h>
     29 #ifdef __FreeBSD__
     30 __FBSDID("$FreeBSD: src/sys/net80211/ieee80211_output.c,v 1.57 2007/12/07 01:46:12 kmacy Exp $");
     31 #endif
     32 #ifdef __NetBSD__
     33 __KERNEL_RCSID(0, "$NetBSD: ieee80211_output.c,v 1.47.34.1 2008/02/22 16:50:25 skrll Exp $");
     34 #endif
     35 
     36 #include "opt_inet.h"
     37 
     38 #ifdef __NetBSD__
     39 #include "bpfilter.h"
     40 #endif /* __NetBSD__ */
     41 
     42 #include <sys/param.h>
     43 #include <sys/systm.h>
     44 #include <sys/mbuf.h>
     45 #include <sys/kernel.h>
     46 #include <sys/endian.h>
     47 #include <sys/errno.h>
     48 #include <sys/proc.h>
     49 #include <sys/sysctl.h>
     50 
     51 #include <net/if.h>
     52 #include <net/if_llc.h>
     53 #include <net/if_media.h>
     54 #include <net/if_arp.h>
     55 #include <net/if_ether.h>
     56 #include <net/if_llc.h>
     57 #include <net/if_vlanvar.h>
     58 
     59 #include <net80211/ieee80211_netbsd.h>
     60 #include <net80211/ieee80211_var.h>
     61 #include <net80211/ieee80211_regdomain.h>
     62 
     63 #if NBPFILTER > 0
     64 #include <net/bpf.h>
     65 #endif
     66 
     67 #ifdef INET
     68 #include <netinet/in.h>
     69 #include <netinet/in_systm.h>
     70 #include <netinet/in_var.h>
     71 #include <netinet/ip.h>
     72 #include <net/if_ether.h>
     73 #endif
     74 
     75 #define	ETHER_HEADER_COPY(dst, src) \
     76 	memcpy(dst, src, sizeof(struct ether_header))
     77 
     78 static struct mbuf *ieee80211_encap_fastframe(struct ieee80211com *ic,
     79 	struct mbuf *m1, const struct ether_header *eh1,
     80 	struct mbuf *m2, const struct ether_header *eh2);
     81 static int ieee80211_fragment(struct ieee80211com *, struct mbuf *,
     82 	u_int hdrsize, u_int ciphdrsize, u_int mtu);
     83 static	void ieee80211_tx_mgt_cb(struct ieee80211_node *, void *, int);
     84 
     85 #ifdef IEEE80211_DEBUG
     86 /*
     87  * Decide if an outbound management frame should be
     88  * printed when debugging is enabled.  This filters some
     89  * of the less interesting frames that come frequently
     90  * (e.g. beacons).
     91  */
     92 static __inline int
     93 doprint(struct ieee80211com *ic, int subtype)
     94 {
     95 	switch (subtype) {
     96 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
     97 		return (ic->ic_opmode == IEEE80211_M_IBSS);
     98 	}
     99 	return 1;
    100 }
    101 #endif
    102 
    103 /*
    104  * Set the direction field and address fields of an outgoing
    105  * non-QoS frame.  Note this should be called early on in
    106  * constructing a frame as it sets i_fc[1]; other bits can
    107  * then be or'd in.
    108  */
    109 static void
    110 ieee80211_send_setup(struct ieee80211com *ic,
    111 	struct ieee80211_node *ni,
    112 	struct ieee80211_frame *wh,
    113 	int type,
    114 	const uint8_t sa[IEEE80211_ADDR_LEN],
    115 	const uint8_t da[IEEE80211_ADDR_LEN],
    116 	const uint8_t bssid[IEEE80211_ADDR_LEN])
    117 {
    118 #define	WH4(wh)	((struct ieee80211_frame_addr4 *)wh)
    119 
    120 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | type;
    121 	if ((type & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_DATA) {
    122 		switch (ic->ic_opmode) {
    123 		case IEEE80211_M_STA:
    124 			wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
    125 			IEEE80211_ADDR_COPY(wh->i_addr1, bssid);
    126 			IEEE80211_ADDR_COPY(wh->i_addr2, sa);
    127 			IEEE80211_ADDR_COPY(wh->i_addr3, da);
    128 			break;
    129 		case IEEE80211_M_IBSS:
    130 		case IEEE80211_M_AHDEMO:
    131 			wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
    132 			IEEE80211_ADDR_COPY(wh->i_addr1, da);
    133 			IEEE80211_ADDR_COPY(wh->i_addr2, sa);
    134 			IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
    135 			break;
    136 		case IEEE80211_M_HOSTAP:
    137 			wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
    138 			IEEE80211_ADDR_COPY(wh->i_addr1, da);
    139 			IEEE80211_ADDR_COPY(wh->i_addr2, bssid);
    140 			IEEE80211_ADDR_COPY(wh->i_addr3, sa);
    141 			break;
    142 		case IEEE80211_M_WDS:
    143 			wh->i_fc[1] = IEEE80211_FC1_DIR_DSTODS;
    144 			/* XXX cheat, bssid holds RA */
    145 			IEEE80211_ADDR_COPY(wh->i_addr1, bssid);
    146 			IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
    147 			IEEE80211_ADDR_COPY(wh->i_addr3, da);
    148 			IEEE80211_ADDR_COPY(WH4(wh)->i_addr4, sa);
    149 			break;
    150 		case IEEE80211_M_MONITOR:	/* NB: to quiet compiler */
    151 			break;
    152 		}
    153 	} else {
    154 		wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
    155 		IEEE80211_ADDR_COPY(wh->i_addr1, da);
    156 		IEEE80211_ADDR_COPY(wh->i_addr2, sa);
    157 		IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
    158 	}
    159 	*(uint16_t *)&wh->i_dur[0] = 0;
    160 	/* NB: use non-QoS tid */
    161 	*(uint16_t *)&wh->i_seq[0] =
    162 	    htole16(ni->ni_txseqs[IEEE80211_NONQOS_TID] << IEEE80211_SEQ_SEQ_SHIFT);
    163 	ni->ni_txseqs[IEEE80211_NONQOS_TID]++;
    164 #undef WH4
    165 }
    166 
    167 /*
    168  * Send a management frame to the specified node.  The node pointer
    169  * must have a reference as the pointer will be passed to the driver
    170  * and potentially held for a long time.  If the frame is successfully
    171  * dispatched to the driver, then it is responsible for freeing the
    172  * reference (and potentially free'ing up any associated storage).
    173  */
    174 int
    175 ieee80211_mgmt_output(struct ieee80211com *ic, struct ieee80211_node *ni,
    176     struct mbuf *m, int type)
    177 {
    178 	struct ifnet *ifp = ic->ic_ifp;
    179 	struct ieee80211_frame *wh;
    180 
    181 	IASSERT(ni != NULL, ("null node"));
    182 
    183 	/*
    184 	 * Yech, hack alert!  We want to pass the node down to the
    185 	 * driver's start routine.  If we don't do so then the start
    186 	 * routine must immediately look it up again and that can
    187 	 * cause a lock order reversal if, for example, this frame
    188 	 * is being sent because the station is being timedout and
    189 	 * the frame being sent is a DEAUTH message.  We could stick
    190 	 * this in an m_tag and tack that on to the mbuf.  However
    191 	 * that's rather expensive to do for every frame so instead
    192 	 * we stuff it in the rcvif field since outbound frames do
    193 	 * not (presently) use this.
    194 	 */
    195 	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
    196 	if (m == NULL)
    197 		return ENOMEM;
    198 #ifdef __FreeBSD__
    199 	IASSERT(m->m_pkthdr.rcvif == NULL, ("rcvif not null"));
    200 #endif
    201 	m->m_pkthdr.rcvif = (void *)ni;
    202 
    203 	wh = mtod(m, struct ieee80211_frame *);
    204 	ieee80211_send_setup(ic, ni, wh,
    205 		IEEE80211_FC0_TYPE_MGT | type,
    206 		ic->ic_myaddr, ni->ni_macaddr, ni->ni_bssid);
    207 	if ((m->m_flags & M_LINK0) != 0 && ni->ni_challenge != NULL) {
    208 		m->m_flags &= ~M_LINK0;
    209 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
    210 			"[%s] encrypting frame (%s)\n",
    211 			ether_sprintf(wh->i_addr1), __func__);
    212 		wh->i_fc[1] |= IEEE80211_FC1_WEP;
    213 	}
    214 	if (ni->ni_flags & IEEE80211_NODE_QOS) {
    215 		/* NB: force all management frames to the highest queue */
    216 		M_WME_SETAC(m, WME_AC_VO);
    217 	} else
    218 		M_WME_SETAC(m, WME_AC_BE);
    219 #ifdef IEEE80211_DEBUG
    220 	/* avoid printing too many frames */
    221 	if ((ieee80211_msg_debug(ic) && doprint(ic, type)) ||
    222 	    ieee80211_msg_dumppkts(ic)) {
    223 		printf("[%s] send %s on channel %u\n",
    224 		    ether_sprintf(wh->i_addr1),
    225 		    ieee80211_mgt_subtype_name[
    226 			(type & IEEE80211_FC0_SUBTYPE_MASK) >>
    227 				IEEE80211_FC0_SUBTYPE_SHIFT],
    228 		    ieee80211_chan2ieee(ic, ic->ic_curchan));
    229 	}
    230 #endif
    231 	IEEE80211_NODE_STAT(ni, tx_mgmt);
    232 	IF_ENQUEUE(&ic->ic_mgtq, m);
    233 	ifp->if_timer = 1;
    234 	(*ifp->if_start)(ifp);
    235 	ifp->if_opackets++;
    236 
    237 	return 0;
    238 }
    239 
    240 /*
    241  * Raw packet transmit stub for legacy drivers.
    242  * Send the packet through the mgt q so we bypass
    243  * the normal encapsulation work.
    244  */
    245 int
    246 ieee80211_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
    247 	const struct ieee80211_bpf_params *params)
    248 {
    249 	struct ieee80211com *ic = ni->ni_ic;
    250 	struct ifnet *ifp = ic->ic_ifp;
    251 
    252 	m->m_pkthdr.rcvif = (void *) ni;
    253 	IF_ENQUEUE(&ic->ic_mgtq, m);
    254 	(*ifp->if_start)(ifp);
    255 	ifp->if_opackets++;
    256 
    257 	return 0;
    258 }
    259 
    260 /* XXXNH */
    261 #if 0
    262 /*
    263  * 802.11 output routine. This is (currently) used only to
    264  * connect bpf write calls to the 802.11 layer for injecting
    265  * raw 802.11 frames.  Note we locate the ieee80211com from
    266  * the ifnet using a spare field setup at attach time.  This
    267  * will go away when the virtual ap support comes in.
    268  */
    269 int
    270 ieee80211_output(struct ifnet *ifp, struct mbuf *m,
    271 	const struct sockaddr *dst, struct rtentry *rt0)
    272 {
    273 #define senderr(e) do { error = (e); goto bad;} while (0)
    274 	struct ieee80211com *ic = ifp->if_llsoftc;	/* XXX */
    275 	struct ieee80211_node *ni = NULL;
    276 	struct ieee80211_frame *wh;
    277 	int error;
    278 
    279 	/*
    280 	 * Hand to the 802.3 code if not tagged as
    281 	 * a raw 802.11 frame.
    282 	 */
    283 	if (dst->sa_family != AF_IEEE80211)
    284 		return ether_output(ifp, m, dst, rt0);
    285 #ifdef MAC
    286 	error = mac_check_ifnet_transmit(ifp, m);
    287 	if (error)
    288 		senderr(error);
    289 #endif
    290 	if (ifp->if_flags & IFF_MONITOR)
    291 		senderr(ENETDOWN);
    292 	if ((ifp->if_flags & IFF_UP) == 0)
    293 		senderr(ENETDOWN);
    294 
    295 	/* XXX bypass bridge, pfil, carp, etc. */
    296 
    297 	if (m->m_pkthdr.len < sizeof(struct ieee80211_frame_ack))
    298 		senderr(EIO);	/* XXX */
    299 	wh = mtod(m, struct ieee80211_frame *);
    300 	if ((wh->i_fc[0] & IEEE80211_FC0_VERSION_MASK) !=
    301 	    IEEE80211_FC0_VERSION_0)
    302 		senderr(EIO);	/* XXX */
    303 
    304 	/* locate destination node */
    305 	switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) {
    306 	case IEEE80211_FC1_DIR_NODS:
    307 	case IEEE80211_FC1_DIR_FROMDS:
    308 		ni = ieee80211_find_txnode(ic, wh->i_addr1);
    309 		break;
    310 	case IEEE80211_FC1_DIR_TODS:
    311 	case IEEE80211_FC1_DIR_DSTODS:
    312 		if (m->m_pkthdr.len < sizeof(struct ieee80211_frame))
    313 			senderr(EIO);	/* XXX */
    314 		ni = ieee80211_find_txnode(ic, wh->i_addr3);
    315 		break;
    316 	default:
    317 		senderr(EIO);	/* XXX */
    318 	}
    319 	if (ni == NULL) {
    320 		/*
    321 		 * Permit packets w/ bpf params through regardless
    322 		 * (see below about sa_len).
    323 		 */
    324 		if (dst->sa_len == 0)
    325 			senderr(EHOSTUNREACH);
    326 		ni = ieee80211_ref_node(ic->ic_bss);
    327 	}
    328 
    329 	/* XXX ctrl frames should go through */
    330 	if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
    331 	    (m->m_flags & M_PWR_SAV) == 0) {
    332 		/*
    333 		 * Station in power save mode; pass the frame
    334 		 * to the 802.11 layer and continue.  We'll get
    335 		 * the frame back when the time is right.
    336 		 */
    337 		ieee80211_pwrsave(ni, m);
    338 		error = 0;
    339 		goto reclaim;
    340 	}
    341 
    342 	/* calculate priority so drivers can find the tx queue */
    343 	/* XXX assumes an 802.3 frame */
    344 	if (ieee80211_classify(ic, m, ni))
    345 		senderr(EIO);		/* XXX */
    346 
    347 	BPF_MTAP(ifp, m);
    348 	/*
    349 	 * NB: DLT_IEEE802_11_RADIO identifies the parameters are
    350 	 * present by setting the sa_len field of the sockaddr (yes,
    351 	 * this is a hack).
    352 	 * NB: we assume sa_data is suitably aligned to cast.
    353 	 */
    354 	return ic->ic_raw_xmit(ni, m, (const struct ieee80211_bpf_params *)
    355 		(dst->sa_len ? dst->sa_data : NULL));
    356 bad:
    357 	if (m != NULL)
    358 		m_freem(m);
    359 reclaim:
    360 	if (ni != NULL)
    361 		ieee80211_free_node(ni);
    362 	return error;
    363 #undef senderr
    364 }
    365 #endif
    366 
    367 /*
    368  * Send a null data frame to the specified node.
    369  *
    370  * NB: the caller is assumed to have setup a node reference
    371  *     for use; this is necessary to deal with a race condition
    372  *     when probing for inactive stations.
    373  */
    374 int
    375 ieee80211_send_nulldata(struct ieee80211_node *ni)
    376 {
    377 	struct ieee80211com *ic = ni->ni_ic;
    378 	struct ifnet *ifp = ic->ic_ifp;
    379 	struct mbuf *m;
    380 	struct ieee80211_frame *wh;
    381 
    382 	MGETHDR(m, M_NOWAIT, MT_DATA);
    383 	if (m == NULL) {
    384 		/* XXX debug msg */
    385 		ieee80211_unref_node(&ni);
    386 		ic->ic_stats.is_tx_nobuf++;
    387 		return ENOMEM;
    388 	}
    389 	MH_ALIGN(m, sizeof(struct ieee80211_frame));
    390 	m->m_pkthdr.rcvif = (void *) ni;
    391 
    392 	wh = mtod(m, struct ieee80211_frame *);
    393 	ieee80211_send_setup(ic, ni, wh,
    394 		IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_NODATA,
    395 		ic->ic_myaddr, ni->ni_macaddr, ni->ni_bssid);
    396 	/* NB: power management bit is never sent by an AP */
    397 	if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
    398 	    ic->ic_opmode != IEEE80211_M_HOSTAP &&
    399 	    ic->ic_opmode != IEEE80211_M_WDS)
    400 		wh->i_fc[1] |= IEEE80211_FC1_PWR_MGT;
    401 	m->m_len = m->m_pkthdr.len = sizeof(struct ieee80211_frame);
    402 	M_WME_SETAC(m, WME_AC_BE);
    403 
    404 	IEEE80211_NODE_STAT(ni, tx_data);
    405 
    406 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
    407 	    "[%s] send null data frame on channel %u, pwr mgt %s\n",
    408 	    ether_sprintf(ni->ni_macaddr),
    409 	    ieee80211_chan2ieee(ic, ic->ic_curchan),
    410 	    wh->i_fc[1] & IEEE80211_FC1_PWR_MGT ? "ena" : "dis");
    411 
    412 	IF_ENQUEUE(&ic->ic_mgtq, m);		/* cheat */
    413 	(*ifp->if_start)(ifp);
    414 
    415 	return 0;
    416 }
    417 
    418 /*
    419  * Assign priority to a frame based on any vlan tag assigned
    420  * to the station and/or any Diffserv setting in an IP header.
    421  * Finally, if an ACM policy is setup (in station mode) it's
    422  * applied.
    423  */
    424 int
    425 ieee80211_classify(struct ieee80211com *ic, struct mbuf *m, struct ieee80211_node *ni)
    426 {
    427 	int v_wme_ac, d_wme_ac, ac;
    428 #ifdef INET
    429 	struct ether_header *eh;
    430 #endif
    431 
    432 	if ((ni->ni_flags & IEEE80211_NODE_QOS) == 0) {
    433 		ac = WME_AC_BE;
    434 		goto done;
    435 	}
    436 
    437 	/*
    438 	 * If node has a vlan tag then all traffic
    439 	 * to it must have a matching tag.
    440 	 */
    441 	v_wme_ac = 0;
    442 	if (ni->ni_vlan != 0) {
    443 		/* XXX used to check ec_nvlans. */
    444 		struct m_tag *mtag = m_tag_find(m, PACKET_TAG_VLAN, NULL);
    445 		if (mtag == NULL) {
    446 			IEEE80211_NODE_STAT(ni, tx_novlantag);
    447 			return 1;
    448 		}
    449 		if (EVL_VLANOFTAG(VLAN_TAG_VALUE(mtag)) !=
    450 		    EVL_VLANOFTAG(ni->ni_vlan)) {
    451 			IEEE80211_NODE_STAT(ni, tx_vlanmismatch);
    452 			return 1;
    453 		}
    454 		/* map vlan priority to AC */
    455 		v_wme_ac = TID_TO_WME_AC(EVL_PRIOFTAG(ni->ni_vlan));
    456 	}
    457 
    458 #ifdef INET
    459 	eh = mtod(m, struct ether_header *);
    460 	if (eh->ether_type == htons(ETHERTYPE_IP)) {
    461 		uint8_t tos;
    462 		/*
    463 		 * IP frame, map the DSCP bits from the TOS field.
    464 		 */
    465 		/* XXX m_copydata may be too slow for fast path */
    466 		/* NB: ip header may not be in first mbuf */
    467 		m_copydata(m, sizeof(struct ether_header) +
    468 		    offsetof(struct ip, ip_tos), sizeof(tos), &tos);
    469 		tos >>= 5;		/* NB: ECN + low 3 bits of DSCP */
    470 		d_wme_ac = TID_TO_WME_AC(tos);
    471 	} else {
    472 #endif /* INET */
    473 		d_wme_ac = WME_AC_BE;
    474 #ifdef INET
    475 	}
    476 #endif
    477 	/*
    478 	 * Use highest priority AC.
    479 	 */
    480 	if (v_wme_ac > d_wme_ac)
    481 		ac = v_wme_ac;
    482 	else
    483 		ac = d_wme_ac;
    484 
    485 	/*
    486 	 * Apply ACM policy.
    487 	 */
    488 	if (ic->ic_opmode == IEEE80211_M_STA) {
    489 		static const int acmap[4] = {
    490 			WME_AC_BK,	/* WME_AC_BE */
    491 			WME_AC_BK,	/* WME_AC_BK */
    492 			WME_AC_BE,	/* WME_AC_VI */
    493 			WME_AC_VI,	/* WME_AC_VO */
    494 		};
    495 		while (ac != WME_AC_BK &&
    496 		    ic->ic_wme.wme_wmeBssChanParams.cap_wmeParams[ac].wmep_acm)
    497 			ac = acmap[ac];
    498 	}
    499 done:
    500 	M_WME_SETAC(m, ac);
    501 	return 0;
    502 }
    503 
    504 /*
    505  * Insure there is sufficient contiguous space to encapsulate the
    506  * 802.11 data frame.  If room isn't already there, arrange for it.
    507  * Drivers and cipher modules assume we have done the necessary work
    508  * and fail rudely if they don't find the space they need.
    509  */
    510 static struct mbuf *
    511 ieee80211_mbuf_adjust(struct ieee80211com *ic, int hdrsize,
    512 	struct ieee80211_key *key, struct mbuf *m)
    513 {
    514 #define	TO_BE_RECLAIMED	(sizeof(struct ether_header) - sizeof(struct llc))
    515 	int needed_space = ic->ic_headroom + hdrsize;
    516 	int wlen = 0;
    517 
    518 	if (key != NULL) {
    519 		/* XXX belongs in crypto code? */
    520 		needed_space += key->wk_cipher->ic_header;
    521 		/* XXX frags */
    522 	}
    523 	/*
    524 	 * We know we are called just before stripping an Ethernet
    525 	 * header and prepending an LLC header.  This means we know
    526 	 * there will be
    527 	 *	sizeof(struct ether_header) - sizeof(struct llc)
    528 	 * bytes recovered to which we need additional space for the
    529 	 * 802.11 header and any crypto header.
    530 	 */
    531 	/* XXX check trailing space and copy instead? */
    532 	if (M_LEADINGSPACE(m) < needed_space - TO_BE_RECLAIMED) {
    533 		struct mbuf *n = m_gethdr(M_NOWAIT, m->m_type);
    534 		if (n == NULL) {
    535 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
    536 			    "%s: cannot expand storage\n", __func__);
    537 			ic->ic_stats.is_tx_nobuf++;
    538 			m_freem(m);
    539 			return NULL;
    540 		}
    541 		IASSERT(needed_space <= MHLEN,
    542 		    ("not enough room, need %u got %zu\n", needed_space, MHLEN));
    543 		/*
    544 		 * Setup new mbuf to have leading space to prepend the
    545 		 * 802.11 header and any crypto header bits that are
    546 		 * required (the latter are added when the driver calls
    547 		 * back to ieee80211_crypto_encap to do crypto encapsulation).
    548 		 */
    549 		/* NB: must be first 'cuz it clobbers m_data */
    550 		M_MOVE_PKTHDR(n, m);
    551 		n->m_len = 0;			/* NB: m_gethdr does not set */
    552 		n->m_data += needed_space;
    553 		/*
    554 		 * Pull up Ethernet header to create the expected layout.
    555 		 * We could use m_pullup but that's overkill (i.e. we don't
    556 		 * need the actual data) and it cannot fail so do it inline
    557 		 * for speed.
    558 		 */
    559 		/* NB: struct ether_header is known to be contiguous */
    560 		n->m_len += sizeof(struct ether_header);
    561 		m->m_len -= sizeof(struct ether_header);
    562 		m->m_data += sizeof(struct ether_header);
    563 		/*
    564 		 * Replace the head of the chain.
    565 		 */
    566 		n->m_next = m;
    567 		m = n;
    568 	} else {
    569                 /* We will overwrite the ethernet header in the
    570                  * 802.11 encapsulation stage.  Make sure that it
    571                  * is writable.
    572 		 */
    573 		wlen = sizeof(struct ether_header);
    574 	}
    575 
    576 	/*
    577 	 * If we're going to s/w encrypt the mbuf chain make sure it is
    578 	 * writable.
    579 	 */
    580 	if (key != NULL && (key->wk_flags & IEEE80211_KEY_SWCRYPT) != 0)
    581 		wlen = M_COPYALL;
    582 
    583 	if (wlen != 0 && m_makewritable(&m, 0, wlen, M_DONTWAIT) != 0) {
    584 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
    585 		    "%s: cannot get writable mbuf\n", __func__);
    586 		ic->ic_stats.is_tx_nobuf++; /* XXX new stat */
    587 		m_freem(m);
    588 		return NULL;
    589 	}
    590 	return m;
    591 #undef TO_BE_RECLAIMED
    592 }
    593 
    594 /*
    595  * Return the transmit key to use in sending a unicast frame.
    596  * If a unicast key is set we use that.  When no unicast key is set
    597  * we fall back to the default transmit key.
    598  */
    599 static __inline struct ieee80211_key *
    600 ieee80211_crypto_getucastkey(struct ieee80211com *ic, struct ieee80211_node *ni)
    601 {
    602 	if (IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey)) {
    603 		if (ic->ic_def_txkey == IEEE80211_KEYIX_NONE ||
    604 		    IEEE80211_KEY_UNDEFINED(&ic->ic_nw_keys[ic->ic_def_txkey]))
    605 			return NULL;
    606 		return &ic->ic_nw_keys[ic->ic_def_txkey];
    607 	} else {
    608 		return &ni->ni_ucastkey;
    609 	}
    610 }
    611 
    612 /*
    613  * Return the transmit key to use in sending a multicast frame.
    614  * Multicast traffic always uses the group key which is installed as
    615  * the default tx key.
    616  */
    617 static __inline struct ieee80211_key *
    618 ieee80211_crypto_getmcastkey(struct ieee80211com *ic,
    619     struct ieee80211_node *ni)
    620 {
    621 	if (ic->ic_def_txkey == IEEE80211_KEYIX_NONE ||
    622 	    IEEE80211_KEY_UNDEFINED(&ic->ic_nw_keys[ic->ic_def_txkey]))
    623 		return NULL;
    624 	return &ic->ic_nw_keys[ic->ic_def_txkey];
    625 }
    626 
    627 /*
    628  * Encapsulate an outbound data frame.  The mbuf chain is updated.
    629  * If an error is encountered NULL is returned.  The caller is required
    630  * to provide a node reference and pullup the ethernet header in the
    631  * first mbuf.
    632  */
    633 struct mbuf *
    634 ieee80211_encap(struct ieee80211com *ic, struct mbuf *m,
    635 	struct ieee80211_node *ni)
    636 {
    637 	struct ether_header eh;
    638 	struct ieee80211_frame *wh;
    639 	struct ieee80211_key *key;
    640 	struct llc *llc;
    641 	int hdrsize, datalen, addqos, txfrag, isff;
    642 
    643 	/*
    644 	 * Copy existing Ethernet header to a safe place.  The
    645 	 * rest of the code assumes it's ok to strip it when
    646 	 * reorganizing state for the final encapsulation.
    647 	 */
    648 	IASSERT(m->m_len >= sizeof(eh), ("no ethernet header!"));
    649 	memcpy(&eh, mtod(m, void *), sizeof(struct ether_header));
    650 
    651 	/*
    652 	 * Insure space for additional headers.  First identify
    653 	 * transmit key to use in calculating any buffer adjustments
    654 	 * required.  This is also used below to do privacy
    655 	 * encapsulation work.  Then calculate the 802.11 header
    656 	 * size and any padding required by the driver.
    657 	 *
    658 	 * Note key may be NULL if we fall back to the default
    659 	 * transmit key and that is not set.  In that case the
    660 	 * buffer may not be expanded as needed by the cipher
    661 	 * routines, but they will/should discard it.
    662 	 */
    663 	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
    664 		if (ic->ic_opmode == IEEE80211_M_STA ||
    665 		    !IEEE80211_IS_MULTICAST(eh.ether_dhost))
    666 			key = ieee80211_crypto_getucastkey(ic, ni);
    667 		else
    668 			key = ieee80211_crypto_getmcastkey(ic, ni);
    669 		if (key == NULL && eh.ether_type != htons(ETHERTYPE_PAE)) {
    670 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_CRYPTO,
    671 			    "[%s] no default transmit key (%s) deftxkey %u\n",
    672 			    ether_sprintf(eh.ether_dhost), __func__,
    673 			    ic->ic_def_txkey);
    674 			ic->ic_stats.is_tx_nodefkey++;
    675 			goto bad;
    676 		}
    677 	} else
    678 		key = NULL;
    679 	/* XXX 4-address format */
    680 	/*
    681 	 * XXX Some ap's don't handle QoS-encapsulated EAPOL
    682 	 * frames so suppress use.  This may be an issue if other
    683 	 * ap's require all data frames to be QoS-encapsulated
    684 	 * once negotiated in which case we'll need to make this
    685 	 * configurable.
    686 	 */
    687 	addqos = (ni->ni_flags & (IEEE80211_NODE_QOS|IEEE80211_NODE_HT)) &&
    688 		 eh.ether_type != htons(ETHERTYPE_PAE);
    689 	if (addqos)
    690 		hdrsize = sizeof(struct ieee80211_qosframe);
    691 	else
    692 		hdrsize = sizeof(struct ieee80211_frame);
    693 	if (ic->ic_flags & IEEE80211_F_DATAPAD)
    694 		hdrsize = roundup(hdrsize, sizeof(uint32_t));
    695 
    696 	if ((isff = m->m_flags & M_FF) != 0) {
    697 		struct mbuf *m2;
    698 		struct ether_header eh2;
    699 
    700 		/*
    701 		 * Fast frame encapsulation.  There must be two packets
    702 		 * chained with m_nextpkt.  We do header adjustment for
    703 		 * each, add the tunnel encapsulation, and then concatenate
    704 		 * the mbuf chains to form a single frame for transmission.
    705 		 */
    706 		m2 = m->m_nextpkt;
    707 		if (m2 == NULL) {
    708 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_SUPERG,
    709 				"%s: only one frame\n", __func__);
    710 			goto bad;
    711 		}
    712 		m->m_nextpkt = NULL;
    713 		/*
    714 		 * Include fast frame headers in adjusting header
    715 		 * layout; this allocates space according to what
    716 		 * ieee80211_encap_fastframe will do.
    717 		 */
    718 		m = ieee80211_mbuf_adjust(ic,
    719 			hdrsize + sizeof(struct llc) + sizeof(uint32_t) + 2 +
    720 			    sizeof(struct ether_header),
    721 			key, m);
    722 		if (m == NULL) {
    723 			/* NB: ieee80211_mbuf_adjust handles msgs+statistics */
    724 			m_freem(m2);
    725 			goto bad;
    726 		}
    727 		/*
    728 		 * Copy second frame's Ethernet header out of line
    729 		 * and adjust for encapsulation headers.  Note that
    730 		 * we make room for padding in case there isn't room
    731 		 * at the end of first frame.
    732 		 */
    733 		IASSERT(m2->m_len >= sizeof(eh2), ("no ethernet header!"));
    734 		memcpy(&eh2, mtod(m2, void *), sizeof(struct ether_header));
    735 		m2 = ieee80211_mbuf_adjust(ic,
    736 			ATH_FF_MAX_HDR_PAD + sizeof(struct ether_header),
    737 			NULL, m2);
    738 		if (m2 == NULL) {
    739 			/* NB: ieee80211_mbuf_adjust handles msgs+statistics */
    740 			goto bad;
    741 		}
    742 		m = ieee80211_encap_fastframe(ic, m, &eh, m2, &eh2);
    743 		if (m == NULL)
    744 			goto bad;
    745 	} else {
    746 		/*
    747 		 * Normal frame.
    748 		 */
    749 		m = ieee80211_mbuf_adjust(ic, hdrsize, key, m);
    750 		if (m == NULL) {
    751 			/* NB: ieee80211_mbuf_adjust handles msgs+statistics */
    752 			goto bad;
    753 		}
    754 		/* NB: this could be optimized 'cuz of ieee80211_mbuf_adjust */
    755 		m_adj(m, sizeof(struct ether_header) - sizeof(struct llc));
    756 		llc = mtod(m, struct llc *);
    757 		llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
    758 		llc->llc_control = LLC_UI;
    759 		llc->llc_snap.org_code[0] = 0;
    760 		llc->llc_snap.org_code[1] = 0;
    761 		llc->llc_snap.org_code[2] = 0;
    762 		llc->llc_snap.ether_type = eh.ether_type;
    763 	}
    764 	datalen = m->m_pkthdr.len;		/* NB: w/o 802.11 header */
    765 
    766 	M_PREPEND(m, hdrsize, M_DONTWAIT);
    767 	if (m == NULL) {
    768 		ic->ic_stats.is_tx_nobuf++;
    769 		goto bad;
    770 	}
    771 	wh = mtod(m, struct ieee80211_frame *);
    772 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_DATA;
    773 	*(uint16_t *)wh->i_dur = 0;
    774 	switch (ic->ic_opmode) {
    775 	case IEEE80211_M_STA:
    776 		wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
    777 		IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_bssid);
    778 		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
    779 		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost);
    780 		break;
    781 	case IEEE80211_M_IBSS:
    782 	case IEEE80211_M_AHDEMO:
    783 		wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
    784 		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
    785 		IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
    786 		/*
    787 		 * NB: always use the bssid from ic_bss as the
    788 		 *     neighbor's may be stale after an ibss merge
    789 		 */
    790 		IEEE80211_ADDR_COPY(wh->i_addr3, ic->ic_bss->ni_bssid);
    791 		break;
    792 	case IEEE80211_M_HOSTAP:
    793 #ifndef IEEE80211_NO_HOSTAP
    794 		wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
    795 		IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
    796 		IEEE80211_ADDR_COPY(wh->i_addr2, ni->ni_bssid);
    797 		IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_shost);
    798 #endif /* !IEEE80211_NO_HOSTAP */
    799 		break;
    800 	case IEEE80211_M_MONITOR:
    801 	case IEEE80211_M_WDS:
    802 		goto bad;
    803 	}
    804 	if (m->m_flags & M_MORE_DATA)
    805 		wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
    806 	if (addqos) {
    807 		struct ieee80211_qosframe *qwh =
    808 			(struct ieee80211_qosframe *) wh;
    809 		int ac, tid;
    810 
    811 		ac = M_WME_GETAC(m);
    812 		/* map from access class/queue to 11e header priorty value */
    813 		tid = WME_AC_TO_TID(ac);
    814 		qwh->i_qos[0] = tid & IEEE80211_QOS_TID;
    815 		/*
    816 		 * Check if A-MPDU tx aggregation is setup or if we
    817 		 * should try to enable it.  The sta must be associated
    818 		 * with HT and A-MPDU enabled for use.  On the first
    819 		 * frame that goes out We issue an ADDBA request and
    820 		 * wait for a reply.  The frame being encapsulated
    821 		 * will go out w/o using A-MPDU, or possibly it might
    822 		 * be collected by the driver and held/retransmit.
    823 		 * ieee80211_ampdu_request handles staggering requests
    824 		 * in case the receiver NAK's us or we are otherwise
    825 		 * unable to establish a BA stream.
    826 		 */
    827 		if ((ni->ni_flags & IEEE80211_NODE_AMPDU_TX) &&
    828 		    (ic->ic_flags_ext & IEEE80211_FEXT_AMPDU_TX)) {
    829 			struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[ac];
    830 
    831 			if (IEEE80211_AMPDU_RUNNING(tap)) {
    832 				/*
    833 				 * Operational, mark frame for aggregation.
    834 				 */
    835 				qwh->i_qos[0] |= IEEE80211_QOS_ACKPOLICY_BA;
    836 			} else if (!IEEE80211_AMPDU_REQUESTED(tap)) {
    837 				/*
    838 				 * Not negotiated yet, request service.
    839 				 */
    840 				ieee80211_ampdu_request(ni, tap);
    841 			}
    842 		}
    843 		/* XXX works even when BA marked above */
    844 		if (ic->ic_wme.wme_wmeChanParams.cap_wmeParams[ac].wmep_noackPolicy)
    845 			qwh->i_qos[0] |= IEEE80211_QOS_ACKPOLICY_NOACK;
    846 		qwh->i_qos[1] = 0;
    847 		qwh->i_fc[0] |= IEEE80211_FC0_SUBTYPE_QOS;
    848 
    849 		*(uint16_t *)wh->i_seq =
    850 		    htole16(ni->ni_txseqs[tid] << IEEE80211_SEQ_SEQ_SHIFT);
    851 		ni->ni_txseqs[tid]++;
    852 	} else {
    853 		*(uint16_t *)wh->i_seq =
    854 		    htole16(ni->ni_txseqs[IEEE80211_NONQOS_TID] << IEEE80211_SEQ_SEQ_SHIFT);
    855 		ni->ni_txseqs[IEEE80211_NONQOS_TID]++;
    856 	}
    857 	/* check if xmit fragmentation is required */
    858 	txfrag = (m->m_pkthdr.len > ic->ic_fragthreshold &&
    859 	    !IEEE80211_IS_MULTICAST(wh->i_addr1) &&
    860 	    (ic->ic_caps & IEEE80211_C_TXFRAG) &&
    861 	    !isff);		/* NB: don't fragment ff's */
    862 	if (key != NULL) {
    863 		/*
    864 		 * IEEE 802.1X: send EAPOL frames always in the clear.
    865 		 * WPA/WPA2: encrypt EAPOL keys when pairwise keys are set.
    866 		 */
    867 		if (eh.ether_type != htons(ETHERTYPE_PAE) ||
    868 		    ((ic->ic_flags & IEEE80211_F_WPA) &&
    869 		     (ic->ic_opmode == IEEE80211_M_STA ?
    870 		      !IEEE80211_KEY_UNDEFINED(key) :
    871 		      !IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey)))) {
    872 			wh->i_fc[1] |= IEEE80211_FC1_WEP;
    873 			if (!ieee80211_crypto_enmic(ic, key, m, txfrag)) {
    874 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
    875 				    "[%s] enmic failed, discard frame\n",
    876 				    ether_sprintf(eh.ether_dhost));
    877 				ic->ic_stats.is_crypto_enmicfail++;
    878 				goto bad;
    879 			}
    880 		}
    881 	}
    882 	/*
    883 	 * NB: frag flags may leak from above; they should only
    884 	 *     be set on return to the caller if we fragment at
    885 	 *     the 802.11 layer.
    886 	 */
    887 	m->m_flags &= ~(M_FRAG | M_FIRSTFRAG);
    888 	if (txfrag && !ieee80211_fragment(ic, m, hdrsize,
    889 	    key != NULL ? key->wk_cipher->ic_header : 0, ic->ic_fragthreshold))
    890 		goto bad;
    891 
    892 	IEEE80211_NODE_STAT(ni, tx_data);
    893 	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
    894 		IEEE80211_NODE_STAT(ni, tx_mcast);
    895 	else
    896 		IEEE80211_NODE_STAT(ni, tx_ucast);
    897 	IEEE80211_NODE_STAT_ADD(ni, tx_bytes, datalen);
    898 
    899 	return m;
    900 bad:
    901 	if (m != NULL)
    902 		m_freem(m);
    903 	return NULL;
    904 }
    905 
    906 /*
    907  * Arguments in:
    908  *
    909  * paylen:  payload length (no FCS, no WEP header)
    910  *
    911  * hdrlen:  header length
    912  *
    913  * rate:    MSDU speed, units 500kb/s
    914  *
    915  * flags:   IEEE80211_F_SHPREAMBLE (use short preamble),
    916  *          IEEE80211_F_SHSLOT (use short slot length)
    917  *
    918  * Arguments out:
    919  *
    920  * d:       802.11 Duration field for RTS,
    921  *          802.11 Duration field for data frame,
    922  *          PLCP Length for data frame,
    923  *          residual octets at end of data slot
    924  */
    925 static int
    926 ieee80211_compute_duration1(int len, int use_ack, uint32_t icflags, int rate,
    927     struct ieee80211_duration *d)
    928 {
    929 	int pre, ctsrate;
    930 	int ack, bitlen, data_dur, remainder;
    931 
    932 	/* RTS reserves medium for SIFS | CTS | SIFS | (DATA) | SIFS | ACK
    933 	 * DATA reserves medium for SIFS | ACK
    934 	 *
    935 	 * XXXMYC: no ACK on multicast/broadcast or control packets
    936 	 */
    937 
    938 	bitlen = len * 8;
    939 
    940 	pre = IEEE80211_DUR_DS_SIFS;
    941 	if ((icflags & IEEE80211_F_SHPREAMBLE) != 0)
    942 		pre += IEEE80211_DUR_DS_SHORT_PREAMBLE + IEEE80211_DUR_DS_FAST_PLCPHDR;
    943 	else
    944 		pre += IEEE80211_DUR_DS_LONG_PREAMBLE + IEEE80211_DUR_DS_SLOW_PLCPHDR;
    945 
    946 	d->d_residue = 0;
    947 	data_dur = (bitlen * 2) / rate;
    948 	remainder = (bitlen * 2) % rate;
    949 	if (remainder != 0) {
    950 		d->d_residue = (rate - remainder) / 16;
    951 		data_dur++;
    952 	}
    953 
    954 	switch (rate) {
    955 	case 2:		/* 1 Mb/s */
    956 	case 4:		/* 2 Mb/s */
    957 		/* 1 - 2 Mb/s WLAN: send ACK/CTS at 1 Mb/s */
    958 		ctsrate = 2;
    959 		break;
    960 	case 11:	/* 5.5 Mb/s */
    961 	case 22:	/* 11  Mb/s */
    962 	case 44:	/* 22  Mb/s */
    963 		/* 5.5 - 11 Mb/s WLAN: send ACK/CTS at 2 Mb/s */
    964 		ctsrate = 4;
    965 		break;
    966 	default:
    967 		/* TBD */
    968 		return -1;
    969 	}
    970 
    971 	d->d_plcp_len = data_dur;
    972 
    973 	ack = (use_ack) ? pre + (IEEE80211_DUR_DS_SLOW_ACK * 2) / ctsrate : 0;
    974 
    975 	d->d_rts_dur =
    976 	    pre + (IEEE80211_DUR_DS_SLOW_CTS * 2) / ctsrate +
    977 	    pre + data_dur +
    978 	    ack;
    979 
    980 	d->d_data_dur = ack;
    981 
    982 	return 0;
    983 }
    984 
    985 /*
    986  * Arguments in:
    987  *
    988  * wh:      802.11 header
    989  *
    990  * paylen:  payload length (no FCS, no WEP header)
    991  *
    992  * rate:    MSDU speed, units 500kb/s
    993  *
    994  * fraglen: fragment length, set to maximum (or higher) for no
    995  *          fragmentation
    996  *
    997  * flags:   IEEE80211_F_PRIVACY (hardware adds WEP),
    998  *          IEEE80211_F_SHPREAMBLE (use short preamble),
    999  *          IEEE80211_F_SHSLOT (use short slot length)
   1000  *
   1001  * Arguments out:
   1002  *
   1003  * d0: 802.11 Duration fields (RTS/Data), PLCP Length, Service fields
   1004  *     of first/only fragment
   1005  *
   1006  * dn: 802.11 Duration fields (RTS/Data), PLCP Length, Service fields
   1007  *     of last fragment
   1008  *
   1009  * ieee80211_compute_duration assumes crypto-encapsulation, if any,
   1010  * has already taken place.
   1011  */
   1012 int
   1013 ieee80211_compute_duration(const struct ieee80211_frame_min *wh,
   1014     const struct ieee80211_key *wk, int len,
   1015     uint32_t icflags, int fraglen, int rate, struct ieee80211_duration *d0,
   1016     struct ieee80211_duration *dn, int *npktp, int debug)
   1017 {
   1018 	int ack, rc;
   1019 	int cryptolen,	/* crypto overhead: header+trailer */
   1020 	    firstlen,	/* first fragment's payload + overhead length */
   1021 	    hdrlen,	/* header length w/o driver padding */
   1022 	    lastlen,	/* last fragment's payload length w/ overhead */
   1023 	    lastlen0,	/* last fragment's payload length w/o overhead */
   1024 	    npkt,	/* number of fragments */
   1025 	    overlen,	/* non-802.11 header overhead per fragment */
   1026 	    paylen;	/* payload length w/o overhead */
   1027 
   1028 	hdrlen = ieee80211_anyhdrsize((const void *)wh);
   1029 
   1030         /* Account for padding required by the driver. */
   1031 	if (icflags & IEEE80211_F_DATAPAD)
   1032 		paylen = len - roundup(hdrlen, sizeof(u_int32_t));
   1033 	else
   1034 		paylen = len - hdrlen;
   1035 
   1036 	overlen = IEEE80211_CRC_LEN;
   1037 
   1038 	if (wk != NULL) {
   1039 		cryptolen = wk->wk_cipher->ic_header +
   1040 		            wk->wk_cipher->ic_trailer;
   1041 		paylen -= cryptolen;
   1042 		overlen += cryptolen;
   1043 	}
   1044 
   1045 	npkt = paylen / fraglen;
   1046 	lastlen0 = paylen % fraglen;
   1047 
   1048 	if (npkt == 0)			/* no fragments */
   1049 		lastlen = paylen + overlen;
   1050 	else if (lastlen0 != 0) {	/* a short "tail" fragment */
   1051 		lastlen = lastlen0 + overlen;
   1052 		npkt++;
   1053 	} else				/* full-length "tail" fragment */
   1054 		lastlen = fraglen + overlen;
   1055 
   1056 	if (npktp != NULL)
   1057 		*npktp = npkt;
   1058 
   1059 	if (npkt > 1)
   1060 		firstlen = fraglen + overlen;
   1061 	else
   1062 		firstlen = paylen + overlen;
   1063 
   1064 	if (debug) {
   1065 		printf("%s: npkt %d firstlen %d lastlen0 %d lastlen %d "
   1066 		    "fraglen %d overlen %d len %d rate %d icflags %08x\n",
   1067 		    __func__, npkt, firstlen, lastlen0, lastlen, fraglen,
   1068 		    overlen, len, rate, icflags);
   1069 	}
   1070 
   1071 	ack = !IEEE80211_IS_MULTICAST(wh->i_addr1) &&
   1072 	    (wh->i_fc[1] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL;
   1073 
   1074 	rc = ieee80211_compute_duration1(firstlen + hdrlen,
   1075 	    ack, icflags, rate, d0);
   1076 	if (rc == -1)
   1077 		return rc;
   1078 
   1079 	if (npkt <= 1) {
   1080 		*dn = *d0;
   1081 		return 0;
   1082 	}
   1083 	return ieee80211_compute_duration1(lastlen + hdrlen, ack, icflags, rate,
   1084 	    dn);
   1085 }
   1086 
   1087 /*
   1088  * Do Ethernet-LLC encapsulation for each payload in a fast frame
   1089  * tunnel encapsulation.  The frame is assumed to have an Ethernet
   1090  * header at the front that must be stripped before prepending the
   1091  * LLC followed by the Ethernet header passed in (with an Ethernet
   1092  * type that specifies the payload size).
   1093  */
   1094 static struct mbuf *
   1095 ieee80211_encap1(struct ieee80211com *ic, struct mbuf *m,
   1096 	const struct ether_header *eh)
   1097 {
   1098 	struct llc *llc;
   1099 	uint16_t payload;
   1100 
   1101 	/* XXX optimize by combining m_adj+M_PREPEND */
   1102 	m_adj(m, sizeof(struct ether_header) - sizeof(struct llc));
   1103 	llc = mtod(m, struct llc *);
   1104 	llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
   1105 	llc->llc_control = LLC_UI;
   1106 	llc->llc_snap.org_code[0] = 0;
   1107 	llc->llc_snap.org_code[1] = 0;
   1108 	llc->llc_snap.org_code[2] = 0;
   1109 	llc->llc_snap.ether_type = eh->ether_type;
   1110 	payload = m->m_pkthdr.len;		/* NB: w/o Ethernet header */
   1111 
   1112 	M_PREPEND(m, sizeof(struct ether_header), M_DONTWAIT);
   1113 	if (m == NULL) {		/* XXX cannot happen */
   1114 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_SUPERG,
   1115 			"%s: no space for ether_header\n", __func__);
   1116 		ic->ic_stats.is_tx_nobuf++;
   1117 		return NULL;
   1118 	}
   1119 	ETHER_HEADER_COPY(mtod(m, void *), eh);
   1120 	mtod(m, struct ether_header *)->ether_type = htons(payload);
   1121 	return m;
   1122 }
   1123 
   1124 /*
   1125  * Do fast frame tunnel encapsulation.  The two frames and
   1126  * Ethernet headers are supplied.  The caller is assumed to
   1127  * have arrange for space in the mbuf chains for encapsulating
   1128  * headers (to avoid major mbuf fragmentation).
   1129  *
   1130  * The encapsulated frame is returned or NULL if there is a
   1131  * problem (should not happen).
   1132  */
   1133 static struct mbuf *
   1134 ieee80211_encap_fastframe(struct ieee80211com *ic,
   1135 	struct mbuf *m1, const struct ether_header *eh1,
   1136 	struct mbuf *m2, const struct ether_header *eh2)
   1137 {
   1138 	struct llc *llc;
   1139 	struct mbuf *m;
   1140 	int pad;
   1141 
   1142 	/*
   1143 	 * First, each frame gets a standard encapsulation.
   1144 	 */
   1145 	m1 = ieee80211_encap1(ic, m1, eh1);
   1146 	if (m1 == NULL) {
   1147 		m_freem(m2);
   1148 		return NULL;
   1149 	}
   1150 	m2 = ieee80211_encap1(ic, m2, eh2);
   1151 	if (m2 == NULL) {
   1152 		m_freem(m1);
   1153 		return NULL;
   1154 	}
   1155 
   1156 	/*
   1157 	 * Pad leading frame to a 4-byte boundary.  If there
   1158 	 * is space at the end of the first frame, put it
   1159 	 * there; otherwise prepend to the front of the second
   1160 	 * frame.  We know doing the second will always work
   1161 	 * because we reserve space above.  We prefer appending
   1162 	 * as this typically has better DMA alignment properties.
   1163 	 */
   1164 	for (m = m1; m->m_next != NULL; m = m->m_next)
   1165 		;
   1166 	pad = roundup2(m1->m_pkthdr.len, 4) - m1->m_pkthdr.len;
   1167 	if (pad) {
   1168 		if (M_TRAILINGSPACE(m) < pad) {		/* prepend to second */
   1169 			m2->m_data -= pad;
   1170 			m2->m_len += pad;
   1171 			m2->m_pkthdr.len += pad;
   1172 		} else {				/* append to first */
   1173 			m->m_len += pad;
   1174 			m1->m_pkthdr.len += pad;
   1175 		}
   1176 	}
   1177 
   1178 	/*
   1179 	 * Now, stick 'em together and prepend the tunnel headers;
   1180 	 * first the Atheros tunnel header (all zero for now) and
   1181 	 * then a special fast frame LLC.
   1182 	 *
   1183 	 * XXX optimize by prepending together
   1184 	 */
   1185 	m->m_next = m2;			/* NB: last mbuf from above */
   1186 	m1->m_pkthdr.len += m2->m_pkthdr.len;
   1187 	M_PREPEND(m1, sizeof(uint32_t)+2, M_DONTWAIT);
   1188 	if (m1 == NULL) {		/* XXX cannot happen */
   1189 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_SUPERG,
   1190 			"%s: no space for tunnel header\n", __func__);
   1191 		ic->ic_stats.is_tx_nobuf++;
   1192 		return NULL;
   1193 	}
   1194 	memset(mtod(m1, void *), 0, sizeof(uint32_t)+2);
   1195 
   1196 	M_PREPEND(m1, sizeof(struct llc), M_DONTWAIT);
   1197 	if (m1 == NULL) {		/* XXX cannot happen */
   1198 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_SUPERG,
   1199 			"%s: no space for llc header\n", __func__);
   1200 		ic->ic_stats.is_tx_nobuf++;
   1201 		return NULL;
   1202 	}
   1203 	llc = mtod(m1, struct llc *);
   1204 	llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
   1205 	llc->llc_control = LLC_UI;
   1206 	llc->llc_snap.org_code[0] = ATH_FF_SNAP_ORGCODE_0;
   1207 	llc->llc_snap.org_code[1] = ATH_FF_SNAP_ORGCODE_1;
   1208 	llc->llc_snap.org_code[2] = ATH_FF_SNAP_ORGCODE_2;
   1209 	llc->llc_snap.ether_type = htons(ATH_FF_ETH_TYPE);
   1210 
   1211 	ic->ic_stats.is_ff_encap++;
   1212 
   1213 	return m1;
   1214 }
   1215 
   1216 /*
   1217  * Fragment the frame according to the specified mtu.
   1218  * The size of the 802.11 header (w/o padding) is provided
   1219  * so we don't need to recalculate it.  We create a new
   1220  * mbuf for each fragment and chain it through m_nextpkt;
   1221  * we might be able to optimize this by reusing the original
   1222  * packet's mbufs but that is significantly more complicated.
   1223  */
   1224 static int
   1225 ieee80211_fragment(struct ieee80211com *ic, struct mbuf *m0,
   1226 	u_int hdrsize, u_int ciphdrsize, u_int mtu)
   1227 {
   1228 	struct ieee80211_frame *wh, *whf;
   1229 	struct mbuf *m, *prev, *next;
   1230 	u_int totalhdrsize, fragno, fragsize, off, remainder, payload;
   1231 
   1232 	IASSERT(m0->m_nextpkt == NULL, ("mbuf already chained?"));
   1233 	IASSERT(m0->m_pkthdr.len > mtu,
   1234 		("pktlen %u mtu %u", m0->m_pkthdr.len, mtu));
   1235 
   1236 	wh = mtod(m0, struct ieee80211_frame *);
   1237 	/* NB: mark the first frag; it will be propagated below */
   1238 	wh->i_fc[1] |= IEEE80211_FC1_MORE_FRAG;
   1239 	totalhdrsize = hdrsize + ciphdrsize;
   1240 	fragno = 1;
   1241 	off = mtu - ciphdrsize;
   1242 	remainder = m0->m_pkthdr.len - off;
   1243 	prev = m0;
   1244 	do {
   1245 		fragsize = totalhdrsize + remainder;
   1246 		if (fragsize > mtu)
   1247 			fragsize = mtu;
   1248 		IASSERT(fragsize < MCLBYTES,
   1249 			("fragment size %u too big!", fragsize));
   1250 		if (fragsize > MHLEN)
   1251 			m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
   1252 		else
   1253 			m = m_gethdr(M_DONTWAIT, MT_DATA);
   1254 		if (m == NULL)
   1255 			goto bad;
   1256 		/* leave room to prepend any cipher header */
   1257 		m_align(m, fragsize - ciphdrsize);
   1258 
   1259 		/*
   1260 		 * Form the header in the fragment.  Note that since
   1261 		 * we mark the first fragment with the MORE_FRAG bit
   1262 		 * it automatically is propagated to each fragment; we
   1263 		 * need only clear it on the last fragment (done below).
   1264 		 */
   1265 		whf = mtod(m, struct ieee80211_frame *);
   1266 		memcpy(whf, wh, hdrsize);
   1267 		*(u_int16_t *)&whf->i_seq[0] |= htole16(
   1268 			(fragno & IEEE80211_SEQ_FRAG_MASK) <<
   1269 				IEEE80211_SEQ_FRAG_SHIFT);
   1270 		fragno++;
   1271 
   1272 		payload = fragsize - totalhdrsize;
   1273 		/* NB: destination is known to be contiguous */
   1274 		m_copydata(m0, off, payload, mtod(m, u_int8_t *) + hdrsize);
   1275 		m->m_len = hdrsize + payload;
   1276 		m->m_pkthdr.len = hdrsize + payload;
   1277 		m->m_flags |= M_FRAG;
   1278 
   1279 		/* chain up the fragment */
   1280 		prev->m_nextpkt = m;
   1281 		prev = m;
   1282 
   1283 		/* deduct fragment just formed */
   1284 		remainder -= payload;
   1285 		off += payload;
   1286 	} while (remainder != 0);
   1287 	whf->i_fc[1] &= ~IEEE80211_FC1_MORE_FRAG;
   1288 
   1289 	/* strip first mbuf now that everything has been copied */
   1290 	m_adj(m0, -(m0->m_pkthdr.len - (mtu - ciphdrsize)));
   1291 	m0->m_flags |= M_FIRSTFRAG | M_FRAG;
   1292 
   1293 	ic->ic_stats.is_tx_fragframes++;
   1294 	ic->ic_stats.is_tx_frags += fragno-1;
   1295 
   1296 	return 1;
   1297 bad:
   1298 	/* reclaim fragments but leave original frame for caller to free */
   1299 	for (m = m0->m_nextpkt; m != NULL; m = next) {
   1300 		next = m->m_nextpkt;
   1301 		m->m_nextpkt = NULL;            /* XXX paranoid */
   1302 		m_freem(m);
   1303 	}
   1304 	m0->m_nextpkt = NULL;
   1305 	return 0;
   1306 }
   1307 
   1308 /*
   1309  * Add a supported rates element id to a frame.
   1310  */
   1311 static uint8_t *
   1312 ieee80211_add_rates(uint8_t *frm, const struct ieee80211_rateset *rs)
   1313 {
   1314 	int nrates;
   1315 
   1316 	*frm++ = IEEE80211_ELEMID_RATES;
   1317 	nrates = rs->rs_nrates;
   1318 	if (nrates > IEEE80211_RATE_SIZE)
   1319 		nrates = IEEE80211_RATE_SIZE;
   1320 	*frm++ = nrates;
   1321 	memcpy(frm, rs->rs_rates, nrates);
   1322 	return frm + nrates;
   1323 }
   1324 
   1325 /*
   1326  * Add an extended supported rates element id to a frame.
   1327  */
   1328 static uint8_t *
   1329 ieee80211_add_xrates(uint8_t *frm, const struct ieee80211_rateset *rs)
   1330 {
   1331 	/*
   1332 	 * Add an extended supported rates element if operating in 11g mode.
   1333 	 */
   1334 	if (rs->rs_nrates > IEEE80211_RATE_SIZE) {
   1335 		int nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
   1336 		*frm++ = IEEE80211_ELEMID_XRATES;
   1337 		*frm++ = nrates;
   1338 		memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
   1339 		frm += nrates;
   1340 	}
   1341 	return frm;
   1342 }
   1343 
   1344 /*
   1345  * Add an ssid elemet to a frame.
   1346  */
   1347 static uint8_t *
   1348 ieee80211_add_ssid(uint8_t *frm, const uint8_t *ssid, u_int len)
   1349 {
   1350 	*frm++ = IEEE80211_ELEMID_SSID;
   1351 	*frm++ = len;
   1352 	memcpy(frm, ssid, len);
   1353 	return frm + len;
   1354 }
   1355 
   1356 /*
   1357  * Add an erp element to a frame.
   1358  */
   1359 static uint8_t *
   1360 ieee80211_add_erp(uint8_t *frm, struct ieee80211com *ic)
   1361 {
   1362 	uint8_t erp;
   1363 
   1364 	*frm++ = IEEE80211_ELEMID_ERP;
   1365 	*frm++ = 1;
   1366 	erp = 0;
   1367 	if (ic->ic_nonerpsta != 0)
   1368 		erp |= IEEE80211_ERP_NON_ERP_PRESENT;
   1369 	if (ic->ic_flags & IEEE80211_F_USEPROT)
   1370 		erp |= IEEE80211_ERP_USE_PROTECTION;
   1371 	if (ic->ic_flags & IEEE80211_F_USEBARKER)
   1372 		erp |= IEEE80211_ERP_LONG_PREAMBLE;
   1373 	*frm++ = erp;
   1374 	return frm;
   1375 }
   1376 
   1377 static uint8_t *
   1378 ieee80211_setup_wpa_ie(struct ieee80211com *ic, uint8_t *ie)
   1379 {
   1380 #define	WPA_OUI_BYTES		0x00, 0x50, 0xf2
   1381 #define	ADDSHORT(frm, v) do {			\
   1382 	frm[0] = (v) & 0xff;			\
   1383 	frm[1] = (v) >> 8;			\
   1384 	frm += 2;				\
   1385 } while (0)
   1386 #define	ADDSELECTOR(frm, sel) do {		\
   1387 	memcpy(frm, sel, 4);			\
   1388 	frm += 4;				\
   1389 } while (0)
   1390 	static const uint8_t oui[4] = { WPA_OUI_BYTES, WPA_OUI_TYPE };
   1391 	static const uint8_t cipher_suite[][4] = {
   1392 		{ WPA_OUI_BYTES, WPA_CSE_WEP40 },	/* NB: 40-bit */
   1393 		{ WPA_OUI_BYTES, WPA_CSE_TKIP },
   1394 		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX WRAP */
   1395 		{ WPA_OUI_BYTES, WPA_CSE_CCMP },
   1396 		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX CKIP */
   1397 		{ WPA_OUI_BYTES, WPA_CSE_NULL },
   1398 	};
   1399 	static const uint8_t wep104_suite[4] =
   1400 		{ WPA_OUI_BYTES, WPA_CSE_WEP104 };
   1401 	static const uint8_t key_mgt_unspec[4] =
   1402 		{ WPA_OUI_BYTES, WPA_ASE_8021X_UNSPEC };
   1403 	static const uint8_t key_mgt_psk[4] =
   1404 		{ WPA_OUI_BYTES, WPA_ASE_8021X_PSK };
   1405 	const struct ieee80211_rsnparms *rsn = &ic->ic_bss->ni_rsn;
   1406 	uint8_t *frm = ie;
   1407 	uint8_t *selcnt;
   1408 
   1409 	*frm++ = IEEE80211_ELEMID_VENDOR;
   1410 	*frm++ = 0;				/* length filled in below */
   1411 	memcpy(frm, oui, sizeof(oui));		/* WPA OUI */
   1412 	frm += sizeof(oui);
   1413 	ADDSHORT(frm, WPA_VERSION);
   1414 
   1415 	/* XXX filter out CKIP */
   1416 
   1417 	/* multicast cipher */
   1418 	if (rsn->rsn_mcastcipher == IEEE80211_CIPHER_WEP &&
   1419 	    rsn->rsn_mcastkeylen >= 13)
   1420 		ADDSELECTOR(frm, wep104_suite);
   1421 	else
   1422 		ADDSELECTOR(frm, cipher_suite[rsn->rsn_mcastcipher]);
   1423 
   1424 	/* unicast cipher list */
   1425 	selcnt = frm;
   1426 	ADDSHORT(frm, 0);			/* selector count */
   1427 	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_AES_CCM)) {
   1428 		selcnt[0]++;
   1429 		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_AES_CCM]);
   1430 	}
   1431 	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_TKIP)) {
   1432 		selcnt[0]++;
   1433 		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_TKIP]);
   1434 	}
   1435 
   1436 	/* authenticator selector list */
   1437 	selcnt = frm;
   1438 	ADDSHORT(frm, 0);			/* selector count */
   1439 	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_UNSPEC) {
   1440 		selcnt[0]++;
   1441 		ADDSELECTOR(frm, key_mgt_unspec);
   1442 	}
   1443 	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_PSK) {
   1444 		selcnt[0]++;
   1445 		ADDSELECTOR(frm, key_mgt_psk);
   1446 	}
   1447 
   1448 	/* optional capabilities */
   1449 	if (rsn->rsn_caps != 0 && rsn->rsn_caps != RSN_CAP_PREAUTH)
   1450 		ADDSHORT(frm, rsn->rsn_caps);
   1451 
   1452 	/* calculate element length */
   1453 	ie[1] = frm - ie - 2;
   1454 	IASSERT(ie[1]+2 <= sizeof(struct ieee80211_ie_wpa),
   1455 		("WPA IE too big, %u > %zu",
   1456 		ie[1]+2, sizeof(struct ieee80211_ie_wpa)));
   1457 	return frm;
   1458 #undef ADDSHORT
   1459 #undef ADDSELECTOR
   1460 #undef WPA_OUI_BYTES
   1461 }
   1462 
   1463 static uint8_t *
   1464 ieee80211_setup_rsn_ie(struct ieee80211com *ic, uint8_t *ie)
   1465 {
   1466 #define	RSN_OUI_BYTES		0x00, 0x0f, 0xac
   1467 #define	ADDSHORT(frm, v) do {			\
   1468 	frm[0] = (v) & 0xff;			\
   1469 	frm[1] = (v) >> 8;			\
   1470 	frm += 2;				\
   1471 } while (0)
   1472 #define	ADDSELECTOR(frm, sel) do {		\
   1473 	memcpy(frm, sel, 4);			\
   1474 	frm += 4;				\
   1475 } while (0)
   1476 	static const uint8_t cipher_suite[][4] = {
   1477 		{ RSN_OUI_BYTES, RSN_CSE_WEP40 },	/* NB: 40-bit */
   1478 		{ RSN_OUI_BYTES, RSN_CSE_TKIP },
   1479 		{ RSN_OUI_BYTES, RSN_CSE_WRAP },
   1480 		{ RSN_OUI_BYTES, RSN_CSE_CCMP },
   1481 		{ 0x00, 0x00, 0x00, 0x00 },		/* XXX CKIP */
   1482 		{ RSN_OUI_BYTES, RSN_CSE_NULL },
   1483 	};
   1484 	static const uint8_t wep104_suite[4] =
   1485 		{ RSN_OUI_BYTES, RSN_CSE_WEP104 };
   1486 	static const uint8_t key_mgt_unspec[4] =
   1487 		{ RSN_OUI_BYTES, RSN_ASE_8021X_UNSPEC };
   1488 	static const uint8_t key_mgt_psk[4] =
   1489 		{ RSN_OUI_BYTES, RSN_ASE_8021X_PSK };
   1490 	const struct ieee80211_rsnparms *rsn = &ic->ic_bss->ni_rsn;
   1491 	uint8_t *frm = ie;
   1492 	uint8_t *selcnt;
   1493 
   1494 	*frm++ = IEEE80211_ELEMID_RSN;
   1495 	*frm++ = 0;				/* length filled in below */
   1496 	ADDSHORT(frm, RSN_VERSION);
   1497 
   1498 	/* XXX filter out CKIP */
   1499 
   1500 	/* multicast cipher */
   1501 	if (rsn->rsn_mcastcipher == IEEE80211_CIPHER_WEP &&
   1502 	    rsn->rsn_mcastkeylen >= 13)
   1503 		ADDSELECTOR(frm, wep104_suite);
   1504 	else
   1505 		ADDSELECTOR(frm, cipher_suite[rsn->rsn_mcastcipher]);
   1506 
   1507 	/* unicast cipher list */
   1508 	selcnt = frm;
   1509 	ADDSHORT(frm, 0);			/* selector count */
   1510 	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_AES_CCM)) {
   1511 		selcnt[0]++;
   1512 		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_AES_CCM]);
   1513 	}
   1514 	if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_TKIP)) {
   1515 		selcnt[0]++;
   1516 		ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_TKIP]);
   1517 	}
   1518 
   1519 	/* authenticator selector list */
   1520 	selcnt = frm;
   1521 	ADDSHORT(frm, 0);			/* selector count */
   1522 	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_UNSPEC) {
   1523 		selcnt[0]++;
   1524 		ADDSELECTOR(frm, key_mgt_unspec);
   1525 	}
   1526 	if (rsn->rsn_keymgmtset & WPA_ASE_8021X_PSK) {
   1527 		selcnt[0]++;
   1528 		ADDSELECTOR(frm, key_mgt_psk);
   1529 	}
   1530 
   1531 	/* optional capabilities */
   1532 	ADDSHORT(frm, rsn->rsn_caps);
   1533 	/* XXX PMKID */
   1534 
   1535 	/* calculate element length */
   1536 	ie[1] = frm - ie - 2;
   1537 	IASSERT(ie[1]+2 <= sizeof(struct ieee80211_ie_wpa),
   1538 		("RSN IE too big, %u > %zu",
   1539 		ie[1]+2, sizeof(struct ieee80211_ie_wpa)));
   1540 	return frm;
   1541 #undef ADDSELECTOR
   1542 #undef ADDSHORT
   1543 #undef RSN_OUI_BYTES
   1544 }
   1545 
   1546 /*
   1547  * Add a WPA/RSN element to a frame.
   1548  */
   1549 static uint8_t *
   1550 ieee80211_add_wpa(uint8_t *frm, struct ieee80211com *ic)
   1551 {
   1552 
   1553 	IASSERT(ic->ic_flags & IEEE80211_F_WPA, ("no WPA/RSN!"));
   1554 	if (ic->ic_flags & IEEE80211_F_WPA2)
   1555 		frm = ieee80211_setup_rsn_ie(ic, frm);
   1556 	if (ic->ic_flags & IEEE80211_F_WPA1)
   1557 		frm = ieee80211_setup_wpa_ie(ic, frm);
   1558 	return frm;
   1559 }
   1560 
   1561 #define	WME_OUI_BYTES		0x00, 0x50, 0xf2
   1562 /*
   1563  * Add a WME information element to a frame.
   1564  */
   1565 static uint8_t *
   1566 ieee80211_add_wme_info(uint8_t *frm, struct ieee80211_wme_state *wme)
   1567 {
   1568 	static const struct ieee80211_wme_info info = {
   1569 		.wme_id		= IEEE80211_ELEMID_VENDOR,
   1570 		.wme_len	= sizeof(struct ieee80211_wme_info) - 2,
   1571 		.wme_oui	= { WME_OUI_BYTES },
   1572 		.wme_type	= WME_OUI_TYPE,
   1573 		.wme_subtype	= WME_INFO_OUI_SUBTYPE,
   1574 		.wme_version	= WME_VERSION,
   1575 		.wme_info	= 0,
   1576 	};
   1577 	memcpy(frm, &info, sizeof(info));
   1578 	return frm + sizeof(info);
   1579 }
   1580 
   1581 /*
   1582  * Add a WME parameters element to a frame.
   1583  */
   1584 static uint8_t *
   1585 ieee80211_add_wme_param(uint8_t *frm, struct ieee80211_wme_state *wme)
   1586 {
   1587 #define	SM(_v, _f)	(((_v) << _f##_S) & _f)
   1588 #define	ADDSHORT(frm, v) do {			\
   1589 	frm[0] = (v) & 0xff;			\
   1590 	frm[1] = (v) >> 8;			\
   1591 	frm += 2;				\
   1592 } while (0)
   1593 	/* NB: this works 'cuz a param has an info at the front */
   1594 	static const struct ieee80211_wme_info param = {
   1595 		.wme_id		= IEEE80211_ELEMID_VENDOR,
   1596 		.wme_len	= sizeof(struct ieee80211_wme_param) - 2,
   1597 		.wme_oui	= { WME_OUI_BYTES },
   1598 		.wme_type	= WME_OUI_TYPE,
   1599 		.wme_subtype	= WME_PARAM_OUI_SUBTYPE,
   1600 		.wme_version	= WME_VERSION,
   1601 	};
   1602 	int i;
   1603 
   1604 	memcpy(frm, &param, sizeof(param));
   1605 	frm += __offsetof(struct ieee80211_wme_info, wme_info);
   1606 	*frm++ = wme->wme_bssChanParams.cap_info;	/* AC info */
   1607 	*frm++ = 0;					/* reserved field */
   1608 	for (i = 0; i < WME_NUM_AC; i++) {
   1609 		const struct wmeParams *ac =
   1610 		       &wme->wme_bssChanParams.cap_wmeParams[i];
   1611 		*frm++ = SM(i, WME_PARAM_ACI)
   1612 		       | SM(ac->wmep_acm, WME_PARAM_ACM)
   1613 		       | SM(ac->wmep_aifsn, WME_PARAM_AIFSN)
   1614 		       ;
   1615 		*frm++ = SM(ac->wmep_logcwmax, WME_PARAM_LOGCWMAX)
   1616 		       | SM(ac->wmep_logcwmin, WME_PARAM_LOGCWMIN)
   1617 		       ;
   1618 		ADDSHORT(frm, ac->wmep_txopLimit);
   1619 	}
   1620 	return frm;
   1621 #undef SM
   1622 #undef ADDSHORT
   1623 }
   1624 #undef WME_OUI_BYTES
   1625 
   1626 #define	ATH_OUI_BYTES		0x00, 0x03, 0x7f
   1627 /*
   1628  * Add a WME information element to a frame.
   1629  */
   1630 static uint8_t *
   1631 ieee80211_add_ath(uint8_t *frm, uint8_t caps, uint16_t defkeyix)
   1632 {
   1633 	static const struct ieee80211_ath_ie info = {
   1634 		.ath_id		= IEEE80211_ELEMID_VENDOR,
   1635 		.ath_len	= sizeof(struct ieee80211_ath_ie) - 2,
   1636 		.ath_oui	= { ATH_OUI_BYTES },
   1637 		.ath_oui_type	= ATH_OUI_TYPE,
   1638 		.ath_oui_subtype= ATH_OUI_SUBTYPE,
   1639 		.ath_version	= ATH_OUI_VERSION,
   1640 	};
   1641 	struct ieee80211_ath_ie *ath = (struct ieee80211_ath_ie *) frm;
   1642 
   1643 	memcpy(frm, &info, sizeof(info));
   1644 	ath->ath_capability = caps;
   1645 	ath->ath_defkeyix[0] = (defkeyix & 0xff);
   1646 	ath->ath_defkeyix[1] = ((defkeyix >> 8) & 0xff);
   1647 	return frm + sizeof(info);
   1648 }
   1649 #undef ATH_OUI_BYTES
   1650 
   1651 /*
   1652  * Send a probe request frame with the specified ssid
   1653  * and any optional information element data.
   1654  */
   1655 int
   1656 ieee80211_send_probereq(struct ieee80211_node *ni,
   1657 	const uint8_t sa[IEEE80211_ADDR_LEN],
   1658 	const uint8_t da[IEEE80211_ADDR_LEN],
   1659 	const uint8_t bssid[IEEE80211_ADDR_LEN],
   1660 	const uint8_t *ssid, size_t ssidlen,
   1661 	const void *optie, size_t optielen)
   1662 {
   1663 	struct ieee80211com *ic = ni->ni_ic;
   1664 	struct ieee80211_frame *wh;
   1665 	const struct ieee80211_rateset *rs;
   1666 	struct mbuf *m;
   1667 	uint8_t *frm;
   1668 
   1669 	/*
   1670 	 * Hold a reference on the node so it doesn't go away until after
   1671 	 * the xmit is complete all the way in the driver.  On error we
   1672 	 * will remove our reference.
   1673 	 */
   1674 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   1675 		"ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
   1676 		__func__, __LINE__,
   1677 		ni, ether_sprintf(ni->ni_macaddr),
   1678 		ieee80211_node_refcnt(ni)+1);
   1679 	ieee80211_ref_node(ni);
   1680 
   1681 	/*
   1682 	 * prreq frame format
   1683 	 *	[tlv] ssid
   1684 	 *	[tlv] supported rates
   1685 	 *	[tlv] extended supported rates
   1686 	 *	[tlv] user-specified ie's
   1687 	 */
   1688 	m = ieee80211_getmgtframe(&frm,
   1689 		 ic->ic_headroom + sizeof(struct ieee80211_frame),
   1690 		 2 + IEEE80211_NWID_LEN
   1691 	       + 2 + IEEE80211_RATE_SIZE
   1692 	       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
   1693 	       + (optie != NULL ? optielen : 0)
   1694 	);
   1695 	if (m == NULL) {
   1696 		ic->ic_stats.is_tx_nobuf++;
   1697 		ieee80211_free_node(ni);
   1698 		return ENOMEM;
   1699 	}
   1700 
   1701 	frm = ieee80211_add_ssid(frm, ssid, ssidlen);
   1702 	rs = ieee80211_get_suprates(ic, ic->ic_curchan);
   1703 	frm = ieee80211_add_rates(frm, rs);
   1704 	frm = ieee80211_add_xrates(frm, rs);
   1705 
   1706 	if (optie != NULL) {
   1707 		memcpy(frm, optie, optielen);
   1708 		frm += optielen;
   1709 	}
   1710 	m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
   1711 
   1712 	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
   1713 	if (m == NULL)
   1714 		return ENOMEM;
   1715 	IASSERT(m->m_pkthdr.rcvif == NULL, ("rcvif not null"));
   1716 	m->m_pkthdr.rcvif = (void *)ni;
   1717 
   1718 	wh = mtod(m, struct ieee80211_frame *);
   1719 	ieee80211_send_setup(ic, ni, wh,
   1720 		IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_REQ,
   1721 		sa, da, bssid);
   1722 	/* XXX power management? */
   1723 
   1724 	IEEE80211_NODE_STAT(ni, tx_probereq);
   1725 	IEEE80211_NODE_STAT(ni, tx_mgmt);
   1726 
   1727 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
   1728 	    "[%s] send probe req on channel %u\n",
   1729 	    ether_sprintf(wh->i_addr1),
   1730 	    ieee80211_chan2ieee(ic, ic->ic_curchan));
   1731 
   1732 	IF_ENQUEUE(&ic->ic_mgtq, m);
   1733 	(*ic->ic_ifp->if_start)(ic->ic_ifp);
   1734 	return 0;
   1735 }
   1736 
   1737 /*
   1738  * Calculate capability information for mgt frames.
   1739  */
   1740 static uint16_t
   1741 getcapinfo(struct ieee80211com *ic, struct ieee80211_channel *chan)
   1742 {
   1743 	uint16_t capinfo;
   1744 
   1745 	IASSERT(ic->ic_opmode != IEEE80211_M_STA, ("station mode"));
   1746 
   1747 	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
   1748 		capinfo = IEEE80211_CAPINFO_ESS;
   1749 	else if (ic->ic_opmode == IEEE80211_M_IBSS)
   1750 		capinfo = IEEE80211_CAPINFO_IBSS;
   1751 	else
   1752 		capinfo = 0;
   1753 	if (ic->ic_flags & IEEE80211_F_PRIVACY)
   1754 		capinfo |= IEEE80211_CAPINFO_PRIVACY;
   1755 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
   1756 	    IEEE80211_IS_CHAN_2GHZ(chan))
   1757 		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
   1758 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
   1759 		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
   1760 	return capinfo;
   1761 }
   1762 
   1763 /*
   1764  * Send a management frame.  The node is for the destination (or ic_bss
   1765  * when in station mode).  Nodes other than ic_bss have their reference
   1766  * count bumped to reflect our use for an indeterminant time.
   1767  */
   1768 int
   1769 ieee80211_send_mgmt(struct ieee80211com *ic, struct ieee80211_node *ni,
   1770 	int type, int arg)
   1771 {
   1772 #define	HTFLAGS (IEEE80211_NODE_HT | IEEE80211_NODE_HTCOMPAT)
   1773 #define	senderr(_x, _v)	do { ic->ic_stats._v++; ret = _x; goto bad; } while (0)
   1774 	const struct ieee80211_rateset *rs;
   1775 	struct mbuf *m;
   1776 	uint8_t *frm;
   1777 	uint16_t capinfo;
   1778 	int has_challenge, is_shared_key, ret, status;
   1779 
   1780 	IASSERT(ni != NULL, ("null node"));
   1781 
   1782 	/*
   1783 	 * Hold a reference on the node so it doesn't go away until after
   1784 	 * the xmit is complete all the way in the driver.  On error we
   1785 	 * will remove our reference.
   1786 	 */
   1787 	IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
   1788 		"ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n",
   1789 		__func__, __LINE__,
   1790 		ni, ether_sprintf(ni->ni_macaddr),
   1791 		ieee80211_node_refcnt(ni)+1);
   1792 	ieee80211_ref_node(ni);
   1793 
   1794 	switch (type) {
   1795 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
   1796 		/*
   1797 		 * probe response frame format
   1798 		 *	[8] time stamp
   1799 		 *	[2] beacon interval
   1800 		 *	[2] cabability information
   1801 		 *	[tlv] ssid
   1802 		 *	[tlv] supported rates
   1803 		 *	[tlv] parameter set (FH/DS)
   1804 		 *	[tlv] parameter set (IBSS)
   1805 		 *	[tlv] extended rate phy (ERP)
   1806 		 *	[tlv] extended supported rates
   1807 		 *	[tlv] WPA
   1808 		 *	[tlv] WME (optional)
   1809 		 *	[tlv] HT capabilities
   1810 		 *	[tlv] HT information
   1811 		 *	[tlv] Vendor OUI HT capabilities (optional)
   1812 		 *	[tlv] Vendor OUI HT information (optional)
   1813 		 *	[tlv] Atheros capabilities
   1814 		 */
   1815 		m = ieee80211_getmgtframe(&frm,
   1816 			 ic->ic_headroom + sizeof(struct ieee80211_frame),
   1817 			 8
   1818 		       + sizeof(uint16_t)
   1819 		       + sizeof(uint16_t)
   1820 		       + 2 + IEEE80211_NWID_LEN
   1821 		       + 2 + IEEE80211_RATE_SIZE
   1822 		       + 7	/* max(7,3) */
   1823 		       + 6
   1824 		       + 3
   1825 		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
   1826 		       /* XXX !WPA1+WPA2 fits w/o a cluster */
   1827 		       + (ic->ic_flags & IEEE80211_F_WPA ?
   1828 				2*sizeof(struct ieee80211_ie_wpa) : 0)
   1829 		       + sizeof(struct ieee80211_wme_param)
   1830 		       /* XXX check for cluster requirement */
   1831 		       + 2*sizeof(struct ieee80211_ie_htcap) + 4
   1832 		       + 2*sizeof(struct ieee80211_ie_htinfo) + 4
   1833 		       + sizeof(struct ieee80211_ath_ie)
   1834 		);
   1835 		if (m == NULL)
   1836 			senderr(ENOMEM, is_tx_nobuf);
   1837 
   1838 		memset(frm, 0, 8);	/* timestamp should be filled later */
   1839 		frm += 8;
   1840 		*(uint16_t *)frm = htole16(ic->ic_bss->ni_intval);
   1841 		frm += 2;
   1842 		capinfo = getcapinfo(ic, ic->ic_curchan);
   1843 		*(uint16_t *)frm = htole16(capinfo);
   1844 		frm += 2;
   1845 
   1846 		frm = ieee80211_add_ssid(frm, ic->ic_bss->ni_essid,
   1847 				ic->ic_bss->ni_esslen);
   1848 		rs = ieee80211_get_suprates(ic, ic->ic_curchan);
   1849 		frm = ieee80211_add_rates(frm, rs);
   1850 
   1851 		if (IEEE80211_IS_CHAN_FHSS(ic->ic_curchan)) {
   1852                         *frm++ = IEEE80211_ELEMID_FHPARMS;
   1853                         *frm++ = 5;
   1854                         *frm++ = ni->ni_fhdwell & 0x00ff;
   1855                         *frm++ = (ni->ni_fhdwell >> 8) & 0x00ff;
   1856                         *frm++ = IEEE80211_FH_CHANSET(
   1857 			    ieee80211_chan2ieee(ic, ic->ic_curchan));
   1858                         *frm++ = IEEE80211_FH_CHANPAT(
   1859 			    ieee80211_chan2ieee(ic, ic->ic_curchan));
   1860                         *frm++ = ni->ni_fhindex;
   1861 		} else {
   1862 			*frm++ = IEEE80211_ELEMID_DSPARMS;
   1863 			*frm++ = 1;
   1864 			*frm++ = ieee80211_chan2ieee(ic, ic->ic_curchan);
   1865 		}
   1866 
   1867 		if (ic->ic_opmode == IEEE80211_M_IBSS) {
   1868 			*frm++ = IEEE80211_ELEMID_IBSSPARMS;
   1869 			*frm++ = 2;
   1870 			*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
   1871 		}
   1872 		if (ic->ic_flags & IEEE80211_F_WPA)
   1873 			frm = ieee80211_add_wpa(frm, ic);
   1874 		if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan))
   1875 			frm = ieee80211_add_erp(frm, ic);
   1876 		frm = ieee80211_add_xrates(frm, rs);
   1877 		/*
   1878 		 * NB: legacy 11b clients do not get certain ie's.
   1879 		 *     The caller identifies such clients by passing
   1880 		 *     a token in arg to us.  Could expand this to be
   1881 		 *     any legacy client for stuff like HT ie's.
   1882 		 */
   1883 		if (IEEE80211_IS_CHAN_HT(ic->ic_curchan) &&
   1884 		    arg != IEEE80211_SEND_LEGACY_11B) {
   1885 			frm = ieee80211_add_htcap(frm, ni);
   1886 			frm = ieee80211_add_htinfo(frm, ni);
   1887 		}
   1888 		if (ic->ic_flags & IEEE80211_F_WME)
   1889 			frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
   1890 		if (IEEE80211_IS_CHAN_HT(ic->ic_curchan) &&
   1891 		    (ic->ic_flags_ext & IEEE80211_FEXT_HTCOMPAT) &&
   1892 		    arg != IEEE80211_SEND_LEGACY_11B) {
   1893 			frm = ieee80211_add_htcap_vendor(frm, ni);
   1894 			frm = ieee80211_add_htinfo_vendor(frm, ni);
   1895 		}
   1896 		if (ni->ni_ath_ie != NULL)
   1897 			frm = ieee80211_add_ath(frm, ni->ni_ath_flags,
   1898 				ni->ni_ath_defkeyix);
   1899 		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
   1900 		break;
   1901 
   1902 	case IEEE80211_FC0_SUBTYPE_AUTH:
   1903 		status = arg >> 16;
   1904 		arg &= 0xffff;
   1905 		has_challenge = ((arg == IEEE80211_AUTH_SHARED_CHALLENGE ||
   1906 		    arg == IEEE80211_AUTH_SHARED_RESPONSE) &&
   1907 		    ni->ni_challenge != NULL);
   1908 
   1909 		/*
   1910 		 * Deduce whether we're doing open authentication or
   1911 		 * shared key authentication.  We do the latter if
   1912 		 * we're in the middle of a shared key authentication
   1913 		 * handshake or if we're initiating an authentication
   1914 		 * request and configured to use shared key.
   1915 		 */
   1916 		is_shared_key = has_challenge ||
   1917 		     arg >= IEEE80211_AUTH_SHARED_RESPONSE ||
   1918 		     (arg == IEEE80211_AUTH_SHARED_REQUEST &&
   1919 		      ic->ic_bss->ni_authmode == IEEE80211_AUTH_SHARED);
   1920 
   1921 		m = ieee80211_getmgtframe(&frm,
   1922 			  ic->ic_headroom + sizeof(struct ieee80211_frame),
   1923 			  3 * sizeof(uint16_t)
   1924 			+ (has_challenge && status == IEEE80211_STATUS_SUCCESS ?
   1925 				sizeof(uint16_t)+IEEE80211_CHALLENGE_LEN : 0)
   1926 		);
   1927 		if (m == NULL)
   1928 			senderr(ENOMEM, is_tx_nobuf);
   1929 
   1930 		((uint16_t *)frm)[0] =
   1931 		    (is_shared_key) ? htole16(IEEE80211_AUTH_ALG_SHARED)
   1932 		                    : htole16(IEEE80211_AUTH_ALG_OPEN);
   1933 		((uint16_t *)frm)[1] = htole16(arg);	/* sequence number */
   1934 		((uint16_t *)frm)[2] = htole16(status);/* status */
   1935 
   1936 		if (has_challenge && status == IEEE80211_STATUS_SUCCESS) {
   1937 			((uint16_t *)frm)[3] =
   1938 			    htole16((IEEE80211_CHALLENGE_LEN << 8) |
   1939 			    IEEE80211_ELEMID_CHALLENGE);
   1940 			memcpy(&((uint16_t *)frm)[4], ni->ni_challenge,
   1941 			    IEEE80211_CHALLENGE_LEN);
   1942 			m->m_pkthdr.len = m->m_len =
   1943 				4 * sizeof(uint16_t) + IEEE80211_CHALLENGE_LEN;
   1944 			if (arg == IEEE80211_AUTH_SHARED_RESPONSE) {
   1945 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
   1946 				    "[%s] request encrypt frame (%s)\n",
   1947 				    ether_sprintf(ni->ni_macaddr), __func__);
   1948 				m->m_flags |= M_LINK0; /* WEP-encrypt, please */
   1949 			}
   1950 		} else
   1951 			m->m_pkthdr.len = m->m_len = 3 * sizeof(uint16_t);
   1952 
   1953 		/* XXX not right for shared key */
   1954 		if (status == IEEE80211_STATUS_SUCCESS)
   1955 			IEEE80211_NODE_STAT(ni, tx_auth);
   1956 		else
   1957 			IEEE80211_NODE_STAT(ni, tx_auth_fail);
   1958 
   1959 		if (ic->ic_opmode == IEEE80211_M_STA)
   1960 			ieee80211_add_callback(m, ieee80211_tx_mgt_cb,
   1961 				(void *) ic->ic_state);
   1962 		break;
   1963 
   1964 	case IEEE80211_FC0_SUBTYPE_DEAUTH:
   1965 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
   1966 			"[%s] send station deauthenticate (reason %d)\n",
   1967 			ether_sprintf(ni->ni_macaddr), arg);
   1968 		m = ieee80211_getmgtframe(&frm,
   1969 			ic->ic_headroom + sizeof(struct ieee80211_frame),
   1970 			sizeof(uint16_t));
   1971 		if (m == NULL)
   1972 			senderr(ENOMEM, is_tx_nobuf);
   1973 		*(uint16_t *)frm = htole16(arg);	/* reason */
   1974 		m->m_pkthdr.len = m->m_len = sizeof(uint16_t);
   1975 
   1976 		IEEE80211_NODE_STAT(ni, tx_deauth);
   1977 		IEEE80211_NODE_STAT_SET(ni, tx_deauth_code, arg);
   1978 
   1979 		ieee80211_node_unauthorize(ni);		/* port closed */
   1980 		break;
   1981 
   1982 	case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
   1983 	case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
   1984 		/*
   1985 		 * asreq frame format
   1986 		 *	[2] capability information
   1987 		 *	[2] listen interval
   1988 		 *	[6*] current AP address (reassoc only)
   1989 		 *	[tlv] ssid
   1990 		 *	[tlv] supported rates
   1991 		 *	[tlv] extended supported rates
   1992 		 *	[tlv] WME
   1993 		 *	[tlv] HT capabilities
   1994 		 *	[tlv] Vendor OUI HT capabilities (optional)
   1995 		 *	[tlv] Atheros capabilities (if negotiated)
   1996 		 *	[tlv] user-specified ie's
   1997 		 */
   1998 		m = ieee80211_getmgtframe(&frm,
   1999 			 ic->ic_headroom + sizeof(struct ieee80211_frame),
   2000 			 sizeof(uint16_t)
   2001 		       + sizeof(uint16_t)
   2002 		       + IEEE80211_ADDR_LEN
   2003 		       + 2 + IEEE80211_NWID_LEN
   2004 		       + 2 + IEEE80211_RATE_SIZE
   2005 		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
   2006 		       + sizeof(struct ieee80211_wme_info)
   2007 		       + 2*sizeof(struct ieee80211_ie_htcap) + 4
   2008 		       + sizeof(struct ieee80211_ath_ie)
   2009 		       + (ic->ic_opt_ie != NULL ? ic->ic_opt_ie_len : 0)
   2010 		);
   2011 		if (m == NULL)
   2012 			senderr(ENOMEM, is_tx_nobuf);
   2013 
   2014 		IASSERT(ic->ic_opmode == IEEE80211_M_STA,
   2015 		    ("wrong mode %u", ic->ic_opmode));
   2016 		capinfo = IEEE80211_CAPINFO_ESS;
   2017 		if (ic->ic_flags & IEEE80211_F_PRIVACY)
   2018 			capinfo |= IEEE80211_CAPINFO_PRIVACY;
   2019 		/*
   2020 		 * NB: Some 11a AP's reject the request when
   2021 		 *     short premable is set.
   2022 		 */
   2023 		if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
   2024 		    IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan))
   2025 			capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
   2026 		if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan) &&
   2027 		    (ic->ic_caps & IEEE80211_C_SHSLOT))
   2028 			capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
   2029 		if ((ni->ni_capinfo & IEEE80211_CAPINFO_SPECTRUM_MGMT) &&
   2030 		    (ic->ic_flags & IEEE80211_F_DOTH))
   2031 			capinfo |= IEEE80211_CAPINFO_SPECTRUM_MGMT;
   2032 		*(uint16_t *)frm = htole16(capinfo);
   2033 		frm += 2;
   2034 
   2035 		IASSERT(ic->ic_bss->ni_intval != 0,
   2036 			("beacon interval is zero!"));
   2037 		*(uint16_t *)frm = htole16(howmany(ic->ic_lintval,
   2038 						   ic->ic_bss->ni_intval));
   2039 		frm += 2;
   2040 
   2041 		if (type == IEEE80211_FC0_SUBTYPE_REASSOC_REQ) {
   2042 			IEEE80211_ADDR_COPY(frm, ic->ic_bss->ni_bssid);
   2043 			frm += IEEE80211_ADDR_LEN;
   2044 		}
   2045 
   2046 		frm = ieee80211_add_ssid(frm, ni->ni_essid, ni->ni_esslen);
   2047 		frm = ieee80211_add_rates(frm, &ni->ni_rates);
   2048 		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
   2049 		if ((ic->ic_flags_ext & IEEE80211_FEXT_HT) &&
   2050 		    ni->ni_htcap_ie != NULL &&
   2051 		    ni->ni_htcap_ie[0] == IEEE80211_ELEMID_HTCAP)
   2052 			frm = ieee80211_add_htcap(frm, ni);
   2053 		if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
   2054 			frm = ieee80211_add_wme_info(frm, &ic->ic_wme);
   2055 		if ((ic->ic_flags_ext & IEEE80211_FEXT_HT) &&
   2056 		    ni->ni_htcap_ie != NULL &&
   2057 		    ni->ni_htcap_ie[0] == IEEE80211_ELEMID_VENDOR)
   2058 			frm = ieee80211_add_htcap_vendor(frm, ni);
   2059 		if (IEEE80211_ATH_CAP(ic, ni, IEEE80211_F_ATHEROS))
   2060 			frm = ieee80211_add_ath(frm,
   2061 				IEEE80211_ATH_CAP(ic, ni, IEEE80211_F_ATHEROS),
   2062 				(ic->ic_flags & IEEE80211_F_WPA) == 0 &&
   2063 				ni->ni_authmode != IEEE80211_AUTH_8021X &&
   2064 				ic->ic_def_txkey != IEEE80211_KEYIX_NONE ?
   2065 				ic->ic_def_txkey : 0x7fff);
   2066 		if (ic->ic_opt_ie != NULL) {
   2067 			memcpy(frm, ic->ic_opt_ie, ic->ic_opt_ie_len);
   2068 			frm += ic->ic_opt_ie_len;
   2069 		}
   2070 		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
   2071 
   2072 		ieee80211_add_callback(m, ieee80211_tx_mgt_cb,
   2073 			(void *) ic->ic_state);
   2074 		break;
   2075 
   2076 	case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
   2077 	case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
   2078 		/*
   2079 		 * asresp frame format
   2080 		 *	[2] capability information
   2081 		 *	[2] status
   2082 		 *	[2] association ID
   2083 		 *	[tlv] supported rates
   2084 		 *	[tlv] extended supported rates
   2085 		 *	[tlv] WME (if enabled and STA enabled)
   2086 		 *	[tlv] HT capabilities (standard or vendor OUI)
   2087 		 *	[tlv] HT information (standard or vendor OUI)
   2088 		 *	[tlv] Atheros capabilities (if enabled and STA enabled)
   2089 		 */
   2090 		m = ieee80211_getmgtframe(&frm,
   2091 			 ic->ic_headroom + sizeof(struct ieee80211_frame),
   2092 			 sizeof(uint16_t)
   2093 		       + sizeof(uint16_t)
   2094 		       + sizeof(uint16_t)
   2095 		       + 2 + IEEE80211_RATE_SIZE
   2096 		       + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
   2097 		       + sizeof(struct ieee80211_wme_param)
   2098 		       + sizeof(struct ieee80211_ie_htcap) + 4
   2099 		       + sizeof(struct ieee80211_ie_htinfo) + 4
   2100 		       + sizeof(struct ieee80211_ath_ie)
   2101 		);
   2102 		if (m == NULL)
   2103 			senderr(ENOMEM, is_tx_nobuf);
   2104 
   2105 		capinfo = getcapinfo(ic, ic->ic_curchan);
   2106 		*(uint16_t *)frm = htole16(capinfo);
   2107 		frm += 2;
   2108 
   2109 		*(uint16_t *)frm = htole16(arg);	/* status */
   2110 		frm += 2;
   2111 
   2112 		if (arg == IEEE80211_STATUS_SUCCESS) {
   2113 			*(uint16_t *)frm = htole16(ni->ni_associd);
   2114 			IEEE80211_NODE_STAT(ni, tx_assoc);
   2115 		} else
   2116 			IEEE80211_NODE_STAT(ni, tx_assoc_fail);
   2117 		frm += 2;
   2118 
   2119 		frm = ieee80211_add_rates(frm, &ni->ni_rates);
   2120 		frm = ieee80211_add_xrates(frm, &ni->ni_rates);
   2121 		/* NB: respond according to what we received */
   2122 		if ((ni->ni_flags & HTFLAGS) == IEEE80211_NODE_HT) {
   2123 			frm = ieee80211_add_htcap(frm, ni);
   2124 			frm = ieee80211_add_htinfo(frm, ni);
   2125 		}
   2126 		if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
   2127 			frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
   2128 		if ((ni->ni_flags & HTFLAGS) == HTFLAGS) {
   2129 			frm = ieee80211_add_htcap_vendor(frm, ni);
   2130 			frm = ieee80211_add_htinfo_vendor(frm, ni);
   2131 		}
   2132 		if (IEEE80211_ATH_CAP(ic, ni, IEEE80211_F_ATHEROS))
   2133 			frm = ieee80211_add_ath(frm,
   2134 				IEEE80211_ATH_CAP(ic, ni, IEEE80211_F_ATHEROS),
   2135 				ni->ni_ath_defkeyix);
   2136 		m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
   2137 		break;
   2138 
   2139 	case IEEE80211_FC0_SUBTYPE_DISASSOC:
   2140 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
   2141 			"[%s] send station disassociate (reason %d)\n",
   2142 			ether_sprintf(ni->ni_macaddr), arg);
   2143 		m = ieee80211_getmgtframe(&frm,
   2144 			ic->ic_headroom + sizeof(struct ieee80211_frame),
   2145 			sizeof(uint16_t));
   2146 		if (m == NULL)
   2147 			senderr(ENOMEM, is_tx_nobuf);
   2148 		*(uint16_t *)frm = htole16(arg);	/* reason */
   2149 		m->m_pkthdr.len = m->m_len = sizeof(uint16_t);
   2150 
   2151 		IEEE80211_NODE_STAT(ni, tx_disassoc);
   2152 		IEEE80211_NODE_STAT_SET(ni, tx_disassoc_code, arg);
   2153 		break;
   2154 
   2155 	default:
   2156 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
   2157 			"[%s] invalid mgmt frame type %u\n",
   2158 			ether_sprintf(ni->ni_macaddr), type);
   2159 		senderr(EINVAL, is_tx_unknownmgt);
   2160 		/* NOTREACHED */
   2161 	}
   2162 
   2163 	ret = ieee80211_mgmt_output(ic, ni, m, type);
   2164 	if (ret != 0)
   2165 		goto bad;
   2166 	return 0;
   2167 bad:
   2168 	ieee80211_free_node(ni);
   2169 	return ret;
   2170 #undef senderr
   2171 #undef HTFLAGS
   2172 }
   2173 
   2174 static void
   2175 ieee80211_tx_mgt_timeout(void *arg)
   2176 {
   2177 	struct ieee80211_node *ni = arg;
   2178 	struct ieee80211com *ic	= ni->ni_ic;
   2179 
   2180 	if (ic->ic_state != IEEE80211_S_INIT &&
   2181 	    (ic->ic_flags & IEEE80211_F_SCAN) == 0) {
   2182 		/*
   2183 		 * NB: it's safe to specify a timeout as the reason here;
   2184 		 *     it'll only be used in the right state.
   2185 		 */
   2186 		ieee80211_new_state(ic, IEEE80211_S_SCAN,
   2187 			IEEE80211_SCAN_FAIL_TIMEOUT);
   2188 	}
   2189 }
   2190 
   2191 static void
   2192 ieee80211_tx_mgt_cb(struct ieee80211_node *ni, void *arg, int status)
   2193 {
   2194 	struct ieee80211com *ic = ni->ni_ic;
   2195 	enum ieee80211_state ostate = (enum ieee80211_state) arg;
   2196 
   2197 	/*
   2198 	 * Frame transmit completed; arrange timer callback.  If
   2199 	 * transmit was successfuly we wait for response.  Otherwise
   2200 	 * we arrange an immediate callback instead of doing the
   2201 	 * callback directly since we don't know what state the driver
   2202 	 * is in (e.g. what locks it is holding).  This work should
   2203 	 * not be too time-critical and not happen too often so the
   2204 	 * added overhead is acceptable.
   2205 	 *
   2206 	 * XXX what happens if !acked but response shows up before callback?
   2207 	 */
   2208 	if (ic->ic_state == ostate)
   2209 		callout_reset(&ic->ic_mgtsend,
   2210 			status == 0 ? IEEE80211_TRANS_WAIT*hz : 0,
   2211 			ieee80211_tx_mgt_timeout, ni);
   2212 }
   2213 
   2214 /*
   2215  * Allocate a beacon frame and fillin the appropriate bits.
   2216  */
   2217 struct mbuf *
   2218 ieee80211_beacon_alloc(struct ieee80211_node *ni,
   2219 	struct ieee80211_beacon_offsets *bo)
   2220 {
   2221 	struct ieee80211com *ic = ni->ni_ic;
   2222 	struct ifnet *ifp = ic->ic_ifp;
   2223 	struct ieee80211_frame *wh;
   2224 	struct mbuf *m;
   2225 	int pktlen;
   2226 	uint8_t *frm;
   2227 	uint16_t capinfo;
   2228 	struct ieee80211_rateset *rs;
   2229 
   2230 	/*
   2231 	 * beacon frame format
   2232 	 *	[8] time stamp
   2233 	 *	[2] beacon interval
   2234 	 *	[2] cabability information
   2235 	 *	[tlv] ssid
   2236 	 *	[tlv] supported rates
   2237 	 *	[3] parameter set (DS)
   2238 	 *	[tlv] parameter set (IBSS/TIM)
   2239 	 *	[tlv] country code
   2240 	 *	[tlv] extended rate phy (ERP)
   2241 	 *	[tlv] extended supported rates
   2242 	 *	[tlv] WME parameters
   2243 	 *	[tlv] WPA/RSN parameters
   2244 	 *	[tlv] HT capabilities
   2245 	 *	[tlv] HT information
   2246 	 *	[tlv] Vendor OUI HT capabilities (optional)
   2247 	 *	[tlv] Vendor OUI HT information (optional)
   2248 	 * XXX Vendor-specific OIDs (e.g. Atheros)
   2249 	 * NB: we allocate the max space required for the TIM bitmap.
   2250 	 */
   2251 	rs = &ni->ni_rates;
   2252 	pktlen =   8					/* time stamp */
   2253 		 + sizeof(uint16_t)			/* beacon interval */
   2254 		 + sizeof(uint16_t)			/* capabilities */
   2255 		 + 2 + ni->ni_esslen			/* ssid */
   2256 	         + 2 + IEEE80211_RATE_SIZE		/* supported rates */
   2257 	         + 2 + 1				/* DS parameters */
   2258 		 + 2 + 4 + ic->ic_tim_len		/* DTIM/IBSSPARMS */
   2259 		 + sizeof(struct ieee80211_country_ie)	/* country code */
   2260 		 + 2 + 1				/* ERP */
   2261 	         + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
   2262 		 + (ic->ic_caps & IEEE80211_C_WME ?	/* WME */
   2263 			sizeof(struct ieee80211_wme_param) : 0)
   2264 		 + (ic->ic_caps & IEEE80211_C_WPA ?	/* WPA 1+2 */
   2265 			2*sizeof(struct ieee80211_ie_wpa) : 0)
   2266 		 /* XXX conditional? */
   2267 		 + 4+2*sizeof(struct ieee80211_ie_htcap)/* HT caps */
   2268 		 + 4+2*sizeof(struct ieee80211_ie_htinfo)/* HT info */
   2269 		 ;
   2270 	m = ieee80211_getmgtframe(&frm,
   2271 		ic->ic_headroom + sizeof(struct ieee80211_frame), pktlen);
   2272 	if (m == NULL) {
   2273 		IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
   2274 			"%s: cannot get buf; size %u\n", __func__, pktlen);
   2275 		ic->ic_stats.is_tx_nobuf++;
   2276 		return NULL;
   2277 	}
   2278 
   2279 	memset(bo, 0, sizeof(*bo));
   2280 
   2281 	memset(frm, 0, 8);	/* XXX timestamp is set by hardware/driver */
   2282 	frm += 8;
   2283 	*(uint16_t *)frm = htole16(ni->ni_intval);
   2284 	frm += 2;
   2285 	capinfo = getcapinfo(ic, ni->ni_chan);
   2286 	bo->bo_caps = (uint16_t *)frm;
   2287 	*(uint16_t *)frm = htole16(capinfo);
   2288 	frm += 2;
   2289 	*frm++ = IEEE80211_ELEMID_SSID;
   2290 	if ((ic->ic_flags & IEEE80211_F_HIDESSID) == 0) {
   2291 		*frm++ = ni->ni_esslen;
   2292 		memcpy(frm, ni->ni_essid, ni->ni_esslen);
   2293 		frm += ni->ni_esslen;
   2294 	} else
   2295 		*frm++ = 0;
   2296 	frm = ieee80211_add_rates(frm, rs);
   2297 	if (!IEEE80211_IS_CHAN_FHSS(ic->ic_bsschan)) {
   2298 		*frm++ = IEEE80211_ELEMID_DSPARMS;
   2299 		*frm++ = 1;
   2300 		*frm++ = ieee80211_chan2ieee(ic, ic->ic_bsschan);
   2301 	}
   2302 	bo->bo_tim = frm;
   2303 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
   2304 		*frm++ = IEEE80211_ELEMID_IBSSPARMS;
   2305 		*frm++ = 2;
   2306 		*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
   2307 		bo->bo_tim_len = 0;
   2308 	} else if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
   2309 		struct ieee80211_tim_ie *tie = (struct ieee80211_tim_ie *) frm;
   2310 
   2311 		tie->tim_ie = IEEE80211_ELEMID_TIM;
   2312 		tie->tim_len = 4;	/* length */
   2313 		tie->tim_count = 0;	/* DTIM count */
   2314 		tie->tim_period = ic->ic_dtim_period;	/* DTIM period */
   2315 		tie->tim_bitctl = 0;	/* bitmap control */
   2316 		tie->tim_bitmap[0] = 0;	/* Partial Virtual Bitmap */
   2317 		frm += sizeof(struct ieee80211_tim_ie);
   2318 		bo->bo_tim_len = 1;
   2319 	}
   2320 	bo->bo_tim_trailer = frm;
   2321 	if (ic->ic_flags & IEEE80211_F_DOTH)
   2322 		frm = ieee80211_add_countryie(frm, ic,
   2323 			ic->ic_countrycode, ic->ic_location);
   2324 	if (ic->ic_flags & IEEE80211_F_WPA)
   2325 		frm = ieee80211_add_wpa(frm, ic);
   2326 	if (IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan)) {
   2327 		bo->bo_erp = frm;
   2328 		frm = ieee80211_add_erp(frm, ic);
   2329 	}
   2330 	frm = ieee80211_add_xrates(frm, rs);
   2331 	if (IEEE80211_IS_CHAN_HT(ic->ic_bsschan)) {
   2332 		frm = ieee80211_add_htcap(frm, ni);
   2333 		bo->bo_htinfo = frm;
   2334 		frm = ieee80211_add_htinfo(frm, ni);
   2335 	}
   2336 	if (ic->ic_flags & IEEE80211_F_WME) {
   2337 		bo->bo_wme = frm;
   2338 		frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
   2339 	}
   2340 	if (IEEE80211_IS_CHAN_HT(ic->ic_bsschan) &&
   2341 	    (ic->ic_flags_ext & IEEE80211_FEXT_HTCOMPAT)) {
   2342 		frm = ieee80211_add_htcap_vendor(frm, ni);
   2343 		frm = ieee80211_add_htinfo_vendor(frm, ni);
   2344 	}
   2345 	bo->bo_tim_trailer_len = frm - bo->bo_tim_trailer;
   2346 	m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
   2347 
   2348 	M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT);
   2349 	IASSERT(m != NULL, ("no space for 802.11 header?"));
   2350 	wh = mtod(m, struct ieee80211_frame *);
   2351 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
   2352 	    IEEE80211_FC0_SUBTYPE_BEACON;
   2353 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
   2354 	*(uint16_t *)wh->i_dur = 0;
   2355 	IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
   2356 	IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
   2357 	IEEE80211_ADDR_COPY(wh->i_addr3, ni->ni_bssid);
   2358 	*(uint16_t *)wh->i_seq = 0;
   2359 
   2360 	return m;
   2361 }
   2362 
   2363 /*
   2364  * Update the dynamic parts of a beacon frame based on the current state.
   2365  */
   2366 int
   2367 ieee80211_beacon_update(struct ieee80211_node *ni,
   2368     struct ieee80211_beacon_offsets *bo, struct mbuf *m, int mcast)
   2369 {
   2370 	struct ieee80211com *ic = ni->ni_ic;
   2371 	int len_changed = 0;
   2372 	uint16_t capinfo;
   2373 
   2374 	IEEE80211_BEACON_LOCK(ic);
   2375 	/* XXX faster to recalculate entirely or just changes? */
   2376 	capinfo = getcapinfo(ic, ni->ni_chan);
   2377 	*bo->bo_caps = htole16(capinfo);
   2378 
   2379 	if (ic->ic_flags & IEEE80211_F_WME) {
   2380 		struct ieee80211_wme_state *wme = &ic->ic_wme;
   2381 
   2382 		/*
   2383 		 * Check for agressive mode change.  When there is
   2384 		 * significant high priority traffic in the BSS
   2385 		 * throttle back BE traffic by using conservative
   2386 		 * parameters.  Otherwise BE uses agressive params
   2387 		 * to optimize performance of legacy/non-QoS traffic.
   2388 		 */
   2389 		if (wme->wme_flags & WME_F_AGGRMODE) {
   2390 			if (wme->wme_hipri_traffic >
   2391 			    wme->wme_hipri_switch_thresh) {
   2392 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_WME,
   2393 				    "%s: traffic %u, disable aggressive mode\n",
   2394 				    __func__, wme->wme_hipri_traffic);
   2395 				wme->wme_flags &= ~WME_F_AGGRMODE;
   2396 				ieee80211_wme_updateparams_locked(ic);
   2397 				wme->wme_hipri_traffic =
   2398 					wme->wme_hipri_switch_hysteresis;
   2399 			} else
   2400 				wme->wme_hipri_traffic = 0;
   2401 		} else {
   2402 			if (wme->wme_hipri_traffic <=
   2403 			    wme->wme_hipri_switch_thresh) {
   2404 				IEEE80211_DPRINTF(ic, IEEE80211_MSG_WME,
   2405 				    "%s: traffic %u, enable aggressive mode\n",
   2406 				    __func__, wme->wme_hipri_traffic);
   2407 				wme->wme_flags |= WME_F_AGGRMODE;
   2408 				ieee80211_wme_updateparams_locked(ic);
   2409 				wme->wme_hipri_traffic = 0;
   2410 			} else
   2411 				wme->wme_hipri_traffic =
   2412 					wme->wme_hipri_switch_hysteresis;
   2413 		}
   2414 		if (isset(bo->bo_flags, IEEE80211_BEACON_WME)) {
   2415 			(void) ieee80211_add_wme_param(bo->bo_wme, wme);
   2416 			clrbit(bo->bo_flags, IEEE80211_BEACON_WME);
   2417 		}
   2418 	}
   2419 
   2420 	if (isset(bo->bo_flags, IEEE80211_BEACON_HTINFO)) {
   2421 		ieee80211_ht_update_beacon(ic, bo);
   2422 		clrbit(bo->bo_flags, IEEE80211_BEACON_HTINFO);
   2423 	}
   2424 
   2425 #ifndef IEEE80211_NO_HOSTAP
   2426 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {	/* NB: no IBSS support*/
   2427 		struct ieee80211_tim_ie *tie =
   2428 			(struct ieee80211_tim_ie *) bo->bo_tim;
   2429 		if (isset(bo->bo_flags, IEEE80211_BEACON_TIM)) {
   2430 			u_int timlen, timoff, i;
   2431 			/*
   2432 			 * ATIM/DTIM needs updating.  If it fits in the
   2433 			 * current space allocated then just copy in the
   2434 			 * new bits.  Otherwise we need to move any trailing
   2435 			 * data to make room.  Note that we know there is
   2436 			 * contiguous space because ieee80211_beacon_allocate
   2437 			 * insures there is space in the mbuf to write a
   2438 			 * maximal-size virtual bitmap (based on ic_max_aid).
   2439 			 */
   2440 			/*
   2441 			 * Calculate the bitmap size and offset, copy any
   2442 			 * trailer out of the way, and then copy in the
   2443 			 * new bitmap and update the information element.
   2444 			 * Note that the tim bitmap must contain at least
   2445 			 * one byte and any offset must be even.
   2446 			 */
   2447 			if (ic->ic_ps_pending != 0) {
   2448 				timoff = 128;		/* impossibly large */
   2449 				for (i = 0; i < ic->ic_tim_len; i++)
   2450 					if (ic->ic_tim_bitmap[i]) {
   2451 						timoff = i &~ 1;
   2452 						break;
   2453 					}
   2454 				IASSERT(timoff != 128, ("tim bitmap empty!"));
   2455 				for (i = ic->ic_tim_len-1; i >= timoff; i--)
   2456 					if (ic->ic_tim_bitmap[i])
   2457 						break;
   2458 				timlen = 1 + (i - timoff);
   2459 			} else {
   2460 				timoff = 0;
   2461 				timlen = 1;
   2462 			}
   2463 			if (timlen != bo->bo_tim_len) {
   2464 				/* copy up/down trailer */
   2465 				int adjust = tie->tim_bitmap+timlen
   2466 					   - bo->bo_tim_trailer;
   2467 				ovbcopy(bo->bo_tim_trailer,
   2468 				    bo->bo_tim_trailer+adjust,
   2469 				    bo->bo_tim_trailer_len);
   2470 				bo->bo_tim_trailer += adjust;
   2471 				bo->bo_wme += adjust;
   2472 				bo->bo_erp += adjust;
   2473 				bo->bo_htinfo += adjust;
   2474 				bo->bo_tim_len = timlen;
   2475 
   2476 				/* update information element */
   2477 				tie->tim_len = 3 + timlen;
   2478 				tie->tim_bitctl = timoff;
   2479 				len_changed = 1;
   2480 			}
   2481 			memcpy(tie->tim_bitmap, ic->ic_tim_bitmap + timoff,
   2482 				bo->bo_tim_len);
   2483 
   2484 			clrbit(bo->bo_flags, IEEE80211_BEACON_TIM);
   2485 
   2486 			IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
   2487 				"%s: TIM updated, pending %u, off %u, len %u\n",
   2488 				__func__, ic->ic_ps_pending, timoff, timlen);
   2489 		}
   2490 		/* count down DTIM period */
   2491 		if (tie->tim_count == 0)
   2492 			tie->tim_count = tie->tim_period - 1;
   2493 		else
   2494 			tie->tim_count--;
   2495 		/* update state for buffered multicast frames on DTIM */
   2496 		if (mcast && tie->tim_count == 0)
   2497 			tie->tim_bitctl |= 1;
   2498 		else
   2499 			tie->tim_bitctl &= ~1;
   2500 		if (isset(bo->bo_flags, IEEE80211_BEACON_ERP)) {
   2501 			/*
   2502 			 * ERP element needs updating.
   2503 			 */
   2504 			(void) ieee80211_add_erp(bo->bo_erp, ic);
   2505 			clrbit(bo->bo_flags, IEEE80211_BEACON_ERP);
   2506 		}
   2507 	}
   2508 #endif /* !IEEE80211_NO_HOSTAP */
   2509 	IEEE80211_BEACON_UNLOCK(ic);
   2510 
   2511 	return len_changed;
   2512 }
   2513