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