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