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