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