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