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