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