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