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