Merge branch 'master' of git://git.theshell.com/dragonfly
[dragonfly.git] / sys / netproto / 802_11 / wlan / ieee80211_node.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  * $FreeBSD: head/sys/net80211/ieee80211_node.c 206358 2010-04-07 15:29:13Z rpaulo $
27  * $DragonFly$
28  */
29
30 #include "opt_wlan.h"
31
32 #include <sys/param.h>
33 #include <sys/systm.h> 
34 #include <sys/mbuf.h>   
35 #include <sys/malloc.h>
36 #include <sys/kernel.h>
37
38 #include <sys/socket.h>
39  
40 #include <net/if.h>
41 #include <net/if_media.h>
42 #include <net/ethernet.h>
43 #include <net/route.h>
44
45 #include <netproto/802_11/ieee80211_var.h>
46 #include <netproto/802_11/ieee80211_input.h>
47 #ifdef IEEE80211_SUPPORT_SUPERG
48 #include <netproto/802_11/ieee80211_superg.h>
49 #endif
50 #ifdef IEEE80211_SUPPORT_TDMA
51 #include <netproto/802_11/ieee80211_tdma.h>
52 #endif
53 #include <netproto/802_11/ieee80211_wds.h>
54 #include <netproto/802_11/ieee80211_mesh.h>
55 #include <netproto/802_11/ieee80211_ratectl.h>
56
57 #include <net/bpf.h>
58
59 /*
60  * IEEE80211_NODE_HASHSIZE must be a power of 2.
61  */
62 CTASSERT((IEEE80211_NODE_HASHSIZE & (IEEE80211_NODE_HASHSIZE-1)) == 0);
63
64 /*
65  * Association id's are managed with a bit vector.
66  */
67 #define IEEE80211_AID_SET(_vap, b) \
68         ((_vap)->iv_aid_bitmap[IEEE80211_AID(b) / 32] |= \
69                 (1 << (IEEE80211_AID(b) % 32)))
70 #define IEEE80211_AID_CLR(_vap, b) \
71         ((_vap)->iv_aid_bitmap[IEEE80211_AID(b) / 32] &= \
72                 ~(1 << (IEEE80211_AID(b) % 32)))
73 #define IEEE80211_AID_ISSET(_vap, b) \
74         ((_vap)->iv_aid_bitmap[IEEE80211_AID(b) / 32] & (1 << (IEEE80211_AID(b) % 32)))
75
76 #ifdef IEEE80211_DEBUG_REFCNT
77 #define REFCNT_LOC "%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line
78 #else
79 #define REFCNT_LOC "%s %p<%s> refcnt %d\n", __func__
80 #endif
81
82 static int ieee80211_sta_join1(struct ieee80211_node *);
83
84 static struct ieee80211_node *node_alloc(struct ieee80211vap *,
85         const uint8_t [IEEE80211_ADDR_LEN]);
86 static void node_cleanup(struct ieee80211_node *);
87 static void node_free(struct ieee80211_node *);
88 static void node_age(struct ieee80211_node *);
89 static int8_t node_getrssi(const struct ieee80211_node *);
90 static void node_getsignal(const struct ieee80211_node *, int8_t *, int8_t *);
91 static void node_getmimoinfo(const struct ieee80211_node *,
92         struct ieee80211_mimo_info *);
93 static void ieee80211_node_timeout_callout(void *arg);
94
95 static void _ieee80211_free_node(struct ieee80211_node *);
96
97 static void ieee80211_node_table_init(struct ieee80211com *ic,
98         struct ieee80211_node_table *nt, const char *name,
99         int inact, int keymaxix);
100 static void ieee80211_node_table_reset(struct ieee80211_node_table *,
101         struct ieee80211vap *);
102 static void ieee80211_node_table_cleanup(struct ieee80211_node_table *nt);
103 static void ieee80211_erp_timeout(struct ieee80211com *);
104
105 MALLOC_DEFINE(M_80211_NODE, "80211node", "802.11 node state");
106 MALLOC_DEFINE(M_80211_NODE_IE, "80211nodeie", "802.11 node ie");
107
108 void
109 ieee80211_node_attach(struct ieee80211com *ic)
110 {
111         /* XXX really want maxlen enforced per-sta */
112         ieee80211_ageq_init(&ic->ic_stageq, ic->ic_max_keyix * 8,
113             "802.11 staging q");
114         ieee80211_node_table_init(ic, &ic->ic_sta, "station",
115                 IEEE80211_INACT_INIT, ic->ic_max_keyix);
116         callout_init_mp(&ic->ic_inact);
117         callout_reset(&ic->ic_inact, IEEE80211_INACT_WAIT*hz,
118                       ieee80211_node_timeout_callout, ic);
119
120         ic->ic_node_alloc = node_alloc;
121         ic->ic_node_free = node_free;
122         ic->ic_node_cleanup = node_cleanup;
123         ic->ic_node_age = node_age;
124         ic->ic_node_drain = node_age;           /* NB: same as age */
125         ic->ic_node_getrssi = node_getrssi;
126         ic->ic_node_getsignal = node_getsignal;
127         ic->ic_node_getmimoinfo = node_getmimoinfo;
128
129         /*
130          * Set flags to be propagated to all vap's;
131          * these define default behaviour/configuration.
132          */
133         ic->ic_flags_ext |= IEEE80211_FEXT_INACT; /* inactivity processing */
134 }
135
136 void
137 ieee80211_node_detach(struct ieee80211com *ic)
138 {
139
140         callout_stop(&ic->ic_inact);
141         ieee80211_node_table_cleanup(&ic->ic_sta);
142         ieee80211_ageq_cleanup(&ic->ic_stageq);
143 }
144
145 void
146 ieee80211_node_vattach(struct ieee80211vap *vap)
147 {
148         /* NB: driver can override */
149         vap->iv_max_aid = IEEE80211_AID_DEF;
150
151         /* default station inactivity timer setings */
152         vap->iv_inact_init = IEEE80211_INACT_INIT;
153         vap->iv_inact_auth = IEEE80211_INACT_AUTH;
154         vap->iv_inact_run = IEEE80211_INACT_RUN;
155         vap->iv_inact_probe = IEEE80211_INACT_PROBE;
156
157         IEEE80211_DPRINTF(vap, IEEE80211_MSG_INACT,
158             "%s: init %u auth %u run %u probe %u\n", __func__,
159             vap->iv_inact_init, vap->iv_inact_auth,
160             vap->iv_inact_run, vap->iv_inact_probe);
161 }
162
163 void
164 ieee80211_node_latevattach(struct ieee80211vap *vap)
165 {
166         if (vap->iv_opmode == IEEE80211_M_HOSTAP) {
167                 /* XXX should we allow max aid to be zero? */
168                 if (vap->iv_max_aid < IEEE80211_AID_MIN) {
169                         vap->iv_max_aid = IEEE80211_AID_MIN;
170                         if_printf(vap->iv_ifp,
171                             "WARNING: max aid too small, changed to %d\n",
172                             vap->iv_max_aid);
173                 }
174                 vap->iv_aid_bitmap = (uint32_t *) kmalloc(
175                         howmany(vap->iv_max_aid, 32) * sizeof(uint32_t),
176                         M_80211_NODE, M_INTWAIT | M_ZERO);
177                 if (vap->iv_aid_bitmap == NULL) {
178                         /* XXX no way to recover */
179                         kprintf("%s: no memory for AID bitmap, max aid %d!\n",
180                             __func__, vap->iv_max_aid);
181                         vap->iv_max_aid = 0;
182                 }
183         }
184
185         ieee80211_reset_bss(vap);
186
187         vap->iv_auth = ieee80211_authenticator_get(vap->iv_bss->ni_authmode);
188 }
189
190 void
191 ieee80211_node_vdetach(struct ieee80211vap *vap)
192 {
193         struct ieee80211com *ic = vap->iv_ic;
194
195         ieee80211_node_table_reset(&ic->ic_sta, vap);
196         if (vap->iv_bss != NULL) {
197                 ieee80211_free_node(vap->iv_bss);
198                 vap->iv_bss = NULL;
199         }
200         if (vap->iv_aid_bitmap != NULL) {
201                 kfree(vap->iv_aid_bitmap, M_80211_NODE);
202                 vap->iv_aid_bitmap = NULL;
203         }
204 }
205
206 /* 
207  * Port authorize/unauthorize interfaces for use by an authenticator.
208  */
209
210 void
211 ieee80211_node_authorize(struct ieee80211_node *ni)
212 {
213         struct ieee80211vap *vap = ni->ni_vap;
214
215         ni->ni_flags |= IEEE80211_NODE_AUTH;
216         ni->ni_inact_reload = vap->iv_inact_run;
217         ni->ni_inact = ni->ni_inact_reload;
218
219         IEEE80211_NOTE(vap, IEEE80211_MSG_INACT, ni,
220             "%s: inact_reload %u", __func__, ni->ni_inact_reload);
221 }
222
223 void
224 ieee80211_node_unauthorize(struct ieee80211_node *ni)
225 {
226         struct ieee80211vap *vap = ni->ni_vap;
227
228         ni->ni_flags &= ~IEEE80211_NODE_AUTH;
229         ni->ni_inact_reload = vap->iv_inact_auth;
230         if (ni->ni_inact > ni->ni_inact_reload)
231                 ni->ni_inact = ni->ni_inact_reload;
232
233         IEEE80211_NOTE(vap, IEEE80211_MSG_INACT, ni,
234             "%s: inact_reload %u inact %u", __func__,
235             ni->ni_inact_reload, ni->ni_inact);
236 }
237
238 /*
239  * Fix tx parameters for a node according to ``association state''.
240  */
241 void
242 ieee80211_node_setuptxparms(struct ieee80211_node *ni)
243 {
244         struct ieee80211vap *vap = ni->ni_vap;
245         enum ieee80211_phymode mode;
246
247         if (ni->ni_flags & IEEE80211_NODE_HT) {
248                 if (IEEE80211_IS_CHAN_5GHZ(ni->ni_chan))
249                         mode = IEEE80211_MODE_11NA;
250                 else
251                         mode = IEEE80211_MODE_11NG;
252         } else {                                /* legacy rate handling */
253                 if (IEEE80211_IS_CHAN_ST(ni->ni_chan))
254                         mode = IEEE80211_MODE_STURBO_A;
255                 else if (IEEE80211_IS_CHAN_HALF(ni->ni_chan))
256                         mode = IEEE80211_MODE_HALF;
257                 else if (IEEE80211_IS_CHAN_QUARTER(ni->ni_chan))
258                         mode = IEEE80211_MODE_QUARTER;
259                 /* NB: 108A should be handled as 11a */
260                 else if (IEEE80211_IS_CHAN_A(ni->ni_chan))
261                         mode = IEEE80211_MODE_11A;
262                 else if (IEEE80211_IS_CHAN_108G(ni->ni_chan) ||
263                     (ni->ni_flags & IEEE80211_NODE_ERP))
264                         mode = IEEE80211_MODE_11G;
265                 else
266                         mode = IEEE80211_MODE_11B;
267         }
268         ni->ni_txparms = &vap->iv_txparms[mode];
269 }
270
271 /*
272  * Set/change the channel.  The rate set is also updated as
273  * to insure a consistent view by drivers.
274  * XXX should be private but hostap needs it to deal with CSA
275  */
276 void
277 ieee80211_node_set_chan(struct ieee80211_node *ni,
278         struct ieee80211_channel *chan)
279 {
280         struct ieee80211com *ic = ni->ni_ic;
281         struct ieee80211vap *vap = ni->ni_vap;
282         enum ieee80211_phymode mode;
283
284         KASSERT(chan != IEEE80211_CHAN_ANYC, ("no channel"));
285
286         ni->ni_chan = chan;
287         mode = ieee80211_chan2mode(chan);
288         if (IEEE80211_IS_CHAN_HT(chan)) {
289                 /*
290                  * XXX Gotta be careful here; the rate set returned by
291                  * ieee80211_get_suprates is actually any HT rate
292                  * set so blindly copying it will be bad.  We must
293                  * install the legacy rate est in ni_rates and the
294                  * HT rate set in ni_htrates.
295                  */
296                 ni->ni_htrates = *ieee80211_get_suphtrates(ic, chan);
297                 /*
298                  * Setup bss tx parameters based on operating mode.  We
299                  * use legacy rates when operating in a mixed HT+non-HT bss
300                  * and non-ERP rates in 11g for mixed ERP+non-ERP bss.
301                  */
302                 if (mode == IEEE80211_MODE_11NA &&
303                     (vap->iv_flags_ht & IEEE80211_FHT_PUREN) == 0)
304                         mode = IEEE80211_MODE_11A;
305                 else if (mode == IEEE80211_MODE_11NG &&
306                     (vap->iv_flags_ht & IEEE80211_FHT_PUREN) == 0)
307                         mode = IEEE80211_MODE_11G;
308                 if (mode == IEEE80211_MODE_11G &&
309                     (vap->iv_flags & IEEE80211_F_PUREG) == 0)
310                         mode = IEEE80211_MODE_11B;
311         }
312         ni->ni_txparms = &vap->iv_txparms[mode];
313         ni->ni_rates = *ieee80211_get_suprates(ic, chan);
314 }
315
316 static __inline void
317 copy_bss(struct ieee80211_node *nbss, const struct ieee80211_node *obss)
318 {
319         /* propagate useful state */
320         nbss->ni_authmode = obss->ni_authmode;
321         nbss->ni_txpower = obss->ni_txpower;
322         nbss->ni_vlan = obss->ni_vlan;
323         /* XXX statistics? */
324         /* XXX legacy WDS bssid? */
325 }
326
327 void
328 ieee80211_create_ibss(struct ieee80211vap* vap, struct ieee80211_channel *chan)
329 {
330         struct ieee80211com *ic = vap->iv_ic;
331         struct ieee80211_node *ni;
332
333         IEEE80211_DPRINTF(vap, IEEE80211_MSG_SCAN,
334                 "%s: creating %s on channel %u\n", __func__,
335                 ieee80211_opmode_name[vap->iv_opmode],
336                 ieee80211_chan2ieee(ic, chan));
337
338         ni = ieee80211_alloc_node(&ic->ic_sta, vap, vap->iv_myaddr);
339         if (ni == NULL) {
340                 /* XXX recovery? */
341                 return;
342         }
343         IEEE80211_ADDR_COPY(ni->ni_bssid, vap->iv_myaddr);
344         ni->ni_esslen = vap->iv_des_ssid[0].len;
345         memcpy(ni->ni_essid, vap->iv_des_ssid[0].ssid, ni->ni_esslen);
346         if (vap->iv_bss != NULL)
347                 copy_bss(ni, vap->iv_bss);
348         ni->ni_intval = ic->ic_bintval;
349         if (vap->iv_flags & IEEE80211_F_PRIVACY)
350                 ni->ni_capinfo |= IEEE80211_CAPINFO_PRIVACY;
351         if (ic->ic_phytype == IEEE80211_T_FH) {
352                 ni->ni_fhdwell = 200;   /* XXX */
353                 ni->ni_fhindex = 1;
354         }
355         if (vap->iv_opmode == IEEE80211_M_IBSS) {
356                 vap->iv_flags |= IEEE80211_F_SIBSS;
357                 ni->ni_capinfo |= IEEE80211_CAPINFO_IBSS;       /* XXX */
358                 if (vap->iv_flags & IEEE80211_F_DESBSSID)
359                         IEEE80211_ADDR_COPY(ni->ni_bssid, vap->iv_des_bssid);
360                 else {
361                         get_random_bytes(ni->ni_bssid, IEEE80211_ADDR_LEN);
362                         /* clear group bit, add local bit */
363                         ni->ni_bssid[0] = (ni->ni_bssid[0] &~ 0x01) | 0x02;
364                 }
365         } else if (vap->iv_opmode == IEEE80211_M_AHDEMO) {
366                 if (vap->iv_flags & IEEE80211_F_DESBSSID)
367                         IEEE80211_ADDR_COPY(ni->ni_bssid, vap->iv_des_bssid);
368                 else
369 #ifdef IEEE80211_SUPPORT_TDMA
370                 if ((vap->iv_caps & IEEE80211_C_TDMA) == 0)
371 #endif
372                         memset(ni->ni_bssid, 0, IEEE80211_ADDR_LEN);
373 #ifdef IEEE80211_SUPPORT_MESH
374         } else if (vap->iv_opmode == IEEE80211_M_MBSS) {
375                 ni->ni_meshidlen = vap->iv_mesh->ms_idlen;
376                 memcpy(ni->ni_meshid, vap->iv_mesh->ms_id, ni->ni_meshidlen);
377 #endif
378         }
379         /* 
380          * Fix the channel and related attributes.
381          */
382         /* clear DFS CAC state on previous channel */
383         if (ic->ic_bsschan != IEEE80211_CHAN_ANYC &&
384             ic->ic_bsschan->ic_freq != chan->ic_freq &&
385             IEEE80211_IS_CHAN_CACDONE(ic->ic_bsschan))
386                 ieee80211_dfs_cac_clear(ic, ic->ic_bsschan);
387         ic->ic_bsschan = chan;
388         ieee80211_node_set_chan(ni, chan);
389         ic->ic_curmode = ieee80211_chan2mode(chan);
390         /*
391          * Do mode-specific setup.
392          */
393         if (IEEE80211_IS_CHAN_FULL(chan)) {
394                 if (IEEE80211_IS_CHAN_ANYG(chan)) {
395                         /*
396                          * Use a mixed 11b/11g basic rate set.
397                          */
398                         ieee80211_setbasicrates(&ni->ni_rates,
399                             IEEE80211_MODE_11G);
400                         if (vap->iv_flags & IEEE80211_F_PUREG) {
401                                 /*
402                                  * Also mark OFDM rates basic so 11b
403                                  * stations do not join (WiFi compliance).
404                                  */
405                                 ieee80211_addbasicrates(&ni->ni_rates,
406                                     IEEE80211_MODE_11A);
407                         }
408                 } else if (IEEE80211_IS_CHAN_B(chan)) {
409                         /*
410                          * Force pure 11b rate set.
411                          */
412                         ieee80211_setbasicrates(&ni->ni_rates,
413                                 IEEE80211_MODE_11B);
414                 }
415         }
416
417         (void) ieee80211_sta_join1(ieee80211_ref_node(ni));
418 }
419
420 /*
421  * Reset bss state on transition to the INIT state.
422  * Clear any stations from the table (they have been
423  * deauth'd) and reset the bss node (clears key, rate
424  * etc. state).
425  */
426 void
427 ieee80211_reset_bss(struct ieee80211vap *vap)
428 {
429         struct ieee80211com *ic = vap->iv_ic;
430         struct ieee80211_node *ni, *obss;
431
432         ieee80211_node_table_reset(&ic->ic_sta, vap);
433         /* XXX multi-bss: wrong */
434         ieee80211_reset_erp(ic);
435
436         ni = ieee80211_alloc_node(&ic->ic_sta, vap, vap->iv_myaddr);
437         KASSERT(ni != NULL, ("unable to setup initial BSS node"));
438         obss = vap->iv_bss;
439         vap->iv_bss = ieee80211_ref_node(ni);
440         if (obss != NULL) {
441                 copy_bss(ni, obss);
442                 ni->ni_intval = ic->ic_bintval;
443                 ieee80211_free_node(obss);
444         } else
445                 IEEE80211_ADDR_COPY(ni->ni_bssid, vap->iv_myaddr);
446 }
447
448 static int
449 match_ssid(const struct ieee80211_node *ni,
450         int nssid, const struct ieee80211_scan_ssid ssids[])
451 {
452         int i;
453
454         for (i = 0; i < nssid; i++) {
455                 if (ni->ni_esslen == ssids[i].len &&
456                      memcmp(ni->ni_essid, ssids[i].ssid, ni->ni_esslen) == 0)
457                         return 1;
458         }
459         return 0;
460 }
461
462 /*
463  * Test a node for suitability/compatibility.
464  */
465 static int
466 check_bss(struct ieee80211vap *vap, struct ieee80211_node *ni)
467 {
468         struct ieee80211com *ic = ni->ni_ic;
469         uint8_t rate;
470
471         if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
472                 return 0;
473         if (vap->iv_opmode == IEEE80211_M_IBSS) {
474                 if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
475                         return 0;
476         } else {
477                 if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
478                         return 0;
479         }
480         if (vap->iv_flags & IEEE80211_F_PRIVACY) {
481                 if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
482                         return 0;
483         } else {
484                 /* XXX does this mean privacy is supported or required? */
485                 if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
486                         return 0;
487         }
488         rate = ieee80211_fix_rate(ni, &ni->ni_rates,
489             IEEE80211_F_JOIN | IEEE80211_F_DONEGO | IEEE80211_F_DOFRATE);
490         if (rate & IEEE80211_RATE_BASIC)
491                 return 0;
492         if (vap->iv_des_nssid != 0 &&
493             !match_ssid(ni, vap->iv_des_nssid, vap->iv_des_ssid))
494                 return 0;
495         if ((vap->iv_flags & IEEE80211_F_DESBSSID) &&
496             !IEEE80211_ADDR_EQ(vap->iv_des_bssid, ni->ni_bssid))
497                 return 0;
498         return 1;
499 }
500
501 #ifdef IEEE80211_DEBUG
502 /*
503  * Display node suitability/compatibility.
504  */
505 static void
506 check_bss_debug(struct ieee80211vap *vap, struct ieee80211_node *ni)
507 {
508         struct ieee80211com *ic = ni->ni_ic;
509         uint8_t rate;
510         int fail;
511
512         fail = 0;
513         if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
514                 fail |= 0x01;
515         if (vap->iv_opmode == IEEE80211_M_IBSS) {
516                 if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
517                         fail |= 0x02;
518         } else {
519                 if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
520                         fail |= 0x02;
521         }
522         if (vap->iv_flags & IEEE80211_F_PRIVACY) {
523                 if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
524                         fail |= 0x04;
525         } else {
526                 /* XXX does this mean privacy is supported or required? */
527                 if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
528                         fail |= 0x04;
529         }
530         rate = ieee80211_fix_rate(ni, &ni->ni_rates,
531              IEEE80211_F_JOIN | IEEE80211_F_DONEGO | IEEE80211_F_DOFRATE);
532         if (rate & IEEE80211_RATE_BASIC)
533                 fail |= 0x08;
534         if (vap->iv_des_nssid != 0 &&
535             !match_ssid(ni, vap->iv_des_nssid, vap->iv_des_ssid))
536                 fail |= 0x10;
537         if ((vap->iv_flags & IEEE80211_F_DESBSSID) &&
538             !IEEE80211_ADDR_EQ(vap->iv_des_bssid, ni->ni_bssid))
539                 fail |= 0x20;
540
541         kprintf(" %c %6D", fail ? '-' : '+', ni->ni_macaddr, ":");
542         kprintf(" %6D%c", ni->ni_bssid, ":", fail & 0x20 ? '!' : ' ');
543         kprintf(" %3d%c",
544             ieee80211_chan2ieee(ic, ni->ni_chan), fail & 0x01 ? '!' : ' ');
545         kprintf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
546             fail & 0x08 ? '!' : ' ');
547         kprintf(" %4s%c",
548             (ni->ni_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
549             (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
550             "????",
551             fail & 0x02 ? '!' : ' ');
552         kprintf(" %3s%c ",
553             (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) ?  "wep" : "no",
554             fail & 0x04 ? '!' : ' ');
555         ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
556         kprintf("%s\n", fail & 0x10 ? "!" : "");
557 }
558 #endif /* IEEE80211_DEBUG */
559  
560 /*
561  * Handle 802.11 ad hoc network merge.  The
562  * convention, set by the Wireless Ethernet Compatibility Alliance
563  * (WECA), is that an 802.11 station will change its BSSID to match
564  * the "oldest" 802.11 ad hoc network, on the same channel, that
565  * has the station's desired SSID.  The "oldest" 802.11 network
566  * sends beacons with the greatest TSF timestamp.
567  *
568  * The caller is assumed to validate TSF's before attempting a merge.
569  *
570  * Return !0 if the BSSID changed, 0 otherwise.
571  */
572 int
573 ieee80211_ibss_merge(struct ieee80211_node *ni)
574 {
575         struct ieee80211vap *vap = ni->ni_vap;
576 #ifdef IEEE80211_DEBUG
577         struct ieee80211com *ic = ni->ni_ic;
578 #endif
579
580         if (ni == vap->iv_bss ||
581             IEEE80211_ADDR_EQ(ni->ni_bssid, vap->iv_bss->ni_bssid)) {
582                 /* unchanged, nothing to do */
583                 return 0;
584         }
585         if (!check_bss(vap, ni)) {
586                 /* capabilities mismatch */
587                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_ASSOC,
588                     "%s: merge failed, capabilities mismatch\n", __func__);
589 #ifdef IEEE80211_DEBUG
590                 if (ieee80211_msg_assoc(vap))
591                         check_bss_debug(vap, ni);
592 #endif
593                 vap->iv_stats.is_ibss_capmismatch++;
594                 return 0;
595         }
596         IEEE80211_DPRINTF(vap, IEEE80211_MSG_ASSOC,
597                 "%s: new bssid %6D: %s preamble, %s slot time%s\n", __func__,
598                 ni->ni_bssid, ":",
599                 ic->ic_flags&IEEE80211_F_SHPREAMBLE ? "short" : "long",
600                 ic->ic_flags&IEEE80211_F_SHSLOT ? "short" : "long",
601                 ic->ic_flags&IEEE80211_F_USEPROT ? ", protection" : ""
602         );
603         return ieee80211_sta_join1(ieee80211_ref_node(ni));
604 }
605
606 /*
607  * Calculate HT channel promotion flags for all vaps.
608  * This assumes ni_chan have been setup for each vap.
609  */
610 static int
611 gethtadjustflags(struct ieee80211com *ic)
612 {
613         struct ieee80211vap *vap;
614         int flags;
615
616         flags = 0;
617         /* XXX locking */
618         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
619                 if (vap->iv_state < IEEE80211_S_RUN)
620                         continue;
621                 switch (vap->iv_opmode) {
622                 case IEEE80211_M_WDS:
623                 case IEEE80211_M_STA:
624                 case IEEE80211_M_AHDEMO:
625                 case IEEE80211_M_HOSTAP:
626                 case IEEE80211_M_IBSS:
627                 case IEEE80211_M_MBSS:
628                         flags |= ieee80211_htchanflags(vap->iv_bss->ni_chan);
629                         break;
630                 default:
631                         break;
632                 }
633         }
634         return flags;
635 }
636
637 /*
638  * Check if the current channel needs to change based on whether
639  * any vap's are using HT20/HT40.  This is used to sync the state
640  * of ic_curchan after a channel width change on a running vap.
641  */
642 void
643 ieee80211_sync_curchan(struct ieee80211com *ic)
644 {
645         struct ieee80211_channel *c;
646
647         c = ieee80211_ht_adjust_channel(ic, ic->ic_curchan, gethtadjustflags(ic));
648         if (c != ic->ic_curchan) {
649                 ic->ic_curchan = c;
650                 ic->ic_curmode = ieee80211_chan2mode(ic->ic_curchan);
651                 ic->ic_rt = ieee80211_get_ratetable(ic->ic_curchan);
652                 ic->ic_set_channel(ic);
653                 ieee80211_radiotap_chan_change(ic);
654         }
655 }
656
657 /*
658  * Setup the current channel.  The request channel may be
659  * promoted if other vap's are operating with HT20/HT40.
660  */
661 void
662 ieee80211_setupcurchan(struct ieee80211com *ic, struct ieee80211_channel *c)
663 {
664         if (ic->ic_htcaps & IEEE80211_HTC_HT) {
665                 int flags = gethtadjustflags(ic);
666                 /*
667                  * Check for channel promotion required to support the
668                  * set of running vap's.  This assumes we are called
669                  * after ni_chan is setup for each vap.
670                  */
671                 /* NB: this assumes IEEE80211_FHT_USEHT40 > IEEE80211_FHT_HT */
672                 if (flags > ieee80211_htchanflags(c))
673                         c = ieee80211_ht_adjust_channel(ic, c, flags);
674         }
675         ic->ic_bsschan = ic->ic_curchan = c;
676         ic->ic_curmode = ieee80211_chan2mode(ic->ic_curchan);
677         ic->ic_rt = ieee80211_get_ratetable(ic->ic_curchan);
678 }
679
680 /*
681  * Change the current channel.  The channel change is guaranteed to have
682  * happened before the next state change.
683  */
684 void
685 ieee80211_setcurchan(struct ieee80211com *ic, struct ieee80211_channel *c)
686 {
687         ieee80211_setupcurchan(ic, c);
688         ieee80211_runtask(ic, &ic->ic_chan_task);
689 }
690
691 /*
692  * Join the specified IBSS/BSS network.  The node is assumed to
693  * be passed in with a held reference.
694  */
695 static int
696 ieee80211_sta_join1(struct ieee80211_node *selbs)
697 {
698         struct ieee80211vap *vap = selbs->ni_vap;
699         struct ieee80211com *ic = selbs->ni_ic;
700         struct ieee80211_node *obss;
701         int canreassoc;
702
703         /*
704          * Committed to selbs, setup state.
705          */
706         obss = vap->iv_bss;
707         /*
708          * Check if old+new node have the same address in which
709          * case we can reassociate when operating in sta mode.
710          */
711         canreassoc = (obss != NULL &&
712                 vap->iv_state == IEEE80211_S_RUN &&
713                 IEEE80211_ADDR_EQ(obss->ni_macaddr, selbs->ni_macaddr));
714         vap->iv_bss = selbs;            /* NB: caller assumed to bump refcnt */
715         if (obss != NULL) {
716                 copy_bss(selbs, obss);
717                 ieee80211_node_decref(obss);    /* iv_bss reference */
718                 ieee80211_free_node(obss);      /* station table reference */
719                 obss = NULL;            /* NB: guard against later use */
720         }
721
722         /*
723          * Delete unusable rates; we've already checked
724          * that the negotiated rate set is acceptable.
725          */
726         ieee80211_fix_rate(vap->iv_bss, &vap->iv_bss->ni_rates,
727                 IEEE80211_F_DODEL | IEEE80211_F_JOIN);
728
729         ieee80211_setcurchan(ic, selbs->ni_chan);
730         /*
731          * Set the erp state (mostly the slot time) to deal with
732          * the auto-select case; this should be redundant if the
733          * mode is locked.
734          */ 
735         ieee80211_reset_erp(ic);
736         ieee80211_wme_initparams(vap);
737
738         if (vap->iv_opmode == IEEE80211_M_STA) {
739                 if (canreassoc) {
740                         /* Reassociate */
741                         ieee80211_new_state(vap, IEEE80211_S_ASSOC, 1);
742                 } else {
743                         /*
744                          * Act as if we received a DEAUTH frame in case we
745                          * are invoked from the RUN state.  This will cause
746                          * us to try to re-authenticate if we are operating
747                          * as a station.
748                          */
749                         ieee80211_new_state(vap, IEEE80211_S_AUTH,
750                                 IEEE80211_FC0_SUBTYPE_DEAUTH);
751                 }
752         } else
753                 ieee80211_new_state(vap, IEEE80211_S_RUN, -1);
754         return 1;
755 }
756
757 int
758 ieee80211_sta_join(struct ieee80211vap *vap, struct ieee80211_channel *chan,
759         const struct ieee80211_scan_entry *se)
760 {
761         struct ieee80211com *ic = vap->iv_ic;
762         struct ieee80211_node *ni;
763
764         ni = ieee80211_alloc_node(&ic->ic_sta, vap, se->se_macaddr);
765         if (ni == NULL) {
766                 /* XXX msg */
767                 return 0;
768         }
769         /*
770          * Expand scan state into node's format.
771          * XXX may not need all this stuff
772          */
773         IEEE80211_ADDR_COPY(ni->ni_bssid, se->se_bssid);
774         ni->ni_esslen = se->se_ssid[1];
775         memcpy(ni->ni_essid, se->se_ssid+2, ni->ni_esslen);
776         ni->ni_tstamp.tsf = se->se_tstamp.tsf;
777         ni->ni_intval = se->se_intval;
778         ni->ni_capinfo = se->se_capinfo;
779         ni->ni_chan = chan;
780         ni->ni_timoff = se->se_timoff;
781         ni->ni_fhdwell = se->se_fhdwell;
782         ni->ni_fhindex = se->se_fhindex;
783         ni->ni_erp = se->se_erp;
784         IEEE80211_RSSI_LPF(ni->ni_avgrssi, se->se_rssi);
785         ni->ni_noise = se->se_noise;
786         if (vap->iv_opmode == IEEE80211_M_STA) {
787                 /* NB: only infrastructure mode requires an associd */
788                 ni->ni_flags |= IEEE80211_NODE_ASSOCID;
789         }
790
791         if (ieee80211_ies_init(&ni->ni_ies, se->se_ies.data, se->se_ies.len)) {
792                 ieee80211_ies_expand(&ni->ni_ies);
793 #ifdef IEEE80211_SUPPORT_SUPERG
794                 if (ni->ni_ies.ath_ie != NULL)
795                         ieee80211_parse_ath(ni, ni->ni_ies.ath_ie);
796 #endif
797                 if (ni->ni_ies.htcap_ie != NULL)
798                         ieee80211_parse_htcap(ni, ni->ni_ies.htcap_ie);
799                 if (ni->ni_ies.htinfo_ie != NULL)
800                         ieee80211_parse_htinfo(ni, ni->ni_ies.htinfo_ie);
801 #ifdef IEEE80211_SUPPORT_MESH
802                 if (ni->ni_ies.meshid_ie != NULL)
803                         ieee80211_parse_meshid(ni, ni->ni_ies.meshid_ie);
804 #endif
805 #ifdef IEEE80211_SUPPORT_TDMA
806                 if (ni->ni_ies.tdma_ie != NULL)
807                         ieee80211_parse_tdma(ni, ni->ni_ies.tdma_ie);
808 #endif
809         }
810
811         vap->iv_dtim_period = se->se_dtimperiod;
812         vap->iv_dtim_count = 0;
813
814         /* NB: must be after ni_chan is setup */
815         ieee80211_setup_rates(ni, se->se_rates, se->se_xrates,
816                 IEEE80211_F_DOSORT);
817         if (ieee80211_iserp_rateset(&ni->ni_rates))
818                 ni->ni_flags |= IEEE80211_NODE_ERP;
819         ieee80211_node_setuptxparms(ni);
820
821         return ieee80211_sta_join1(ieee80211_ref_node(ni));
822 }
823
824 /*
825  * Leave the specified IBSS/BSS network.  The node is assumed to
826  * be passed in with a held reference.
827  */
828 void
829 ieee80211_sta_leave(struct ieee80211_node *ni)
830 {
831         struct ieee80211com *ic = ni->ni_ic;
832
833         ic->ic_node_cleanup(ni);
834         ieee80211_notify_node_leave(ni);
835 }
836
837 /*
838  * Send a deauthenticate frame and drop the station.
839  */
840 void
841 ieee80211_node_deauth(struct ieee80211_node *ni, int reason)
842 {
843         /* NB: bump the refcnt to be sure temporay nodes are not reclaimed */
844         ieee80211_ref_node(ni);
845         if (ni->ni_associd != 0)
846                 IEEE80211_SEND_MGMT(ni, IEEE80211_FC0_SUBTYPE_DEAUTH, reason);
847         ieee80211_node_leave(ni);
848         ieee80211_free_node(ni);
849 }
850
851 static struct ieee80211_node *
852 node_alloc(struct ieee80211vap *vap, const uint8_t macaddr[IEEE80211_ADDR_LEN])
853 {
854         struct ieee80211_node *ni;
855
856         ni = (struct ieee80211_node *) kmalloc(sizeof(struct ieee80211_node),
857                 M_80211_NODE, M_INTWAIT | M_ZERO);
858         return ni;
859 }
860
861 /*
862  * Initialize an ie blob with the specified data.  If previous
863  * data exists re-use the data block.  As a side effect we clear
864  * all references to specific ie's; the caller is required to
865  * recalculate them.
866  */
867 int
868 ieee80211_ies_init(struct ieee80211_ies *ies, const uint8_t *data, int len)
869 {
870         /* NB: assumes data+len are the last fields */
871         memset(ies, 0, offsetof(struct ieee80211_ies, data));
872         if (ies->data != NULL && ies->len != len) {
873                 /* data size changed */
874                 kfree(ies->data, M_80211_NODE_IE);
875                 ies->data = NULL;
876         }
877         if (ies->data == NULL) {
878                 ies->data = (uint8_t *) kmalloc(len, M_80211_NODE_IE, M_INTWAIT);
879                 if (ies->data == NULL) {
880                         ies->len = 0;
881                         /* NB: pointers have already been zero'd above */
882                         return 0;
883                 }
884         }
885         memcpy(ies->data, data, len);
886         ies->len = len;
887         return 1;
888 }
889
890 /*
891  * Reclaim storage for an ie blob.
892  */
893 void
894 ieee80211_ies_cleanup(struct ieee80211_ies *ies)
895 {
896         if (ies->data != NULL)
897                 kfree(ies->data, M_80211_NODE_IE);
898 }
899
900 /*
901  * Expand an ie blob data contents and to fillin individual
902  * ie pointers.  The data blob is assumed to be well-formed;
903  * we don't do any validity checking of ie lengths.
904  */
905 void
906 ieee80211_ies_expand(struct ieee80211_ies *ies)
907 {
908         uint8_t *ie;
909         int ielen;
910
911         ie = ies->data;
912         ielen = ies->len;
913         while (ielen > 0) {
914                 switch (ie[0]) {
915                 case IEEE80211_ELEMID_VENDOR:
916                         if (iswpaoui(ie))
917                                 ies->wpa_ie = ie;
918                         else if (iswmeoui(ie))
919                                 ies->wme_ie = ie;
920 #ifdef IEEE80211_SUPPORT_SUPERG
921                         else if (isatherosoui(ie))
922                                 ies->ath_ie = ie;
923 #endif
924 #ifdef IEEE80211_SUPPORT_TDMA
925                         else if (istdmaoui(ie))
926                                 ies->tdma_ie = ie;
927 #endif
928                         break;
929                 case IEEE80211_ELEMID_RSN:
930                         ies->rsn_ie = ie;
931                         break;
932                 case IEEE80211_ELEMID_HTCAP:
933                         ies->htcap_ie = ie;
934                         break;
935 #ifdef IEEE80211_SUPPORT_MESH
936                 case IEEE80211_ELEMID_MESHID:
937                         ies->meshid_ie = ie;
938                         break;
939 #endif
940                 }
941                 ielen -= 2 + ie[1];
942                 ie += 2 + ie[1];
943         }
944 }
945
946 /*
947  * Reclaim any resources in a node and reset any critical
948  * state.  Typically nodes are free'd immediately after,
949  * but in some cases the storage may be reused so we need
950  * to insure consistent state (should probably fix that).
951  */
952 static void
953 node_cleanup(struct ieee80211_node *ni)
954 {
955         struct ieee80211vap *vap = ni->ni_vap;
956         struct ieee80211com *ic = ni->ni_ic;
957         int i;
958
959         /* NB: preserve ni_table */
960         if (ni->ni_flags & IEEE80211_NODE_PWR_MGT) {
961                 if (vap->iv_opmode != IEEE80211_M_STA)
962                         vap->iv_ps_sta--;
963                 ni->ni_flags &= ~IEEE80211_NODE_PWR_MGT;
964                 IEEE80211_NOTE(vap, IEEE80211_MSG_POWER, ni,
965                     "power save mode off, %u sta's in ps mode", vap->iv_ps_sta);
966         }
967         /*
968          * Cleanup any HT-related state.
969          */
970         if (ni->ni_flags & IEEE80211_NODE_HT)
971                 ieee80211_ht_node_cleanup(ni);
972 #ifdef IEEE80211_SUPPORT_SUPERG
973         else if (ni->ni_ath_flags & IEEE80211_NODE_ATH)
974                 ieee80211_ff_node_cleanup(ni);
975 #endif
976 #ifdef IEEE80211_SUPPORT_MESH
977         /*
978          * Cleanup any mesh-related state.
979          */
980         if (vap->iv_opmode == IEEE80211_M_MBSS)
981                 ieee80211_mesh_node_cleanup(ni);
982 #endif
983         /*
984          * Clear any staging queue entries.
985          */
986         ieee80211_ageq_drain_node(&ic->ic_stageq, ni);
987
988         /*
989          * Clear AREF flag that marks the authorization refcnt bump
990          * has happened.  This is probably not needed as the node
991          * should always be removed from the table so not found but
992          * do it just in case.
993          * Likewise clear the ASSOCID flag as these flags are intended
994          * to be managed in tandem.
995          */
996         ni->ni_flags &= ~(IEEE80211_NODE_AREF | IEEE80211_NODE_ASSOCID);
997
998         /*
999          * Drain power save queue and, if needed, clear TIM.
1000          */
1001         if (ieee80211_node_psq_drain(ni) != 0 && vap->iv_set_tim != NULL)
1002                 vap->iv_set_tim(ni, 0);
1003
1004         ni->ni_associd = 0;
1005         if (ni->ni_challenge != NULL) {
1006                 kfree(ni->ni_challenge, M_80211_NODE);
1007                 ni->ni_challenge = NULL;
1008         }
1009         /*
1010          * Preserve SSID, WPA, and WME ie's so the bss node is
1011          * reusable during a re-auth/re-assoc state transition.
1012          * If we remove these data they will not be recreated
1013          * because they come from a probe-response or beacon frame
1014          * which cannot be expected prior to the association-response.
1015          * This should not be an issue when operating in other modes
1016          * as stations leaving always go through a full state transition
1017          * which will rebuild this state.
1018          *
1019          * XXX does this leave us open to inheriting old state?
1020          */
1021         for (i = 0; i < NELEM(ni->ni_rxfrag); i++)
1022                 if (ni->ni_rxfrag[i] != NULL) {
1023                         m_freem(ni->ni_rxfrag[i]);
1024                         ni->ni_rxfrag[i] = NULL;
1025                 }
1026         /*
1027          * Must be careful here to remove any key map entry w/o a LOR.
1028          */
1029         ieee80211_node_delucastkey(ni);
1030 }
1031
1032 static void
1033 node_free(struct ieee80211_node *ni)
1034 {
1035         struct ieee80211com *ic = ni->ni_ic;
1036
1037         ieee80211_ratectl_node_deinit(ni);
1038         ic->ic_node_cleanup(ni);
1039         ieee80211_ies_cleanup(&ni->ni_ies);
1040         ieee80211_psq_cleanup(&ni->ni_psq);
1041         kfree(ni, M_80211_NODE);
1042 }
1043
1044 static void
1045 node_age(struct ieee80211_node *ni)
1046 {
1047         struct ieee80211vap *vap = ni->ni_vap;
1048
1049         /*
1050          * Age frames on the power save queue.
1051          */
1052         if (ieee80211_node_psq_age(ni) != 0 &&
1053             ni->ni_psq.psq_len == 0 && vap->iv_set_tim != NULL)
1054                 vap->iv_set_tim(ni, 0);
1055         /*
1056          * Age out HT resources (e.g. frames on the
1057          * A-MPDU reorder queues).
1058          */
1059         if (ni->ni_associd != 0 && (ni->ni_flags & IEEE80211_NODE_HT))
1060                 ieee80211_ht_node_age(ni);
1061 }
1062
1063 static int8_t
1064 node_getrssi(const struct ieee80211_node *ni)
1065 {
1066         uint32_t avgrssi = ni->ni_avgrssi;
1067         int32_t rssi;
1068
1069         if (avgrssi == IEEE80211_RSSI_DUMMY_MARKER)
1070                 return 0;
1071         rssi = IEEE80211_RSSI_GET(avgrssi);
1072         return rssi < 0 ? 0 : rssi > 127 ? 127 : rssi;
1073 }
1074
1075 static void
1076 node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
1077 {
1078         *rssi = node_getrssi(ni);
1079         *noise = ni->ni_noise;
1080 }
1081
1082 static void
1083 node_getmimoinfo(const struct ieee80211_node *ni,
1084         struct ieee80211_mimo_info *info)
1085 {
1086         /* XXX zero data? */
1087 }
1088
1089 struct ieee80211_node *
1090 ieee80211_alloc_node(struct ieee80211_node_table *nt,
1091         struct ieee80211vap *vap, const uint8_t macaddr[IEEE80211_ADDR_LEN])
1092 {
1093         struct ieee80211com *ic = nt->nt_ic;
1094         struct ieee80211_node *ni;
1095         int hash;
1096
1097         ni = ic->ic_node_alloc(vap, macaddr);
1098         if (ni == NULL) {
1099                 vap->iv_stats.is_rx_nodealloc++;
1100                 return NULL;
1101         }
1102
1103         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1104                 "%s %p<%6D> in %s table\n", __func__, ni,
1105                 macaddr, ":", nt->nt_name);
1106
1107         IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
1108         hash = IEEE80211_NODE_HASH(ic, macaddr);
1109         ieee80211_node_initref(ni);             /* mark referenced */
1110         ni->ni_chan = IEEE80211_CHAN_ANYC;
1111         ni->ni_authmode = IEEE80211_AUTH_OPEN;
1112         ni->ni_txpower = ic->ic_txpowlimit;     /* max power */
1113         ni->ni_txparms = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
1114         ieee80211_crypto_resetkey(vap, &ni->ni_ucastkey, IEEE80211_KEYIX_NONE);
1115         ni->ni_avgrssi = IEEE80211_RSSI_DUMMY_MARKER;
1116         ni->ni_inact_reload = nt->nt_inact_init;
1117         ni->ni_inact = ni->ni_inact_reload;
1118         ni->ni_ath_defkeyix = 0x7fff;
1119         ieee80211_psq_init(&ni->ni_psq, "unknown");
1120 #ifdef IEEE80211_SUPPORT_MESH
1121         if (vap->iv_opmode == IEEE80211_M_MBSS)
1122                 ieee80211_mesh_node_init(vap, ni);
1123 #endif
1124         TAILQ_INSERT_TAIL(&nt->nt_node, ni, ni_list);
1125         LIST_INSERT_HEAD(&nt->nt_hash[hash], ni, ni_hash);
1126         ni->ni_table = nt;
1127         ni->ni_vap = vap;
1128         ni->ni_ic = ic;
1129
1130         IEEE80211_NOTE(vap, IEEE80211_MSG_INACT, ni,
1131             "%s: inact_reload %u", __func__, ni->ni_inact_reload);
1132
1133         return ni;
1134 }
1135
1136 /*
1137  * Craft a temporary node suitable for sending a management frame
1138  * to the specified station.  We craft only as much state as we
1139  * need to do the work since the node will be immediately reclaimed
1140  * once the send completes.
1141  */
1142 struct ieee80211_node *
1143 ieee80211_tmp_node(struct ieee80211vap *vap,
1144         const uint8_t macaddr[IEEE80211_ADDR_LEN])
1145 {
1146         struct ieee80211com *ic = vap->iv_ic;
1147         struct ieee80211_node *ni;
1148
1149         ni = ic->ic_node_alloc(vap, macaddr);
1150         if (ni != NULL) {
1151                 struct ieee80211_node *bss = vap->iv_bss;
1152
1153                 IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1154                         "%s %p<%6D>\n", __func__, ni, macaddr, ":");
1155
1156                 ni->ni_table = NULL;            /* NB: pedantic */
1157                 ni->ni_ic = ic;                 /* NB: needed to set channel */
1158                 ni->ni_vap = vap;
1159
1160                 IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
1161                 IEEE80211_ADDR_COPY(ni->ni_bssid, bss->ni_bssid);
1162                 ieee80211_node_initref(ni);             /* mark referenced */
1163                 /* NB: required by ieee80211_fix_rate */
1164                 ieee80211_node_set_chan(ni, bss->ni_chan);
1165                 ieee80211_crypto_resetkey(vap, &ni->ni_ucastkey,
1166                         IEEE80211_KEYIX_NONE);
1167                 ni->ni_txpower = bss->ni_txpower;
1168                 /* XXX optimize away */
1169                 ieee80211_psq_init(&ni->ni_psq, "unknown");
1170         } else {
1171                 /* XXX msg */
1172                 vap->iv_stats.is_rx_nodealloc++;
1173         }
1174         return ni;
1175 }
1176
1177 struct ieee80211_node *
1178 ieee80211_dup_bss(struct ieee80211vap *vap,
1179         const uint8_t macaddr[IEEE80211_ADDR_LEN])
1180 {
1181         struct ieee80211com *ic = vap->iv_ic;
1182         struct ieee80211_node *ni;
1183
1184         ni = ieee80211_alloc_node(&ic->ic_sta, vap, macaddr);
1185         if (ni != NULL) {
1186                 struct ieee80211_node *bss = vap->iv_bss;
1187                 /*
1188                  * Inherit from iv_bss.
1189                  */
1190                 copy_bss(ni, bss);
1191                 IEEE80211_ADDR_COPY(ni->ni_bssid, bss->ni_bssid);
1192                 ieee80211_node_set_chan(ni, bss->ni_chan);
1193         }
1194         return ni;
1195 }
1196
1197 /*
1198  * Create a bss node for a legacy WDS vap.  The far end does
1199  * not associate so we just create create a new node and
1200  * simulate an association.  The caller is responsible for
1201  * installing the node as the bss node and handling any further
1202  * setup work like authorizing the port.
1203  */
1204 struct ieee80211_node *
1205 ieee80211_node_create_wds(struct ieee80211vap *vap,
1206         const uint8_t bssid[IEEE80211_ADDR_LEN], struct ieee80211_channel *chan)
1207 {
1208         struct ieee80211com *ic = vap->iv_ic;
1209         struct ieee80211_node *ni;
1210
1211         /* XXX check if node already in sta table? */
1212         ni = ieee80211_alloc_node(&ic->ic_sta, vap, bssid);
1213         if (ni != NULL) {
1214                 ni->ni_wdsvap = vap;
1215                 IEEE80211_ADDR_COPY(ni->ni_bssid, bssid);
1216                 /*
1217                  * Inherit any manually configured settings.
1218                  */
1219                 copy_bss(ni, vap->iv_bss);
1220                 ieee80211_node_set_chan(ni, chan);
1221                 /* NB: propagate ssid so available to WPA supplicant */
1222                 ni->ni_esslen = vap->iv_des_ssid[0].len;
1223                 memcpy(ni->ni_essid, vap->iv_des_ssid[0].ssid, ni->ni_esslen);
1224                 /* NB: no associd for peer */
1225                 /*
1226                  * There are no management frames to use to
1227                  * discover neighbor capabilities, so blindly
1228                  * propagate the local configuration.
1229                  */
1230                 if (vap->iv_flags & IEEE80211_F_WME)
1231                         ni->ni_flags |= IEEE80211_NODE_QOS;
1232 #ifdef IEEE80211_SUPPORT_SUPERG
1233                 if (vap->iv_flags & IEEE80211_F_FF)
1234                         ni->ni_flags |= IEEE80211_NODE_FF;
1235 #endif
1236                 if ((ic->ic_htcaps & IEEE80211_HTC_HT) &&
1237                     (vap->iv_flags_ht & IEEE80211_FHT_HT)) {
1238                         /*
1239                          * Device is HT-capable and HT is enabled for
1240                          * the vap; setup HT operation.  On return
1241                          * ni_chan will be adjusted to an HT channel.
1242                          */
1243                         ieee80211_ht_wds_init(ni);
1244                 } else {
1245                         struct ieee80211_channel *c = ni->ni_chan;
1246                         /*
1247                          * Force a legacy channel to be used.
1248                          */
1249                         c = ieee80211_find_channel(ic,
1250                             c->ic_freq, c->ic_flags &~ IEEE80211_CHAN_HT);
1251                         KASSERT(c != NULL, ("no legacy channel, %u/%x",
1252                             ni->ni_chan->ic_freq, ni->ni_chan->ic_flags));
1253                         ni->ni_chan = c;
1254                 }
1255         }
1256         return ni;
1257 }
1258
1259 struct ieee80211_node *
1260 #ifdef IEEE80211_DEBUG_REFCNT
1261 ieee80211_find_node_locked_debug(struct ieee80211_node_table *nt,
1262         const uint8_t macaddr[IEEE80211_ADDR_LEN], const char *func, int line)
1263 #else
1264 ieee80211_find_node_locked(struct ieee80211_node_table *nt,
1265         const uint8_t macaddr[IEEE80211_ADDR_LEN])
1266 #endif
1267 {
1268         struct ieee80211_node *ni;
1269         int hash;
1270
1271         hash = IEEE80211_NODE_HASH(nt->nt_ic, macaddr);
1272         LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1273                 if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
1274                         ieee80211_ref_node(ni); /* mark referenced */
1275 #ifdef IEEE80211_DEBUG_REFCNT
1276                         IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_NODE,
1277                             "%s (%s:%u) %p<%6D> refcnt %d\n", __func__,
1278                             func, line,
1279                             ni, ni->ni_macaddr, ":",
1280                             ieee80211_node_refcnt(ni));
1281 #endif
1282                         return ni;
1283                 }
1284         }
1285         return NULL;
1286 }
1287
1288 struct ieee80211_node *
1289 #ifdef IEEE80211_DEBUG_REFCNT
1290 ieee80211_find_node_debug(struct ieee80211_node_table *nt,
1291         const uint8_t macaddr[IEEE80211_ADDR_LEN], const char *func, int line)
1292 #else
1293 ieee80211_find_node(struct ieee80211_node_table *nt,
1294         const uint8_t macaddr[IEEE80211_ADDR_LEN])
1295 #endif
1296 {
1297         struct ieee80211_node *ni;
1298
1299         ni = ieee80211_find_node_locked(nt, macaddr);
1300         return ni;
1301 }
1302
1303 struct ieee80211_node *
1304 #ifdef IEEE80211_DEBUG_REFCNT
1305 ieee80211_find_vap_node_locked_debug(struct ieee80211_node_table *nt,
1306         const struct ieee80211vap *vap,
1307         const uint8_t macaddr[IEEE80211_ADDR_LEN], const char *func, int line)
1308 #else
1309 ieee80211_find_vap_node_locked(struct ieee80211_node_table *nt,
1310         const struct ieee80211vap *vap,
1311         const uint8_t macaddr[IEEE80211_ADDR_LEN])
1312 #endif
1313 {
1314         struct ieee80211_node *ni;
1315         int hash;
1316
1317         hash = IEEE80211_NODE_HASH(nt->nt_ic, macaddr);
1318         LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1319                 if (ni->ni_vap == vap &&
1320                     IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
1321                         ieee80211_ref_node(ni); /* mark referenced */
1322 #ifdef IEEE80211_DEBUG_REFCNT
1323                         IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_NODE,
1324                             "%s (%s:%u) %p<%6D> refcnt %d\n", __func__,
1325                             func, line,
1326                             ni, ni->ni_macaddr, ":",
1327                             ieee80211_node_refcnt(ni));
1328 #endif
1329                         return ni;
1330                 }
1331         }
1332         return NULL;
1333 }
1334
1335 struct ieee80211_node *
1336 #ifdef IEEE80211_DEBUG_REFCNT
1337 ieee80211_find_vap_node_debug(struct ieee80211_node_table *nt,
1338         const struct ieee80211vap *vap,
1339         const uint8_t macaddr[IEEE80211_ADDR_LEN], const char *func, int line)
1340 #else
1341 ieee80211_find_vap_node(struct ieee80211_node_table *nt,
1342         const struct ieee80211vap *vap,
1343         const uint8_t macaddr[IEEE80211_ADDR_LEN])
1344 #endif
1345 {
1346         struct ieee80211_node *ni;
1347
1348         ni = ieee80211_find_vap_node_locked(nt, vap, macaddr);
1349         return ni;
1350 }
1351
1352 /*
1353  * Fake up a node; this handles node discovery in adhoc mode.
1354  * Note that for the driver's benefit we we treat this like
1355  * an association so the driver has an opportunity to setup
1356  * it's private state.
1357  */
1358 struct ieee80211_node *
1359 ieee80211_fakeup_adhoc_node(struct ieee80211vap *vap,
1360         const uint8_t macaddr[IEEE80211_ADDR_LEN])
1361 {
1362         struct ieee80211_node *ni;
1363
1364         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1365             "%s: mac<%6D>\n", __func__, macaddr, ":");
1366         ni = ieee80211_dup_bss(vap, macaddr);
1367         if (ni != NULL) {
1368                 struct ieee80211com *ic = vap->iv_ic;
1369
1370                 /* XXX no rate negotiation; just dup */
1371                 ni->ni_rates = vap->iv_bss->ni_rates;
1372                 if (ieee80211_iserp_rateset(&ni->ni_rates))
1373                         ni->ni_flags |= IEEE80211_NODE_ERP;
1374                 if (vap->iv_opmode == IEEE80211_M_AHDEMO) {
1375                         /*
1376                          * In adhoc demo mode there are no management
1377                          * frames to use to discover neighbor capabilities,
1378                          * so blindly propagate the local configuration 
1379                          * so we can do interesting things (e.g. use
1380                          * WME to disable ACK's).
1381                          */
1382                         if (vap->iv_flags & IEEE80211_F_WME)
1383                                 ni->ni_flags |= IEEE80211_NODE_QOS;
1384 #ifdef IEEE80211_SUPPORT_SUPERG
1385                         if (vap->iv_flags & IEEE80211_F_FF)
1386                                 ni->ni_flags |= IEEE80211_NODE_FF;
1387 #endif
1388                 }
1389                 ieee80211_node_setuptxparms(ni);
1390                 if (ic->ic_newassoc != NULL)
1391                         ic->ic_newassoc(ni, 1);
1392                 /* XXX not right for 802.1x/WPA */
1393                 ieee80211_node_authorize(ni);
1394         }
1395         return ni;
1396 }
1397
1398 void
1399 ieee80211_init_neighbor(struct ieee80211_node *ni,
1400         const struct ieee80211_frame *wh,
1401         const struct ieee80211_scanparams *sp)
1402 {
1403         ni->ni_esslen = sp->ssid[1];
1404         memcpy(ni->ni_essid, sp->ssid + 2, sp->ssid[1]);
1405         IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
1406         memcpy(ni->ni_tstamp.data, sp->tstamp, sizeof(ni->ni_tstamp));
1407         ni->ni_intval = sp->bintval;
1408         ni->ni_capinfo = sp->capinfo;
1409         ni->ni_chan = ni->ni_ic->ic_curchan;
1410         ni->ni_fhdwell = sp->fhdwell;
1411         ni->ni_fhindex = sp->fhindex;
1412         ni->ni_erp = sp->erp;
1413         ni->ni_timoff = sp->timoff;
1414 #ifdef IEEE80211_SUPPORT_MESH
1415         if (ni->ni_vap->iv_opmode == IEEE80211_M_MBSS)
1416                 ieee80211_mesh_init_neighbor(ni, wh, sp);
1417 #endif
1418         if (ieee80211_ies_init(&ni->ni_ies, sp->ies, sp->ies_len)) {
1419                 ieee80211_ies_expand(&ni->ni_ies);
1420                 if (ni->ni_ies.wme_ie != NULL)
1421                         ni->ni_flags |= IEEE80211_NODE_QOS;
1422                 else
1423                         ni->ni_flags &= ~IEEE80211_NODE_QOS;
1424 #ifdef IEEE80211_SUPPORT_SUPERG
1425                 if (ni->ni_ies.ath_ie != NULL)
1426                         ieee80211_parse_ath(ni, ni->ni_ies.ath_ie);
1427 #endif
1428         }
1429
1430         /* NB: must be after ni_chan is setup */
1431         ieee80211_setup_rates(ni, sp->rates, sp->xrates,
1432                 IEEE80211_F_DOSORT | IEEE80211_F_DOFRATE |
1433                 IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
1434 }
1435
1436 /*
1437  * Do node discovery in adhoc mode on receipt of a beacon
1438  * or probe response frame.  Note that for the driver's
1439  * benefit we we treat this like an association so the
1440  * driver has an opportunity to setup it's private state.
1441  */
1442 struct ieee80211_node *
1443 ieee80211_add_neighbor(struct ieee80211vap *vap,
1444         const struct ieee80211_frame *wh,
1445         const struct ieee80211_scanparams *sp)
1446 {
1447         struct ieee80211_node *ni;
1448
1449         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1450             "%s: mac<%6D>\n", __func__, wh->i_addr2, ":");
1451         ni = ieee80211_dup_bss(vap, wh->i_addr2);/* XXX alloc_node? */
1452         if (ni != NULL) {
1453                 struct ieee80211com *ic = vap->iv_ic;
1454
1455                 ieee80211_init_neighbor(ni, wh, sp);
1456                 if (ieee80211_iserp_rateset(&ni->ni_rates))
1457                         ni->ni_flags |= IEEE80211_NODE_ERP;
1458                 ieee80211_node_setuptxparms(ni);
1459                 if (ic->ic_newassoc != NULL)
1460                         ic->ic_newassoc(ni, 1);
1461                 /* XXX not right for 802.1x/WPA */
1462                 ieee80211_node_authorize(ni);
1463         }
1464         return ni;
1465 }
1466
1467 #define IS_PROBEREQ(wh) \
1468         ((wh->i_fc[0] & (IEEE80211_FC0_TYPE_MASK|IEEE80211_FC0_SUBTYPE_MASK)) \
1469             == (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_REQ))
1470 #define IS_BCAST_PROBEREQ(wh) \
1471         (IS_PROBEREQ(wh) && IEEE80211_IS_MULTICAST( \
1472             ((const struct ieee80211_frame *)(wh))->i_addr3))
1473
1474 static __inline struct ieee80211_node *
1475 _find_rxnode(struct ieee80211_node_table *nt,
1476     const struct ieee80211_frame_min *wh)
1477 {
1478         if (IS_BCAST_PROBEREQ(wh))
1479                 return NULL;            /* spam bcast probe req to all vap's */
1480         return ieee80211_find_node_locked(nt, wh->i_addr2);
1481 }
1482
1483 /*
1484  * Locate the node for sender, track state, and then pass the
1485  * (referenced) node up to the 802.11 layer for its use.  Note
1486  * we can return NULL if the sender is not in the table.
1487  */
1488 struct ieee80211_node *
1489 #ifdef IEEE80211_DEBUG_REFCNT
1490 ieee80211_find_rxnode_debug(struct ieee80211com *ic,
1491         const struct ieee80211_frame_min *wh, const char *func, int line)
1492 #else
1493 ieee80211_find_rxnode(struct ieee80211com *ic,
1494         const struct ieee80211_frame_min *wh)
1495 #endif
1496 {
1497         struct ieee80211_node_table *nt;
1498         struct ieee80211_node *ni;
1499
1500         nt = &ic->ic_sta;
1501         ni = _find_rxnode(nt, wh);
1502
1503         return ni;
1504 }
1505
1506 /*
1507  * Like ieee80211_find_rxnode but use the supplied h/w
1508  * key index as a hint to locate the node in the key
1509  * mapping table.  If an entry is present at the key
1510  * index we return it; otherwise do a normal lookup and
1511  * update the mapping table if the station has a unicast
1512  * key assigned to it.
1513  */
1514 struct ieee80211_node *
1515 #ifdef IEEE80211_DEBUG_REFCNT
1516 ieee80211_find_rxnode_withkey_debug(struct ieee80211com *ic,
1517         const struct ieee80211_frame_min *wh, ieee80211_keyix keyix,
1518         const char *func, int line)
1519 #else
1520 ieee80211_find_rxnode_withkey(struct ieee80211com *ic,
1521         const struct ieee80211_frame_min *wh, ieee80211_keyix keyix)
1522 #endif
1523 {
1524         struct ieee80211_node_table *nt;
1525         struct ieee80211_node *ni;
1526
1527         nt = &ic->ic_sta;
1528         if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax)
1529                 ni = nt->nt_keyixmap[keyix];
1530         else
1531                 ni = NULL;
1532         if (ni == NULL) {
1533                 ni = _find_rxnode(nt, wh);
1534                 if (ni != NULL && nt->nt_keyixmap != NULL) {
1535                         /*
1536                          * If the station has a unicast key cache slot
1537                          * assigned update the key->node mapping table.
1538                          */
1539                         keyix = ni->ni_ucastkey.wk_rxkeyix;
1540                         /* XXX can keyixmap[keyix] != NULL? */
1541                         if (keyix < nt->nt_keyixmax &&
1542                             nt->nt_keyixmap[keyix] == NULL) {
1543                                 IEEE80211_DPRINTF(ni->ni_vap,
1544                                     IEEE80211_MSG_NODE,
1545                                     "%s: add key map entry %p<%6D> refcnt %d\n",
1546                                     __func__, ni, ni->ni_macaddr, ":",
1547                                     ieee80211_node_refcnt(ni)+1);
1548                                 nt->nt_keyixmap[keyix] = ieee80211_ref_node(ni);
1549                         }
1550                 }
1551         } else {
1552                 if (IS_BCAST_PROBEREQ(wh))
1553                         ni = NULL;      /* spam bcast probe req to all vap's */
1554                 else
1555                         ieee80211_ref_node(ni);
1556         }
1557         return ni;
1558 }
1559 #undef IS_BCAST_PROBEREQ
1560 #undef IS_PROBEREQ
1561
1562 /*
1563  * Return a reference to the appropriate node for sending
1564  * a data frame.  This handles node discovery in adhoc networks.
1565  */
1566 struct ieee80211_node *
1567 #ifdef IEEE80211_DEBUG_REFCNT
1568 ieee80211_find_txnode_debug(struct ieee80211vap *vap,
1569         const uint8_t macaddr[IEEE80211_ADDR_LEN],
1570         const char *func, int line)
1571 #else
1572 ieee80211_find_txnode(struct ieee80211vap *vap,
1573         const uint8_t macaddr[IEEE80211_ADDR_LEN])
1574 #endif
1575 {
1576         struct ieee80211_node_table *nt = &vap->iv_ic->ic_sta;
1577         struct ieee80211_node *ni;
1578
1579         /*
1580          * The destination address should be in the node table
1581          * unless this is a multicast/broadcast frame.  We can
1582          * also optimize station mode operation, all frames go
1583          * to the bss node.
1584          */
1585         /* XXX can't hold lock across dup_bss 'cuz of recursive locking */
1586         if (vap->iv_opmode == IEEE80211_M_STA ||
1587             vap->iv_opmode == IEEE80211_M_WDS ||
1588             IEEE80211_IS_MULTICAST(macaddr))
1589                 ni = ieee80211_ref_node(vap->iv_bss);
1590         else
1591                 ni = ieee80211_find_node_locked(nt, macaddr);
1592
1593         if (ni == NULL) {
1594                 if (vap->iv_opmode == IEEE80211_M_IBSS ||
1595                     vap->iv_opmode == IEEE80211_M_AHDEMO) {
1596                         /*
1597                          * In adhoc mode cons up a node for the destination.
1598                          * Note that we need an additional reference for the
1599                          * caller to be consistent with
1600                          * ieee80211_find_node_locked.
1601                          */
1602                         ni = ieee80211_fakeup_adhoc_node(vap, macaddr);
1603                         if (ni != NULL)
1604                                 (void) ieee80211_ref_node(ni);
1605                 } else {
1606                         IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_OUTPUT, macaddr,
1607                             "no node, discard frame (%s)", __func__);
1608                         vap->iv_stats.is_tx_nonode++;
1609                 }
1610         }
1611         return ni;
1612 }
1613
1614 static void
1615 _ieee80211_free_node(struct ieee80211_node *ni)
1616 {
1617         struct ieee80211_node_table *nt = ni->ni_table;
1618
1619         /*
1620          * NB: careful about referencing the vap as it may be
1621          * gone if the last reference was held by a driver.
1622          * We know the com will always be present so it's safe
1623          * to use ni_ic below to reclaim resources.
1624          */
1625 #if 0
1626         IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE,
1627                 "%s %p<%6D> in %s table\n", __func__, ni,
1628                 ni->ni_macaddr, ":",
1629                 nt != NULL ? nt->nt_name : "<gone>");
1630 #endif
1631         if (ni->ni_associd != 0) {
1632                 struct ieee80211vap *vap = ni->ni_vap;
1633                 if (vap->iv_aid_bitmap != NULL)
1634                         IEEE80211_AID_CLR(vap, ni->ni_associd);
1635         }
1636         if (nt != NULL) {
1637                 TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1638                 LIST_REMOVE(ni, ni_hash);
1639         }
1640         ni->ni_ic->ic_node_free(ni);
1641 }
1642
1643 void
1644 #ifdef IEEE80211_DEBUG_REFCNT
1645 ieee80211_free_node_debug(struct ieee80211_node *ni, const char *func, int line)
1646 #else
1647 ieee80211_free_node(struct ieee80211_node *ni)
1648 #endif
1649 {
1650         struct ieee80211_node_table *nt = ni->ni_table;
1651
1652 #ifdef IEEE80211_DEBUG_REFCNT
1653         IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_NODE,
1654                 "%s (%s:%u) %p<%6D> refcnt %d\n", __func__, func, line, ni,
1655                  ni->ni_macaddr, ":", ieee80211_node_refcnt(ni)-1);
1656 #endif
1657         if (nt != NULL) {
1658                 if (ieee80211_node_dectestref(ni)) {
1659                         /*
1660                          * Last reference, reclaim state.
1661                          */
1662                         _ieee80211_free_node(ni);
1663                 } else if (ieee80211_node_refcnt(ni) == 1 &&
1664                     nt->nt_keyixmap != NULL) {
1665                         ieee80211_keyix keyix;
1666                         /*
1667                          * Check for a last reference in the key mapping table.
1668                          */
1669                         keyix = ni->ni_ucastkey.wk_rxkeyix;
1670                         if (keyix < nt->nt_keyixmax &&
1671                             nt->nt_keyixmap[keyix] == ni) {
1672                                 IEEE80211_DPRINTF(ni->ni_vap,
1673                                     IEEE80211_MSG_NODE,
1674                                     "%s: %p<%6D> clear key map entry", __func__,
1675                                     ni, ni->ni_macaddr, ":");
1676                                 nt->nt_keyixmap[keyix] = NULL;
1677                                 ieee80211_node_decref(ni); /* XXX needed? */
1678                                 _ieee80211_free_node(ni);
1679                         }
1680                 }
1681         } else {
1682                 if (ieee80211_node_dectestref(ni))
1683                         _ieee80211_free_node(ni);
1684         }
1685 }
1686
1687 /*
1688  * Reclaim a unicast key and clear any key cache state.
1689  */
1690 int
1691 ieee80211_node_delucastkey(struct ieee80211_node *ni)
1692 {
1693         struct ieee80211com *ic = ni->ni_ic;
1694         struct ieee80211_node_table *nt = &ic->ic_sta;
1695         struct ieee80211_node *nikey;
1696         ieee80211_keyix keyix;
1697         int status;
1698
1699         /*
1700          * NB: We must beware of LOR here; deleting the key
1701          * can cause the crypto layer to block traffic updates
1702          * which can generate a LOR against the node table lock;
1703          * grab it here and stash the key index for our use below.
1704          *
1705          * Must also beware of recursion on the node table lock.
1706          * When called from node_cleanup we may already have
1707          * the node table lock held.  Unfortunately there's no
1708          * way to separate out this path so we must do this
1709          * conditionally.
1710          */
1711         nikey = NULL;
1712         status = 1;             /* NB: success */
1713         if (ni->ni_ucastkey.wk_keyix != IEEE80211_KEYIX_NONE) {
1714                 keyix = ni->ni_ucastkey.wk_rxkeyix;
1715                 status = ieee80211_crypto_delkey(ni->ni_vap, &ni->ni_ucastkey);
1716                 if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax) {
1717                         nikey = nt->nt_keyixmap[keyix];
1718                         nt->nt_keyixmap[keyix] = NULL;
1719                 }
1720         }
1721
1722         if (nikey != NULL) {
1723                 KASSERT(nikey == ni,
1724                         ("key map out of sync, ni %p nikey %p", ni, nikey));
1725                 IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_NODE,
1726                         "%s: delete key map entry %p<%6D> refcnt %d\n",
1727                         __func__, ni, ni->ni_macaddr, ":",
1728                         ieee80211_node_refcnt(ni)-1);
1729                 ieee80211_free_node(ni);
1730         }
1731         return status;
1732 }
1733
1734 /*
1735  * Reclaim a node.  If this is the last reference count then
1736  * do the normal free work.  Otherwise remove it from the node
1737  * table and mark it gone by clearing the back-reference.
1738  */
1739 static void
1740 node_reclaim(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1741 {
1742         ieee80211_keyix keyix;
1743
1744         IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_NODE,
1745                 "%s: remove %p<%6D> from %s table, refcnt %d\n",
1746                 __func__, ni, ni->ni_macaddr, ":",
1747                 nt->nt_name, ieee80211_node_refcnt(ni)-1);
1748         /*
1749          * Clear any entry in the unicast key mapping table.
1750          * We need to do it here so rx lookups don't find it
1751          * in the mapping table even if it's not in the hash
1752          * table.  We cannot depend on the mapping table entry
1753          * being cleared because the node may not be free'd.
1754          */
1755         keyix = ni->ni_ucastkey.wk_rxkeyix;
1756         if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax &&
1757             nt->nt_keyixmap[keyix] == ni) {
1758                 IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_NODE,
1759                         "%s: %p<%6D> clear key map entry %u\n",
1760                         __func__, ni, ni->ni_macaddr, ":", keyix);
1761                 nt->nt_keyixmap[keyix] = NULL;
1762                 ieee80211_node_decref(ni);      /* NB: don't need free */
1763         }
1764         if (!ieee80211_node_dectestref(ni)) {
1765                 /*
1766                  * Other references are present, just remove the
1767                  * node from the table so it cannot be found.  When
1768                  * the references are dropped storage will be
1769                  * reclaimed.
1770                  */
1771                 TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1772                 LIST_REMOVE(ni, ni_hash);
1773                 ni->ni_table = NULL;            /* clear reference */
1774         } else
1775                 _ieee80211_free_node(ni);
1776 }
1777
1778 /*
1779  * Node table support.
1780  */
1781
1782 static void
1783 ieee80211_node_table_init(struct ieee80211com *ic,
1784         struct ieee80211_node_table *nt,
1785         const char *name, int inact, int keyixmax)
1786 {
1787         nt->nt_ic = ic;
1788         TAILQ_INIT(&nt->nt_node);
1789         nt->nt_name = name;
1790         nt->nt_scangen = 1;
1791         nt->nt_inact_init = inact;
1792         nt->nt_keyixmax = keyixmax;
1793         if (nt->nt_keyixmax > 0) {
1794                 nt->nt_keyixmap = (struct ieee80211_node **) kmalloc(
1795                         keyixmax * sizeof(struct ieee80211_node *),
1796                         M_80211_NODE, M_INTWAIT | M_ZERO);
1797                 if (nt->nt_keyixmap == NULL)
1798                         if_printf(ic->ic_ifp,
1799                             "Cannot allocate key index map with %u entries\n",
1800                             keyixmax);
1801         } else
1802                 nt->nt_keyixmap = NULL;
1803 }
1804
1805 static void
1806 ieee80211_node_table_reset(struct ieee80211_node_table *nt,
1807         struct ieee80211vap *match)
1808 {
1809         struct ieee80211_node *ni, *next;
1810
1811         TAILQ_FOREACH_MUTABLE(ni, &nt->nt_node, ni_list, next) {
1812                 if (match != NULL && ni->ni_vap != match)
1813                         continue;
1814                 /* XXX can this happen?  if so need's work */
1815                 if (ni->ni_associd != 0) {
1816                         struct ieee80211vap *vap = ni->ni_vap;
1817
1818                         if (vap->iv_auth->ia_node_leave != NULL)
1819                                 vap->iv_auth->ia_node_leave(ni);
1820                         if (vap->iv_aid_bitmap != NULL)
1821                                 IEEE80211_AID_CLR(vap, ni->ni_associd);
1822                 }
1823                 ni->ni_wdsvap = NULL;           /* clear reference */
1824                 node_reclaim(nt, ni);
1825         }
1826         if (match != NULL && match->iv_opmode == IEEE80211_M_WDS) {
1827                 /*
1828                  * Make a separate pass to clear references to this vap
1829                  * held by DWDS entries.  They will not be matched above
1830                  * because ni_vap will point to the ap vap but we still
1831                  * need to clear ni_wdsvap when the WDS vap is destroyed
1832                  * and/or reset.
1833                  */
1834                 TAILQ_FOREACH_MUTABLE(ni, &nt->nt_node, ni_list, next)
1835                         if (ni->ni_wdsvap == match)
1836                                 ni->ni_wdsvap = NULL;
1837         }
1838 }
1839
1840 static void
1841 ieee80211_node_table_cleanup(struct ieee80211_node_table *nt)
1842 {
1843         ieee80211_node_table_reset(nt, NULL);
1844         if (nt->nt_keyixmap != NULL) {
1845 #ifdef DIAGNOSTIC
1846                 /* XXX verify all entries are NULL */
1847                 int i;
1848                 for (i = 0; i < nt->nt_keyixmax; i++)
1849                         if (nt->nt_keyixmap[i] != NULL)
1850                                 kprintf("%s: %s[%u] still active\n", __func__,
1851                                         nt->nt_name, i);
1852 #endif
1853                 kfree(nt->nt_keyixmap, M_80211_NODE);
1854                 nt->nt_keyixmap = NULL;
1855         }
1856 }
1857
1858 /*
1859  * Timeout inactive stations and do related housekeeping.
1860  * Note that we cannot hold the node lock while sending a
1861  * frame as this would lead to a LOR.  Instead we use a
1862  * generation number to mark nodes that we've scanned and
1863  * drop the lock and restart a scan if we have to time out
1864  * a node.  Since we are single-threaded by virtue of
1865  * controlling the inactivity timer we can be sure this will
1866  * process each node only once.
1867  */
1868 static void
1869 ieee80211_timeout_stations(struct ieee80211com *ic)
1870 {
1871         struct ieee80211_node_table *nt = &ic->ic_sta;
1872         struct ieee80211vap *vap;
1873         struct ieee80211_node *ni;
1874         int gen = 0;
1875
1876         gen = ++nt->nt_scangen;
1877 restart:
1878         TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1879                 if (ni->ni_scangen == gen)      /* previously handled */
1880                         continue;
1881                 ni->ni_scangen = gen;
1882                 /*
1883                  * Ignore entries for which have yet to receive an
1884                  * authentication frame.  These are transient and
1885                  * will be reclaimed when the last reference to them
1886                  * goes away (when frame xmits complete).
1887                  */
1888                 vap = ni->ni_vap;
1889                 /*
1890                  * Only process stations when in RUN state.  This
1891                  * insures, for example, that we don't timeout an
1892                  * inactive station during CAC.  Note that CSA state
1893                  * is actually handled in ieee80211_node_timeout as
1894                  * it applies to more than timeout processing.
1895                  */
1896                 if (vap->iv_state != IEEE80211_S_RUN)
1897                         continue;
1898                 /* XXX can vap be NULL? */
1899                 if ((vap->iv_opmode == IEEE80211_M_HOSTAP ||
1900                      vap->iv_opmode == IEEE80211_M_STA) &&
1901                     (ni->ni_flags & IEEE80211_NODE_AREF) == 0)
1902                         continue;
1903                 /*
1904                  * Free fragment if not needed anymore
1905                  * (last fragment older than 1s).
1906                  * XXX doesn't belong here, move to node_age
1907                  */
1908                 if (ni->ni_rxfrag[0] != NULL &&
1909                     ticks > ni->ni_rxfragstamp + hz) {
1910                         m_freem(ni->ni_rxfrag[0]);
1911                         ni->ni_rxfrag[0] = NULL;
1912                 }
1913                 if (ni->ni_inact > 0) {
1914                         ni->ni_inact--;
1915                         IEEE80211_NOTE(vap, IEEE80211_MSG_INACT, ni,
1916                             "%s: inact %u inact_reload %u nrates %u",
1917                             __func__, ni->ni_inact, ni->ni_inact_reload,
1918                             ni->ni_rates.rs_nrates);
1919                 }
1920                 /*
1921                  * Special case ourself; we may be idle for extended periods
1922                  * of time and regardless reclaiming our state is wrong.
1923                  * XXX run ic_node_age
1924                  */
1925                 if (ni == vap->iv_bss)
1926                         continue;
1927                 if (ni->ni_associd != 0 || 
1928                     (vap->iv_opmode == IEEE80211_M_IBSS ||
1929                      vap->iv_opmode == IEEE80211_M_AHDEMO)) {
1930                         /*
1931                          * Age/drain resources held by the station.
1932                          */
1933                         ic->ic_node_age(ni);
1934                         /*
1935                          * Probe the station before time it out.  We
1936                          * send a null data frame which may not be
1937                          * universally supported by drivers (need it
1938                          * for ps-poll support so it should be...).
1939                          *
1940                          * XXX don't probe the station unless we've
1941                          *     received a frame from them (and have
1942                          *     some idea of the rates they are capable
1943                          *     of); this will get fixed more properly
1944                          *     soon with better handling of the rate set.
1945                          */
1946                         if ((vap->iv_flags_ext & IEEE80211_FEXT_INACT) &&
1947                             (0 < ni->ni_inact &&
1948                              ni->ni_inact <= vap->iv_inact_probe) &&
1949                             ni->ni_rates.rs_nrates != 0) {
1950                                 IEEE80211_NOTE(vap,
1951                                     IEEE80211_MSG_INACT | IEEE80211_MSG_NODE,
1952                                     ni, "%s",
1953                                     "probe station due to inactivity");
1954                                 /*
1955                                  * Grab a reference before unlocking the table
1956                                  * so the node cannot be reclaimed before we
1957                                  * send the frame. ieee80211_send_nulldata
1958                                  * understands we've done this and reclaims the
1959                                  * ref for us as needed.
1960                                  */
1961                                 ieee80211_ref_node(ni);
1962                                 ieee80211_send_nulldata(ni);
1963                                 /* XXX stat? */
1964                                 goto restart;
1965                         }
1966                 }
1967                 if ((vap->iv_flags_ext & IEEE80211_FEXT_INACT) &&
1968                     ni->ni_inact <= 0) {
1969                         IEEE80211_NOTE(vap,
1970                             IEEE80211_MSG_INACT | IEEE80211_MSG_NODE, ni,
1971                             "station timed out due to inactivity "
1972                             "(refcnt %u)", ieee80211_node_refcnt(ni));
1973                         /*
1974                          * Send a deauthenticate frame and drop the station.
1975                          * This is somewhat complicated due to reference counts
1976                          * and locking.  At this point a station will typically
1977                          * have a reference count of 1.  ieee80211_node_leave
1978                          * will do a "free" of the node which will drop the
1979                          * reference count.  But in the meantime a reference
1980                          * wil be held by the deauth frame.  The actual reclaim
1981                          * of the node will happen either after the tx is
1982                          * completed or by ieee80211_node_leave.
1983                          *
1984                          * Separately we must drop the node lock before sending
1985                          * in case the driver takes a lock, as this can result
1986                          * in a LOR between the node lock and the driver lock.
1987                          */
1988                         ieee80211_ref_node(ni);
1989                         if (ni->ni_associd != 0) {
1990                                 IEEE80211_SEND_MGMT(ni,
1991                                     IEEE80211_FC0_SUBTYPE_DEAUTH,
1992                                     IEEE80211_REASON_AUTH_EXPIRE);
1993                         }
1994                         ieee80211_node_leave(ni);
1995                         ieee80211_free_node(ni);
1996                         vap->iv_stats.is_node_timeout++;
1997                         goto restart;
1998                 }
1999         }
2000 }
2001
2002 /*
2003  * Aggressively reclaim resources.  This should be used
2004  * only in a critical situation to reclaim mbuf resources.
2005  */
2006 void
2007 ieee80211_drain(struct ieee80211com *ic)
2008 {
2009         struct ieee80211_node_table *nt = &ic->ic_sta;
2010         struct ieee80211vap *vap;
2011         struct ieee80211_node *ni;
2012
2013         TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
2014                 /*
2015                  * Ignore entries for which have yet to receive an
2016                  * authentication frame.  These are transient and
2017                  * will be reclaimed when the last reference to them
2018                  * goes away (when frame xmits complete).
2019                  */
2020                 vap = ni->ni_vap;
2021                 /*
2022                  * Only process stations when in RUN state.  This
2023                  * insures, for example, that we don't timeout an
2024                  * inactive station during CAC.  Note that CSA state
2025                  * is actually handled in ieee80211_node_timeout as
2026                  * it applies to more than timeout processing.
2027                  */
2028                 if (vap->iv_state != IEEE80211_S_RUN)
2029                         continue;
2030                 /* XXX can vap be NULL? */
2031                 if ((vap->iv_opmode == IEEE80211_M_HOSTAP ||
2032                      vap->iv_opmode == IEEE80211_M_STA) &&
2033                     (ni->ni_flags & IEEE80211_NODE_AREF) == 0)
2034                         continue;
2035                 /*
2036                  * Free fragments.
2037                  * XXX doesn't belong here, move to node_drain
2038                  */
2039                 if (ni->ni_rxfrag[0] != NULL) {
2040                         m_freem(ni->ni_rxfrag[0]);
2041                         ni->ni_rxfrag[0] = NULL;
2042                 }
2043                 /*
2044                  * Drain resources held by the station.
2045                  */
2046                 ic->ic_node_drain(ni);
2047         }
2048 }
2049
2050 /*
2051  * Per-ieee80211com inactivity timer callback.
2052  */
2053 static void
2054 ieee80211_node_timeout_callout(void *arg)
2055 {
2056         struct ieee80211com *ic = arg;
2057
2058         /*
2059          * Defer timeout processing if a channel switch is pending.
2060          * We typically need to be mute so not doing things that
2061          * might generate frames is good to handle in one place.
2062          * Supressing the station timeout processing may extend the
2063          * lifetime of inactive stations (by not decrementing their
2064          * idle counters) but this should be ok unless the CSA is
2065          * active for an unusually long time.
2066          */
2067         wlan_serialize_enter();
2068         if ((ic->ic_flags & IEEE80211_F_CSAPENDING) == 0) {
2069                 ieee80211_scan_timeout(ic);
2070                 ieee80211_timeout_stations(ic);
2071                 ieee80211_ageq_age(&ic->ic_stageq, IEEE80211_INACT_WAIT);
2072
2073                 ieee80211_erp_timeout(ic);
2074                 ieee80211_ht_timeout(ic);
2075         }
2076         callout_reset(&ic->ic_inact, IEEE80211_INACT_WAIT*hz,
2077                       ieee80211_node_timeout_callout, ic);
2078         wlan_serialize_exit();
2079 }
2080
2081 void
2082 ieee80211_iterate_nodes(struct ieee80211_node_table *nt,
2083         ieee80211_iter_func *f, void *arg)
2084 {
2085         struct ieee80211_node *ni;
2086         u_int gen;
2087
2088         gen = ++nt->nt_scangen;
2089 restart:
2090         TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
2091                 if (ni->ni_scangen != gen) {
2092                         ni->ni_scangen = gen;
2093                         (void) ieee80211_ref_node(ni);
2094                         (*f)(arg, ni);
2095                         ieee80211_free_node(ni);
2096                         goto restart;
2097                 }
2098         }
2099 }
2100
2101 void
2102 ieee80211_dump_node(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
2103 {
2104         kprintf("0x%p: mac %6D refcnt %d\n", ni, ni->ni_macaddr, ":",
2105                 ieee80211_node_refcnt(ni));
2106         kprintf("\tscangen %u authmode %u flags 0x%x\n",
2107                 ni->ni_scangen, ni->ni_authmode, ni->ni_flags);
2108         kprintf("\tassocid 0x%x txpower %u vlan %u\n",
2109                 ni->ni_associd, ni->ni_txpower, ni->ni_vlan);
2110         kprintf("\ttxseq %u rxseq %u fragno %u rxfragstamp %u\n",
2111                 ni->ni_txseqs[IEEE80211_NONQOS_TID],
2112                 ni->ni_rxseqs[IEEE80211_NONQOS_TID] >> IEEE80211_SEQ_SEQ_SHIFT,
2113                 ni->ni_rxseqs[IEEE80211_NONQOS_TID] & IEEE80211_SEQ_FRAG_MASK,
2114                 ni->ni_rxfragstamp);
2115         kprintf("\trssi %d noise %d intval %u capinfo 0x%x\n",
2116                 node_getrssi(ni), ni->ni_noise,
2117                 ni->ni_intval, ni->ni_capinfo);
2118         kprintf("\tbssid %6D essid \"%.*s\" channel %u:0x%x\n",
2119                 ni->ni_bssid, ":",
2120                 ni->ni_esslen, ni->ni_essid,
2121                 ni->ni_chan->ic_freq, ni->ni_chan->ic_flags);
2122         kprintf("\tinact %u inact_reload %u txrate %u\n",
2123                 ni->ni_inact, ni->ni_inact_reload, ni->ni_txrate);
2124         kprintf("\thtcap %x htparam %x htctlchan %u ht2ndchan %u\n",
2125                 ni->ni_htcap, ni->ni_htparam,
2126                 ni->ni_htctlchan, ni->ni_ht2ndchan);
2127         kprintf("\thtopmode %x htstbc %x chw %u\n",
2128                 ni->ni_htopmode, ni->ni_htstbc, ni->ni_chw);
2129 }
2130
2131 void
2132 ieee80211_dump_nodes(struct ieee80211_node_table *nt)
2133 {
2134         ieee80211_iterate_nodes(nt,
2135                 (ieee80211_iter_func *) ieee80211_dump_node, nt);
2136 }
2137
2138 static void
2139 ieee80211_notify_erp_locked(struct ieee80211com *ic)
2140 {
2141         struct ieee80211vap *vap;
2142
2143         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
2144                 if (vap->iv_opmode == IEEE80211_M_HOSTAP)
2145                         ieee80211_beacon_notify(vap, IEEE80211_BEACON_ERP);
2146 }
2147
2148 void
2149 ieee80211_notify_erp(struct ieee80211com *ic)
2150 {
2151         ieee80211_notify_erp_locked(ic);
2152 }
2153
2154 /*
2155  * Handle a station joining an 11g network.
2156  */
2157 static void
2158 ieee80211_node_join_11g(struct ieee80211_node *ni)
2159 {
2160         struct ieee80211com *ic = ni->ni_ic;
2161
2162         /*
2163          * Station isn't capable of short slot time.  Bump
2164          * the count of long slot time stations and disable
2165          * use of short slot time.  Note that the actual switch
2166          * over to long slot time use may not occur until the
2167          * next beacon transmission (per sec. 7.3.1.4 of 11g).
2168          */
2169         if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
2170                 ic->ic_longslotsta++;
2171                 IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ASSOC, ni,
2172                     "station needs long slot time, count %d",
2173                     ic->ic_longslotsta);
2174                 /* XXX vap's w/ conflicting needs won't work */
2175                 if (!IEEE80211_IS_CHAN_108G(ic->ic_bsschan)) {
2176                         /*
2177                          * Don't force slot time when switched to turbo
2178                          * mode as non-ERP stations won't be present; this
2179                          * need only be done when on the normal G channel.
2180                          */
2181                         ieee80211_set_shortslottime(ic, 0);
2182                 }
2183         }
2184         /*
2185          * If the new station is not an ERP station
2186          * then bump the counter and enable protection
2187          * if configured.
2188          */
2189         if (!ieee80211_iserp_rateset(&ni->ni_rates)) {
2190                 ic->ic_nonerpsta++;
2191                 IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ASSOC, ni,
2192                     "station is !ERP, %d non-ERP stations associated",
2193                     ic->ic_nonerpsta);
2194                 /*
2195                  * If station does not support short preamble
2196                  * then we must enable use of Barker preamble.
2197                  */
2198                 if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE) == 0) {
2199                         IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ASSOC, ni,
2200                             "%s", "station needs long preamble");
2201                         ic->ic_flags |= IEEE80211_F_USEBARKER;
2202                         ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
2203                 }
2204                 /*
2205                  * If protection is configured and this is the first
2206                  * indication we should use protection, enable it.
2207                  */
2208                 if (ic->ic_protmode != IEEE80211_PROT_NONE &&
2209                     ic->ic_nonerpsta == 1 &&
2210                     (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) == 0) {
2211                         IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_ASSOC,
2212                             "%s: enable use of protection\n", __func__);
2213                         ic->ic_flags |= IEEE80211_F_USEPROT;
2214                         ieee80211_notify_erp_locked(ic);
2215                 }
2216         } else
2217                 ni->ni_flags |= IEEE80211_NODE_ERP;
2218 }
2219
2220 void
2221 ieee80211_node_join(struct ieee80211_node *ni, int resp)
2222 {
2223         struct ieee80211com *ic = ni->ni_ic;
2224         struct ieee80211vap *vap = ni->ni_vap;
2225         int newassoc;
2226
2227         if (ni->ni_associd == 0) {
2228                 uint16_t aid;
2229
2230                 KASSERT(vap->iv_aid_bitmap != NULL, ("no aid bitmap"));
2231                 /*
2232                  * It would be good to search the bitmap
2233                  * more efficiently, but this will do for now.
2234                  */
2235                 for (aid = 1; aid < vap->iv_max_aid; aid++) {
2236                         if (!IEEE80211_AID_ISSET(vap, aid))
2237                                 break;
2238                 }
2239                 if (aid >= vap->iv_max_aid) {
2240                         IEEE80211_SEND_MGMT(ni, resp, IEEE80211_STATUS_TOOMANY);
2241                         ieee80211_node_leave(ni);
2242                         return;
2243                 }
2244                 ni->ni_associd = aid | 0xc000;
2245                 ni->ni_jointime = time_second;
2246                 IEEE80211_AID_SET(vap, ni->ni_associd);
2247                 vap->iv_sta_assoc++;
2248                 ic->ic_sta_assoc++;
2249
2250                 if (IEEE80211_IS_CHAN_HT(ic->ic_bsschan))
2251                         ieee80211_ht_node_join(ni);
2252                 if (IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan) &&
2253                     IEEE80211_IS_CHAN_FULL(ic->ic_bsschan))
2254                         ieee80211_node_join_11g(ni);
2255
2256                 newassoc = 1;
2257         } else
2258                 newassoc = 0;
2259
2260         IEEE80211_NOTE(vap, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG, ni,
2261             "station associated at aid %d: %s preamble, %s slot time%s%s%s%s%s%s%s%s",
2262             IEEE80211_NODE_AID(ni),
2263             ic->ic_flags & IEEE80211_F_SHPREAMBLE ? "short" : "long",
2264             ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long",
2265             ic->ic_flags & IEEE80211_F_USEPROT ? ", protection" : "",
2266             ni->ni_flags & IEEE80211_NODE_QOS ? ", QoS" : "",
2267             ni->ni_flags & IEEE80211_NODE_HT ?
2268                 (ni->ni_chw == 40 ? ", HT40" : ", HT20") : "",
2269             ni->ni_flags & IEEE80211_NODE_AMPDU ? " (+AMPDU)" : "",
2270             ni->ni_flags & IEEE80211_NODE_MIMO_RTS ? " (+SMPS-DYN)" :
2271                 ni->ni_flags & IEEE80211_NODE_MIMO_PS ? " (+SMPS)" : "",
2272             ni->ni_flags & IEEE80211_NODE_RIFS ? " (+RIFS)" : "",
2273             IEEE80211_ATH_CAP(vap, ni, IEEE80211_NODE_FF) ?
2274                 ", fast-frames" : "",
2275             IEEE80211_ATH_CAP(vap, ni, IEEE80211_NODE_TURBOP) ?
2276                 ", turbo" : ""
2277         );
2278
2279         ieee80211_node_setuptxparms(ni);
2280         /* give driver a chance to setup state like ni_txrate */
2281         if (ic->ic_newassoc != NULL)
2282                 ic->ic_newassoc(ni, newassoc);
2283         IEEE80211_SEND_MGMT(ni, resp, IEEE80211_STATUS_SUCCESS);
2284         /* tell the authenticator about new station */
2285         if (vap->iv_auth->ia_node_join != NULL)
2286                 vap->iv_auth->ia_node_join(ni);
2287         ieee80211_notify_node_join(ni,
2288             resp == IEEE80211_FC0_SUBTYPE_ASSOC_RESP);
2289 }
2290
2291 static void
2292 disable_protection(struct ieee80211com *ic)
2293 {
2294         KASSERT(ic->ic_nonerpsta == 0 &&
2295             (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) == 0,
2296            ("%d non ERP stations, flags 0x%x", ic->ic_nonerpsta,
2297            ic->ic_flags_ext));
2298
2299         ic->ic_flags &= ~IEEE80211_F_USEPROT;
2300         /* XXX verify mode? */
2301         if (ic->ic_caps & IEEE80211_C_SHPREAMBLE) {
2302                 ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
2303                 ic->ic_flags &= ~IEEE80211_F_USEBARKER;
2304         }
2305         ieee80211_notify_erp_locked(ic);
2306 }
2307
2308 /*
2309  * Handle a station leaving an 11g network.
2310  */
2311 static void
2312 ieee80211_node_leave_11g(struct ieee80211_node *ni)
2313 {
2314         struct ieee80211com *ic = ni->ni_ic;
2315
2316         KASSERT(IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan),
2317              ("not in 11g, bss %u:0x%x", ic->ic_bsschan->ic_freq,
2318               ic->ic_bsschan->ic_flags));
2319
2320         /*
2321          * If a long slot station do the slot time bookkeeping.
2322          */
2323         if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
2324                 KASSERT(ic->ic_longslotsta > 0,
2325                     ("bogus long slot station count %d", ic->ic_longslotsta));
2326                 ic->ic_longslotsta--;
2327                 IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ASSOC, ni,
2328                     "long slot time station leaves, count now %d",
2329                     ic->ic_longslotsta);
2330                 if (ic->ic_longslotsta == 0) {
2331                         /*
2332                          * Re-enable use of short slot time if supported
2333                          * and not operating in IBSS mode (per spec).
2334                          */
2335                         if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
2336                             ic->ic_opmode != IEEE80211_M_IBSS) {
2337                                 IEEE80211_DPRINTF(ni->ni_vap,
2338                                     IEEE80211_MSG_ASSOC,
2339                                     "%s: re-enable use of short slot time\n",
2340                                     __func__);
2341                                 ieee80211_set_shortslottime(ic, 1);
2342                         }
2343                 }
2344         }
2345         /*
2346          * If a non-ERP station do the protection-related bookkeeping.
2347          */
2348         if ((ni->ni_flags & IEEE80211_NODE_ERP) == 0) {
2349                 KASSERT(ic->ic_nonerpsta > 0,
2350                     ("bogus non-ERP station count %d", ic->ic_nonerpsta));
2351                 ic->ic_nonerpsta--;
2352                 IEEE80211_NOTE(ni->ni_vap, IEEE80211_MSG_ASSOC, ni,
2353                     "non-ERP station leaves, count now %d%s", ic->ic_nonerpsta,
2354                     (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) ?
2355                         " (non-ERP sta present)" : "");
2356                 if (ic->ic_nonerpsta == 0 &&
2357                     (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) == 0) {
2358                         IEEE80211_DPRINTF(ni->ni_vap, IEEE80211_MSG_ASSOC,
2359                                 "%s: disable use of protection\n", __func__);
2360                         disable_protection(ic);
2361                 }
2362         }
2363 }
2364
2365 /*
2366  * Time out presence of an overlapping bss with non-ERP
2367  * stations.  When operating in hostap mode we listen for
2368  * beacons from other stations and if we identify a non-ERP
2369  * station is present we enable protection.  To identify
2370  * when all non-ERP stations are gone we time out this
2371  * condition.
2372  */
2373 static void
2374 ieee80211_erp_timeout(struct ieee80211com *ic)
2375 {
2376         if ((ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) &&
2377             time_after(ticks, ic->ic_lastnonerp + IEEE80211_NONERP_PRESENT_AGE)) {
2378 #if 0
2379                 IEEE80211_NOTE(vap, IEEE80211_MSG_ASSOC, ni,
2380                     "%s", "age out non-ERP sta present on channel");
2381 #endif
2382                 ic->ic_flags_ext &= ~IEEE80211_FEXT_NONERP_PR;
2383                 if (ic->ic_nonerpsta == 0)
2384                         disable_protection(ic);
2385         }
2386 }
2387
2388 /*
2389  * Handle bookkeeping for station deauthentication/disassociation
2390  * when operating as an ap.
2391  */
2392 void
2393 ieee80211_node_leave(struct ieee80211_node *ni)
2394 {
2395         struct ieee80211com *ic = ni->ni_ic;
2396         struct ieee80211vap *vap = ni->ni_vap;
2397         struct ieee80211_node_table *nt = ni->ni_table;
2398
2399         IEEE80211_NOTE(vap, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG, ni,
2400             "station with aid %d leaves", IEEE80211_NODE_AID(ni));
2401
2402         KASSERT(vap->iv_opmode != IEEE80211_M_STA,
2403                 ("unexpected operating mode %u", vap->iv_opmode));
2404         /*
2405          * If node wasn't previously associated all
2406          * we need to do is reclaim the reference.
2407          */
2408         /* XXX ibss mode bypasses 11g and notification */
2409         if (ni->ni_associd == 0)
2410                 goto done;
2411         /*
2412          * Tell the authenticator the station is leaving.
2413          * Note that we must do this before yanking the
2414          * association id as the authenticator uses the
2415          * associd to locate it's state block.
2416          */
2417         if (vap->iv_auth->ia_node_leave != NULL)
2418                 vap->iv_auth->ia_node_leave(ni);
2419
2420         IEEE80211_AID_CLR(vap, ni->ni_associd);
2421         ni->ni_associd = 0;
2422         vap->iv_sta_assoc--;
2423         ic->ic_sta_assoc--;
2424
2425         if (IEEE80211_IS_CHAN_HT(ic->ic_bsschan))
2426                 ieee80211_ht_node_leave(ni);
2427         if (IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan) &&
2428             IEEE80211_IS_CHAN_FULL(ic->ic_bsschan))
2429                 ieee80211_node_leave_11g(ni);
2430         /*
2431          * Cleanup station state.  In particular clear various
2432          * state that might otherwise be reused if the node
2433          * is reused before the reference count goes to zero
2434          * (and memory is reclaimed).
2435          */
2436         ieee80211_sta_leave(ni);
2437 done:
2438         /*
2439          * Remove the node from any table it's recorded in and
2440          * drop the caller's reference.  Removal from the table
2441          * is important to insure the node is not reprocessed
2442          * for inactivity.
2443          */
2444         if (nt != NULL) {
2445                 node_reclaim(nt, ni);
2446         } else
2447                 ieee80211_free_node(ni);
2448 }
2449
2450 struct rssiinfo {
2451         struct ieee80211vap *vap;
2452         int     rssi_samples;
2453         uint32_t rssi_total;
2454 };
2455
2456 static void
2457 get_hostap_rssi(void *arg, struct ieee80211_node *ni)
2458 {
2459         struct rssiinfo *info = arg;
2460         struct ieee80211vap *vap = ni->ni_vap;
2461         int8_t rssi;
2462
2463         if (info->vap != vap)
2464                 return;
2465         /* only associated stations */
2466         if (ni->ni_associd == 0)
2467                 return;
2468         rssi = vap->iv_ic->ic_node_getrssi(ni);
2469         if (rssi != 0) {
2470                 info->rssi_samples++;
2471                 info->rssi_total += rssi;
2472         }
2473 }
2474
2475 static void
2476 get_adhoc_rssi(void *arg, struct ieee80211_node *ni)
2477 {
2478         struct rssiinfo *info = arg;
2479         struct ieee80211vap *vap = ni->ni_vap;
2480         int8_t rssi;
2481
2482         if (info->vap != vap)
2483                 return;
2484         /* only neighbors */
2485         /* XXX check bssid */
2486         if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
2487                 return;
2488         rssi = vap->iv_ic->ic_node_getrssi(ni);
2489         if (rssi != 0) {
2490                 info->rssi_samples++;
2491                 info->rssi_total += rssi;
2492         }
2493 }
2494
2495 #ifdef IEEE80211_SUPPORT_MESH
2496 static void
2497 get_mesh_rssi(void *arg, struct ieee80211_node *ni)
2498 {
2499         struct rssiinfo *info = arg;
2500         struct ieee80211vap *vap = ni->ni_vap;
2501         int8_t rssi;
2502
2503         if (info->vap != vap)
2504                 return;
2505         /* only neighbors that peered successfully */
2506         if (ni->ni_mlstate != IEEE80211_NODE_MESH_ESTABLISHED)
2507                 return;
2508         rssi = vap->iv_ic->ic_node_getrssi(ni);
2509         if (rssi != 0) {
2510                 info->rssi_samples++;
2511                 info->rssi_total += rssi;
2512         }
2513 }
2514 #endif /* IEEE80211_SUPPORT_MESH */
2515
2516 int8_t
2517 ieee80211_getrssi(struct ieee80211vap *vap)
2518 {
2519 #define NZ(x)   ((x) == 0 ? 1 : (x))
2520         struct ieee80211com *ic = vap->iv_ic;
2521         struct rssiinfo info;
2522
2523         info.rssi_total = 0;
2524         info.rssi_samples = 0;
2525         info.vap = vap;
2526         switch (vap->iv_opmode) {
2527         case IEEE80211_M_IBSS:          /* average of all ibss neighbors */
2528         case IEEE80211_M_AHDEMO:        /* average of all neighbors */
2529                 ieee80211_iterate_nodes(&ic->ic_sta, get_adhoc_rssi, &info);
2530                 break;
2531         case IEEE80211_M_HOSTAP:        /* average of all associated stations */
2532                 ieee80211_iterate_nodes(&ic->ic_sta, get_hostap_rssi, &info);
2533                 break;
2534 #ifdef IEEE80211_SUPPORT_MESH
2535         case IEEE80211_M_MBSS:          /* average of all mesh neighbors */
2536                 ieee80211_iterate_nodes(&ic->ic_sta, get_mesh_rssi, &info);
2537                 break;
2538 #endif
2539         case IEEE80211_M_MONITOR:       /* XXX */
2540         case IEEE80211_M_STA:           /* use stats from associated ap */
2541         default:
2542                 if (vap->iv_bss != NULL)
2543                         info.rssi_total = ic->ic_node_getrssi(vap->iv_bss);
2544                 info.rssi_samples = 1;
2545                 break;
2546         }
2547         return info.rssi_total / NZ(info.rssi_samples);
2548 #undef NZ
2549 }
2550
2551 void
2552 ieee80211_getsignal(struct ieee80211vap *vap, int8_t *rssi, int8_t *noise)
2553 {
2554
2555         if (vap->iv_bss == NULL)                /* NB: shouldn't happen */
2556                 return;
2557         vap->iv_ic->ic_node_getsignal(vap->iv_bss, rssi, noise);
2558         /* for non-station mode return avg'd rssi accounting */
2559         if (vap->iv_opmode != IEEE80211_M_STA)
2560                 *rssi = ieee80211_getrssi(vap);
2561 }