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