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