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