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