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