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