Merge branch 'vendor/BIND' into bind_vendor2
[dragonfly.git] / sys / netproto / 802_11 / wlan / ieee80211_output.c
1 /*
2  * Copyright (c) 2001 Atsushi Onoe
3  * Copyright (c) 2002-2005 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  * 3. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * Alternatively, this software may be distributed under the terms of the
18  * GNU General Public License ("GPL") version 2 as published by the Free
19  * Software Foundation.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
23  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
26  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
30  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  * $FreeBSD: src/sys/net80211/ieee80211_output.c,v 1.26.2.8 2006/09/02 15:06:04 sam Exp $
33  * $DragonFly: src/sys/netproto/802_11/wlan/ieee80211_output.c,v 1.24 2007/09/15 07:19:23 sephe Exp $
34  */
35
36 #include "opt_inet.h"
37
38 #include <sys/param.h>
39 #include <sys/systm.h> 
40 #include <sys/mbuf.h>   
41 #include <sys/kernel.h>
42 #include <sys/endian.h>
43
44 #include <sys/socket.h>
45  
46 #include <net/bpf.h>
47 #include <net/ethernet.h>
48 #include <net/if.h>
49 #include <net/if_arp.h>
50 #include <net/if_llc.h>
51 #include <net/if_media.h>
52 #include <net/vlan/if_vlan_var.h>
53
54 #include <netproto/802_11/ieee80211_var.h>
55
56 #ifdef INET
57 #include <netinet/in.h> 
58 #include <netinet/if_ether.h>
59 #include <netinet/in_systm.h>
60 #include <netinet/ip.h>
61 #endif
62
63 #ifdef IEEE80211_DEBUG
64 /*
65  * Decide if an outbound management frame should be
66  * printed when debugging is enabled.  This filters some
67  * of the less interesting frames that come frequently
68  * (e.g. beacons).
69  */
70 static __inline int
71 doprint(struct ieee80211com *ic, int subtype)
72 {
73         switch (subtype) {
74         case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
75                 return (ic->ic_opmode == IEEE80211_M_IBSS);
76         }
77         return 1;
78 }
79 #endif
80
81 /*
82  * Set the direction field and address fields of an outgoing
83  * non-QoS frame.  Note this should be called early on in
84  * constructing a frame as it sets i_fc[1]; other bits can
85  * then be or'd in.
86  */
87 static void
88 ieee80211_send_setup(struct ieee80211com *ic,
89         struct ieee80211_node *ni,
90         struct ieee80211_frame *wh,
91         int type,
92         const uint8_t sa[IEEE80211_ADDR_LEN],
93         const uint8_t da[IEEE80211_ADDR_LEN],
94         const uint8_t bssid[IEEE80211_ADDR_LEN])
95 {
96 #define WH4(wh) ((struct ieee80211_frame_addr4 *)wh)
97
98         wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | type;
99         if ((type & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_DATA) {
100                 switch (ic->ic_opmode) {
101                 case IEEE80211_M_STA:
102                         wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
103                         IEEE80211_ADDR_COPY(wh->i_addr1, bssid);
104                         IEEE80211_ADDR_COPY(wh->i_addr2, sa);
105                         IEEE80211_ADDR_COPY(wh->i_addr3, da);
106                         break;
107                 case IEEE80211_M_IBSS:
108                 case IEEE80211_M_AHDEMO:
109                         wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
110                         IEEE80211_ADDR_COPY(wh->i_addr1, da);
111                         IEEE80211_ADDR_COPY(wh->i_addr2, sa);
112                         IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
113                         break;
114                 case IEEE80211_M_HOSTAP:
115                         wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
116                         IEEE80211_ADDR_COPY(wh->i_addr1, da);
117                         IEEE80211_ADDR_COPY(wh->i_addr2, bssid);
118                         IEEE80211_ADDR_COPY(wh->i_addr3, sa);
119                         break;
120                 case IEEE80211_M_MONITOR:       /* NB: to quiet compiler */
121                         break;
122                 }
123         } else {
124                 wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
125                 IEEE80211_ADDR_COPY(wh->i_addr1, da);
126                 IEEE80211_ADDR_COPY(wh->i_addr2, sa);
127                 IEEE80211_ADDR_COPY(wh->i_addr3, bssid);
128         }
129         *(uint16_t *)&wh->i_dur[0] = 0;
130         /* NB: use non-QoS tid */
131         *(uint16_t *)&wh->i_seq[0] =
132             htole16(ni->ni_txseqs[0] << IEEE80211_SEQ_SEQ_SHIFT);
133         ni->ni_txseqs[0]++;
134 #undef WH4
135 }
136
137 /*
138  * Send a management frame to the specified node.  The node pointer
139  * must have a reference as the pointer will be passed to the driver
140  * and potentially held for a long time.  If the frame is successfully
141  * dispatched to the driver, then it is responsible for freeing the
142  * reference (and potentially free'ing up any associated storage).
143  */
144 static int
145 ieee80211_mgmt_output(struct ieee80211com *ic, struct ieee80211_node *ni,
146     struct mbuf *m, int type, int timer, int encrypt)
147 {
148         struct ifnet *ifp = ic->ic_ifp;
149         struct ieee80211_frame *wh;
150
151         KASSERT(ni != NULL, ("null node"));
152
153         /*
154          * Yech, hack alert!  We want to pass the node down to the
155          * driver's start routine.  If we don't do so then the start
156          * routine must immediately look it up again and that can
157          * cause a lock order reversal if, for example, this frame
158          * is being sent because the station is being timedout and
159          * the frame being sent is a DEAUTH message.  We could stick
160          * this in an m_tag and tack that on to the mbuf.  However
161          * that's rather expensive to do for every frame so instead
162          * we stuff it in the rcvif field since outbound frames do
163          * not (presently) use this.
164          */
165         M_PREPEND(m, sizeof(struct ieee80211_frame), MB_DONTWAIT);
166         if (m == NULL)
167                 return ENOMEM;
168         KASSERT(m->m_pkthdr.rcvif == NULL, ("rcvif not null"));
169         m->m_pkthdr.rcvif = (void *)ni;
170
171         wh = mtod(m, struct ieee80211_frame *);
172         ieee80211_send_setup(ic, ni, wh,
173                 IEEE80211_FC0_TYPE_MGT | type,
174                 ic->ic_myaddr, ni->ni_macaddr, ni->ni_bssid);
175         if (encrypt) {
176                 IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
177                         "[%6D] encrypting frame (%s)\n",
178                         wh->i_addr1, ":", __func__);
179                 wh->i_fc[1] |= IEEE80211_FC1_WEP;
180         }
181 #ifdef IEEE80211_DEBUG
182         /* avoid printing too many frames */
183         if ((ieee80211_msg_debug(ic) && doprint(ic, type)) ||
184             ieee80211_msg_dumppkts(ic)) {
185                 kprintf("[%6D] send %s on channel %u\n",
186                     wh->i_addr1, ":",
187                     ieee80211_mgt_subtype_name[
188                         (type & IEEE80211_FC0_SUBTYPE_MASK) >>
189                                 IEEE80211_FC0_SUBTYPE_SHIFT],
190                     ieee80211_chan2ieee(ic, ic->ic_curchan));
191         }
192 #endif
193         IEEE80211_NODE_STAT(ni, tx_mgmt);
194         IF_ENQUEUE(&ic->ic_mgtq, m);
195         if (timer) {
196                 /*
197                  * Set the mgt frame timeout.
198                  */
199                 ic->ic_mgt_timer = timer;
200                 ifp->if_timer = 1;
201         }
202         ifp->if_start(ifp);
203         return 0;
204 }
205
206 /*
207  * Send a null data frame to the specified node.
208  *
209  * NB: the caller is assumed to have setup a node reference
210  *     for use; this is necessary to deal with a race condition
211  *     when probing for inactive stations.
212  */
213 int
214 ieee80211_send_nulldata(struct ieee80211_node *ni)
215 {
216         struct ieee80211com *ic = ni->ni_ic;
217         struct ifnet *ifp = ic->ic_ifp;
218         struct mbuf *m;
219         struct ieee80211_frame *wh;
220
221         MGETHDR(m, MB_DONTWAIT, MT_HEADER);
222         if (m == NULL) {
223                 /* XXX debug msg */
224                 ic->ic_stats.is_tx_nobuf++;
225                 ieee80211_unref_node(&ni);
226                 return ENOMEM;
227         }
228         m->m_pkthdr.rcvif = (void *) ni;
229
230         wh = mtod(m, struct ieee80211_frame *);
231         ieee80211_send_setup(ic, ni, wh,
232                 IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_NODATA,
233                 ic->ic_myaddr, ni->ni_macaddr, ni->ni_bssid);
234         /* NB: power management bit is never sent by an AP */
235         if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
236             ic->ic_opmode != IEEE80211_M_HOSTAP)
237                 wh->i_fc[1] |= IEEE80211_FC1_PWR_MGT;
238         m->m_len = m->m_pkthdr.len = sizeof(struct ieee80211_frame);
239
240         IEEE80211_NODE_STAT(ni, tx_data);
241
242         IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
243             "[%s] send null data frame on channel %u, pwr mgt %s\n",
244             ni->ni_macaddr, ":",
245             ieee80211_chan2ieee(ic, ic->ic_curchan),
246             wh->i_fc[1] & IEEE80211_FC1_PWR_MGT ? "ena" : "dis");
247
248         IF_ENQUEUE(&ic->ic_mgtq, m);            /* cheat */
249         ifp->if_start(ifp);
250         return 0;
251 }
252
253 /* 
254  * Assign priority to a frame based on any vlan tag assigned
255  * to the station and/or any Diffserv setting in an IP header.
256  * Finally, if an ACM policy is setup (in station mode) it's
257  * applied.
258  */
259 int
260 ieee80211_classify(struct ieee80211com *ic, struct mbuf *m, struct ieee80211_node *ni)
261 {
262         int v_wme_ac = 0, d_wme_ac, ac;
263 #ifdef INET
264         struct ether_header *eh;
265 #endif
266
267         if ((ni->ni_flags & IEEE80211_NODE_QOS) == 0) {
268                 ac = WME_AC_BE;
269                 goto done;
270         }
271
272 #ifdef FREEBSD_VLAN
273         /* 
274          * If node has a vlan tag then all traffic
275          * to it must have a matching tag.
276          */
277         v_wme_ac = 0;
278         if (ni->ni_vlan != 0) {
279                 struct m_tag *mtag = VLAN_OUTPUT_TAG(ic->ic_ifp, m);
280                 if (mtag == NULL) {
281                         IEEE80211_NODE_STAT(ni, tx_novlantag);
282                         return 1;
283                 }
284                 if (EVL_VLANOFTAG(VLAN_TAG_VALUE(mtag)) !=
285                     EVL_VLANOFTAG(ni->ni_vlan)) {
286                         IEEE80211_NODE_STAT(ni, tx_vlanmismatch);
287                         return 1;
288                 }
289                 /* map vlan priority to AC */
290                 switch (EVL_PRIOFTAG(ni->ni_vlan)) {
291                 case 1:
292                 case 2:
293                         v_wme_ac = WME_AC_BK;
294                         break;
295                 case 0:
296                 case 3:
297                         v_wme_ac = WME_AC_BE;
298                         break;
299                 case 4:
300                 case 5:
301                         v_wme_ac = WME_AC_VI;
302                         break;
303                 case 6:
304                 case 7:
305                         v_wme_ac = WME_AC_VO;
306                         break;
307                 }
308         }
309 #endif  /* FREEBSD_VLAN */
310
311 #ifdef INET
312         eh = mtod(m, struct ether_header *);
313         if (eh->ether_type == htons(ETHERTYPE_IP)) {
314                 const struct ip *ip = (struct ip *)
315                         (mtod(m, uint8_t *) + sizeof (*eh));
316                 /*
317                  * IP frame, map the TOS field.
318                  */
319                 switch (ip->ip_tos) {
320                 case 0x08:
321                 case 0x20:
322                         d_wme_ac = WME_AC_BK;   /* background */
323                         break;
324                 case 0x28:
325                 case 0xa0:
326                         d_wme_ac = WME_AC_VI;   /* video */
327                         break;
328                 case 0x30:                      /* voice */
329                 case 0xe0:
330                 case 0x88:                      /* XXX UPSD */
331                 case 0xb8:
332                         d_wme_ac = WME_AC_VO;
333                         break;
334                 default:
335                         d_wme_ac = WME_AC_BE;
336                         break;
337                 }
338         } else {
339 #endif /* INET */
340                 d_wme_ac = WME_AC_BE;
341 #ifdef INET
342         }
343 #endif
344         /*
345          * Use highest priority AC.
346          */
347         if (v_wme_ac > d_wme_ac)
348                 ac = v_wme_ac;
349         else
350                 ac = d_wme_ac;
351
352         /*
353          * Apply ACM policy.
354          */
355         if (ic->ic_opmode == IEEE80211_M_STA) {
356                 static const int acmap[4] = {
357                         WME_AC_BK,      /* WME_AC_BE */
358                         WME_AC_BK,      /* WME_AC_BK */
359                         WME_AC_BE,      /* WME_AC_VI */
360                         WME_AC_VI,      /* WME_AC_VO */
361                 };
362                 while (ac != WME_AC_BK &&
363                     ic->ic_wme.wme_wmeBssChanParams.cap_wmeParams[ac].wmep_acm)
364                         ac = acmap[ac];
365         }
366 done:
367         M_WME_SETAC(m, ac);
368         return 0;
369 }
370
371 /*
372  * Insure there is sufficient contiguous space to encapsulate the
373  * 802.11 data frame.  If room isn't already there, arrange for it.
374  * Drivers and cipher modules assume we have done the necessary work
375  * and fail rudely if they don't find the space they need.
376  */
377 static struct mbuf *
378 ieee80211_mbuf_adjust(struct ieee80211com *ic, int hdrsize,
379         struct ieee80211_key *key, struct mbuf *m)
380 {
381 #define TO_BE_RECLAIMED (sizeof(struct ether_header) - sizeof(struct llc))
382         int needed_space = hdrsize + ic->ic_headroom;
383
384         if (key != NULL) {
385                 /* XXX belongs in crypto code? */
386                 if ((key->wk_flags & IEEE80211_KEY_NOHDR) == 0)
387                         needed_space += key->wk_cipher->ic_header;
388                 /* XXX frags */
389                 /*
390                  * When crypto is being done in the host we must insure
391                  * the data are writable for the cipher routines; clone
392                  * a writable mbuf chain.
393                  * XXX handle SWMIC specially
394                  */
395                 if (key->wk_flags & (IEEE80211_KEY_SWCRYPT|IEEE80211_KEY_SWMIC)) {
396                         m = ieee80211_mbuf_clone(m, MB_DONTWAIT);
397                         if (m == NULL) {
398                                 IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
399                                     "%s: cannot get writable mbuf\n", __func__);
400                                 ic->ic_stats.is_tx_nobuf++; /* XXX new stat */
401                                 return NULL;
402                         }
403                 }
404         }
405         /*
406          * We know we are called just before stripping an Ethernet
407          * header and prepending an LLC header.  This means we know
408          * there will be
409          *      sizeof(struct ether_header) - sizeof(struct llc)
410          * bytes recovered to which we need additional space for the
411          * 802.11 header and any crypto header.
412          */
413         /* XXX check trailing space and copy instead? */
414         if (M_LEADINGSPACE(m) < needed_space - TO_BE_RECLAIMED) {
415                 struct mbuf *n = m_gethdr(MB_DONTWAIT, m->m_type);
416                 if (n == NULL) {
417                         IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
418                             "%s: cannot expand storage\n", __func__);
419                         ic->ic_stats.is_tx_nobuf++;
420                         m_freem(m);
421                         return NULL;
422                 }
423                 KASSERT(needed_space <= MHLEN,
424                     ("not enough room, need %u got %zu\n", needed_space, MHLEN));
425                 /*
426                  * Setup new mbuf to have leading space to prepend the
427                  * 802.11 header and any crypto header bits that are
428                  * required (the latter are added when the driver calls
429                  * back to ieee80211_crypto_encap to do crypto encapsulation).
430                  */
431                 /* NB: must be first 'cuz it clobbers m_data */
432                 m_move_pkthdr(n, m);
433                 n->m_len = 0;                   /* NB: m_gethdr does not set */
434                 n->m_data += needed_space;
435                 /*
436                  * Pull up Ethernet header to create the expected layout.
437                  * We could use m_pullup but that's overkill (i.e. we don't
438                  * need the actual data) and it cannot fail so do it inline
439                  * for speed.
440                  */
441                 /* NB: struct ether_header is known to be contiguous */
442                 n->m_len += sizeof(struct ether_header);
443                 m->m_len -= sizeof(struct ether_header);
444                 m->m_data += sizeof(struct ether_header);
445                 /*
446                  * Replace the head of the chain.
447                  */
448                 n->m_next = m;
449                 m = n;
450         }
451         return m;
452 #undef TO_BE_RECLAIMED
453 }
454
455 #define KEY_UNDEFINED(k)        ((k).wk_cipher == &ieee80211_cipher_none)
456 /*
457  * Return the transmit key to use in sending a unicast frame.
458  * If a unicast key is set we use that.  When no unicast key is set
459  * we fall back to the default transmit key.
460  */ 
461 static __inline struct ieee80211_key *
462 ieee80211_crypto_getucastkey(struct ieee80211com *ic, struct ieee80211_node *ni)
463 {
464         if (KEY_UNDEFINED(ni->ni_ucastkey)) {
465                 if (ic->ic_def_txkey == IEEE80211_KEYIX_NONE ||
466                     KEY_UNDEFINED(ic->ic_nw_keys[ic->ic_def_txkey]))
467                         return NULL;
468                 return &ic->ic_nw_keys[ic->ic_def_txkey];
469         } else {
470                 return &ni->ni_ucastkey;
471         }
472 }
473
474 /*
475  * Return the transmit key to use in sending a multicast frame.
476  * Multicast traffic always uses the group key which is installed as
477  * the default tx key.
478  */ 
479 static __inline struct ieee80211_key *
480 ieee80211_crypto_getmcastkey(struct ieee80211com *ic, struct ieee80211_node *ni)
481 {
482         if (ic->ic_def_txkey == IEEE80211_KEYIX_NONE ||
483             KEY_UNDEFINED(ic->ic_nw_keys[ic->ic_def_txkey]))
484                 return NULL;
485         return &ic->ic_nw_keys[ic->ic_def_txkey];
486 }
487
488 /*
489  * Encapsulate an outbound data frame.  The mbuf chain is updated.
490  * If an error is encountered NULL is returned.  The caller is required
491  * to provide a node reference and pullup the ethernet header in the
492  * first mbuf.
493  */
494 struct mbuf *
495 ieee80211_encap(struct ieee80211com *ic, struct mbuf *m,
496         struct ieee80211_node *ni)
497 {
498         struct ether_header eh;
499         struct ieee80211_frame *wh;
500         struct ieee80211_key *key;
501         struct llc *llc;
502         int hdrsize, datalen, addqos;
503
504         KASSERT(m->m_len >= sizeof(eh), ("no ethernet header!"));
505         memcpy(&eh, mtod(m, caddr_t), sizeof(struct ether_header));
506
507         /*
508          * Insure space for additional headers.  First identify
509          * transmit key to use in calculating any buffer adjustments
510          * required.  This is also used below to do privacy
511          * encapsulation work.  Then calculate the 802.11 header
512          * size and any padding required by the driver.
513          *
514          * Note key may be NULL if we fall back to the default
515          * transmit key and that is not set.  In that case the
516          * buffer may not be expanded as needed by the cipher
517          * routines, but they will/should discard it.
518          */
519         if (ic->ic_flags & IEEE80211_F_PRIVACY) {
520                 if (ic->ic_opmode == IEEE80211_M_STA ||
521                     !IEEE80211_IS_MULTICAST(eh.ether_dhost))
522                         key = ieee80211_crypto_getucastkey(ic, ni);
523                 else
524                         key = ieee80211_crypto_getmcastkey(ic, ni);
525                 if (key == NULL && eh.ether_type != htons(ETHERTYPE_PAE)) {
526                         IEEE80211_DPRINTF(ic, IEEE80211_MSG_CRYPTO,
527                             "[%6D] no default transmit key (%s) deftxkey %u\n",
528                             eh.ether_dhost, ":", __func__,
529                             ic->ic_def_txkey);
530                         ic->ic_stats.is_tx_nodefkey++;
531                         goto bad;
532                 }
533         } else
534                 key = NULL;
535         /* XXX 4-address format */
536         /*
537          * XXX Some ap's don't handle QoS-encapsulated EAPOL
538          * frames so suppress use.  This may be an issue if other
539          * ap's require all data frames to be QoS-encapsulated
540          * once negotiated in which case we'll need to make this
541          * configurable.
542          */
543         addqos = (ni->ni_flags & IEEE80211_NODE_QOS) &&
544                  eh.ether_type != htons(ETHERTYPE_PAE);
545         if (addqos)
546                 hdrsize = sizeof(struct ieee80211_qosframe);
547         else
548                 hdrsize = sizeof(struct ieee80211_frame);
549         if (ic->ic_flags & IEEE80211_F_DATAPAD)
550                 hdrsize = roundup(hdrsize, sizeof(uint32_t));
551         m = ieee80211_mbuf_adjust(ic, hdrsize, key, m);
552         if (m == NULL) {
553                 /* NB: ieee80211_mbuf_adjust handles msgs+statistics */
554                 goto bad;
555         }
556
557         /* NB: this could be optimized because of ieee80211_mbuf_adjust */
558         m_adj(m, sizeof(struct ether_header) - sizeof(struct llc));
559         llc = mtod(m, struct llc *);
560         llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP;
561         llc->llc_control = LLC_UI;
562         llc->llc_snap.org_code[0] = 0;
563         llc->llc_snap.org_code[1] = 0;
564         llc->llc_snap.org_code[2] = 0;
565         llc->llc_snap.ether_type = eh.ether_type;
566         datalen = m->m_pkthdr.len;              /* NB: w/o 802.11 header */
567
568         M_PREPEND(m, hdrsize, MB_DONTWAIT);
569         if (m == NULL) {
570                 ic->ic_stats.is_tx_nobuf++;
571                 goto bad;
572         }
573         wh = mtod(m, struct ieee80211_frame *);
574         wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_DATA;
575         *(uint16_t *)wh->i_dur = 0;
576         switch (ic->ic_opmode) {
577         case IEEE80211_M_STA:
578                 wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
579                 IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_bssid);
580                 IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
581                 IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost);
582                 break;
583         case IEEE80211_M_IBSS:
584         case IEEE80211_M_AHDEMO:
585                 wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
586                 IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
587                 IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost);
588                 /*
589                  * NB: always use the bssid from ic_bss as the
590                  *     neighbor's may be stale after an ibss merge
591                  */
592                 IEEE80211_ADDR_COPY(wh->i_addr3, ic->ic_bss->ni_bssid);
593                 break;
594         case IEEE80211_M_HOSTAP:
595                 wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS;
596                 IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost);
597                 IEEE80211_ADDR_COPY(wh->i_addr2, ni->ni_bssid);
598                 IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_shost);
599                 break;
600         case IEEE80211_M_MONITOR:
601                 goto bad;
602         }
603         if (m->m_flags & M_MORE_DATA)
604                 wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
605         if (addqos) {
606                 struct ieee80211_qosframe *qwh =
607                         (struct ieee80211_qosframe *) wh;
608                 int ac, tid;
609
610                 ac = M_WME_GETAC(m);
611                 /* map from access class/queue to 11e header priorty value */
612                 tid = WME_AC_TO_TID(ac);
613                 qwh->i_qos[0] = tid & IEEE80211_QOS_TID;
614                 if (ic->ic_wme.wme_wmeChanParams.cap_wmeParams[ac].wmep_noackPolicy)
615                         qwh->i_qos[0] |= 1 << IEEE80211_QOS_ACKPOLICY_S;
616                 qwh->i_qos[1] = 0;
617                 qwh->i_fc[0] |= IEEE80211_FC0_SUBTYPE_QOS;
618
619                 *(uint16_t *)wh->i_seq =
620                     htole16(ni->ni_txseqs[tid] << IEEE80211_SEQ_SEQ_SHIFT);
621                 ni->ni_txseqs[tid]++;
622         } else {
623                 *(uint16_t *)wh->i_seq =
624                     htole16(ni->ni_txseqs[0] << IEEE80211_SEQ_SEQ_SHIFT);
625                 ni->ni_txseqs[0]++;
626         }
627         if (key != NULL) {
628                 /*
629                  * IEEE 802.1X: send EAPOL frames always in the clear.
630                  * WPA/WPA2: encrypt EAPOL keys when pairwise keys are set.
631                  */
632                 if (eh.ether_type != htons(ETHERTYPE_PAE) ||
633                     ((ic->ic_flags & IEEE80211_F_WPA) &&
634                      (ic->ic_opmode == IEEE80211_M_STA ?
635                       !KEY_UNDEFINED(*key) : !KEY_UNDEFINED(ni->ni_ucastkey)))) {
636                         wh->i_fc[1] |= IEEE80211_FC1_WEP;
637                         /* XXX do fragmentation */
638                         if (!ieee80211_crypto_enmic(ic, key, m, 0)) {
639                                 IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
640                                     "[%6D] enmic failed, discard frame\n",
641                                     eh.ether_dhost, ":");
642                                 ic->ic_stats.is_crypto_enmicfail++;
643                                 goto bad;
644                         }
645                 }
646         }
647
648         IEEE80211_NODE_STAT(ni, tx_data);
649         if (IEEE80211_IS_MULTICAST(wh->i_addr1))
650                 IEEE80211_NODE_STAT(ni, tx_mcast);
651         else
652                 IEEE80211_NODE_STAT(ni, tx_ucast);
653         IEEE80211_NODE_STAT_ADD(ni, tx_bytes, datalen);
654
655         return m;
656 bad:
657         if (m != NULL)
658                 m_freem(m);
659         return NULL;
660 }
661
662 /*
663  * Add a supported rates element id to a frame.
664  */
665 uint8_t *
666 ieee80211_add_rates(uint8_t *frm, const struct ieee80211_rateset *rs)
667 {
668         int nrates;
669
670         *frm++ = IEEE80211_ELEMID_RATES;
671         nrates = rs->rs_nrates;
672         if (nrates > IEEE80211_RATE_SIZE)
673                 nrates = IEEE80211_RATE_SIZE;
674         *frm++ = nrates;
675         memcpy(frm, rs->rs_rates, nrates);
676         return frm + nrates;
677 }
678
679 /*
680  * Add an extended supported rates element id to a frame.
681  */
682 uint8_t *
683 ieee80211_add_xrates(uint8_t *frm, const struct ieee80211_rateset *rs)
684 {
685         /*
686          * Add an extended supported rates element if operating in 11g mode.
687          */
688         if (rs->rs_nrates > IEEE80211_RATE_SIZE) {
689                 int nrates = rs->rs_nrates - IEEE80211_RATE_SIZE;
690                 *frm++ = IEEE80211_ELEMID_XRATES;
691                 *frm++ = nrates;
692                 memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates);
693                 frm += nrates;
694         }
695         return frm;
696 }
697
698 /* 
699  * Add an ssid elemet to a frame.
700  */
701 uint8_t *
702 ieee80211_add_ssid(uint8_t *frm, const uint8_t *ssid, u_int len)
703 {
704         *frm++ = IEEE80211_ELEMID_SSID;
705         *frm++ = len;
706         memcpy(frm, ssid, len);
707         return frm + len;
708 }
709
710 /*
711  * Add an erp element to a frame.
712  */
713 static uint8_t *
714 ieee80211_add_erp(uint8_t *frm, struct ieee80211com *ic)
715 {
716         uint8_t erp;
717
718         *frm++ = IEEE80211_ELEMID_ERP;
719         *frm++ = 1;
720         erp = 0;
721         if (ic->ic_nonerpsta != 0)
722                 erp |= IEEE80211_ERP_NON_ERP_PRESENT;
723         if (ic->ic_flags & IEEE80211_F_USEPROT)
724                 erp |= IEEE80211_ERP_USE_PROTECTION;
725         if (ic->ic_flags & IEEE80211_F_USEBARKER)
726                 erp |= IEEE80211_ERP_LONG_PREAMBLE;
727         *frm++ = erp;
728         return frm;
729 }
730
731 static uint8_t *
732 ieee80211_setup_wpa_ie(struct ieee80211com *ic, uint8_t *ie)
733 {
734 #define WPA_OUI_BYTES           0x00, 0x50, 0xf2
735 #define ADDSHORT(frm, v) do {                   \
736         frm[0] = (v) & 0xff;                    \
737         frm[1] = (v) >> 8;                      \
738         frm += 2;                               \
739 } while (0)
740 #define ADDSELECTOR(frm, sel) do {              \
741         memcpy(frm, sel, 4);                    \
742         frm += 4;                               \
743 } while (0)
744         static const uint8_t oui[4] = { WPA_OUI_BYTES, WPA_OUI_TYPE };
745         static const uint8_t cipher_suite[][4] = {
746                 { WPA_OUI_BYTES, WPA_CSE_WEP40 },       /* NB: 40-bit */
747                 { WPA_OUI_BYTES, WPA_CSE_TKIP },
748                 { 0x00, 0x00, 0x00, 0x00 },             /* XXX WRAP */
749                 { WPA_OUI_BYTES, WPA_CSE_CCMP },
750                 { 0x00, 0x00, 0x00, 0x00 },             /* XXX CKIP */
751                 { WPA_OUI_BYTES, WPA_CSE_NULL },
752         };
753         static const uint8_t wep104_suite[4] =
754                 { WPA_OUI_BYTES, WPA_CSE_WEP104 };
755         static const uint8_t key_mgt_unspec[4] =
756                 { WPA_OUI_BYTES, WPA_ASE_8021X_UNSPEC };
757         static const uint8_t key_mgt_psk[4] =
758                 { WPA_OUI_BYTES, WPA_ASE_8021X_PSK };
759         const struct ieee80211_rsnparms *rsn = &ic->ic_bss->ni_rsn;
760         uint8_t *frm = ie;
761         uint8_t *selcnt;
762
763         *frm++ = IEEE80211_ELEMID_VENDOR;
764         *frm++ = 0;                             /* length filled in below */
765         memcpy(frm, oui, sizeof(oui));          /* WPA OUI */
766         frm += sizeof(oui);
767         ADDSHORT(frm, WPA_VERSION);
768
769         /* XXX filter out CKIP */
770
771         /* multicast cipher */
772         if (rsn->rsn_mcastcipher == IEEE80211_CIPHER_WEP &&
773             rsn->rsn_mcastkeylen >= 13)
774                 ADDSELECTOR(frm, wep104_suite);
775         else
776                 ADDSELECTOR(frm, cipher_suite[rsn->rsn_mcastcipher]);
777
778         /* unicast cipher list */
779         selcnt = frm;
780         ADDSHORT(frm, 0);                       /* selector count */
781         if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_AES_CCM)) {
782                 selcnt[0]++;
783                 ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_AES_CCM]);
784         }
785         if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_TKIP)) {
786                 selcnt[0]++;
787                 ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_TKIP]);
788         }
789
790         /* authenticator selector list */
791         selcnt = frm;
792         ADDSHORT(frm, 0);                       /* selector count */
793         if (rsn->rsn_keymgmtset & WPA_ASE_8021X_UNSPEC) {
794                 selcnt[0]++;
795                 ADDSELECTOR(frm, key_mgt_unspec);
796         }
797         if (rsn->rsn_keymgmtset & WPA_ASE_8021X_PSK) {
798                 selcnt[0]++;
799                 ADDSELECTOR(frm, key_mgt_psk);
800         }
801
802         /* optional capabilities */
803         if (rsn->rsn_caps != 0 && rsn->rsn_caps != RSN_CAP_PREAUTH)
804                 ADDSHORT(frm, rsn->rsn_caps);
805
806         /* calculate element length */
807         ie[1] = frm - ie - 2;
808         KASSERT(ie[1]+2 <= sizeof(struct ieee80211_ie_wpa),
809                 ("WPA IE too big, %u > %zu",
810                 ie[1]+2, sizeof(struct ieee80211_ie_wpa)));
811         return frm;
812 #undef ADDSHORT
813 #undef ADDSELECTOR
814 #undef WPA_OUI_BYTES
815 }
816
817 static uint8_t *
818 ieee80211_setup_rsn_ie(struct ieee80211com *ic, uint8_t *ie)
819 {
820 #define RSN_OUI_BYTES           0x00, 0x0f, 0xac
821 #define ADDSHORT(frm, v) do {                   \
822         frm[0] = (v) & 0xff;                    \
823         frm[1] = (v) >> 8;                      \
824         frm += 2;                               \
825 } while (0)
826 #define ADDSELECTOR(frm, sel) do {              \
827         memcpy(frm, sel, 4);                    \
828         frm += 4;                               \
829 } while (0)
830         static const uint8_t cipher_suite[][4] = {
831                 { RSN_OUI_BYTES, RSN_CSE_WEP40 },       /* NB: 40-bit */
832                 { RSN_OUI_BYTES, RSN_CSE_TKIP },
833                 { RSN_OUI_BYTES, RSN_CSE_WRAP },
834                 { RSN_OUI_BYTES, RSN_CSE_CCMP },
835                 { 0x00, 0x00, 0x00, 0x00 },             /* XXX CKIP */
836                 { RSN_OUI_BYTES, RSN_CSE_NULL },
837         };
838         static const uint8_t wep104_suite[4] =
839                 { RSN_OUI_BYTES, RSN_CSE_WEP104 };
840         static const uint8_t key_mgt_unspec[4] =
841                 { RSN_OUI_BYTES, RSN_ASE_8021X_UNSPEC };
842         static const uint8_t key_mgt_psk[4] =
843                 { RSN_OUI_BYTES, RSN_ASE_8021X_PSK };
844         const struct ieee80211_rsnparms *rsn = &ic->ic_bss->ni_rsn;
845         uint8_t *frm = ie;
846         uint8_t *selcnt;
847
848         *frm++ = IEEE80211_ELEMID_RSN;
849         *frm++ = 0;                             /* length filled in below */
850         ADDSHORT(frm, RSN_VERSION);
851
852         /* XXX filter out CKIP */
853
854         /* multicast cipher */
855         if (rsn->rsn_mcastcipher == IEEE80211_CIPHER_WEP &&
856             rsn->rsn_mcastkeylen >= 13)
857                 ADDSELECTOR(frm, wep104_suite);
858         else
859                 ADDSELECTOR(frm, cipher_suite[rsn->rsn_mcastcipher]);
860
861         /* unicast cipher list */
862         selcnt = frm;
863         ADDSHORT(frm, 0);                       /* selector count */
864         if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_AES_CCM)) {
865                 selcnt[0]++;
866                 ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_AES_CCM]);
867         }
868         if (rsn->rsn_ucastcipherset & (1<<IEEE80211_CIPHER_TKIP)) {
869                 selcnt[0]++;
870                 ADDSELECTOR(frm, cipher_suite[IEEE80211_CIPHER_TKIP]);
871         }
872
873         /* authenticator selector list */
874         selcnt = frm;
875         ADDSHORT(frm, 0);                       /* selector count */
876         if (rsn->rsn_keymgmtset & WPA_ASE_8021X_UNSPEC) {
877                 selcnt[0]++;
878                 ADDSELECTOR(frm, key_mgt_unspec);
879         }
880         if (rsn->rsn_keymgmtset & WPA_ASE_8021X_PSK) {
881                 selcnt[0]++;
882                 ADDSELECTOR(frm, key_mgt_psk);
883         }
884
885         /* optional capabilities */
886         ADDSHORT(frm, rsn->rsn_caps);
887         /* XXX PMKID */
888
889         /* calculate element length */
890         ie[1] = frm - ie - 2;
891         KASSERT(ie[1]+2 <= sizeof(struct ieee80211_ie_wpa),
892                 ("RSN IE too big, %u > %zu",
893                 ie[1]+2, sizeof(struct ieee80211_ie_wpa)));
894         return frm;
895 #undef ADDSELECTOR
896 #undef ADDSHORT
897 #undef RSN_OUI_BYTES
898 }
899
900 /*
901  * Add a WPA/RSN element to a frame.
902  */
903 static uint8_t *
904 ieee80211_add_wpa(uint8_t *frm, struct ieee80211com *ic)
905 {
906
907         KASSERT(ic->ic_flags & IEEE80211_F_WPA, ("no WPA/RSN!"));
908         if (ic->ic_flags & IEEE80211_F_WPA2)
909                 frm = ieee80211_setup_rsn_ie(ic, frm);
910         if (ic->ic_flags & IEEE80211_F_WPA1)
911                 frm = ieee80211_setup_wpa_ie(ic, frm);
912         return frm;
913 }
914
915 #define WME_OUI_BYTES           0x00, 0x50, 0xf2
916 /*
917  * Add a WME information element to a frame.
918  */
919 static uint8_t *
920 ieee80211_add_wme_info(uint8_t *frm, struct ieee80211_wme_state *wme)
921 {
922         static const struct ieee80211_wme_info info = {
923                 .wme_id         = IEEE80211_ELEMID_VENDOR,
924                 .wme_len        = sizeof(struct ieee80211_wme_info) - 2,
925                 .wme_oui        = { WME_OUI_BYTES },
926                 .wme_type       = WME_OUI_TYPE,
927                 .wme_subtype    = WME_INFO_OUI_SUBTYPE,
928                 .wme_version    = WME_VERSION,
929                 .wme_info       = 0,
930         };
931         memcpy(frm, &info, sizeof(info));
932         return frm + sizeof(info); 
933 }
934
935 /*
936  * Add a WME parameters element to a frame.
937  */
938 static uint8_t *
939 ieee80211_add_wme_param(uint8_t *frm, struct ieee80211_wme_state *wme)
940 {
941 #define SM(_v, _f)      (((_v) << _f##_S) & _f)
942 #define ADDSHORT(frm, v) do {                   \
943         frm[0] = (v) & 0xff;                    \
944         frm[1] = (v) >> 8;                      \
945         frm += 2;                               \
946 } while (0)
947         /* NB: this works 'cuz a param has an info at the front */
948         static const struct ieee80211_wme_info param = {
949                 .wme_id         = IEEE80211_ELEMID_VENDOR,
950                 .wme_len        = sizeof(struct ieee80211_wme_param) - 2,
951                 .wme_oui        = { WME_OUI_BYTES },
952                 .wme_type       = WME_OUI_TYPE,
953                 .wme_subtype    = WME_PARAM_OUI_SUBTYPE,
954                 .wme_version    = WME_VERSION,
955         };
956         int i;
957
958         memcpy(frm, &param, sizeof(param));
959         frm += __offsetof(struct ieee80211_wme_info, wme_info);
960         *frm++ = wme->wme_bssChanParams.cap_info;       /* AC info */
961         *frm++ = 0;                                     /* reserved field */
962         for (i = 0; i < WME_NUM_AC; i++) {
963                 const struct wmeParams *ac =
964                        &wme->wme_bssChanParams.cap_wmeParams[i];
965                 *frm++ = SM(i, WME_PARAM_ACI)
966                        | SM(ac->wmep_acm, WME_PARAM_ACM)
967                        | SM(ac->wmep_aifsn, WME_PARAM_AIFSN)
968                        ;
969                 *frm++ = SM(ac->wmep_logcwmax, WME_PARAM_LOGCWMAX)
970                        | SM(ac->wmep_logcwmin, WME_PARAM_LOGCWMIN)
971                        ;
972                 ADDSHORT(frm, ac->wmep_txopLimit);
973         }
974         return frm;
975 #undef SM
976 #undef ADDSHORT
977 }
978 #undef WME_OUI_BYTES
979
980 /*
981  * Send a probe request frame with the specified ssid
982  * and any optional information element data.
983  */
984 int
985 ieee80211_send_probereq(struct ieee80211_node *ni,
986         const uint8_t sa[IEEE80211_ADDR_LEN],
987         const uint8_t da[IEEE80211_ADDR_LEN],
988         const uint8_t bssid[IEEE80211_ADDR_LEN],
989         const uint8_t *ssid, size_t ssidlen,
990         const void *optie, size_t optielen)
991 {
992         struct ieee80211com *ic = ni->ni_ic;
993         struct ifnet *ifp = ic->ic_ifp;
994         enum ieee80211_phymode mode;
995         struct ieee80211_frame *wh;
996         struct ieee80211_rateset rs;
997         struct mbuf *m;
998         uint8_t *frm;
999
1000         /*
1001          * Hold a reference on the node so it doesn't go away until after
1002          * the xmit is complete all the way in the driver.  On error we
1003          * will remove our reference.
1004          */
1005         IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1006                 "ieee80211_ref_node (%s:%u) %p<%6D> refcnt %d\n",
1007                 __func__, __LINE__,
1008                 ni, ni->ni_macaddr, ":",
1009                 ieee80211_node_refcnt(ni) + 1);
1010         ieee80211_ref_node(ni);
1011
1012         /*
1013          * prreq frame format
1014          *      [tlv] ssid
1015          *      [tlv] supported rates
1016          *      [tlv] extended supported rates
1017          *      [tlv] user-specified ie's
1018          */
1019         m = ieee80211_getmgtframe(&frm,
1020                  ic->ic_headroom + sizeof(struct ieee80211_frame),
1021                  2 + IEEE80211_NWID_LEN
1022                + 2 + IEEE80211_RATE_SIZE
1023                + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1024                + (optie != NULL ? optielen : 0)
1025         );
1026         if (m == NULL) {
1027                 ic->ic_stats.is_tx_nobuf++;
1028                 ieee80211_free_node(ni);
1029                 return ENOMEM;
1030         }
1031
1032         frm = ieee80211_add_ssid(frm, ssid, ssidlen);
1033
1034         /*
1035          * XXX
1036          * Clear basic rates.
1037          *
1038          * Though according to 802.11 standard: MSB of each supported rate
1039          * octet in (Extended) Supported Rates ie of probe requests should
1040          * be ignored, some HostAP implementations still check it ...
1041          */
1042         mode = ieee80211_chan2mode(ic, ic->ic_curchan);
1043         rs = ic->ic_sup_rates[mode];
1044         ieee80211_set_basicrates(&rs, IEEE80211_MODE_AUTO, 0);
1045         frm = ieee80211_add_rates(frm, &rs);
1046         frm = ieee80211_add_xrates(frm, &rs);
1047
1048         if (optie != NULL) {
1049                 memcpy(frm, optie, optielen);
1050                 frm += optielen;
1051         }
1052         m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
1053
1054         M_PREPEND(m, sizeof(struct ieee80211_frame), MB_DONTWAIT);
1055         if (m == NULL)
1056                 return ENOMEM;
1057         KASSERT(m->m_pkthdr.rcvif == NULL, ("rcvif not null"));
1058         m->m_pkthdr.rcvif = (void *)ni;
1059
1060         wh = mtod(m, struct ieee80211_frame *);
1061         ieee80211_send_setup(ic, ni, wh,
1062                 IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_REQ,
1063                 sa, da, bssid);
1064         /* XXX power management? */
1065
1066         IEEE80211_NODE_STAT(ni, tx_probereq);
1067         IEEE80211_NODE_STAT(ni, tx_mgmt);
1068
1069         IEEE80211_DPRINTF(ic, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS,
1070             "[%6D] send probe req on channel %u\n",
1071             wh->i_addr1, ":",
1072             ieee80211_chan2ieee(ic, ic->ic_curchan));
1073
1074         IF_ENQUEUE(&ic->ic_mgtq, m);
1075         ifp->if_start(ifp);
1076         return 0;
1077 }
1078
1079 /*
1080  * Calculate capability information for mgt frames.
1081  */
1082 static uint16_t
1083 getcapinfo(struct ieee80211com *ic, struct ieee80211_channel *chan)
1084 {
1085         uint16_t capinfo;
1086
1087         KASSERT(ic->ic_opmode != IEEE80211_M_STA, ("station mode"));
1088
1089         if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1090                 capinfo = IEEE80211_CAPINFO_ESS;
1091         else if (ic->ic_opmode == IEEE80211_M_IBSS)
1092                 capinfo = IEEE80211_CAPINFO_IBSS;
1093         else
1094                 capinfo = 0;
1095         if (ic->ic_flags & IEEE80211_F_PRIVACY)
1096                 capinfo |= IEEE80211_CAPINFO_PRIVACY;
1097         if (IEEE80211_IS_CHAN_2GHZ(chan)) {
1098                 if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
1099                         capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1100                 if (ic->ic_caps_ext & IEEE80211_CEXT_PBCC)
1101                         capinfo |= IEEE80211_CAPINFO_PBCC;
1102         }
1103         if (ic->ic_flags & IEEE80211_F_SHSLOT)
1104                 capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1105         return capinfo;
1106 }
1107
1108 static struct mbuf *
1109 _ieee80211_probe_resp_alloc(struct ieee80211com *ic, struct ieee80211_node *ni)
1110 {
1111         const struct ieee80211_rateset *rs;
1112         uint16_t capinfo;
1113         struct mbuf *m;
1114         uint8_t *frm;
1115         int pktlen;
1116
1117         /*
1118          * probe response frame format
1119          *      [8] time stamp
1120          *      [2] beacon interval
1121          *      [2] cabability information
1122          *      [tlv] ssid
1123          *      [tlv] supported rates
1124          *      [tlv] parameter set (FH/DS)
1125          *      [4] parameter set (IBSS)
1126          *      [tlv] extended rate phy (ERP)
1127          *      [tlv] extended supported rates
1128          *      [tlv] WPA
1129          *      [tlv] WME (optional)
1130          */
1131         KKASSERT(ic->ic_curmode != IEEE80211_MODE_AUTO);
1132         rs = &ic->ic_sup_rates[ic->ic_curmode];
1133         pktlen =  8                                     /* time stamp */
1134                 + sizeof(uint16_t)                      /* beacon interval */
1135                 + sizeof(uint16_t)                      /* capabilities */
1136                 + 2 + ni->ni_esslen                     /* ssid */
1137                 + 2 + IEEE80211_RATE_SIZE               /* supported rates */
1138                 + 2 + 5 /* max(5,1) */                  /* DS/FH parameters */
1139                 + 2 + 2                                 /* IBSS parameters */
1140                 + 2 + 1                                 /* ERP */
1141                 + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1142                 /* XXX !WPA1+WPA2 fits w/o a cluster */
1143                 + (ic->ic_flags & IEEE80211_F_WPA ?     /* WPA 1+2 */
1144                         2*sizeof(struct ieee80211_ie_wpa) : 0)
1145                 + sizeof(struct ieee80211_wme_param);   /* WME */
1146
1147         m = ieee80211_getmgtframe(&frm,
1148                 ic->ic_headroom + sizeof(struct ieee80211_frame), pktlen);
1149         if (m == NULL) {
1150                 IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
1151                         "%s: cannot get buf; size %u\n", __func__, pktlen);
1152                 ic->ic_stats.is_tx_nobuf++;
1153                 return NULL;
1154         }
1155
1156         memset(frm, 0, 8);      /* timestamp should be filled later */
1157         frm += 8;
1158         *(uint16_t *)frm = htole16(ni->ni_intval);
1159         frm += 2;
1160         capinfo = getcapinfo(ic, ni->ni_chan);
1161         *(uint16_t *)frm = htole16(capinfo);
1162         frm += 2;
1163
1164         frm = ieee80211_add_ssid(frm, ni->ni_essid, ni->ni_esslen);
1165         frm = ieee80211_add_rates(frm, rs);
1166
1167         if (ic->ic_phytype == IEEE80211_T_FH) {
1168                 *frm++ = IEEE80211_ELEMID_FHPARMS;
1169                 *frm++ = 5;
1170                 *frm++ = ni->ni_fhdwell & 0x00ff;
1171                 *frm++ = (ni->ni_fhdwell >> 8) & 0x00ff;
1172                 *frm++ = IEEE80211_FH_CHANSET(
1173                     ieee80211_chan2ieee(ic, ni->ni_chan));
1174                 *frm++ = IEEE80211_FH_CHANPAT(
1175                     ieee80211_chan2ieee(ic, ni->ni_chan));
1176                 *frm++ = ni->ni_fhindex;
1177         } else {
1178                 *frm++ = IEEE80211_ELEMID_DSPARMS;
1179                 *frm++ = 1;
1180                 *frm++ = ieee80211_chan2ieee(ic, ni->ni_chan);
1181         }
1182
1183         if (ic->ic_opmode == IEEE80211_M_IBSS) {
1184                 *frm++ = IEEE80211_ELEMID_IBSSPARMS;
1185                 *frm++ = 2;
1186                 *frm++ = 0; *frm++ = 0;         /* TODO: ATIM window */
1187         }
1188         if (ic->ic_flags & IEEE80211_F_WPA)
1189                 frm = ieee80211_add_wpa(frm, ic);
1190         if (ic->ic_curmode == IEEE80211_MODE_11G)
1191                 frm = ieee80211_add_erp(frm, ic);
1192         frm = ieee80211_add_xrates(frm, rs);
1193         if (ic->ic_flags & IEEE80211_F_WME)
1194                 frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
1195         m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
1196         KKASSERT(m->m_len <= pktlen);
1197
1198         return m;
1199 }
1200
1201 /*
1202  * Send a management frame.  The node is for the destination (or ic_bss
1203  * when in station mode).  Nodes other than ic_bss have their reference
1204  * count bumped to reflect our use for an indeterminant time.
1205  */
1206 int
1207 ieee80211_send_mgmt(struct ieee80211com *ic, struct ieee80211_node *ni,
1208         int type, int arg)
1209 {
1210 #define senderr(_x, _v) do { ic->ic_stats._v++; ret = _x; goto bad; } while (0)
1211         struct mbuf *m;
1212         uint8_t *frm;
1213         uint16_t capinfo;
1214         int has_challenge, is_shared_key, ret, timer, status, encrypt;
1215         const struct ieee80211_rateset *rs;
1216
1217         KASSERT(ni != NULL, ("null node"));
1218
1219         /*
1220          * Hold a reference on the node so it doesn't go away until after
1221          * the xmit is complete all the way in the driver.  On error we
1222          * will remove our reference.
1223          */
1224         IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1225                 "ieee80211_ref_node (%s:%u) %p<%6D> refcnt %d\n",
1226                 __func__, __LINE__,
1227                 ni, ni->ni_macaddr, ":",
1228                 ieee80211_node_refcnt(ni) + 1);
1229         ieee80211_ref_node(ni);
1230
1231         encrypt = 0;
1232         timer = 0;
1233         switch (type) {
1234         case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
1235                 m = _ieee80211_probe_resp_alloc(ic, ic->ic_bss);
1236                 if (m == NULL) {
1237                         /* NB: Statistics have been updated. */
1238                         ret = ENOMEM;
1239                         goto bad;
1240                 }
1241                 break;
1242
1243         case IEEE80211_FC0_SUBTYPE_AUTH:
1244                 status = arg >> 16;
1245                 arg &= 0xffff;
1246                 has_challenge = ((arg == IEEE80211_AUTH_SHARED_CHALLENGE ||
1247                     arg == IEEE80211_AUTH_SHARED_RESPONSE) &&
1248                     ni->ni_challenge != NULL);
1249
1250                 /*
1251                  * Deduce whether we're doing open authentication or
1252                  * shared key authentication.  We do the latter if
1253                  * we're in the middle of a shared key authentication
1254                  * handshake or if we're initiating an authentication
1255                  * request and configured to use shared key.
1256                  */
1257                 is_shared_key = has_challenge ||
1258                      arg >= IEEE80211_AUTH_SHARED_RESPONSE ||
1259                      (arg == IEEE80211_AUTH_SHARED_REQUEST &&
1260                       ic->ic_bss->ni_authmode == IEEE80211_AUTH_SHARED);
1261
1262                 m = ieee80211_getmgtframe(&frm,
1263                           ic->ic_headroom + sizeof(struct ieee80211_frame),
1264                           3 * sizeof(uint16_t)
1265                         + (has_challenge && status == IEEE80211_STATUS_SUCCESS ?
1266                                 sizeof(uint16_t)+IEEE80211_CHALLENGE_LEN : 0)
1267                 );
1268                 if (m == NULL)
1269                         senderr(ENOMEM, is_tx_nobuf);
1270
1271                 ((uint16_t *)frm)[0] =
1272                     (is_shared_key) ? htole16(IEEE80211_AUTH_ALG_SHARED)
1273                                     : htole16(IEEE80211_AUTH_ALG_OPEN);
1274                 ((uint16_t *)frm)[1] = htole16(arg);    /* sequence number */
1275                 ((uint16_t *)frm)[2] = htole16(status);/* status */
1276
1277                 if (has_challenge && status == IEEE80211_STATUS_SUCCESS) {
1278                         ((uint16_t *)frm)[3] =
1279                             htole16((IEEE80211_CHALLENGE_LEN << 8) |
1280                             IEEE80211_ELEMID_CHALLENGE);
1281                         memcpy(&((uint16_t *)frm)[4], ni->ni_challenge,
1282                             IEEE80211_CHALLENGE_LEN);
1283                         m->m_pkthdr.len = m->m_len =
1284                                 4 * sizeof(uint16_t) + IEEE80211_CHALLENGE_LEN;
1285                         if (arg == IEEE80211_AUTH_SHARED_RESPONSE) {
1286                                 IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
1287                                     "[%6D] request encrypt frame (%s)\n",
1288                                     ni->ni_macaddr, ":", __func__);
1289                                 encrypt = 1;    /* WEP-encrypt, please */
1290                         }
1291                 } else
1292                         m->m_pkthdr.len = m->m_len = 3 * sizeof(uint16_t);
1293
1294                 /* XXX not right for shared key */
1295                 if (status == IEEE80211_STATUS_SUCCESS)
1296                         IEEE80211_NODE_STAT(ni, tx_auth);
1297                 else
1298                         IEEE80211_NODE_STAT(ni, tx_auth_fail);
1299
1300                 if (ic->ic_opmode == IEEE80211_M_STA)
1301                         timer = IEEE80211_TRANS_WAIT;
1302                 break;
1303
1304         case IEEE80211_FC0_SUBTYPE_DEAUTH:
1305                 IEEE80211_DPRINTF(ic, IEEE80211_MSG_AUTH,
1306                         "[%6D] send station deauthenticate (reason %d)\n",
1307                         ni->ni_macaddr, ":", arg);
1308                 m = ieee80211_getmgtframe(&frm,
1309                         ic->ic_headroom + sizeof(struct ieee80211_frame),
1310                         sizeof(uint16_t));
1311                 if (m == NULL)
1312                         senderr(ENOMEM, is_tx_nobuf);
1313                 *(uint16_t *)frm = htole16(arg);        /* reason */
1314                 m->m_pkthdr.len = m->m_len = sizeof(uint16_t);
1315
1316                 IEEE80211_NODE_STAT(ni, tx_deauth);
1317                 IEEE80211_NODE_STAT_SET(ni, tx_deauth_code, arg);
1318
1319                 ieee80211_node_unauthorize(ni);         /* port closed */
1320                 break;
1321
1322         case IEEE80211_FC0_SUBTYPE_ASSOC_REQ:
1323         case IEEE80211_FC0_SUBTYPE_REASSOC_REQ:
1324                 /*
1325                  * asreq frame format
1326                  *      [2] capability information
1327                  *      [2] listen interval
1328                  *      [6*] current AP address (reassoc only)
1329                  *      [tlv] ssid
1330                  *      [tlv] supported rates
1331                  *      [tlv] extended supported rates
1332                  *      [tlv] WME
1333                  *      [tlv] user-specified ie's
1334                  */
1335                 m = ieee80211_getmgtframe(&frm,
1336                          ic->ic_headroom + sizeof(struct ieee80211_frame),
1337                          sizeof(uint16_t)
1338                        + sizeof(uint16_t)
1339                        + IEEE80211_ADDR_LEN
1340                        + 2 + IEEE80211_NWID_LEN
1341                        + 2 + IEEE80211_RATE_SIZE
1342                        + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1343                        + sizeof(struct ieee80211_wme_info)
1344                        + (ic->ic_opt_ie != NULL ? ic->ic_opt_ie_len : 0)
1345                 );
1346                 if (m == NULL)
1347                         senderr(ENOMEM, is_tx_nobuf);
1348
1349                 KASSERT(ic->ic_opmode == IEEE80211_M_STA,
1350                     ("wrong mode %u", ic->ic_opmode));
1351                 capinfo = IEEE80211_CAPINFO_ESS;
1352                 if (ic->ic_flags & IEEE80211_F_PRIVACY)
1353                         capinfo |= IEEE80211_CAPINFO_PRIVACY;
1354                 /*
1355                  * NB: Some 11a AP's reject the request when
1356                  *     short premable or PBCC modulation is set.
1357                  */
1358                 if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan)) {
1359                         if (ic->ic_caps & IEEE80211_C_SHPREAMBLE)
1360                                 capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1361                         if (ic->ic_caps_ext & IEEE80211_CEXT_PBCC)
1362                                 capinfo |= IEEE80211_CAPINFO_PBCC;
1363                 }
1364                 if (IEEE80211_IS_CHAN_2GHZ(ni->ni_chan) &&
1365                     (ic->ic_caps & IEEE80211_C_SHSLOT))
1366                         capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1367                 *(uint16_t *)frm = htole16(capinfo);
1368                 frm += 2;
1369
1370                 KKASSERT(ic->ic_bss->ni_intval != 0);
1371                 *(uint16_t *)frm = htole16(howmany(ic->ic_lintval,
1372                                                    ic->ic_bss->ni_intval));
1373                 frm += 2;
1374
1375                 if (type == IEEE80211_FC0_SUBTYPE_REASSOC_REQ) {
1376                         IEEE80211_ADDR_COPY(frm, ic->ic_bss->ni_bssid);
1377                         frm += IEEE80211_ADDR_LEN;
1378                 }
1379
1380                 frm = ieee80211_add_ssid(frm, ni->ni_essid, ni->ni_esslen);
1381
1382                 rs = &ic->ic_sup_rates[ieee80211_chan2mode(ic, ni->ni_chan)];
1383                 frm = ieee80211_add_rates(frm, rs);
1384                 frm = ieee80211_add_xrates(frm, rs);
1385
1386                 if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
1387                         frm = ieee80211_add_wme_info(frm, &ic->ic_wme);
1388                 if (ic->ic_opt_ie != NULL) {
1389                         memcpy(frm, ic->ic_opt_ie, ic->ic_opt_ie_len);
1390                         frm += ic->ic_opt_ie_len;
1391                 }
1392                 m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
1393
1394                 timer = IEEE80211_TRANS_WAIT;
1395                 break;
1396
1397         case IEEE80211_FC0_SUBTYPE_ASSOC_RESP:
1398         case IEEE80211_FC0_SUBTYPE_REASSOC_RESP:
1399                 /*
1400                  * asreq frame format
1401                  *      [2] capability information
1402                  *      [2] status
1403                  *      [2] association ID
1404                  *      [tlv] supported rates
1405                  *      [tlv] extended supported rates
1406                  *      [tlv] WME (if enabled and STA enabled)
1407                  */
1408                 m = ieee80211_getmgtframe(&frm,
1409                          ic->ic_headroom + sizeof(struct ieee80211_frame),
1410                          sizeof(uint16_t)
1411                        + sizeof(uint16_t)
1412                        + sizeof(uint16_t)
1413                        + 2 + IEEE80211_RATE_SIZE
1414                        + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1415                        + sizeof(struct ieee80211_wme_param)
1416                 );
1417                 if (m == NULL)
1418                         senderr(ENOMEM, is_tx_nobuf);
1419
1420                 capinfo = getcapinfo(ic, ic->ic_curchan);
1421                 *(uint16_t *)frm = htole16(capinfo);
1422                 frm += 2;
1423
1424                 *(uint16_t *)frm = htole16(arg);        /* status */
1425                 frm += 2;
1426
1427                 if (arg == IEEE80211_STATUS_SUCCESS) {
1428                         *(uint16_t *)frm = htole16(ni->ni_associd);
1429                         IEEE80211_NODE_STAT(ni, tx_assoc);
1430                 } else
1431                         IEEE80211_NODE_STAT(ni, tx_assoc_fail);
1432                 frm += 2;
1433
1434                 KKASSERT(ic->ic_curmode != IEEE80211_MODE_AUTO);
1435                 rs = &ic->ic_sup_rates[ic->ic_curmode];
1436                 frm = ieee80211_add_rates(frm, rs);
1437                 frm = ieee80211_add_xrates(frm, rs);
1438                 if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_wme_ie != NULL)
1439                         frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
1440                 m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *);
1441                 break;
1442
1443         case IEEE80211_FC0_SUBTYPE_DISASSOC:
1444                 IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1445                         "[%6D] send station disassociate (reason %d)\n",
1446                         ni->ni_macaddr, ":", arg);
1447                 m = ieee80211_getmgtframe(&frm,
1448                         ic->ic_headroom + sizeof(struct ieee80211_frame),
1449                         sizeof(uint16_t));
1450                 if (m == NULL)
1451                         senderr(ENOMEM, is_tx_nobuf);
1452                 *(uint16_t *)frm = htole16(arg);        /* reason */
1453                 m->m_pkthdr.len = m->m_len = sizeof(uint16_t);
1454
1455                 IEEE80211_NODE_STAT(ni, tx_disassoc);
1456                 IEEE80211_NODE_STAT_SET(ni, tx_disassoc_code, arg);
1457                 break;
1458
1459         default:
1460                 IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
1461                         "[%6D] invalid mgmt frame type %u\n",
1462                         ni->ni_macaddr, ":", type);
1463                 senderr(EINVAL, is_tx_unknownmgt);
1464                 /* NOTREACHED */
1465         }
1466         ret = ieee80211_mgmt_output(ic, ni, m, type, timer, encrypt);
1467         if (ret != 0) {
1468 bad:
1469                 ieee80211_free_node(ni);
1470         }
1471         return ret;
1472 #undef senderr
1473 }
1474
1475 /*
1476  * Allocate a probe response frame and fillin the appropriate bits.
1477  */
1478 struct mbuf *
1479 ieee80211_probe_resp_alloc(struct ieee80211com *ic, struct ieee80211_node *ni)
1480 {
1481         struct ieee80211_frame *wh;
1482         struct mbuf *m;
1483
1484         m = _ieee80211_probe_resp_alloc(ic, ni);
1485         if (m == NULL)
1486                 return NULL;
1487
1488         M_PREPEND(m, sizeof(struct ieee80211_frame), MB_DONTWAIT);
1489         KASSERT(m != NULL, ("no space for 802.11 header?"));
1490
1491         wh = mtod(m, struct ieee80211_frame *);
1492         wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
1493                       IEEE80211_FC0_SUBTYPE_PROBE_RESP;
1494         wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1495         *(uint16_t *)wh->i_dur = 0;
1496         bzero(wh->i_addr1, sizeof(wh->i_addr1));
1497         IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
1498         IEEE80211_ADDR_COPY(wh->i_addr3, ni->ni_bssid);
1499         *(uint16_t *)wh->i_seq = 0;
1500
1501         return m;
1502 }
1503
1504 /*
1505  * Allocate a beacon frame and fillin the appropriate bits.
1506  */
1507 struct mbuf *
1508 ieee80211_beacon_alloc(struct ieee80211com *ic, struct ieee80211_node *ni,
1509         struct ieee80211_beacon_offsets *bo)
1510 {
1511         struct ifnet *ifp = ic->ic_ifp;
1512         struct ieee80211_frame *wh;
1513         struct mbuf *m;
1514         int pktlen;
1515         uint8_t *frm, *efrm;
1516         uint16_t capinfo;
1517         const struct ieee80211_rateset *rs;
1518
1519         /*
1520          * beacon frame format
1521          *      [8] time stamp
1522          *      [2] beacon interval
1523          *      [2] cabability information
1524          *      [tlv] ssid
1525          *      [tlv] supported rates
1526          *      [3] parameter set (DS)
1527          *      [tlv] parameter set (IBSS/TIM)
1528          *      [tlv] extended rate phy (ERP)
1529          *      [tlv] extended supported rates
1530          *      [tlv] WME parameters
1531          *      [tlv] WPA/RSN parameters
1532          * XXX Vendor-specific OIDs (e.g. Atheros)
1533          * NB: we allocate the max space required for the TIM bitmap.
1534          */
1535         KKASSERT(ic->ic_curmode != IEEE80211_MODE_AUTO);
1536         rs = &ic->ic_sup_rates[ic->ic_curmode];
1537         pktlen =   8                                    /* time stamp */
1538                  + sizeof(uint16_t)                     /* beacon interval */
1539                  + sizeof(uint16_t)                     /* capabilities */
1540                  + 2 + ni->ni_esslen                    /* ssid */
1541                  + 2 + IEEE80211_RATE_SIZE              /* supported rates */
1542                  + 2 + 1                                /* DS parameters */
1543                  + 2 + 4 + ic->ic_tim_len               /* DTIM/IBSSPARMS */
1544                  + 2 + 1                                /* ERP */
1545                  + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE)
1546                  + (ic->ic_caps & IEEE80211_C_WME ?     /* WME */
1547                         sizeof(struct ieee80211_wme_param) : 0)
1548                  + (ic->ic_caps & IEEE80211_C_WPA ?     /* WPA 1+2 */
1549                         2*sizeof(struct ieee80211_ie_wpa) : 0)
1550                  ;
1551         m = ieee80211_getmgtframe(&frm,
1552                 ic->ic_headroom + sizeof(struct ieee80211_frame), pktlen);
1553         if (m == NULL) {
1554                 IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
1555                         "%s: cannot get buf; size %u\n", __func__, pktlen);
1556                 ic->ic_stats.is_tx_nobuf++;
1557                 return NULL;
1558         }
1559
1560         memset(frm, 0, 8);      /* XXX timestamp is set by hardware/driver */
1561         frm += 8;
1562         *(uint16_t *)frm = htole16(ni->ni_intval);
1563         frm += 2;
1564         capinfo = getcapinfo(ic, ni->ni_chan);
1565         bo->bo_caps = (uint16_t *)frm;
1566         *(uint16_t *)frm = htole16(capinfo);
1567         frm += 2;
1568         *frm++ = IEEE80211_ELEMID_SSID;
1569         if ((ic->ic_flags & IEEE80211_F_HIDESSID) == 0) {
1570                 *frm++ = ni->ni_esslen;
1571                 memcpy(frm, ni->ni_essid, ni->ni_esslen);
1572                 frm += ni->ni_esslen;
1573         } else
1574                 *frm++ = 0;
1575         frm = ieee80211_add_rates(frm, rs);
1576         if (ic->ic_curmode != IEEE80211_MODE_FH) {
1577                 *frm++ = IEEE80211_ELEMID_DSPARMS;
1578                 *frm++ = 1;
1579                 *frm++ = ieee80211_chan2ieee(ic, ni->ni_chan);
1580         }
1581         bo->bo_tim = frm;
1582         if (ic->ic_opmode == IEEE80211_M_IBSS) {
1583                 *frm++ = IEEE80211_ELEMID_IBSSPARMS;
1584                 *frm++ = 2;
1585                 *frm++ = 0; *frm++ = 0;         /* TODO: ATIM window */
1586                 bo->bo_tim_len = 0;
1587         } else if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
1588                 struct ieee80211_tim_ie *tie = (struct ieee80211_tim_ie *) frm;
1589
1590                 tie->tim_ie = IEEE80211_ELEMID_TIM;
1591                 tie->tim_len = 4;       /* length */
1592                 tie->tim_count = 0;     /* DTIM count */ 
1593                 tie->tim_period = ic->ic_dtim_period;   /* DTIM period */
1594                 tie->tim_bitctl = 0;    /* bitmap control */
1595                 tie->tim_bitmap[0] = 0; /* Partial Virtual Bitmap */
1596                 frm += sizeof(struct ieee80211_tim_ie);
1597                 bo->bo_tim_len = 1;
1598         }
1599         bo->bo_trailer = frm;
1600         if (ic->ic_flags & IEEE80211_F_WME) {
1601                 bo->bo_wme = frm;
1602                 frm = ieee80211_add_wme_param(frm, &ic->ic_wme);
1603                 ic->ic_flags &= ~IEEE80211_F_WMEUPDATE;
1604         }
1605         if (ic->ic_flags & IEEE80211_F_WPA)
1606                 frm = ieee80211_add_wpa(frm, ic);
1607         if (ic->ic_curmode == IEEE80211_MODE_11G) {
1608                 bo->bo_erp = frm;
1609                 frm = ieee80211_add_erp(frm, ic);
1610         }
1611         efrm = ieee80211_add_xrates(frm, rs);
1612         bo->bo_trailer_len = efrm - bo->bo_trailer;
1613         m->m_pkthdr.len = m->m_len = efrm - mtod(m, uint8_t *);
1614         KKASSERT(m->m_len <= pktlen);
1615
1616         M_PREPEND(m, sizeof(struct ieee80211_frame), MB_DONTWAIT);
1617         KASSERT(m != NULL, ("no space for 802.11 header?"));
1618         wh = mtod(m, struct ieee80211_frame *);
1619         wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
1620             IEEE80211_FC0_SUBTYPE_BEACON;
1621         wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1622         *(uint16_t *)wh->i_dur = 0;
1623         IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr);
1624         IEEE80211_ADDR_COPY(wh->i_addr2, ic->ic_myaddr);
1625         IEEE80211_ADDR_COPY(wh->i_addr3, ni->ni_bssid);
1626         *(uint16_t *)wh->i_seq = 0;
1627
1628         return m;
1629 }
1630
1631 /*
1632  * Update the dynamic parts of a beacon frame based on the current state.
1633  */
1634 int
1635 ieee80211_beacon_update(struct ieee80211com *ic, struct ieee80211_node *ni,
1636         struct ieee80211_beacon_offsets *bo, struct mbuf *m, int mcast)
1637 {
1638         int len_changed = 0;
1639         uint16_t capinfo;
1640
1641         ASSERT_SERIALIZED(ic->ic_ifp->if_serializer);
1642
1643         /* XXX faster to recalculate entirely or just changes? */
1644         capinfo = getcapinfo(ic, ni->ni_chan);
1645         *bo->bo_caps = htole16(capinfo);
1646
1647         if (ic->ic_flags & IEEE80211_F_WME) {
1648                 struct ieee80211_wme_state *wme = &ic->ic_wme;
1649
1650                 /*
1651                  * Check for agressive mode change.  When there is
1652                  * significant high priority traffic in the BSS
1653                  * throttle back BE traffic by using conservative
1654                  * parameters.  Otherwise BE uses agressive params
1655                  * to optimize performance of legacy/non-QoS traffic.
1656                  */
1657                 if (wme->wme_flags & WME_F_AGGRMODE) {
1658                         if (wme->wme_hipri_traffic >
1659                             wme->wme_hipri_switch_thresh) {
1660                                 IEEE80211_DPRINTF(ic, IEEE80211_MSG_WME,
1661                                     "%s: traffic %u, disable aggressive mode\n",
1662                                     __func__, wme->wme_hipri_traffic);
1663                                 wme->wme_flags &= ~WME_F_AGGRMODE;
1664                                 ieee80211_wme_updateparams(ic);
1665                                 wme->wme_hipri_traffic =
1666                                         wme->wme_hipri_switch_hysteresis;
1667                         } else
1668                                 wme->wme_hipri_traffic = 0;
1669                 } else {
1670                         if (wme->wme_hipri_traffic <=
1671                             wme->wme_hipri_switch_thresh) {
1672                                 IEEE80211_DPRINTF(ic, IEEE80211_MSG_WME,
1673                                     "%s: traffic %u, enable aggressive mode\n",
1674                                     __func__, wme->wme_hipri_traffic);
1675                                 wme->wme_flags |= WME_F_AGGRMODE;
1676                                 ieee80211_wme_updateparams(ic);
1677                                 wme->wme_hipri_traffic = 0;
1678                         } else
1679                                 wme->wme_hipri_traffic =
1680                                         wme->wme_hipri_switch_hysteresis;
1681                 }
1682                 if (ic->ic_flags & IEEE80211_F_WMEUPDATE) {
1683                         (void) ieee80211_add_wme_param(bo->bo_wme, wme);
1684                         ic->ic_flags &= ~IEEE80211_F_WMEUPDATE;
1685                 }
1686         }
1687
1688         if (ic->ic_opmode == IEEE80211_M_HOSTAP) {      /* NB: no IBSS support*/
1689                 struct ieee80211_tim_ie *tie =
1690                         (struct ieee80211_tim_ie *) bo->bo_tim;
1691                 if (ic->ic_flags & IEEE80211_F_TIMUPDATE) {
1692                         u_int timlen, timoff, i;
1693                         /* 
1694                          * ATIM/DTIM needs updating.  If it fits in the
1695                          * current space allocated then just copy in the
1696                          * new bits.  Otherwise we need to move any trailing
1697                          * data to make room.  Note that we know there is
1698                          * contiguous space because ieee80211_beacon_allocate
1699                          * insures there is space in the mbuf to write a
1700                          * maximal-size virtual bitmap (based on ic_max_aid).
1701                          */
1702                         /*
1703                          * Calculate the bitmap size and offset, copy any
1704                          * trailer out of the way, and then copy in the
1705                          * new bitmap and update the information element.
1706                          * Note that the tim bitmap must contain at least
1707                          * one byte and any offset must be even.
1708                          */
1709                         if (ic->ic_ps_pending != 0) {
1710                                 timoff = 128;           /* impossibly large */
1711                                 for (i = 0; i < ic->ic_tim_len; i++)
1712                                         if (ic->ic_tim_bitmap[i]) {
1713                                                 timoff = i &~ 1;
1714                                                 break;
1715                                         }
1716                                 KASSERT(timoff != 128, ("tim bitmap empty!"));
1717                                 for (i = ic->ic_tim_len-1; i >= timoff; i--)
1718                                         if (ic->ic_tim_bitmap[i])
1719                                                 break;
1720                                 timlen = 1 + (i - timoff);
1721                         } else {
1722                                 timoff = 0;
1723                                 timlen = 1;
1724                         }
1725                         if (timlen != bo->bo_tim_len) {
1726                                 /* copy up/down trailer */
1727                                 int adjust = tie->tim_bitmap+timlen
1728                                            - bo->bo_trailer;
1729                                 ovbcopy(bo->bo_trailer, bo->bo_trailer+adjust,
1730                                         bo->bo_trailer_len);
1731                                 bo->bo_trailer += adjust;
1732                                 bo->bo_wme += adjust;
1733                                 bo->bo_erp += adjust;
1734                                 bo->bo_tim_len = timlen;
1735
1736                                 /* update information element */
1737                                 tie->tim_len = 3 + timlen;
1738                                 tie->tim_bitctl = timoff;
1739                                 len_changed = 1;
1740                         }
1741                         memcpy(tie->tim_bitmap, ic->ic_tim_bitmap + timoff,
1742                                 bo->bo_tim_len);
1743
1744                         ic->ic_flags &= ~IEEE80211_F_TIMUPDATE;
1745
1746                         IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
1747                                 "%s: TIM updated, pending %u, off %u, len %u\n",
1748                                 __func__, ic->ic_ps_pending, timoff, timlen);
1749                 }
1750                 /* count down DTIM period */
1751                 if (tie->tim_count == 0)
1752                         tie->tim_count = tie->tim_period - 1;
1753                 else
1754                         tie->tim_count--;
1755                 /* update state for buffered multicast frames on DTIM */
1756                 if (mcast && tie->tim_count == 0)
1757                         tie->tim_bitctl |= 1;
1758                 else
1759                         tie->tim_bitctl &= ~1;
1760                 if (ic->ic_flags_ext & IEEE80211_FEXT_ERPUPDATE) {
1761                         /*
1762                          * ERP element needs updating.
1763                          */
1764                         (void) ieee80211_add_erp(bo->bo_erp, ic);
1765                         ic->ic_flags_ext &= ~IEEE80211_FEXT_ERPUPDATE;
1766                 }
1767         }
1768
1769         return len_changed;
1770 }
1771
1772 /*
1773  * Save an outbound packet for a node in power-save sleep state.
1774  * The new packet is placed on the node's saved queue, and the TIM
1775  * is changed, if necessary.
1776  */
1777 void
1778 ieee80211_pwrsave(struct ieee80211com *ic, struct ieee80211_node *ni, 
1779                   struct mbuf *m)
1780 {
1781         int qlen, age;
1782
1783         ASSERT_SERIALIZED(ic->ic_ifp->if_serializer);
1784
1785         if (IF_QFULL(&ni->ni_savedq)) {
1786                 IF_DROP(&ni->ni_savedq);
1787                 IEEE80211_DPRINTF(ic, IEEE80211_MSG_ANY,
1788                         "[%6D] pwr save q overflow, drops %d (size %d)\n",
1789                         ni->ni_macaddr, ":",
1790                         ni->ni_savedq.ifq_drops, IEEE80211_PS_MAX_QUEUE);
1791 #ifdef IEEE80211_DEBUG
1792                 if (ieee80211_msg_dumppkts(ic)) {
1793                         ieee80211_dump_pkt(mtod(m, uint8_t *), m->m_len,
1794                                            -1, -1);
1795                 }
1796 #endif
1797                 m_freem(m);
1798                 return;
1799         }
1800         /*
1801          * Tag the frame with it's expiry time and insert
1802          * it in the queue.  The aging interval is 4 times
1803          * the listen interval specified by the station. 
1804          * Frames that sit around too long are reclaimed
1805          * using this information.
1806          */
1807         /* TU -> secs.  XXX handle overflow? */
1808         age = IEEE80211_TU_TO_MS((ni->ni_intval * ic->ic_bintval) << 2) / 1000;
1809         _IEEE80211_NODE_SAVEQ_ENQUEUE(ni, m, qlen, age);
1810
1811         IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
1812                 "[%6D] save frame with age %d, %u now queued\n",
1813                 ni->ni_macaddr, ":", age, qlen);
1814
1815         if (qlen == 1)
1816                 ic->ic_set_tim(ni, 1);
1817 }
1818
1819 uint8_t
1820 ieee80211_ack_rate(struct ieee80211_node *ni, uint8_t rate)
1821 {
1822         const struct ieee80211_rateset *rs = &ni->ni_rates;
1823         uint8_t ack_rate = 0;
1824         enum ieee80211_modtype modtype;
1825         int i;
1826
1827         rate &= IEEE80211_RATE_VAL;
1828
1829         modtype = ieee80211_rate2modtype(rate);
1830
1831         for (i = 0; i < rs->rs_nrates; ++i) {
1832                 uint8_t rate1 = IEEE80211_RS_RATE(rs, i);
1833
1834                 if (rate1 > rate) {
1835                         if (ack_rate != 0)
1836                                 return ack_rate;
1837                         else
1838                                 break;
1839                 }
1840
1841                 if ((rs->rs_rates[i] & IEEE80211_RATE_BASIC) &&
1842                     ieee80211_rate2modtype(rate1) == modtype)
1843                         ack_rate = rate1;
1844         }
1845
1846         switch (rate) {
1847         /* CCK */
1848         case 2:
1849         case 4:
1850         case 11:
1851         case 22:
1852                 ack_rate = rate;
1853                 break;
1854
1855         /* PBCC */
1856         case 44:
1857                 ack_rate = 22;
1858                 break;
1859
1860         /* OFDM */
1861         case 12:
1862         case 18:
1863                 ack_rate = 12;
1864                 break;
1865         case 24:
1866         case 36:
1867                 ack_rate = 24;
1868                 break;
1869         case 48:
1870         case 72:
1871         case 96:
1872         case 108:
1873                 ack_rate = 48;
1874                 break;
1875         default:
1876                 panic("unsupported rate %d\n", rate);
1877         }
1878         return ack_rate;
1879 }
1880
1881 /* IEEE Std 802.11a-1999, page 9, table 79 */
1882 #define IEEE80211_OFDM_SYM_TIME                 4
1883 #define IEEE80211_OFDM_PREAMBLE_TIME            16
1884 #define IEEE80211_OFDM_SIGNAL_TIME              4
1885 /* IEEE Std 802.11g-2003, page 44 */
1886 #define IEEE80211_OFDM_SIGNAL_EXT_TIME          6
1887
1888 /* IEEE Std 802.11a-1999, page 7, figure 107 */
1889 #define IEEE80211_OFDM_PLCP_SERVICE_NBITS       16
1890 #define IEEE80211_OFDM_TAIL_NBITS               6
1891
1892 #define IEEE80211_OFDM_NBITS(frmlen) \
1893         (IEEE80211_OFDM_PLCP_SERVICE_NBITS + \
1894          ((frmlen) * NBBY) + \
1895          IEEE80211_OFDM_TAIL_NBITS)
1896
1897 #define IEEE80211_OFDM_NBITS_PER_SYM(kbps) \
1898         (((kbps) * IEEE80211_OFDM_SYM_TIME) / 1000)
1899
1900 #define IEEE80211_OFDM_NSYMS(kbps, frmlen) \
1901         howmany(IEEE80211_OFDM_NBITS((frmlen)), \
1902                 IEEE80211_OFDM_NBITS_PER_SYM((kbps)))
1903
1904 #define IEEE80211_OFDM_TXTIME(kbps, frmlen) \
1905         (IEEE80211_OFDM_PREAMBLE_TIME + \
1906          IEEE80211_OFDM_SIGNAL_TIME + \
1907          (IEEE80211_OFDM_NSYMS((kbps), (frmlen)) * IEEE80211_OFDM_SYM_TIME))
1908
1909 /* IEEE Std 802.11b-1999, page 28, subclause 18.3.4 */
1910 #define IEEE80211_CCK_PREAMBLE_LEN      144
1911 #define IEEE80211_CCK_PLCP_HDR_TIME     48
1912 #define IEEE80211_CCK_SHPREAMBLE_LEN    72
1913 #define IEEE80211_CCK_SHPLCP_HDR_TIME   24
1914
1915 #define IEEE80211_CCK_NBITS(frmlen)     ((frmlen) * NBBY)
1916 #define IEEE80211_CCK_TXTIME(kbps, frmlen) \
1917         (((IEEE80211_CCK_NBITS((frmlen)) * 1000) + (kbps) - 1) / (kbps))
1918
1919 uint16_t
1920 ieee80211_txtime(struct ieee80211_node *ni, u_int len, uint8_t rs_rate,
1921                  uint32_t flags)
1922 {
1923         struct ieee80211com *ic = ni->ni_ic;
1924         enum ieee80211_modtype modtype;
1925         uint16_t txtime;
1926         int rate;
1927
1928         rs_rate &= IEEE80211_RATE_VAL;
1929
1930         rate = rs_rate * 500;   /* ieee80211 rate -> kbps */
1931
1932         modtype = ieee80211_rate2modtype(rs_rate);
1933         if (modtype == IEEE80211_MODTYPE_OFDM) {
1934                 /*
1935                  * IEEE Std 802.11a-1999, page 37, equation (29)
1936                  * IEEE Std 802.11g-2003, page 44, equation (42)
1937                  */
1938                 txtime = IEEE80211_OFDM_TXTIME(rate, len);
1939                 if (ic->ic_curmode == IEEE80211_MODE_11G)
1940                         txtime += IEEE80211_OFDM_SIGNAL_EXT_TIME;
1941         } else {
1942                 /*
1943                  * IEEE Std 802.11b-1999, page 28, subclause 18.3.4
1944                  * IEEE Std 802.11g-2003, page 45, equation (43)
1945                  */
1946                 if (modtype == IEEE80211_MODTYPE_PBCC)
1947                         ++len;
1948                 txtime = IEEE80211_CCK_TXTIME(rate, len);
1949
1950                 /*
1951                  * Short preamble is not applicable for DS 1Mbits/s
1952                  */
1953                 if (rs_rate != 2 && (flags & IEEE80211_F_SHPREAMBLE)) {
1954                         txtime += IEEE80211_CCK_SHPREAMBLE_LEN +
1955                                   IEEE80211_CCK_SHPLCP_HDR_TIME;
1956                 } else {
1957                         txtime += IEEE80211_CCK_PREAMBLE_LEN +
1958                                   IEEE80211_CCK_PLCP_HDR_TIME;
1959                 }
1960         }
1961         return txtime;
1962 }