]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - sys/net80211/ieee80211_node.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.git] / sys / net80211 / ieee80211_node.c
1 /*-
2  * Copyright (c) 2001 Atsushi Onoe
3  * Copyright (c) 2002-2007 Sam Leffler, Errno Consulting
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29
30 #include <sys/param.h>
31 #include <sys/systm.h> 
32 #include <sys/mbuf.h>   
33 #include <sys/malloc.h>
34 #include <sys/kernel.h>
35
36 #include <sys/socket.h>
37  
38 #include <net/if.h>
39 #include <net/if_media.h>
40 #include <net/ethernet.h>
41
42 #include <net80211/ieee80211_var.h>
43 #include <net80211/ieee80211_input.h>
44
45 #include <net/bpf.h>
46
47 /*
48  * Association id's are managed with a bit vector.
49  */
50 #define IEEE80211_AID_SET(b, w) \
51         ((w)[IEEE80211_AID(b) / 32] |= (1 << (IEEE80211_AID(b) % 32)))
52 #define IEEE80211_AID_CLR(b, w) \
53         ((w)[IEEE80211_AID(b) / 32] &= ~(1 << (IEEE80211_AID(b) % 32)))
54 #define IEEE80211_AID_ISSET(b, w) \
55         ((w)[IEEE80211_AID(b) / 32] & (1 << (IEEE80211_AID(b) % 32)))
56
57 #ifdef IEEE80211_DEBUG_REFCNT
58 #define REFCNT_LOC "%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line
59 #else
60 #define REFCNT_LOC "%s %p<%s> refcnt %d\n", __func__
61 #endif
62
63 static int ieee80211_sta_join1(struct ieee80211_node *);
64
65 static struct ieee80211_node *node_alloc(struct ieee80211_node_table *);
66 static void node_cleanup(struct ieee80211_node *);
67 static void node_free(struct ieee80211_node *);
68 static int8_t node_getrssi(const struct ieee80211_node *);
69 static void node_getsignal(const struct ieee80211_node *, int8_t *, int8_t *);
70
71 static void ieee80211_setup_node(struct ieee80211_node_table *,
72                 struct ieee80211_node *, const uint8_t *);
73 static void _ieee80211_free_node(struct ieee80211_node *);
74
75 static void ieee80211_node_table_init(struct ieee80211com *ic,
76         struct ieee80211_node_table *nt, const char *name,
77         int inact, int keymaxix);
78 static void ieee80211_node_table_reset(struct ieee80211_node_table *);
79 static void ieee80211_node_table_cleanup(struct ieee80211_node_table *nt);
80 static void ieee80211_erp_timeout(struct ieee80211com *);
81
82 MALLOC_DEFINE(M_80211_NODE, "80211node", "802.11 node state");
83 MALLOC_DEFINE(M_80211_NODE_IE, "80211nodeie", "802.11 node ie");
84
85 void
86 ieee80211_node_attach(struct ieee80211com *ic)
87 {
88
89         ic->ic_node_alloc = node_alloc;
90         ic->ic_node_free = node_free;
91         ic->ic_node_cleanup = node_cleanup;
92         ic->ic_node_getrssi = node_getrssi;
93         ic->ic_node_getsignal = node_getsignal;
94
95         /* default station inactivity timer setings */
96         ic->ic_inact_init = IEEE80211_INACT_INIT;
97         ic->ic_inact_auth = IEEE80211_INACT_AUTH;
98         ic->ic_inact_run = IEEE80211_INACT_RUN;
99         ic->ic_inact_probe = IEEE80211_INACT_PROBE;
100
101         callout_init(&ic->ic_inact, CALLOUT_MPSAFE);
102
103         /* NB: driver should override */
104         ic->ic_max_aid = IEEE80211_AID_DEF;
105
106         ic->ic_flags_ext |= IEEE80211_FEXT_INACT; /* inactivity processing */
107 }
108
109 void
110 ieee80211_node_lateattach(struct ieee80211com *ic)
111 {
112         struct ieee80211_rsnparms *rsn;
113
114         if (ic->ic_max_aid > IEEE80211_AID_MAX)
115                 ic->ic_max_aid = IEEE80211_AID_MAX;
116         MALLOC(ic->ic_aid_bitmap, uint32_t *,
117                 howmany(ic->ic_max_aid, 32) * sizeof(uint32_t),
118                 M_80211_NODE, M_NOWAIT | M_ZERO);
119         if (ic->ic_aid_bitmap == NULL) {
120                 /* XXX no way to recover */
121                 printf("%s: no memory for AID bitmap!\n", __func__);
122                 ic->ic_max_aid = 0;
123         }
124
125         ieee80211_node_table_init(ic, &ic->ic_sta, "station",
126                 IEEE80211_INACT_INIT, ic->ic_crypto.cs_max_keyix);
127
128         ieee80211_reset_bss(ic);
129         /*
130          * Setup "global settings" in the bss node so that
131          * each new station automatically inherits them.
132          */
133         rsn = &ic->ic_bss->ni_rsn;
134         /* WEP, TKIP, and AES-CCM are always supported */
135         rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_WEP;
136         rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_TKIP;
137         rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_AES_CCM;
138         if (ic->ic_caps & IEEE80211_C_AES)
139                 rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_AES_OCB;
140         if (ic->ic_caps & IEEE80211_C_CKIP)
141                 rsn->rsn_ucastcipherset |= 1<<IEEE80211_CIPHER_CKIP;
142         /*
143          * Default unicast cipher to WEP for 802.1x use.  If
144          * WPA is enabled the management code will set these
145          * values to reflect.
146          */
147         rsn->rsn_ucastcipher = IEEE80211_CIPHER_WEP;
148         rsn->rsn_ucastkeylen = 104 / NBBY;
149         /*
150          * WPA says the multicast cipher is the lowest unicast
151          * cipher supported.  But we skip WEP which would
152          * otherwise be used based on this criteria.
153          */
154         rsn->rsn_mcastcipher = IEEE80211_CIPHER_TKIP;
155         rsn->rsn_mcastkeylen = 128 / NBBY;
156
157         /*
158          * We support both WPA-PSK and 802.1x; the one used
159          * is determined by the authentication mode and the
160          * setting of the PSK state.
161          */
162         rsn->rsn_keymgmtset = WPA_ASE_8021X_UNSPEC | WPA_ASE_8021X_PSK;
163         rsn->rsn_keymgmt = WPA_ASE_8021X_PSK;
164
165         ic->ic_auth = ieee80211_authenticator_get(ic->ic_bss->ni_authmode);
166 }
167
168 void
169 ieee80211_node_detach(struct ieee80211com *ic)
170 {
171
172         if (ic->ic_bss != NULL) {
173                 ieee80211_free_node(ic->ic_bss);
174                 ic->ic_bss = NULL;
175         }
176         ieee80211_node_table_cleanup(&ic->ic_sta);
177         if (ic->ic_aid_bitmap != NULL) {
178                 FREE(ic->ic_aid_bitmap, M_80211_NODE);
179                 ic->ic_aid_bitmap = NULL;
180         }
181 }
182
183 /* 
184  * Port authorize/unauthorize interfaces for use by an authenticator.
185  */
186
187 void
188 ieee80211_node_authorize(struct ieee80211_node *ni)
189 {
190         struct ieee80211com *ic = ni->ni_ic;
191
192         ni->ni_flags |= IEEE80211_NODE_AUTH;
193         ni->ni_inact_reload = ic->ic_inact_run;
194         ni->ni_inact = ni->ni_inact_reload;
195 }
196
197 void
198 ieee80211_node_unauthorize(struct ieee80211_node *ni)
199 {
200         struct ieee80211com *ic = ni->ni_ic;
201
202         ni->ni_flags &= ~IEEE80211_NODE_AUTH;
203         ni->ni_inact_reload = ic->ic_inact_auth;
204         if (ni->ni_inact > ni->ni_inact_reload)
205                 ni->ni_inact = ni->ni_inact_reload;
206 }
207
208 /*
209  * Set/change the channel.  The rate set is also updated as
210  * to insure a consistent view by drivers.
211  */
212 static void
213 ieee80211_node_set_chan(struct ieee80211com *ic, struct ieee80211_node *ni)
214 {
215         struct ieee80211_channel *chan = ic->ic_bsschan;
216
217 #if 0
218         KASSERT(chan != IEEE80211_CHAN_ANYC, ("bss channel not setup"));
219 #else
220         if (chan == IEEE80211_CHAN_ANYC)        /* XXX while scanning */
221                 chan = ic->ic_curchan;
222 #endif
223         ni->ni_chan = chan;
224         if (IEEE80211_IS_CHAN_HT(chan)) {
225                 /*
226                  * XXX Gotta be careful here; the rate set returned by
227                  * ieee80211_get_suprates is actually any HT rate
228                  * set so blindly copying it will be bad.  We must
229                  * install the legacy rate est in ni_rates and the
230                  * HT rate set in ni_htrates.
231                  */
232                 ni->ni_htrates = *ieee80211_get_suphtrates(ic, chan);
233         }
234         ni->ni_rates = *ieee80211_get_suprates(ic, chan);
235 }
236
237 /*
238  * Probe the curent channel, if allowed, while scanning.
239  * If the channel is not marked passive-only then send
240  * a probe request immediately.  Otherwise mark state and
241  * listen for beacons on the channel; if we receive something
242  * then we'll transmit a probe request.
243  */
244 void
245 ieee80211_probe_curchan(struct ieee80211com *ic, int force)
246 {
247         struct ifnet *ifp = ic->ic_ifp;
248
249         if ((ic->ic_curchan->ic_flags & IEEE80211_CHAN_PASSIVE) == 0 || force) {
250                 /*
251                  * XXX send both broadcast+directed probe request
252                  */
253                 ieee80211_send_probereq(ic->ic_bss,
254                         ic->ic_myaddr, ifp->if_broadcastaddr,
255                         ifp->if_broadcastaddr,
256                         ic->ic_des_ssid[0].ssid, ic->ic_des_ssid[0].len,
257                         ic->ic_opt_ie, ic->ic_opt_ie_len);
258         } else
259                 ic->ic_flags_ext |= IEEE80211_FEXT_PROBECHAN;
260 }
261
262 static __inline void
263 copy_bss(struct ieee80211_node *nbss, const struct ieee80211_node *obss)
264 {
265         /* propagate useful state */
266         nbss->ni_authmode = obss->ni_authmode;
267         nbss->ni_txpower = obss->ni_txpower;
268         nbss->ni_vlan = obss->ni_vlan;
269         nbss->ni_rsn = obss->ni_rsn;
270         /* XXX statistics? */
271 }
272
273 void
274 ieee80211_create_ibss(struct ieee80211com* ic, struct ieee80211_channel *chan)
275 {
276         struct ieee80211_node_table *nt;
277         struct ieee80211_node *ni;
278
279         IEEE80211_DPRINTF(ic, IEEE80211_MSG_SCAN,
280                 "%s: creating ibss\n", __func__);
281
282         /*
283          * Create the station/neighbor table.  Note that for adhoc
284          * mode we make the initial inactivity timer longer since
285          * we create nodes only through discovery and they typically
286          * are long-lived associations.
287          */
288         nt = &ic->ic_sta;
289         IEEE80211_NODE_LOCK(nt);
290         if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
291                 nt->nt_name = "station";
292                 nt->nt_inact_init = ic->ic_inact_init;
293         } else {
294                 nt->nt_name = "neighbor";
295                 nt->nt_inact_init = ic->ic_inact_run;
296         }
297         IEEE80211_NODE_UNLOCK(nt);
298
299         ni = ieee80211_alloc_node(&ic->ic_sta, ic->ic_myaddr);
300         if (ni == NULL) {
301                 /* XXX recovery? */
302                 return;
303         }
304         IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_myaddr);
305         ni->ni_esslen = ic->ic_des_ssid[0].len;
306         memcpy(ni->ni_essid, ic->ic_des_ssid[0].ssid, ni->ni_esslen);
307         if (ic->ic_bss != NULL)
308                 copy_bss(ni, ic->ic_bss);
309         ni->ni_intval = ic->ic_bintval;
310         if (ic->ic_flags & IEEE80211_F_PRIVACY)
311                 ni->ni_capinfo |= IEEE80211_CAPINFO_PRIVACY;
312         if (ic->ic_phytype == IEEE80211_T_FH) {
313                 ni->ni_fhdwell = 200;   /* XXX */
314                 ni->ni_fhindex = 1;
315         }
316         if (ic->ic_opmode == IEEE80211_M_IBSS) {
317                 ic->ic_flags |= IEEE80211_F_SIBSS;
318                 ni->ni_capinfo |= IEEE80211_CAPINFO_IBSS;       /* XXX */
319                 if (ic->ic_flags & IEEE80211_F_DESBSSID)
320                         IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_des_bssid);
321                 else {
322                         get_random_bytes(ni->ni_bssid, IEEE80211_ADDR_LEN);
323                         /* clear group bit, add local bit */
324                         ni->ni_bssid[0] = (ni->ni_bssid[0] &~ 0x01) | 0x02;
325                 }
326         } else if (ic->ic_opmode == IEEE80211_M_AHDEMO) {
327                 if (ic->ic_flags & IEEE80211_F_DESBSSID)
328                         IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_des_bssid);
329                 else
330                         memset(ni->ni_bssid, 0, IEEE80211_ADDR_LEN);
331         }
332         /* 
333          * Fix the channel and related attributes.
334          */
335         ic->ic_bsschan = chan;
336         ieee80211_node_set_chan(ic, ni);
337         ic->ic_curmode = ieee80211_chan2mode(chan);
338         /*
339          * Do mode-specific rate setup.
340          */
341         if (IEEE80211_IS_CHAN_FULL(chan)) {
342                 if (IEEE80211_IS_CHAN_ANYG(chan)) {
343                         /*
344                          * Use a mixed 11b/11g rate set.
345                          */
346                         ieee80211_set11gbasicrates(&ni->ni_rates,
347                                 IEEE80211_MODE_11G);
348                 } else if (IEEE80211_IS_CHAN_B(chan)) {
349                         /*
350                          * Force pure 11b rate set.
351                          */
352                         ieee80211_set11gbasicrates(&ni->ni_rates,
353                                 IEEE80211_MODE_11B);
354                 }
355         }
356
357         (void) ieee80211_sta_join1(ieee80211_ref_node(ni));
358 }
359
360 /*
361  * Reset bss state on transition to the INIT state.
362  * Clear any stations from the table (they have been
363  * deauth'd) and reset the bss node (clears key, rate
364  * etc. state).
365  */
366 void
367 ieee80211_reset_bss(struct ieee80211com *ic)
368 {
369         struct ieee80211_node *ni, *obss;
370
371         callout_drain(&ic->ic_inact);
372         ieee80211_node_table_reset(&ic->ic_sta);
373         ieee80211_reset_erp(ic);
374
375         ni = ieee80211_alloc_node(&ic->ic_sta, ic->ic_myaddr);
376         KASSERT(ni != NULL, ("unable to setup inital BSS node"));
377         obss = ic->ic_bss;
378         ic->ic_bss = ieee80211_ref_node(ni);
379         if (obss != NULL) {
380                 copy_bss(ni, obss);
381                 ni->ni_intval = ic->ic_bintval;
382                 ieee80211_free_node(obss);
383         }
384 }
385
386 static int
387 match_ssid(const struct ieee80211_node *ni,
388         int nssid, const struct ieee80211_scan_ssid ssids[])
389 {
390         int i;
391
392         for (i = 0; i < nssid; i++) {
393                 if (ni->ni_esslen == ssids[i].len &&
394                      memcmp(ni->ni_essid, ssids[i].ssid, ni->ni_esslen) == 0)
395                         return 1;
396         }
397         return 0;
398 }
399
400 /*
401  * Test a node for suitability/compatibility.
402  */
403 static int
404 check_bss(struct ieee80211com *ic, struct ieee80211_node *ni)
405 {
406         uint8_t rate;
407
408         if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
409                 return 0;
410         if (ic->ic_opmode == IEEE80211_M_IBSS) {
411                 if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
412                         return 0;
413         } else {
414                 if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
415                         return 0;
416         }
417         if (ic->ic_flags & IEEE80211_F_PRIVACY) {
418                 if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
419                         return 0;
420         } else {
421                 /* XXX does this mean privacy is supported or required? */
422                 if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
423                         return 0;
424         }
425         rate = ieee80211_fix_rate(ni, &ni->ni_rates,
426             IEEE80211_F_JOIN | IEEE80211_F_DONEGO | IEEE80211_F_DOFRATE);
427         if (rate & IEEE80211_RATE_BASIC)
428                 return 0;
429         if (ic->ic_des_nssid != 0 &&
430             !match_ssid(ni, ic->ic_des_nssid, ic->ic_des_ssid))
431                 return 0;
432         if ((ic->ic_flags & IEEE80211_F_DESBSSID) &&
433             !IEEE80211_ADDR_EQ(ic->ic_des_bssid, ni->ni_bssid))
434                 return 0;
435         return 1;
436 }
437
438 #ifdef IEEE80211_DEBUG
439 /*
440  * Display node suitability/compatibility.
441  */
442 static void
443 check_bss_debug(struct ieee80211com *ic, struct ieee80211_node *ni)
444 {
445         uint8_t rate;
446         int fail;
447
448         fail = 0;
449         if (isclr(ic->ic_chan_active, ieee80211_chan2ieee(ic, ni->ni_chan)))
450                 fail |= 0x01;
451         if (ic->ic_opmode == IEEE80211_M_IBSS) {
452                 if ((ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) == 0)
453                         fail |= 0x02;
454         } else {
455                 if ((ni->ni_capinfo & IEEE80211_CAPINFO_ESS) == 0)
456                         fail |= 0x02;
457         }
458         if (ic->ic_flags & IEEE80211_F_PRIVACY) {
459                 if ((ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) == 0)
460                         fail |= 0x04;
461         } else {
462                 /* XXX does this mean privacy is supported or required? */
463                 if (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY)
464                         fail |= 0x04;
465         }
466         rate = ieee80211_fix_rate(ni, &ni->ni_rates,
467              IEEE80211_F_JOIN | IEEE80211_F_DONEGO | IEEE80211_F_DOFRATE);
468         if (rate & IEEE80211_RATE_BASIC)
469                 fail |= 0x08;
470         if (ic->ic_des_nssid != 0 &&
471             !match_ssid(ni, ic->ic_des_nssid, ic->ic_des_ssid))
472                 fail |= 0x10;
473         if ((ic->ic_flags & IEEE80211_F_DESBSSID) &&
474             !IEEE80211_ADDR_EQ(ic->ic_des_bssid, ni->ni_bssid))
475                 fail |= 0x20;
476
477         printf(" %c %s", fail ? '-' : '+', ether_sprintf(ni->ni_macaddr));
478         printf(" %s%c", ether_sprintf(ni->ni_bssid), fail & 0x20 ? '!' : ' ');
479         printf(" %3d%c",
480             ieee80211_chan2ieee(ic, ni->ni_chan), fail & 0x01 ? '!' : ' ');
481         printf(" %+4d", ni->ni_rssi);
482         printf(" %2dM%c", (rate & IEEE80211_RATE_VAL) / 2,
483             fail & 0x08 ? '!' : ' ');
484         printf(" %4s%c",
485             (ni->ni_capinfo & IEEE80211_CAPINFO_ESS) ? "ess" :
486             (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS) ? "ibss" :
487             "????",
488             fail & 0x02 ? '!' : ' ');
489         printf(" %3s%c ",
490             (ni->ni_capinfo & IEEE80211_CAPINFO_PRIVACY) ?  "wep" : "no",
491             fail & 0x04 ? '!' : ' ');
492         ieee80211_print_essid(ni->ni_essid, ni->ni_esslen);
493         printf("%s\n", fail & 0x10 ? "!" : "");
494 }
495 #endif /* IEEE80211_DEBUG */
496  
497 /*
498  * Handle 802.11 ad hoc network merge.  The
499  * convention, set by the Wireless Ethernet Compatibility Alliance
500  * (WECA), is that an 802.11 station will change its BSSID to match
501  * the "oldest" 802.11 ad hoc network, on the same channel, that
502  * has the station's desired SSID.  The "oldest" 802.11 network
503  * sends beacons with the greatest TSF timestamp.
504  *
505  * The caller is assumed to validate TSF's before attempting a merge.
506  *
507  * Return !0 if the BSSID changed, 0 otherwise.
508  */
509 int
510 ieee80211_ibss_merge(struct ieee80211_node *ni)
511 {
512         struct ieee80211com *ic = ni->ni_ic;
513
514         if (ni == ic->ic_bss ||
515             IEEE80211_ADDR_EQ(ni->ni_bssid, ic->ic_bss->ni_bssid)) {
516                 /* unchanged, nothing to do */
517                 return 0;
518         }
519         if (!check_bss(ic, ni)) {
520                 /* capabilities mismatch */
521                 IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
522                     "%s: merge failed, capabilities mismatch\n", __func__);
523 #ifdef IEEE80211_DEBUG
524                 if (ieee80211_msg_assoc(ic))
525                         check_bss_debug(ic, ni);
526 #endif
527                 ic->ic_stats.is_ibss_capmismatch++;
528                 return 0;
529         }
530         IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
531                 "%s: new bssid %s: %s preamble, %s slot time%s\n", __func__,
532                 ether_sprintf(ni->ni_bssid),
533                 ic->ic_flags&IEEE80211_F_SHPREAMBLE ? "short" : "long",
534                 ic->ic_flags&IEEE80211_F_SHSLOT ? "short" : "long",
535                 ic->ic_flags&IEEE80211_F_USEPROT ? ", protection" : ""
536         );
537         return ieee80211_sta_join1(ieee80211_ref_node(ni));
538 }
539
540 /*
541  * Change the bss channel.
542  */
543 void
544 ieee80211_setbsschan(struct ieee80211com *ic, struct ieee80211_channel *c)
545 {
546         ic->ic_bsschan = c;
547         ic->ic_curchan = ic->ic_bsschan;
548         ic->ic_curmode = ieee80211_chan2mode(ic->ic_curchan);
549         ic->ic_set_channel(ic);
550 }
551
552 /*
553  * Join the specified IBSS/BSS network.  The node is assumed to
554  * be passed in with a held reference.
555  */
556 static int
557 ieee80211_sta_join1(struct ieee80211_node *selbs)
558 {
559         struct ieee80211com *ic = selbs->ni_ic;
560         struct ieee80211_node *obss;
561         int canreassoc;
562
563         if (ic->ic_opmode == IEEE80211_M_IBSS) {
564                 struct ieee80211_node_table *nt;
565                 /*
566                  * Fillin the neighbor table; it will already
567                  * exist if we are simply switching mastership.
568                  * XXX ic_sta always setup so this is unnecessary?
569                  */
570                 nt = &ic->ic_sta;
571                 IEEE80211_NODE_LOCK(nt);
572                 nt->nt_name = "neighbor";
573                 nt->nt_inact_init = ic->ic_inact_run;
574                 IEEE80211_NODE_UNLOCK(nt);
575         }
576
577         /*
578          * Committed to selbs, setup state.
579          */
580         obss = ic->ic_bss;
581         /*
582          * Check if old+new node have the same address in which
583          * case we can reassociate when operating in sta mode.
584          */
585         canreassoc = (obss != NULL &&
586                 ic->ic_state == IEEE80211_S_RUN &&
587                 IEEE80211_ADDR_EQ(obss->ni_macaddr, selbs->ni_macaddr));
588         ic->ic_bss = selbs;             /* NB: caller assumed to bump refcnt */
589         if (obss != NULL) {
590                 copy_bss(selbs, obss);
591                 ieee80211_free_node(obss);
592         }
593
594         /*
595          * Delete unusable rates; we've already checked
596          * that the negotiated rate set is acceptable.
597          */
598         ieee80211_fix_rate(ic->ic_bss, &ic->ic_bss->ni_rates,
599                 IEEE80211_F_DODEL | IEEE80211_F_JOIN);
600
601         ieee80211_setbsschan(ic, selbs->ni_chan);
602         /*
603          * Set the erp state (mostly the slot time) to deal with
604          * the auto-select case; this should be redundant if the
605          * mode is locked.
606          */ 
607         ieee80211_reset_erp(ic);
608         ieee80211_wme_initparams(ic);
609
610         if (ic->ic_opmode == IEEE80211_M_STA) {
611                 if (canreassoc) {
612                         /* Reassociate */
613                         ieee80211_new_state(ic, IEEE80211_S_ASSOC, 1);
614                 } else {
615                         /*
616                          * Act as if we received a DEAUTH frame in case we
617                          * are invoked from the RUN state.  This will cause
618                          * us to try to re-authenticate if we are operating
619                          * as a station.
620                          */
621                         ieee80211_new_state(ic, IEEE80211_S_AUTH,
622                                 IEEE80211_FC0_SUBTYPE_DEAUTH);
623                 }
624         } else
625                 ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
626         return 1;
627 }
628
629 int
630 ieee80211_sta_join(struct ieee80211com *ic,
631         const struct ieee80211_scan_entry *se)
632 {
633         struct ieee80211_node *ni;
634
635         ni = ieee80211_alloc_node(&ic->ic_sta, se->se_macaddr);
636         if (ni == NULL) {
637                 /* XXX msg */
638                 return 0;
639         }
640         /*
641          * Expand scan state into node's format.
642          * XXX may not need all this stuff
643          */
644         IEEE80211_ADDR_COPY(ni->ni_bssid, se->se_bssid);
645         ni->ni_esslen = se->se_ssid[1];
646         memcpy(ni->ni_essid, se->se_ssid+2, ni->ni_esslen);
647         ni->ni_rstamp = se->se_rstamp;
648         ni->ni_tstamp.tsf = se->se_tstamp.tsf;
649         ni->ni_intval = se->se_intval;
650         ni->ni_capinfo = se->se_capinfo;
651         ni->ni_chan = se->se_chan;
652         ni->ni_timoff = se->se_timoff;
653         ni->ni_fhdwell = se->se_fhdwell;
654         ni->ni_fhindex = se->se_fhindex;
655         ni->ni_erp = se->se_erp;
656         ni->ni_rssi = se->se_rssi;
657         ni->ni_noise = se->se_noise;
658
659         if (ieee80211_ies_init(&ni->ni_ies, se->se_ies.data, se->se_ies.len)) {
660                 ieee80211_ies_expand(&ni->ni_ies);
661                 if (ni->ni_ies.ath_ie != NULL)
662                         ieee80211_parse_ath(ni, ni->ni_ies.ath_ie);
663                 if (ni->ni_ies.htcap_ie != NULL)
664                         ieee80211_parse_htcap(ni, ni->ni_ies.htcap_ie);
665                 if (ni->ni_ies.htinfo_ie != NULL)
666                         ieee80211_parse_htinfo(ni, ni->ni_ies.htinfo_ie);
667         }
668
669         ic->ic_dtim_period = se->se_dtimperiod;
670         ic->ic_dtim_count = 0;
671
672         /* NB: must be after ni_chan is setup */
673         ieee80211_setup_rates(ni, se->se_rates, se->se_xrates,
674                 IEEE80211_F_DOSORT);
675
676         return ieee80211_sta_join1(ieee80211_ref_node(ni));
677 }
678
679 /*
680  * Leave the specified IBSS/BSS network.  The node is assumed to
681  * be passed in with a held reference.
682  */
683 void
684 ieee80211_sta_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
685 {
686         ic->ic_node_cleanup(ni);
687         ieee80211_notify_node_leave(ic, ni);
688 }
689
690 static struct ieee80211_node *
691 node_alloc(struct ieee80211_node_table *nt)
692 {
693         struct ieee80211_node *ni;
694
695         MALLOC(ni, struct ieee80211_node *, sizeof(struct ieee80211_node),
696                 M_80211_NODE, M_NOWAIT | M_ZERO);
697         return ni;
698 }
699
700 /*
701  * Initialize an ie blob with the specified data.  If previous
702  * data exists re-use the data block.  As a side effect we clear
703  * all references to specific ie's; the caller is required to
704  * recalculate them.
705  */
706 int
707 ieee80211_ies_init(struct ieee80211_ies *ies, const uint8_t *data, int len)
708 {
709         /* NB: assumes data+len are the last fields */
710         memset(ies, 0, offsetof(struct ieee80211_ies, data));
711         if (ies->data != NULL && ies->len != len) {
712                 /* data size changed */
713                 FREE(ies->data, M_80211_NODE_IE);
714                 ies->data = NULL;
715         }
716         if (ies->data == NULL) {
717                 MALLOC(ies->data, uint8_t *, len, M_80211_NODE_IE, M_NOWAIT);
718                 if (ies->data == NULL) {
719                         ies->len = 0;
720                         /* NB: pointers have already been zero'd above */
721                         return 0;
722                 }
723         }
724         memcpy(ies->data, data, len);
725         ies->len = len;
726         return 1;
727 }
728
729 /*
730  * Reclaim storage for an ie blob.
731  */
732 void
733 ieee80211_ies_cleanup(struct ieee80211_ies *ies)
734 {
735         if (ies->data != NULL)
736                 FREE(ies->data, M_80211_NODE_IE);
737 }
738
739 /*
740  * Expand an ie blob data contents and to fillin individual
741  * ie pointers.  The data blob is assumed to be well-formed;
742  * we don't do any validity checking of ie lengths.
743  */
744 void
745 ieee80211_ies_expand(struct ieee80211_ies *ies)
746 {
747         uint8_t *ie;
748         int ielen;
749
750         ie = ies->data;
751         ielen = ies->len;
752         while (ielen > 0) {
753                 switch (ie[0]) {
754                 case IEEE80211_ELEMID_VENDOR:
755                         if (iswpaoui(ie))
756                                 ies->wpa_ie = ie;
757                         else if (iswmeoui(ie))
758                                 ies->wme_ie = ie;
759                         else if (isatherosoui(ie))
760                                 ies->ath_ie = ie;
761                         break;
762                 case IEEE80211_ELEMID_RSN:
763                         ies->rsn_ie = ie;
764                         break;
765                 case IEEE80211_ELEMID_HTCAP:
766                         ies->htcap_ie = ie;
767                         break;
768                 }
769                 ielen -= 2 + ie[1];
770                 ie += 2 + ie[1];
771         }
772 }
773
774 /*
775  * Reclaim any resources in a node and reset any critical
776  * state.  Typically nodes are free'd immediately after,
777  * but in some cases the storage may be reused so we need
778  * to insure consistent state (should probably fix that).
779  */
780 static void
781 node_cleanup(struct ieee80211_node *ni)
782 {
783 #define N(a)    (sizeof(a)/sizeof(a[0]))
784         struct ieee80211com *ic = ni->ni_ic;
785         int i;
786
787         /* NB: preserve ni_table */
788         if (ni->ni_flags & IEEE80211_NODE_PWR_MGT) {
789                 if (ic->ic_opmode != IEEE80211_M_STA)
790                         ic->ic_ps_sta--;
791                 ni->ni_flags &= ~IEEE80211_NODE_PWR_MGT;
792                 IEEE80211_DPRINTF(ic, IEEE80211_MSG_POWER,
793                     "[%s] power save mode off, %u sta's in ps mode\n",
794                     ether_sprintf(ni->ni_macaddr), ic->ic_ps_sta);
795         }
796         /*
797          * Cleanup any HT-related state.
798          */
799         if (ni->ni_flags & IEEE80211_NODE_HT)
800                 ieee80211_ht_node_cleanup(ni);
801         /*
802          * Clear AREF flag that marks the authorization refcnt bump
803          * has happened.  This is probably not needed as the node
804          * should always be removed from the table so not found but
805          * do it just in case.
806          */
807         ni->ni_flags &= ~IEEE80211_NODE_AREF;
808
809         /*
810          * Drain power save queue and, if needed, clear TIM.
811          */
812         if (ieee80211_node_saveq_drain(ni) != 0 && ic->ic_set_tim != NULL)
813                 ic->ic_set_tim(ni, 0);
814
815         ni->ni_associd = 0;
816         if (ni->ni_challenge != NULL) {
817                 FREE(ni->ni_challenge, M_80211_NODE);
818                 ni->ni_challenge = NULL;
819         }
820         /*
821          * Preserve SSID, WPA, and WME ie's so the bss node is
822          * reusable during a re-auth/re-assoc state transition.
823          * If we remove these data they will not be recreated
824          * because they come from a probe-response or beacon frame
825          * which cannot be expected prior to the association-response.
826          * This should not be an issue when operating in other modes
827          * as stations leaving always go through a full state transition
828          * which will rebuild this state.
829          *
830          * XXX does this leave us open to inheriting old state?
831          */
832         for (i = 0; i < N(ni->ni_rxfrag); i++)
833                 if (ni->ni_rxfrag[i] != NULL) {
834                         m_freem(ni->ni_rxfrag[i]);
835                         ni->ni_rxfrag[i] = NULL;
836                 }
837         /*
838          * Must be careful here to remove any key map entry w/o a LOR.
839          */
840         ieee80211_node_delucastkey(ni);
841 #undef N
842 }
843
844 static void
845 node_free(struct ieee80211_node *ni)
846 {
847         struct ieee80211com *ic = ni->ni_ic;
848
849         ic->ic_node_cleanup(ni);
850         ieee80211_ies_cleanup(&ni->ni_ies);
851         IEEE80211_NODE_SAVEQ_DESTROY(ni);
852         FREE(ni, M_80211_NODE);
853 }
854
855 static int8_t
856 node_getrssi(const struct ieee80211_node *ni)
857 {
858         return ni->ni_rssi;
859 }
860
861 static void
862 node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
863 {
864         *rssi = ni->ni_rssi;
865         *noise = ni->ni_noise;
866 }
867
868 static void
869 ieee80211_setup_node(struct ieee80211_node_table *nt,
870         struct ieee80211_node *ni, const uint8_t *macaddr)
871 {
872         struct ieee80211com *ic = nt->nt_ic;
873         int hash;
874
875         IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
876                 "%s %p<%s> in %s table\n", __func__, ni,
877                 ether_sprintf(macaddr), nt->nt_name);
878
879         IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
880         hash = IEEE80211_NODE_HASH(macaddr);
881         ieee80211_node_initref(ni);             /* mark referenced */
882         ni->ni_chan = IEEE80211_CHAN_ANYC;
883         ni->ni_authmode = IEEE80211_AUTH_OPEN;
884         ni->ni_txpower = ic->ic_txpowlimit;     /* max power */
885         ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey, IEEE80211_KEYIX_NONE);
886         ni->ni_inact_reload = nt->nt_inact_init;
887         ni->ni_inact = ni->ni_inact_reload;
888         ni->ni_ath_defkeyix = 0x7fff;
889         IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
890
891         IEEE80211_NODE_LOCK(nt);
892         TAILQ_INSERT_TAIL(&nt->nt_node, ni, ni_list);
893         LIST_INSERT_HEAD(&nt->nt_hash[hash], ni, ni_hash);
894         ni->ni_table = nt;
895         ni->ni_ic = ic;
896         IEEE80211_NODE_UNLOCK(nt);
897 }
898
899 struct ieee80211_node *
900 ieee80211_alloc_node(struct ieee80211_node_table *nt, const uint8_t *macaddr)
901 {
902         struct ieee80211com *ic = nt->nt_ic;
903         struct ieee80211_node *ni;
904
905         ni = ic->ic_node_alloc(nt);
906         if (ni != NULL)
907                 ieee80211_setup_node(nt, ni, macaddr);
908         else
909                 ic->ic_stats.is_rx_nodealloc++;
910         return ni;
911 }
912
913 /*
914  * Craft a temporary node suitable for sending a management frame
915  * to the specified station.  We craft only as much state as we
916  * need to do the work since the node will be immediately reclaimed
917  * once the send completes.
918  */
919 struct ieee80211_node *
920 ieee80211_tmp_node(struct ieee80211com *ic, const uint8_t *macaddr)
921 {
922         struct ieee80211_node *ni;
923
924         ni = ic->ic_node_alloc(&ic->ic_sta);
925         if (ni != NULL) {
926                 IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
927                         "%s %p<%s>\n", __func__, ni, ether_sprintf(macaddr));
928
929                 IEEE80211_ADDR_COPY(ni->ni_macaddr, macaddr);
930                 IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
931                 ieee80211_node_initref(ni);             /* mark referenced */
932                 ni->ni_txpower = ic->ic_bss->ni_txpower;
933                 /* NB: required by ieee80211_fix_rate */
934                 ieee80211_node_set_chan(ic, ni);
935                 ieee80211_crypto_resetkey(ic, &ni->ni_ucastkey,
936                         IEEE80211_KEYIX_NONE);
937                 /* XXX optimize away */
938                 IEEE80211_NODE_SAVEQ_INIT(ni, "unknown");
939
940                 ni->ni_table = NULL;            /* NB: pedantic */
941                 ni->ni_ic = ic;
942         } else {
943                 /* XXX msg */
944                 ic->ic_stats.is_rx_nodealloc++;
945         }
946         return ni;
947 }
948
949 struct ieee80211_node *
950 ieee80211_dup_bss(struct ieee80211_node_table *nt, const uint8_t *macaddr)
951 {
952         struct ieee80211com *ic = nt->nt_ic;
953         struct ieee80211_node *ni;
954
955         ni = ic->ic_node_alloc(nt);
956         if (ni != NULL) {
957                 ieee80211_setup_node(nt, ni, macaddr);
958                 /*
959                  * Inherit from ic_bss.
960                  */
961                 ni->ni_authmode = ic->ic_bss->ni_authmode;
962                 ni->ni_txpower = ic->ic_bss->ni_txpower;
963                 ni->ni_vlan = ic->ic_bss->ni_vlan;      /* XXX?? */
964                 IEEE80211_ADDR_COPY(ni->ni_bssid, ic->ic_bss->ni_bssid);
965                 ieee80211_node_set_chan(ic, ni);
966                 ni->ni_rsn = ic->ic_bss->ni_rsn;
967         } else
968                 ic->ic_stats.is_rx_nodealloc++;
969         return ni;
970 }
971
972 static struct ieee80211_node *
973 #ifdef IEEE80211_DEBUG_REFCNT
974 _ieee80211_find_node_debug(struct ieee80211_node_table *nt,
975         const uint8_t *macaddr, const char *func, int line)
976 #else
977 _ieee80211_find_node(struct ieee80211_node_table *nt,
978         const uint8_t *macaddr)
979 #endif
980 {
981         struct ieee80211_node *ni;
982         int hash;
983
984         IEEE80211_NODE_LOCK_ASSERT(nt);
985
986         hash = IEEE80211_NODE_HASH(macaddr);
987         LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
988                 if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr)) {
989                         ieee80211_ref_node(ni); /* mark referenced */
990 #ifdef IEEE80211_DEBUG_REFCNT
991                         IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
992                             "%s (%s:%u) %p<%s> refcnt %d\n", __func__,
993                             func, line,
994                             ni, ether_sprintf(ni->ni_macaddr),
995                             ieee80211_node_refcnt(ni));
996 #endif
997                         return ni;
998                 }
999         }
1000         return NULL;
1001 }
1002 #ifdef IEEE80211_DEBUG_REFCNT
1003 #define _ieee80211_find_node(nt, mac) \
1004         _ieee80211_find_node_debug(nt, mac, func, line)
1005 #endif
1006
1007 struct ieee80211_node *
1008 #ifdef IEEE80211_DEBUG_REFCNT
1009 ieee80211_find_node_debug(struct ieee80211_node_table *nt,
1010         const uint8_t *macaddr, const char *func, int line)
1011 #else
1012 ieee80211_find_node(struct ieee80211_node_table *nt, const uint8_t *macaddr)
1013 #endif
1014 {
1015         struct ieee80211_node *ni;
1016
1017         IEEE80211_NODE_LOCK(nt);
1018         ni = _ieee80211_find_node(nt, macaddr);
1019         IEEE80211_NODE_UNLOCK(nt);
1020         return ni;
1021 }
1022
1023 /*
1024  * Fake up a node; this handles node discovery in adhoc mode.
1025  * Note that for the driver's benefit we we treat this like
1026  * an association so the driver has an opportunity to setup
1027  * it's private state.
1028  */
1029 struct ieee80211_node *
1030 ieee80211_fakeup_adhoc_node(struct ieee80211_node_table *nt,
1031         const uint8_t macaddr[IEEE80211_ADDR_LEN])
1032 {
1033         struct ieee80211com *ic = nt->nt_ic;
1034         struct ieee80211_node *ni;
1035
1036         IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1037             "%s: mac<%s>\n", __func__, ether_sprintf(macaddr));
1038         ni = ieee80211_dup_bss(nt, macaddr);
1039         if (ni != NULL) {
1040                 /* XXX no rate negotiation; just dup */
1041                 ni->ni_rates = ic->ic_bss->ni_rates;
1042                 if (ic->ic_newassoc != NULL)
1043                         ic->ic_newassoc(ni, 1);
1044                 if (ic->ic_opmode == IEEE80211_M_AHDEMO) {
1045                         /*
1046                          * In adhoc demo mode there are no management
1047                          * frames to use to discover neighbor capabilities,
1048                          * so blindly propagate the local configuration 
1049                          * so we can do interesting things (e.g. use
1050                          * WME to disable ACK's).
1051                          */
1052                         if (ic->ic_flags & IEEE80211_F_WME)
1053                                 ni->ni_flags |= IEEE80211_NODE_QOS;
1054                         if (ic->ic_flags & IEEE80211_F_FF)
1055                                 ni->ni_flags |= IEEE80211_NODE_FF;
1056                 }
1057                 /* XXX not right for 802.1x/WPA */
1058                 ieee80211_node_authorize(ni);
1059         }
1060         return ni;
1061 }
1062
1063 void
1064 ieee80211_init_neighbor(struct ieee80211_node *ni,
1065         const struct ieee80211_frame *wh,
1066         const struct ieee80211_scanparams *sp)
1067 {
1068         ni->ni_esslen = sp->ssid[1];
1069         memcpy(ni->ni_essid, sp->ssid + 2, sp->ssid[1]);
1070         IEEE80211_ADDR_COPY(ni->ni_bssid, wh->i_addr3);
1071         memcpy(ni->ni_tstamp.data, sp->tstamp, sizeof(ni->ni_tstamp));
1072         ni->ni_intval = sp->bintval;
1073         ni->ni_capinfo = sp->capinfo;
1074         ni->ni_chan = ni->ni_ic->ic_curchan;
1075         ni->ni_fhdwell = sp->fhdwell;
1076         ni->ni_fhindex = sp->fhindex;
1077         ni->ni_erp = sp->erp;
1078         ni->ni_timoff = sp->timoff;
1079
1080         if (ieee80211_ies_init(&ni->ni_ies, sp->ies, sp->ies_len)) {
1081                 ieee80211_ies_expand(&ni->ni_ies);
1082                 if (ni->ni_ies.ath_ie != NULL)
1083                         ieee80211_parse_ath(ni, ni->ni_ies.ath_ie);
1084         }
1085
1086         /* NB: must be after ni_chan is setup */
1087         ieee80211_setup_rates(ni, sp->rates, sp->xrates,
1088                 IEEE80211_F_DOSORT | IEEE80211_F_DOFRATE |
1089                 IEEE80211_F_DONEGO | IEEE80211_F_DODEL);
1090 }
1091
1092 /*
1093  * Do node discovery in adhoc mode on receipt of a beacon
1094  * or probe response frame.  Note that for the driver's
1095  * benefit we we treat this like an association so the
1096  * driver has an opportunity to setup it's private state.
1097  */
1098 struct ieee80211_node *
1099 ieee80211_add_neighbor(struct ieee80211com *ic,
1100         const struct ieee80211_frame *wh,
1101         const struct ieee80211_scanparams *sp)
1102 {
1103         struct ieee80211_node *ni;
1104
1105         IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1106             "%s: mac<%s>\n", __func__, ether_sprintf(wh->i_addr2));
1107         ni = ieee80211_dup_bss(&ic->ic_sta, wh->i_addr2);/* XXX alloc_node? */
1108         if (ni != NULL) {
1109                 ieee80211_init_neighbor(ni, wh, sp);
1110                 if (ic->ic_newassoc != NULL)
1111                         ic->ic_newassoc(ni, 1);
1112                 /* XXX not right for 802.1x/WPA */
1113                 ieee80211_node_authorize(ni);
1114         }
1115         return ni;
1116 }
1117
1118 #define IS_CTL(wh) \
1119         ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_CTL)
1120 #define IS_PSPOLL(wh) \
1121         ((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_PS_POLL)
1122 #define IS_BAR(wh) \
1123         ((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) == IEEE80211_FC0_SUBTYPE_BAR)
1124
1125 /*
1126  * Locate the node for sender, track state, and then pass the
1127  * (referenced) node up to the 802.11 layer for its use.  We
1128  * are required to pass some node so we fall back to ic_bss
1129  * when this frame is from an unknown sender.  The 802.11 layer
1130  * knows this means the sender wasn't in the node table and
1131  * acts accordingly. 
1132  */
1133 struct ieee80211_node *
1134 #ifdef IEEE80211_DEBUG_REFCNT
1135 ieee80211_find_rxnode_debug(struct ieee80211com *ic,
1136         const struct ieee80211_frame_min *wh, const char *func, int line)
1137 #else
1138 ieee80211_find_rxnode(struct ieee80211com *ic,
1139         const struct ieee80211_frame_min *wh)
1140 #endif
1141 {
1142         struct ieee80211_node_table *nt;
1143         struct ieee80211_node *ni;
1144
1145         /* XXX check ic_bss first in station mode */
1146         /* XXX 4-address frames? */
1147         nt = &ic->ic_sta;
1148         IEEE80211_NODE_LOCK(nt);
1149         if (IS_CTL(wh) && !IS_PSPOLL(wh) && !IS_BAR(wh) /*&& !IS_RTS(ah)*/)
1150                 ni = _ieee80211_find_node(nt, wh->i_addr1);
1151         else
1152                 ni = _ieee80211_find_node(nt, wh->i_addr2);
1153         if (ni == NULL)
1154                 ni = ieee80211_ref_node(ic->ic_bss);
1155         IEEE80211_NODE_UNLOCK(nt);
1156
1157         return ni;
1158 }
1159
1160 /*
1161  * Like ieee80211_find_rxnode but use the supplied h/w
1162  * key index as a hint to locate the node in the key
1163  * mapping table.  If an entry is present at the key
1164  * index we return it; otherwise do a normal lookup and
1165  * update the mapping table if the station has a unicast
1166  * key assigned to it.
1167  */
1168 struct ieee80211_node *
1169 #ifdef IEEE80211_DEBUG_REFCNT
1170 ieee80211_find_rxnode_withkey_debug(struct ieee80211com *ic,
1171         const struct ieee80211_frame_min *wh, ieee80211_keyix keyix,
1172         const char *func, int line)
1173 #else
1174 ieee80211_find_rxnode_withkey(struct ieee80211com *ic,
1175         const struct ieee80211_frame_min *wh, ieee80211_keyix keyix)
1176 #endif
1177 {
1178         struct ieee80211_node_table *nt;
1179         struct ieee80211_node *ni;
1180
1181         nt = &ic->ic_sta;
1182         IEEE80211_NODE_LOCK(nt);
1183         if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax)
1184                 ni = nt->nt_keyixmap[keyix];
1185         else
1186                 ni = NULL;
1187         if (ni == NULL) {
1188                 if (IS_CTL(wh) && !IS_PSPOLL(wh) && !IS_BAR(wh) /*&& !IS_RTS(ah)*/)
1189                         ni = _ieee80211_find_node(nt, wh->i_addr1);
1190                 else
1191                         ni = _ieee80211_find_node(nt, wh->i_addr2);
1192                 if (ni == NULL)
1193                         ni = ieee80211_ref_node(ic->ic_bss);
1194                 if (nt->nt_keyixmap != NULL) {
1195                         /*
1196                          * If the station has a unicast key cache slot
1197                          * assigned update the key->node mapping table.
1198                          */
1199                         keyix = ni->ni_ucastkey.wk_rxkeyix;
1200                         /* XXX can keyixmap[keyix] != NULL? */
1201                         if (keyix < nt->nt_keyixmax &&
1202                             nt->nt_keyixmap[keyix] == NULL) {
1203                                 IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1204                                     "%s: add key map entry %p<%s> refcnt %d\n",
1205                                     __func__, ni, ether_sprintf(ni->ni_macaddr),
1206                                     ieee80211_node_refcnt(ni)+1);
1207                                 nt->nt_keyixmap[keyix] = ieee80211_ref_node(ni);
1208                         }
1209                 }
1210         } else
1211                 ieee80211_ref_node(ni);
1212         IEEE80211_NODE_UNLOCK(nt);
1213
1214         return ni;
1215 }
1216 #undef IS_BAR
1217 #undef IS_PSPOLL
1218 #undef IS_CTL
1219
1220 /*
1221  * Return a reference to the appropriate node for sending
1222  * a data frame.  This handles node discovery in adhoc networks.
1223  */
1224 struct ieee80211_node *
1225 #ifdef IEEE80211_DEBUG_REFCNT
1226 ieee80211_find_txnode_debug(struct ieee80211com *ic, const uint8_t *macaddr,
1227         const char *func, int line)
1228 #else
1229 ieee80211_find_txnode(struct ieee80211com *ic, const uint8_t *macaddr)
1230 #endif
1231 {
1232         struct ieee80211_node_table *nt = &ic->ic_sta;
1233         struct ieee80211_node *ni;
1234
1235         /*
1236          * The destination address should be in the node table
1237          * unless this is a multicast/broadcast frame.  We can
1238          * also optimize station mode operation, all frames go
1239          * to the bss node.
1240          */
1241         /* XXX can't hold lock across dup_bss 'cuz of recursive locking */
1242         IEEE80211_NODE_LOCK(nt);
1243         if (ic->ic_opmode == IEEE80211_M_STA || IEEE80211_IS_MULTICAST(macaddr))
1244                 ni = ieee80211_ref_node(ic->ic_bss);
1245         else {
1246                 ni = _ieee80211_find_node(nt, macaddr);
1247                 if (ic->ic_opmode == IEEE80211_M_HOSTAP && 
1248                     (ni != NULL && ni->ni_associd == 0)) {
1249                         /*
1250                          * Station is not associated; don't permit the
1251                          * data frame to be sent by returning NULL.  This
1252                          * is kinda a kludge but the least intrusive way
1253                          * to add this check into all drivers.
1254                          */
1255                         ieee80211_unref_node(&ni);      /* NB: null's ni */
1256                 }
1257         }
1258         IEEE80211_NODE_UNLOCK(nt);
1259
1260         if (ni == NULL) {
1261                 if (ic->ic_opmode == IEEE80211_M_IBSS ||
1262                     ic->ic_opmode == IEEE80211_M_AHDEMO) {
1263                         /*
1264                          * In adhoc mode cons up a node for the destination.
1265                          * Note that we need an additional reference for the
1266                          * caller to be consistent with _ieee80211_find_node.
1267                          */
1268                         ni = ieee80211_fakeup_adhoc_node(nt, macaddr);
1269                         if (ni != NULL)
1270                                 (void) ieee80211_ref_node(ni);
1271                 } else {
1272                         IEEE80211_DPRINTF(ic, IEEE80211_MSG_OUTPUT,
1273                                 "[%s] no node, discard frame (%s)\n",
1274                                 ether_sprintf(macaddr), __func__);
1275                         ic->ic_stats.is_tx_nonode++;
1276                 }
1277         }
1278         return ni;
1279 }
1280
1281 /*
1282  * Like find but search based on the ssid too.
1283  */
1284 struct ieee80211_node *
1285 #ifdef IEEE80211_DEBUG_REFCNT
1286 ieee80211_find_node_with_ssid_debug(struct ieee80211_node_table *nt,
1287         const uint8_t *macaddr, u_int ssidlen, const uint8_t *ssid,
1288         const char *func, int line)
1289 #else
1290 ieee80211_find_node_with_ssid(struct ieee80211_node_table *nt,
1291         const uint8_t *macaddr, u_int ssidlen, const uint8_t *ssid)
1292 #endif
1293 {
1294 #define MATCH_SSID(ni, ssid, ssidlen) \
1295         (ni->ni_esslen == ssidlen && memcmp(ni->ni_essid, ssid, ssidlen) == 0)
1296         static const uint8_t zeromac[IEEE80211_ADDR_LEN];
1297         struct ieee80211_node *ni;
1298         int hash;
1299
1300         IEEE80211_NODE_LOCK(nt);
1301         /*
1302          * A mac address that is all zero means match only the ssid;
1303          * otherwise we must match both.
1304          */
1305         if (IEEE80211_ADDR_EQ(macaddr, zeromac)) {
1306                 TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1307                         if (MATCH_SSID(ni, ssid, ssidlen))
1308                                 break;
1309                 }
1310         } else {
1311                 hash = IEEE80211_NODE_HASH(macaddr);
1312                 LIST_FOREACH(ni, &nt->nt_hash[hash], ni_hash) {
1313                         if (IEEE80211_ADDR_EQ(ni->ni_macaddr, macaddr) &&
1314                             MATCH_SSID(ni, ssid, ssidlen))
1315                                 break;
1316                 }
1317         }
1318         if (ni != NULL) {
1319                 ieee80211_ref_node(ni); /* mark referenced */
1320                 IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
1321                      REFCNT_LOC, ni, ether_sprintf(ni->ni_macaddr),
1322                      ieee80211_node_refcnt(ni));
1323         }
1324         IEEE80211_NODE_UNLOCK(nt);
1325         return ni;
1326 #undef MATCH_SSID
1327 }
1328
1329 static void
1330 _ieee80211_free_node(struct ieee80211_node *ni)
1331 {
1332         struct ieee80211com *ic = ni->ni_ic;
1333         struct ieee80211_node_table *nt = ni->ni_table;
1334
1335         IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1336                 "%s %p<%s> in %s table\n", __func__, ni,
1337                 ether_sprintf(ni->ni_macaddr),
1338                 nt != NULL ? nt->nt_name : "<gone>");
1339
1340         IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1341         if (nt != NULL) {
1342                 TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1343                 LIST_REMOVE(ni, ni_hash);
1344         }
1345         ic->ic_node_free(ni);
1346 }
1347
1348 void
1349 #ifdef IEEE80211_DEBUG_REFCNT
1350 ieee80211_free_node_debug(struct ieee80211_node *ni, const char *func, int line)
1351 #else
1352 ieee80211_free_node(struct ieee80211_node *ni)
1353 #endif
1354 {
1355         struct ieee80211_node_table *nt = ni->ni_table;
1356
1357 #ifdef IEEE80211_DEBUG_REFCNT
1358         IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1359                 "%s (%s:%u) %p<%s> refcnt %d\n", __func__, func, line, ni,
1360                  ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)-1);
1361 #endif
1362         if (nt != NULL) {
1363                 IEEE80211_NODE_LOCK(nt);
1364                 if (ieee80211_node_dectestref(ni)) {
1365                         /*
1366                          * Last reference, reclaim state.
1367                          */
1368                         _ieee80211_free_node(ni);
1369                 } else if (ieee80211_node_refcnt(ni) == 1 &&
1370                     nt->nt_keyixmap != NULL) {
1371                         ieee80211_keyix keyix;
1372                         /*
1373                          * Check for a last reference in the key mapping table.
1374                          */
1375                         keyix = ni->ni_ucastkey.wk_rxkeyix;
1376                         if (keyix < nt->nt_keyixmax &&
1377                             nt->nt_keyixmap[keyix] == ni) {
1378                                 IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1379                                     "%s: %p<%s> clear key map entry", __func__,
1380                                     ni, ether_sprintf(ni->ni_macaddr));
1381                                 nt->nt_keyixmap[keyix] = NULL;
1382                                 ieee80211_node_decref(ni); /* XXX needed? */
1383                                 _ieee80211_free_node(ni);
1384                         }
1385                 }
1386                 IEEE80211_NODE_UNLOCK(nt);
1387         } else {
1388                 if (ieee80211_node_dectestref(ni))
1389                         _ieee80211_free_node(ni);
1390         }
1391 }
1392
1393 /*
1394  * Reclaim a unicast key and clear any key cache state.
1395  */
1396 int
1397 ieee80211_node_delucastkey(struct ieee80211_node *ni)
1398 {
1399         struct ieee80211com *ic = ni->ni_ic;
1400         struct ieee80211_node_table *nt = &ic->ic_sta;
1401         struct ieee80211_node *nikey;
1402         ieee80211_keyix keyix;
1403         int isowned, status;
1404
1405         /*
1406          * NB: We must beware of LOR here; deleting the key
1407          * can cause the crypto layer to block traffic updates
1408          * which can generate a LOR against the node table lock;
1409          * grab it here and stash the key index for our use below.
1410          *
1411          * Must also beware of recursion on the node table lock.
1412          * When called from node_cleanup we may already have
1413          * the node table lock held.  Unfortunately there's no
1414          * way to separate out this path so we must do this
1415          * conditionally.
1416          */
1417         isowned = IEEE80211_NODE_IS_LOCKED(nt);
1418         if (!isowned)
1419                 IEEE80211_NODE_LOCK(nt);
1420         keyix = ni->ni_ucastkey.wk_rxkeyix;
1421         status = ieee80211_crypto_delkey(ic, &ni->ni_ucastkey);
1422         if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax) {
1423                 nikey = nt->nt_keyixmap[keyix];
1424                 nt->nt_keyixmap[keyix] = NULL;;
1425         } else
1426                 nikey = NULL;
1427         if (!isowned)
1428                 IEEE80211_NODE_UNLOCK(&ic->ic_sta);
1429
1430         if (nikey != NULL) {
1431                 KASSERT(nikey == ni,
1432                         ("key map out of sync, ni %p nikey %p", ni, nikey));
1433                 IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1434                         "%s: delete key map entry %p<%s> refcnt %d\n",
1435                         __func__, ni, ether_sprintf(ni->ni_macaddr),
1436                         ieee80211_node_refcnt(ni)-1);
1437                 ieee80211_free_node(ni);
1438         }
1439         return status;
1440 }
1441
1442 /*
1443  * Reclaim a node.  If this is the last reference count then
1444  * do the normal free work.  Otherwise remove it from the node
1445  * table and mark it gone by clearing the back-reference.
1446  */
1447 static void
1448 node_reclaim(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1449 {
1450         ieee80211_keyix keyix;
1451
1452         IEEE80211_NODE_LOCK_ASSERT(nt);
1453
1454         IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1455                 "%s: remove %p<%s> from %s table, refcnt %d\n",
1456                 __func__, ni, ether_sprintf(ni->ni_macaddr),
1457                 nt->nt_name, ieee80211_node_refcnt(ni)-1);
1458         /*
1459          * Clear any entry in the unicast key mapping table.
1460          * We need to do it here so rx lookups don't find it
1461          * in the mapping table even if it's not in the hash
1462          * table.  We cannot depend on the mapping table entry
1463          * being cleared because the node may not be free'd.
1464          */
1465         keyix = ni->ni_ucastkey.wk_rxkeyix;
1466         if (nt->nt_keyixmap != NULL && keyix < nt->nt_keyixmax &&
1467             nt->nt_keyixmap[keyix] == ni) {
1468                 IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_NODE,
1469                         "%s: %p<%s> clear key map entry\n",
1470                         __func__, ni, ether_sprintf(ni->ni_macaddr));
1471                 nt->nt_keyixmap[keyix] = NULL;
1472                 ieee80211_node_decref(ni);      /* NB: don't need free */
1473         }
1474         if (!ieee80211_node_dectestref(ni)) {
1475                 /*
1476                  * Other references are present, just remove the
1477                  * node from the table so it cannot be found.  When
1478                  * the references are dropped storage will be
1479                  * reclaimed.
1480                  */
1481                 TAILQ_REMOVE(&nt->nt_node, ni, ni_list);
1482                 LIST_REMOVE(ni, ni_hash);
1483                 ni->ni_table = NULL;            /* clear reference */
1484         } else
1485                 _ieee80211_free_node(ni);
1486 }
1487
1488 static void
1489 ieee80211_free_allnodes_locked(struct ieee80211_node_table *nt)
1490 {
1491         struct ieee80211com *ic = nt->nt_ic;
1492         struct ieee80211_node *ni;
1493
1494         IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
1495                 "%s: free all nodes in %s table\n", __func__, nt->nt_name);
1496
1497         while ((ni = TAILQ_FIRST(&nt->nt_node)) != NULL) {
1498                 if (ni->ni_associd != 0) {
1499                         if (ic->ic_auth->ia_node_leave != NULL)
1500                                 ic->ic_auth->ia_node_leave(ic, ni);
1501                         IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1502                 }
1503                 node_reclaim(nt, ni);
1504         }
1505 }
1506
1507 /*
1508  * Timeout inactive stations and do related housekeeping.
1509  * Note that we cannot hold the node lock while sending a
1510  * frame as this would lead to a LOR.  Instead we use a
1511  * generation number to mark nodes that we've scanned and
1512  * drop the lock and restart a scan if we have to time out
1513  * a node.  Since we are single-threaded by virtue of
1514  * controlling the inactivity timer we can be sure this will
1515  * process each node only once.
1516  */
1517 static void
1518 ieee80211_timeout_stations(struct ieee80211_node_table *nt)
1519 {
1520         struct ieee80211com *ic = nt->nt_ic;
1521         struct ieee80211_node *ni;
1522         u_int gen;
1523         int isadhoc;
1524
1525         isadhoc = (ic->ic_opmode == IEEE80211_M_IBSS ||
1526                    ic->ic_opmode == IEEE80211_M_AHDEMO);
1527         IEEE80211_SCAN_LOCK(nt);
1528         gen = ++nt->nt_scangen;
1529 restart:
1530         IEEE80211_NODE_LOCK(nt);
1531         TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1532                 if (ni->ni_scangen == gen)      /* previously handled */
1533                         continue;
1534                 ni->ni_scangen = gen;
1535                 /*
1536                  * Ignore entries for which have yet to receive an
1537                  * authentication frame.  These are transient and
1538                  * will be reclaimed when the last reference to them
1539                  * goes away (when frame xmits complete).
1540                  */
1541                 if ((ic->ic_opmode == IEEE80211_M_HOSTAP ||
1542                      ic->ic_opmode == IEEE80211_M_STA) &&
1543                     (ni->ni_flags & IEEE80211_NODE_AREF) == 0)
1544                         continue;
1545                 /*
1546                  * Free fragment if not needed anymore
1547                  * (last fragment older than 1s).
1548                  * XXX doesn't belong here
1549                  */
1550                 if (ni->ni_rxfrag[0] != NULL &&
1551                     ticks > ni->ni_rxfragstamp + hz) {
1552                         m_freem(ni->ni_rxfrag[0]);
1553                         ni->ni_rxfrag[0] = NULL;
1554                 }
1555                 if (ni->ni_inact > 0)
1556                         ni->ni_inact--;
1557                 /*
1558                  * Special case ourself; we may be idle for extended periods
1559                  * of time and regardless reclaiming our state is wrong.
1560                  */
1561                 if (ni == ic->ic_bss)
1562                         continue;
1563                 if (ni->ni_associd != 0 || isadhoc) {
1564                         /*
1565                          * Age frames on the power save queue.
1566                          */
1567                         if (ieee80211_node_saveq_age(ni) != 0 &&
1568                             IEEE80211_NODE_SAVEQ_QLEN(ni) == 0 &&
1569                             ic->ic_set_tim != NULL)
1570                                 ic->ic_set_tim(ni, 0);
1571                         /*
1572                          * Probe the station before time it out.  We
1573                          * send a null data frame which may not be
1574                          * universally supported by drivers (need it
1575                          * for ps-poll support so it should be...).
1576                          *
1577                          * XXX don't probe the station unless we've
1578                          *     received a frame from them (and have
1579                          *     some idea of the rates they are capable
1580                          *     of); this will get fixed more properly
1581                          *     soon with better handling of the rate set.
1582                          */
1583                         if ((ic->ic_flags_ext & IEEE80211_FEXT_INACT) &&
1584                             (0 < ni->ni_inact &&
1585                              ni->ni_inact <= ic->ic_inact_probe) &&
1586                             ni->ni_rates.rs_nrates != 0) {
1587                                 IEEE80211_NOTE(ic,
1588                                     IEEE80211_MSG_INACT | IEEE80211_MSG_NODE,
1589                                     ni, "%s",
1590                                     "probe station due to inactivity");
1591                                 /*
1592                                  * Grab a reference before unlocking the table
1593                                  * so the node cannot be reclaimed before we
1594                                  * send the frame. ieee80211_send_nulldata
1595                                  * understands we've done this and reclaims the
1596                                  * ref for us as needed.
1597                                  */
1598                                 ieee80211_ref_node(ni);
1599                                 IEEE80211_NODE_UNLOCK(nt);
1600                                 ieee80211_send_nulldata(ni);
1601                                 /* XXX stat? */
1602                                 goto restart;
1603                         }
1604                 }
1605                 if ((ic->ic_flags_ext & IEEE80211_FEXT_INACT) &&
1606                     ni->ni_inact <= 0) {
1607                         IEEE80211_NOTE(ic,
1608                             IEEE80211_MSG_INACT | IEEE80211_MSG_NODE, ni,
1609                             "station timed out due to inactivity "
1610                             "(refcnt %u)", ieee80211_node_refcnt(ni));
1611                         /*
1612                          * Send a deauthenticate frame and drop the station.
1613                          * This is somewhat complicated due to reference counts
1614                          * and locking.  At this point a station will typically
1615                          * have a reference count of 1.  ieee80211_node_leave
1616                          * will do a "free" of the node which will drop the
1617                          * reference count.  But in the meantime a reference
1618                          * wil be held by the deauth frame.  The actual reclaim
1619                          * of the node will happen either after the tx is
1620                          * completed or by ieee80211_node_leave.
1621                          *
1622                          * Separately we must drop the node lock before sending
1623                          * in case the driver takes a lock, as this can result
1624                          * in a LOR between the node lock and the driver lock.
1625                          */
1626                         ieee80211_ref_node(ni);
1627                         IEEE80211_NODE_UNLOCK(nt);
1628                         if (ni->ni_associd != 0) {
1629                                 IEEE80211_SEND_MGMT(ic, ni,
1630                                     IEEE80211_FC0_SUBTYPE_DEAUTH,
1631                                     IEEE80211_REASON_AUTH_EXPIRE);
1632                         }
1633                         ieee80211_node_leave(ic, ni);
1634                         ieee80211_free_node(ni);
1635                         ic->ic_stats.is_node_timeout++;
1636                         goto restart;
1637                 }
1638         }
1639         IEEE80211_NODE_UNLOCK(nt);
1640
1641         IEEE80211_SCAN_UNLOCK(nt);
1642 }
1643
1644 void
1645 ieee80211_node_timeout(void *arg)
1646 {
1647         struct ieee80211com *ic = arg;
1648
1649         ieee80211_scan_timeout(ic);
1650         ieee80211_timeout_stations(&ic->ic_sta);
1651
1652         IEEE80211_LOCK(ic);
1653         ieee80211_erp_timeout(ic);
1654         ieee80211_ht_timeout(ic);
1655         IEEE80211_UNLOCK(ic);
1656
1657         callout_reset(&ic->ic_inact, IEEE80211_INACT_WAIT*hz,
1658                 ieee80211_node_timeout, ic);
1659 }
1660
1661 void
1662 ieee80211_iterate_nodes(struct ieee80211_node_table *nt, ieee80211_iter_func *f, void *arg)
1663 {
1664         struct ieee80211_node *ni;
1665         u_int gen;
1666
1667         IEEE80211_SCAN_LOCK(nt);
1668         gen = ++nt->nt_scangen;
1669 restart:
1670         IEEE80211_NODE_LOCK(nt);
1671         TAILQ_FOREACH(ni, &nt->nt_node, ni_list) {
1672                 if (ni->ni_scangen != gen) {
1673                         ni->ni_scangen = gen;
1674                         (void) ieee80211_ref_node(ni);
1675                         IEEE80211_NODE_UNLOCK(nt);
1676                         (*f)(arg, ni);
1677                         ieee80211_free_node(ni);
1678                         goto restart;
1679                 }
1680         }
1681         IEEE80211_NODE_UNLOCK(nt);
1682
1683         IEEE80211_SCAN_UNLOCK(nt);
1684 }
1685
1686 void
1687 ieee80211_dump_node(struct ieee80211_node_table *nt, struct ieee80211_node *ni)
1688 {
1689         printf("0x%p: mac %s refcnt %d\n", ni,
1690                 ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni));
1691         printf("\tscangen %u authmode %u flags 0x%x\n",
1692                 ni->ni_scangen, ni->ni_authmode, ni->ni_flags);
1693         printf("\tassocid 0x%x txpower %u vlan %u\n",
1694                 ni->ni_associd, ni->ni_txpower, ni->ni_vlan);
1695         printf("\ttxseq %u rxseq %u fragno %u rxfragstamp %u\n",
1696                 ni->ni_txseqs[IEEE80211_NONQOS_TID],
1697                 ni->ni_rxseqs[IEEE80211_NONQOS_TID] >> IEEE80211_SEQ_SEQ_SHIFT,
1698                 ni->ni_rxseqs[IEEE80211_NONQOS_TID] & IEEE80211_SEQ_FRAG_MASK,
1699                 ni->ni_rxfragstamp);
1700         printf("\trstamp %u rssi %d noise %d intval %u capinfo 0x%x\n",
1701                 ni->ni_rstamp, ni->ni_rssi, ni->ni_noise,
1702                 ni->ni_intval, ni->ni_capinfo);
1703         printf("\tbssid %s essid \"%.*s\" channel %u:0x%x\n",
1704                 ether_sprintf(ni->ni_bssid),
1705                 ni->ni_esslen, ni->ni_essid,
1706                 ni->ni_chan->ic_freq, ni->ni_chan->ic_flags);
1707         printf("\tfails %u inact %u txrate %u\n",
1708                 ni->ni_fails, ni->ni_inact, ni->ni_txrate);
1709         printf("\thtcap %x htparam %x htctlchan %u ht2ndchan %u\n",
1710                 ni->ni_htcap, ni->ni_htparam,
1711                 ni->ni_htctlchan, ni->ni_ht2ndchan);
1712         printf("\thtopmode %x htstbc %x chw %u\n",
1713                 ni->ni_htopmode, ni->ni_htstbc, ni->ni_chw);
1714 }
1715
1716 void
1717 ieee80211_dump_nodes(struct ieee80211_node_table *nt)
1718 {
1719         ieee80211_iterate_nodes(nt,
1720                 (ieee80211_iter_func *) ieee80211_dump_node, nt);
1721 }
1722
1723 void
1724 ieee80211_notify_erp(struct ieee80211com *ic)
1725 {
1726         if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1727                 ieee80211_beacon_notify(ic, IEEE80211_BEACON_ERP);
1728 }
1729
1730 /*
1731  * Handle a station joining an 11g network.
1732  */
1733 static void
1734 ieee80211_node_join_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
1735 {
1736
1737         IEEE80211_LOCK_ASSERT(ic);
1738
1739         /*
1740          * Station isn't capable of short slot time.  Bump
1741          * the count of long slot time stations and disable
1742          * use of short slot time.  Note that the actual switch
1743          * over to long slot time use may not occur until the
1744          * next beacon transmission (per sec. 7.3.1.4 of 11g).
1745          */
1746         if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
1747                 ic->ic_longslotsta++;
1748                 IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC, ni,
1749                     "station needs long slot time, count %d",
1750                     ic->ic_longslotsta);
1751                 /* XXX vap's w/ conflicting needs won't work */
1752                 if (!IEEE80211_IS_CHAN_108G(ic->ic_bsschan)) {
1753                         /*
1754                          * Don't force slot time when switched to turbo
1755                          * mode as non-ERP stations won't be present; this
1756                          * need only be done when on the normal G channel.
1757                          */
1758                         ieee80211_set_shortslottime(ic, 0);
1759                 }
1760         }
1761         /*
1762          * If the new station is not an ERP station
1763          * then bump the counter and enable protection
1764          * if configured.
1765          */
1766         if (!ieee80211_iserp_rateset(ic, &ni->ni_rates)) {
1767                 ic->ic_nonerpsta++;
1768                 IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC, ni,
1769                     "station is !ERP, %d non-ERP stations associated",
1770                     ic->ic_nonerpsta);
1771                 /*
1772                  * If station does not support short preamble
1773                  * then we must enable use of Barker preamble.
1774                  */
1775                 if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE) == 0) {
1776                         IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC, ni,
1777                             "%s", "station needs long preamble");
1778                         ic->ic_flags |= IEEE80211_F_USEBARKER;
1779                         ic->ic_flags &= ~IEEE80211_F_SHPREAMBLE;
1780                 }
1781                 /*
1782                  * If protection is configured, enable it.
1783                  */
1784                 if (ic->ic_protmode != IEEE80211_PROT_NONE &&
1785                     ic->ic_nonerpsta == 1 &&
1786                     (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) == 0) {
1787                         IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1788                             "%s: enable use of protection\n", __func__);
1789                         ic->ic_flags |= IEEE80211_F_USEPROT;
1790                         ieee80211_notify_erp(ic);
1791                 }
1792         } else
1793                 ni->ni_flags |= IEEE80211_NODE_ERP;
1794 }
1795
1796 void
1797 ieee80211_node_join(struct ieee80211com *ic, struct ieee80211_node *ni, int resp)
1798 {
1799         int newassoc;
1800
1801         if (ni->ni_associd == 0) {
1802                 uint16_t aid;
1803
1804                 IEEE80211_LOCK(ic);
1805                 /*
1806                  * It would be good to search the bitmap
1807                  * more efficiently, but this will do for now.
1808                  */
1809                 for (aid = 1; aid < ic->ic_max_aid; aid++) {
1810                         if (!IEEE80211_AID_ISSET(aid,
1811                             ic->ic_aid_bitmap))
1812                                 break;
1813                 }
1814                 if (aid >= ic->ic_max_aid) {
1815                         IEEE80211_UNLOCK(ic);
1816                         IEEE80211_SEND_MGMT(ic, ni, resp,
1817                             IEEE80211_STATUS_TOOMANY);
1818                         ieee80211_node_leave(ic, ni);
1819                         return;
1820                 }
1821                 ni->ni_associd = aid | 0xc000;
1822                 ni->ni_jointime = time_uptime;
1823                 IEEE80211_AID_SET(ni->ni_associd, ic->ic_aid_bitmap);
1824                 ic->ic_sta_assoc++;
1825
1826                 if (IEEE80211_IS_CHAN_HT(ic->ic_bsschan))
1827                         ieee80211_ht_node_join(ni);
1828                 if (IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan) &&
1829                     IEEE80211_IS_CHAN_FULL(ic->ic_bsschan))
1830                         ieee80211_node_join_11g(ic, ni);
1831                 IEEE80211_UNLOCK(ic);
1832
1833                 newassoc = 1;
1834         } else
1835                 newassoc = 0;
1836
1837         IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG, ni,
1838             "station associated at aid %d: %s preamble, %s slot time%s%s%s%s%s%s",
1839             IEEE80211_NODE_AID(ni),
1840             ic->ic_flags & IEEE80211_F_SHPREAMBLE ? "short" : "long",
1841             ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long",
1842             ic->ic_flags & IEEE80211_F_USEPROT ? ", protection" : "",
1843             ni->ni_flags & IEEE80211_NODE_QOS ? ", QoS" : "",
1844             ni->ni_flags & IEEE80211_NODE_HT ?
1845                 (ni->ni_chw == 20 ? ", HT20" : ", HT40") : "",
1846             ni->ni_flags & IEEE80211_NODE_AMPDU ? " (+AMPDU)" : "",
1847             IEEE80211_ATH_CAP(ic, ni, IEEE80211_NODE_FF) ?
1848                 ", fast-frames" : "",
1849             IEEE80211_ATH_CAP(ic, ni, IEEE80211_NODE_TURBOP) ?
1850                 ", turbo" : ""
1851         );
1852
1853         /* give driver a chance to setup state like ni_txrate */
1854         if (ic->ic_newassoc != NULL)
1855                 ic->ic_newassoc(ni, newassoc);
1856         IEEE80211_SEND_MGMT(ic, ni, resp, IEEE80211_STATUS_SUCCESS);
1857         /* tell the authenticator about new station */
1858         if (ic->ic_auth->ia_node_join != NULL)
1859                 ic->ic_auth->ia_node_join(ic, ni);
1860         ieee80211_notify_node_join(ic, ni,
1861             resp == IEEE80211_FC0_SUBTYPE_ASSOC_RESP);
1862 }
1863
1864 static void
1865 disable_protection(struct ieee80211com *ic)
1866 {
1867         KASSERT(ic->ic_nonerpsta == 0 &&
1868             (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) == 0,
1869            ("%d non ERP stations, flags 0x%x", ic->ic_nonerpsta,
1870            ic->ic_flags_ext));
1871
1872         ic->ic_flags &= ~IEEE80211_F_USEPROT;
1873         /* XXX verify mode? */
1874         if (ic->ic_caps & IEEE80211_C_SHPREAMBLE) {
1875                 ic->ic_flags |= IEEE80211_F_SHPREAMBLE;
1876                 ic->ic_flags &= ~IEEE80211_F_USEBARKER;
1877         }
1878         ieee80211_notify_erp(ic);
1879 }
1880
1881 /*
1882  * Handle a station leaving an 11g network.
1883  */
1884 static void
1885 ieee80211_node_leave_11g(struct ieee80211com *ic, struct ieee80211_node *ni)
1886 {
1887
1888         IEEE80211_LOCK_ASSERT(ic);
1889
1890         KASSERT(IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan),
1891              ("not in 11g, bss %u:0x%x, curmode %u", ic->ic_bsschan->ic_freq,
1892               ic->ic_bsschan->ic_flags, ic->ic_curmode));
1893
1894         /*
1895          * If a long slot station do the slot time bookkeeping.
1896          */
1897         if ((ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME) == 0) {
1898                 KASSERT(ic->ic_longslotsta > 0,
1899                     ("bogus long slot station count %d", ic->ic_longslotsta));
1900                 ic->ic_longslotsta--;
1901                 IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC, ni,
1902                     "long slot time station leaves, count now %d",
1903                     ic->ic_longslotsta);
1904                 if (ic->ic_longslotsta == 0) {
1905                         /*
1906                          * Re-enable use of short slot time if supported
1907                          * and not operating in IBSS mode (per spec).
1908                          */
1909                         if ((ic->ic_caps & IEEE80211_C_SHSLOT) &&
1910                             ic->ic_opmode != IEEE80211_M_IBSS) {
1911                                 IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1912                                     "%s: re-enable use of short slot time\n",
1913                                     __func__);
1914                                 ieee80211_set_shortslottime(ic, 1);
1915                         }
1916                 }
1917         }
1918         /*
1919          * If a non-ERP station do the protection-related bookkeeping.
1920          */
1921         if ((ni->ni_flags & IEEE80211_NODE_ERP) == 0) {
1922                 KASSERT(ic->ic_nonerpsta > 0,
1923                     ("bogus non-ERP station count %d", ic->ic_nonerpsta));
1924                 ic->ic_nonerpsta--;
1925                 IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC, ni,
1926                     "non-ERP station leaves, count now %d%s", ic->ic_nonerpsta,
1927                     (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) ?
1928                         " (non-ERP sta present)" : "");
1929                 if (ic->ic_nonerpsta == 0 &&
1930                     (ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) == 0) {
1931                         IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1932                                 "%s: disable use of protection\n", __func__);
1933                         disable_protection(ic);
1934                 }
1935         }
1936 }
1937
1938 /*
1939  * Time out presence of an overlapping bss with non-ERP
1940  * stations.  When operating in hostap mode we listen for
1941  * beacons from other stations and if we identify a non-ERP
1942  * station is present we enable protection.  To identify
1943  * when all non-ERP stations are gone we time out this
1944  * condition.
1945  */
1946 static void
1947 ieee80211_erp_timeout(struct ieee80211com *ic)
1948 {
1949
1950         IEEE80211_LOCK_ASSERT(ic);
1951
1952         if ((ic->ic_flags_ext & IEEE80211_FEXT_NONERP_PR) &&
1953             time_after(ticks, ic->ic_lastnonerp + IEEE80211_NONERP_PRESENT_AGE)) {
1954                 IEEE80211_DPRINTF(ic, IEEE80211_MSG_ASSOC,
1955                     "%s\n", "age out non-ERP sta present on channel");
1956                 ic->ic_flags_ext &= ~IEEE80211_FEXT_NONERP_PR;
1957                 if (ic->ic_nonerpsta == 0)
1958                         disable_protection(ic);
1959         }
1960 }
1961
1962 /*
1963  * Handle bookkeeping for station deauthentication/disassociation
1964  * when operating as an ap.
1965  */
1966 void
1967 ieee80211_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
1968 {
1969         struct ieee80211_node_table *nt = ni->ni_table;
1970
1971         IEEE80211_NOTE(ic, IEEE80211_MSG_ASSOC | IEEE80211_MSG_DEBUG, ni,
1972             "station with aid %d leaves", IEEE80211_NODE_AID(ni));
1973
1974         KASSERT(ic->ic_opmode != IEEE80211_M_STA,
1975                 ("unexpected operating mode %u", ic->ic_opmode));
1976         /*
1977          * If node wasn't previously associated all
1978          * we need to do is reclaim the reference.
1979          */
1980         /* XXX ibss mode bypasses 11g and notification */
1981         if (ni->ni_associd == 0)
1982                 goto done;
1983         /*
1984          * Tell the authenticator the station is leaving.
1985          * Note that we must do this before yanking the
1986          * association id as the authenticator uses the
1987          * associd to locate it's state block.
1988          */
1989         if (ic->ic_auth->ia_node_leave != NULL)
1990                 ic->ic_auth->ia_node_leave(ic, ni);
1991
1992         IEEE80211_LOCK(ic);
1993         IEEE80211_AID_CLR(ni->ni_associd, ic->ic_aid_bitmap);
1994         ni->ni_associd = 0;
1995         ic->ic_sta_assoc--;
1996
1997         if (IEEE80211_IS_CHAN_HT(ic->ic_bsschan))
1998                 ieee80211_ht_node_leave(ni);
1999         if (IEEE80211_IS_CHAN_ANYG(ic->ic_bsschan) &&
2000             IEEE80211_IS_CHAN_FULL(ic->ic_bsschan))
2001                 ieee80211_node_leave_11g(ic, ni);
2002         IEEE80211_UNLOCK(ic);
2003         /*
2004          * Cleanup station state.  In particular clear various
2005          * state that might otherwise be reused if the node
2006          * is reused before the reference count goes to zero
2007          * (and memory is reclaimed).
2008          */
2009         ieee80211_sta_leave(ic, ni);
2010 done:
2011         /*
2012          * Remove the node from any table it's recorded in and
2013          * drop the caller's reference.  Removal from the table
2014          * is important to insure the node is not reprocessed
2015          * for inactivity.
2016          */
2017         if (nt != NULL) {
2018                 IEEE80211_NODE_LOCK(nt);
2019                 node_reclaim(nt, ni);
2020                 IEEE80211_NODE_UNLOCK(nt);
2021         } else
2022                 ieee80211_free_node(ni);
2023 }
2024
2025 int8_t
2026 ieee80211_getrssi(struct ieee80211com *ic)
2027 {
2028 #define NZ(x)   ((x) == 0 ? 1 : (x))
2029         struct ieee80211_node_table *nt = &ic->ic_sta;
2030         int rssi_samples;
2031         int32_t rssi_total;
2032         struct ieee80211_node *ni;
2033
2034         rssi_total = 0;
2035         rssi_samples = 0;
2036         switch (ic->ic_opmode) {
2037         case IEEE80211_M_IBSS:          /* average of all ibss neighbors */
2038         case IEEE80211_M_AHDEMO:        /* average of all neighbors */
2039         case IEEE80211_M_HOSTAP:        /* average of all associated stations */
2040                 /* XXX locking */
2041                 TAILQ_FOREACH(ni, &nt->nt_node, ni_list)
2042                         if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2043                             (ni->ni_capinfo & IEEE80211_CAPINFO_IBSS)) {
2044                                 int8_t rssi = ic->ic_node_getrssi(ni);
2045                                 if (rssi != 0) {
2046                                         rssi_samples++;
2047                                         rssi_total += rssi;
2048                                 }
2049                         }
2050                 break;
2051         case IEEE80211_M_MONITOR:       /* XXX */
2052         case IEEE80211_M_STA:           /* use stats from associated ap */
2053         default:
2054                 if (ic->ic_bss != NULL)
2055                         rssi_total = ic->ic_node_getrssi(ic->ic_bss);
2056                 rssi_samples = 1;
2057                 break;
2058         }
2059         return rssi_total / NZ(rssi_samples);
2060 #undef NZ
2061 }
2062
2063 void
2064 ieee80211_getsignal(struct ieee80211com *ic, int8_t *rssi, int8_t *noise)
2065 {
2066
2067         if (ic->ic_bss == NULL)         /* NB: shouldn't happen */
2068                 return;
2069         ic->ic_node_getsignal(ic->ic_bss, rssi, noise);
2070         /* for non-station mode return avg'd rssi accounting */
2071         if (ic->ic_opmode != IEEE80211_M_STA)
2072                 *rssi = ieee80211_getrssi(ic);
2073 }
2074
2075 /*
2076  * Node table support.
2077  */
2078
2079 static void
2080 ieee80211_node_table_init(struct ieee80211com *ic,
2081         struct ieee80211_node_table *nt,
2082         const char *name, int inact, int keyixmax)
2083 {
2084
2085         IEEE80211_DPRINTF(ic, IEEE80211_MSG_NODE,
2086                 "%s %s table, inact %u\n", __func__, name, inact);
2087
2088         nt->nt_ic = ic;
2089         /* XXX need unit */
2090         IEEE80211_NODE_LOCK_INIT(nt, ic->ic_ifp->if_xname);
2091         IEEE80211_SCAN_LOCK_INIT(nt, ic->ic_ifp->if_xname);
2092         TAILQ_INIT(&nt->nt_node);
2093         nt->nt_name = name;
2094         nt->nt_scangen = 1;
2095         nt->nt_inact_init = inact;
2096         nt->nt_keyixmax = keyixmax;
2097         if (nt->nt_keyixmax > 0) {
2098                 MALLOC(nt->nt_keyixmap, struct ieee80211_node **,
2099                         keyixmax * sizeof(struct ieee80211_node *),
2100                         M_80211_NODE, M_NOWAIT | M_ZERO);
2101                 if (nt->nt_keyixmap == NULL)
2102                         if_printf(ic->ic_ifp,
2103                             "Cannot allocate key index map with %u entries\n",
2104                             keyixmax);
2105         } else
2106                 nt->nt_keyixmap = NULL;
2107 }
2108
2109 static void
2110 ieee80211_node_table_reset(struct ieee80211_node_table *nt)
2111 {
2112
2113         IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
2114                 "%s %s table\n", __func__, nt->nt_name);
2115
2116         IEEE80211_NODE_LOCK(nt);
2117         ieee80211_free_allnodes_locked(nt);
2118         IEEE80211_NODE_UNLOCK(nt);
2119 }
2120
2121 static void
2122 ieee80211_node_table_cleanup(struct ieee80211_node_table *nt)
2123 {
2124
2125         IEEE80211_DPRINTF(nt->nt_ic, IEEE80211_MSG_NODE,
2126                 "%s %s table\n", __func__, nt->nt_name);
2127
2128         IEEE80211_NODE_LOCK(nt);
2129         ieee80211_free_allnodes_locked(nt);
2130         if (nt->nt_keyixmap != NULL) {
2131                 /* XXX verify all entries are NULL */
2132                 int i;
2133                 for (i = 0; i < nt->nt_keyixmax; i++)
2134                         if (nt->nt_keyixmap[i] != NULL)
2135                                 printf("%s: %s[%u] still active\n", __func__,
2136                                         nt->nt_name, i);
2137                 FREE(nt->nt_keyixmap, M_80211_NODE);
2138                 nt->nt_keyixmap = NULL;
2139         }
2140         IEEE80211_SCAN_LOCK_DESTROY(nt);
2141         IEEE80211_NODE_LOCK_DESTROY(nt);
2142 }