Home | History | Annotate | Line # | Download | only in netinet6
nd6.c revision 1.237
      1 /*	$NetBSD: nd6.c,v 1.237 2017/11/10 07:24:28 ozaki-r Exp $	*/
      2 /*	$KAME: nd6.c,v 1.279 2002/06/08 11:16:51 itojun Exp $	*/
      3 
      4 /*
      5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
      6  * All rights reserved.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  * 3. Neither the name of the project nor the names of its contributors
     17  *    may be used to endorse or promote products derived from this software
     18  *    without specific prior written permission.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     30  * SUCH DAMAGE.
     31  */
     32 
     33 #include <sys/cdefs.h>
     34 __KERNEL_RCSID(0, "$NetBSD: nd6.c,v 1.237 2017/11/10 07:24:28 ozaki-r Exp $");
     35 
     36 #ifdef _KERNEL_OPT
     37 #include "opt_net_mpsafe.h"
     38 #endif
     39 
     40 #include "bridge.h"
     41 #include "carp.h"
     42 
     43 #include <sys/param.h>
     44 #include <sys/systm.h>
     45 #include <sys/callout.h>
     46 #include <sys/kmem.h>
     47 #include <sys/mbuf.h>
     48 #include <sys/socket.h>
     49 #include <sys/socketvar.h>
     50 #include <sys/sockio.h>
     51 #include <sys/time.h>
     52 #include <sys/kernel.h>
     53 #include <sys/errno.h>
     54 #include <sys/ioctl.h>
     55 #include <sys/syslog.h>
     56 #include <sys/queue.h>
     57 #include <sys/cprng.h>
     58 #include <sys/workqueue.h>
     59 
     60 #include <net/if.h>
     61 #include <net/if_dl.h>
     62 #include <net/if_llatbl.h>
     63 #include <net/if_types.h>
     64 #include <net/route.h>
     65 #include <net/if_ether.h>
     66 #include <net/if_fddi.h>
     67 #include <net/if_arc.h>
     68 
     69 #include <netinet/in.h>
     70 #include <netinet6/in6_var.h>
     71 #include <netinet/ip6.h>
     72 #include <netinet6/ip6_var.h>
     73 #include <netinet6/scope6_var.h>
     74 #include <netinet6/nd6.h>
     75 #include <netinet6/in6_ifattach.h>
     76 #include <netinet/icmp6.h>
     77 #include <netinet6/icmp6_private.h>
     78 
     79 #include <net/net_osdep.h>
     80 
     81 #define ND6_SLOWTIMER_INTERVAL (60 * 60) /* 1 hour */
     82 #define ND6_RECALC_REACHTM_INTERVAL (60 * 120) /* 2 hours */
     83 
     84 /* timer values */
     85 int	nd6_prune	= 1;	/* walk list every 1 seconds */
     86 int	nd6_delay	= 5;	/* delay first probe time 5 second */
     87 int	nd6_umaxtries	= 3;	/* maximum unicast query */
     88 int	nd6_mmaxtries	= 3;	/* maximum multicast query */
     89 int	nd6_useloopback = 1;	/* use loopback interface for local traffic */
     90 int	nd6_gctimer	= (60 * 60 * 24); /* 1 day: garbage collection timer */
     91 
     92 /* preventing too many loops in ND option parsing */
     93 int nd6_maxndopt = 10;	/* max # of ND options allowed */
     94 
     95 int nd6_maxnudhint = 0;	/* max # of subsequent upper layer hints */
     96 
     97 int nd6_maxqueuelen = 1; /* max # of packets cached in unresolved ND entries */
     98 
     99 #ifdef ND6_DEBUG
    100 int nd6_debug = 1;
    101 #else
    102 int nd6_debug = 0;
    103 #endif
    104 
    105 krwlock_t nd6_lock __cacheline_aligned;
    106 
    107 struct nd_drhead nd_defrouter;
    108 struct nd_prhead nd_prefix = { 0 };
    109 
    110 int nd6_recalc_reachtm_interval = ND6_RECALC_REACHTM_INTERVAL;
    111 
    112 static void nd6_setmtu0(struct ifnet *, struct nd_ifinfo *);
    113 static void nd6_slowtimo(void *);
    114 static int regen_tmpaddr(const struct in6_ifaddr *);
    115 static void nd6_free(struct llentry *, int);
    116 static void nd6_llinfo_timer(void *);
    117 static void nd6_timer(void *);
    118 static void nd6_timer_work(struct work *, void *);
    119 static void clear_llinfo_pqueue(struct llentry *);
    120 static struct nd_opt_hdr *nd6_option(union nd_opts *);
    121 
    122 static callout_t nd6_slowtimo_ch;
    123 static callout_t nd6_timer_ch;
    124 static struct workqueue	*nd6_timer_wq;
    125 static struct work	nd6_timer_wk;
    126 
    127 static int fill_drlist(void *, size_t *, size_t);
    128 static int fill_prlist(void *, size_t *, size_t);
    129 
    130 static struct ifnet *nd6_defifp;
    131 static int nd6_defifindex;
    132 
    133 static int nd6_setdefaultiface(int);
    134 
    135 MALLOC_DEFINE(M_IP6NDP, "NDP", "IPv6 Neighbour Discovery");
    136 
    137 void
    138 nd6_init(void)
    139 {
    140 	int error;
    141 
    142 	rw_init(&nd6_lock);
    143 
    144 	/* initialization of the default router list */
    145 	ND_DEFROUTER_LIST_INIT();
    146 
    147 	callout_init(&nd6_slowtimo_ch, CALLOUT_MPSAFE);
    148 	callout_init(&nd6_timer_ch, CALLOUT_MPSAFE);
    149 
    150 	error = workqueue_create(&nd6_timer_wq, "nd6_timer",
    151 	    nd6_timer_work, NULL, PRI_SOFTNET, IPL_SOFTNET, WQ_MPSAFE);
    152 	if (error)
    153 		panic("%s: workqueue_create failed (%d)\n", __func__, error);
    154 
    155 	/* start timer */
    156 	callout_reset(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
    157 	    nd6_slowtimo, NULL);
    158 	callout_reset(&nd6_timer_ch, hz, nd6_timer, NULL);
    159 }
    160 
    161 struct nd_ifinfo *
    162 nd6_ifattach(struct ifnet *ifp)
    163 {
    164 	struct nd_ifinfo *nd;
    165 
    166 	nd = kmem_zalloc(sizeof(*nd), KM_SLEEP);
    167 
    168 	nd->initialized = 1;
    169 
    170 	nd->chlim = IPV6_DEFHLIM;
    171 	nd->basereachable = REACHABLE_TIME;
    172 	nd->reachable = ND_COMPUTE_RTIME(nd->basereachable);
    173 	nd->retrans = RETRANS_TIMER;
    174 
    175 	nd->flags = ND6_IFF_PERFORMNUD | ND6_IFF_ACCEPT_RTADV;
    176 
    177 	/* A loopback interface always has ND6_IFF_AUTO_LINKLOCAL.
    178 	 * A bridge interface should not have ND6_IFF_AUTO_LINKLOCAL
    179 	 * because one of its members should. */
    180 	if ((ip6_auto_linklocal && ifp->if_type != IFT_BRIDGE) ||
    181 	    (ifp->if_flags & IFF_LOOPBACK))
    182 		nd->flags |= ND6_IFF_AUTO_LINKLOCAL;
    183 
    184 	/* A loopback interface does not need to accept RTADV.
    185 	 * A bridge interface should not accept RTADV
    186 	 * because one of its members should. */
    187 	if (ip6_accept_rtadv &&
    188 	    !(ifp->if_flags & IFF_LOOPBACK) &&
    189 	    !(ifp->if_type != IFT_BRIDGE))
    190 		nd->flags |= ND6_IFF_ACCEPT_RTADV;
    191 
    192 	/* XXX: we cannot call nd6_setmtu since ifp is not fully initialized */
    193 	nd6_setmtu0(ifp, nd);
    194 
    195 	return nd;
    196 }
    197 
    198 void
    199 nd6_ifdetach(struct ifnet *ifp, struct in6_ifextra *ext)
    200 {
    201 
    202 	/* Ensure all IPv6 addresses are purged before calling nd6_purge */
    203 	if_purgeaddrs(ifp, AF_INET6, in6_purgeaddr);
    204 	nd6_purge(ifp, ext);
    205 	kmem_free(ext->nd_ifinfo, sizeof(struct nd_ifinfo));
    206 }
    207 
    208 void
    209 nd6_setmtu(struct ifnet *ifp)
    210 {
    211 	nd6_setmtu0(ifp, ND_IFINFO(ifp));
    212 }
    213 
    214 void
    215 nd6_setmtu0(struct ifnet *ifp, struct nd_ifinfo *ndi)
    216 {
    217 	u_int32_t omaxmtu;
    218 
    219 	omaxmtu = ndi->maxmtu;
    220 
    221 	switch (ifp->if_type) {
    222 	case IFT_ARCNET:
    223 		ndi->maxmtu = MIN(ARC_PHDS_MAXMTU, ifp->if_mtu); /* RFC2497 */
    224 		break;
    225 	case IFT_FDDI:
    226 		ndi->maxmtu = MIN(FDDIIPMTU, ifp->if_mtu);
    227 		break;
    228 	default:
    229 		ndi->maxmtu = ifp->if_mtu;
    230 		break;
    231 	}
    232 
    233 	/*
    234 	 * Decreasing the interface MTU under IPV6 minimum MTU may cause
    235 	 * undesirable situation.  We thus notify the operator of the change
    236 	 * explicitly.  The check for omaxmtu is necessary to restrict the
    237 	 * log to the case of changing the MTU, not initializing it.
    238 	 */
    239 	if (omaxmtu >= IPV6_MMTU && ndi->maxmtu < IPV6_MMTU) {
    240 		log(LOG_NOTICE, "nd6_setmtu0: new link MTU on %s (%lu) is too"
    241 		    " small for IPv6 which needs %lu\n",
    242 		    if_name(ifp), (unsigned long)ndi->maxmtu, (unsigned long)
    243 		    IPV6_MMTU);
    244 	}
    245 
    246 	if (ndi->maxmtu > in6_maxmtu)
    247 		in6_setmaxmtu(); /* check all interfaces just in case */
    248 }
    249 
    250 void
    251 nd6_option_init(void *opt, int icmp6len, union nd_opts *ndopts)
    252 {
    253 
    254 	memset(ndopts, 0, sizeof(*ndopts));
    255 	ndopts->nd_opts_search = (struct nd_opt_hdr *)opt;
    256 	ndopts->nd_opts_last
    257 		= (struct nd_opt_hdr *)(((u_char *)opt) + icmp6len);
    258 
    259 	if (icmp6len == 0) {
    260 		ndopts->nd_opts_done = 1;
    261 		ndopts->nd_opts_search = NULL;
    262 	}
    263 }
    264 
    265 /*
    266  * Take one ND option.
    267  */
    268 static struct nd_opt_hdr *
    269 nd6_option(union nd_opts *ndopts)
    270 {
    271 	struct nd_opt_hdr *nd_opt;
    272 	int olen;
    273 
    274 	KASSERT(ndopts != NULL);
    275 	KASSERT(ndopts->nd_opts_last != NULL);
    276 
    277 	if (ndopts->nd_opts_search == NULL)
    278 		return NULL;
    279 	if (ndopts->nd_opts_done)
    280 		return NULL;
    281 
    282 	nd_opt = ndopts->nd_opts_search;
    283 
    284 	/* make sure nd_opt_len is inside the buffer */
    285 	if ((void *)&nd_opt->nd_opt_len >= (void *)ndopts->nd_opts_last) {
    286 		memset(ndopts, 0, sizeof(*ndopts));
    287 		return NULL;
    288 	}
    289 
    290 	olen = nd_opt->nd_opt_len << 3;
    291 	if (olen == 0) {
    292 		/*
    293 		 * Message validation requires that all included
    294 		 * options have a length that is greater than zero.
    295 		 */
    296 		memset(ndopts, 0, sizeof(*ndopts));
    297 		return NULL;
    298 	}
    299 
    300 	ndopts->nd_opts_search = (struct nd_opt_hdr *)((char *)nd_opt + olen);
    301 	if (ndopts->nd_opts_search > ndopts->nd_opts_last) {
    302 		/* option overruns the end of buffer, invalid */
    303 		memset(ndopts, 0, sizeof(*ndopts));
    304 		return NULL;
    305 	} else if (ndopts->nd_opts_search == ndopts->nd_opts_last) {
    306 		/* reached the end of options chain */
    307 		ndopts->nd_opts_done = 1;
    308 		ndopts->nd_opts_search = NULL;
    309 	}
    310 	return nd_opt;
    311 }
    312 
    313 /*
    314  * Parse multiple ND options.
    315  * This function is much easier to use, for ND routines that do not need
    316  * multiple options of the same type.
    317  */
    318 int
    319 nd6_options(union nd_opts *ndopts)
    320 {
    321 	struct nd_opt_hdr *nd_opt;
    322 	int i = 0;
    323 
    324 	KASSERT(ndopts != NULL);
    325 	KASSERT(ndopts->nd_opts_last != NULL);
    326 
    327 	if (ndopts->nd_opts_search == NULL)
    328 		return 0;
    329 
    330 	while (1) {
    331 		nd_opt = nd6_option(ndopts);
    332 		if (nd_opt == NULL && ndopts->nd_opts_last == NULL) {
    333 			/*
    334 			 * Message validation requires that all included
    335 			 * options have a length that is greater than zero.
    336 			 */
    337 			ICMP6_STATINC(ICMP6_STAT_ND_BADOPT);
    338 			memset(ndopts, 0, sizeof(*ndopts));
    339 			return -1;
    340 		}
    341 
    342 		if (nd_opt == NULL)
    343 			goto skip1;
    344 
    345 		switch (nd_opt->nd_opt_type) {
    346 		case ND_OPT_SOURCE_LINKADDR:
    347 		case ND_OPT_TARGET_LINKADDR:
    348 		case ND_OPT_MTU:
    349 		case ND_OPT_REDIRECTED_HEADER:
    350 			if (ndopts->nd_opt_array[nd_opt->nd_opt_type]) {
    351 				nd6log(LOG_INFO,
    352 				    "duplicated ND6 option found (type=%d)\n",
    353 				    nd_opt->nd_opt_type);
    354 				/* XXX bark? */
    355 			} else {
    356 				ndopts->nd_opt_array[nd_opt->nd_opt_type]
    357 					= nd_opt;
    358 			}
    359 			break;
    360 		case ND_OPT_PREFIX_INFORMATION:
    361 			if (ndopts->nd_opt_array[nd_opt->nd_opt_type] == 0) {
    362 				ndopts->nd_opt_array[nd_opt->nd_opt_type]
    363 					= nd_opt;
    364 			}
    365 			ndopts->nd_opts_pi_end =
    366 				(struct nd_opt_prefix_info *)nd_opt;
    367 			break;
    368 		default:
    369 			/*
    370 			 * Unknown options must be silently ignored,
    371 			 * to accommodate future extension to the protocol.
    372 			 */
    373 			nd6log(LOG_DEBUG,
    374 			    "nd6_options: unsupported option %d - "
    375 			    "option ignored\n", nd_opt->nd_opt_type);
    376 		}
    377 
    378 skip1:
    379 		i++;
    380 		if (i > nd6_maxndopt) {
    381 			ICMP6_STATINC(ICMP6_STAT_ND_TOOMANYOPT);
    382 			nd6log(LOG_INFO, "too many loop in nd opt\n");
    383 			break;
    384 		}
    385 
    386 		if (ndopts->nd_opts_done)
    387 			break;
    388 	}
    389 
    390 	return 0;
    391 }
    392 
    393 /*
    394  * ND6 timer routine to handle ND6 entries
    395  */
    396 void
    397 nd6_llinfo_settimer(struct llentry *ln, time_t xtick)
    398 {
    399 
    400 	CTASSERT(sizeof(time_t) > sizeof(int));
    401 	LLE_WLOCK_ASSERT(ln);
    402 
    403 	KASSERT(xtick >= 0);
    404 
    405 	ln->ln_expire = time_uptime + xtick / hz;
    406 	LLE_ADDREF(ln);
    407 	if (xtick > INT_MAX) {
    408 		ln->ln_ntick = xtick - INT_MAX;
    409 		callout_reset(&ln->ln_timer_ch, INT_MAX,
    410 		    nd6_llinfo_timer, ln);
    411 	} else {
    412 		ln->ln_ntick = 0;
    413 		callout_reset(&ln->ln_timer_ch, xtick,
    414 		    nd6_llinfo_timer, ln);
    415 	}
    416 }
    417 
    418 /*
    419  * Gets source address of the first packet in hold queue
    420  * and stores it in @src.
    421  * Returns pointer to @src (if hold queue is not empty) or NULL.
    422  */
    423 static struct in6_addr *
    424 nd6_llinfo_get_holdsrc(struct llentry *ln, struct in6_addr *src)
    425 {
    426 	struct ip6_hdr *hip6;
    427 
    428 	if (ln == NULL || ln->ln_hold == NULL)
    429 		return NULL;
    430 
    431 	/*
    432 	 * assuming every packet in ln_hold has the same IP header
    433 	 */
    434 	hip6 = mtod(ln->ln_hold, struct ip6_hdr *);
    435 	/* XXX pullup? */
    436 	if (sizeof(*hip6) < ln->ln_hold->m_len)
    437 		*src = hip6->ip6_src;
    438 	else
    439 		src = NULL;
    440 
    441 	return src;
    442 }
    443 
    444 static void
    445 nd6_llinfo_timer(void *arg)
    446 {
    447 	struct llentry *ln = arg;
    448 	struct ifnet *ifp;
    449 	struct nd_ifinfo *ndi = NULL;
    450 	bool send_ns = false;
    451 	const struct in6_addr *daddr6 = NULL;
    452 
    453 #ifndef NET_MPSAFE
    454 	mutex_enter(softnet_lock);
    455 	KERNEL_LOCK(1, NULL);
    456 #endif
    457 	LLE_WLOCK(ln);
    458 	if ((ln->la_flags & LLE_LINKED) == 0)
    459 		goto out;
    460 	if (ln->ln_ntick > 0) {
    461 		nd6_llinfo_settimer(ln, ln->ln_ntick);
    462 		goto out;
    463 	}
    464 
    465 	if (callout_pending(&ln->la_timer)) {
    466 		/*
    467 		 * Here we are a bit odd here in the treatment of
    468 		 * active/pending. If the pending bit is set, it got
    469 		 * rescheduled before I ran. The active
    470 		 * bit we ignore, since if it was stopped
    471 		 * in ll_tablefree() and was currently running
    472 		 * it would have return 0 so the code would
    473 		 * not have deleted it since the callout could
    474 		 * not be stopped so we want to go through
    475 		 * with the delete here now. If the callout
    476 		 * was restarted, the pending bit will be back on and
    477 		 * we just want to bail since the callout_reset would
    478 		 * return 1 and our reference would have been removed
    479 		 * by nd6_llinfo_settimer above since canceled
    480 		 * would have been 1.
    481 		 */
    482 		goto out;
    483 	}
    484 
    485 	ifp = ln->lle_tbl->llt_ifp;
    486 
    487 	KASSERT(ifp != NULL);
    488 
    489 	ndi = ND_IFINFO(ifp);
    490 
    491 	switch (ln->ln_state) {
    492 	case ND6_LLINFO_INCOMPLETE:
    493 		if (ln->ln_asked < nd6_mmaxtries) {
    494 			ln->ln_asked++;
    495 			send_ns = true;
    496 		} else {
    497 			struct mbuf *m = ln->ln_hold;
    498 			if (m) {
    499 				struct mbuf *m0;
    500 
    501 				/*
    502 				 * assuming every packet in ln_hold has
    503 				 * the same IP header
    504 				 */
    505 				m0 = m->m_nextpkt;
    506 				m->m_nextpkt = NULL;
    507 				ln->ln_hold = m0;
    508 				clear_llinfo_pqueue(ln);
    509  			}
    510 			nd6_free(ln, 0);
    511 			ln = NULL;
    512 			if (m != NULL) {
    513 				icmp6_error2(m, ICMP6_DST_UNREACH,
    514 				    ICMP6_DST_UNREACH_ADDR, 0, ifp);
    515 			}
    516 		}
    517 		break;
    518 	case ND6_LLINFO_REACHABLE:
    519 		if (!ND6_LLINFO_PERMANENT(ln)) {
    520 			ln->ln_state = ND6_LLINFO_STALE;
    521 			nd6_llinfo_settimer(ln, nd6_gctimer * hz);
    522 		}
    523 		break;
    524 
    525 	case ND6_LLINFO_PURGE:
    526 	case ND6_LLINFO_STALE:
    527 		/* Garbage Collection(RFC 2461 5.3) */
    528 		if (!ND6_LLINFO_PERMANENT(ln)) {
    529 			nd6_free(ln, 1);
    530 			ln = NULL;
    531 		}
    532 		break;
    533 
    534 	case ND6_LLINFO_DELAY:
    535 		if (ndi && (ndi->flags & ND6_IFF_PERFORMNUD) != 0) {
    536 			/* We need NUD */
    537 			ln->ln_asked = 1;
    538 			ln->ln_state = ND6_LLINFO_PROBE;
    539 			daddr6 = &ln->r_l3addr.addr6;
    540 			send_ns = true;
    541 		} else {
    542 			ln->ln_state = ND6_LLINFO_STALE; /* XXX */
    543 			nd6_llinfo_settimer(ln, nd6_gctimer * hz);
    544 		}
    545 		break;
    546 	case ND6_LLINFO_PROBE:
    547 		if (ln->ln_asked < nd6_umaxtries) {
    548 			ln->ln_asked++;
    549 			daddr6 = &ln->r_l3addr.addr6;
    550 			send_ns = true;
    551 		} else {
    552 			nd6_free(ln, 0);
    553 			ln = NULL;
    554 		}
    555 		break;
    556 	}
    557 
    558 	if (send_ns) {
    559 		struct in6_addr src, *psrc;
    560 		const struct in6_addr *taddr6 = &ln->r_l3addr.addr6;
    561 
    562 		nd6_llinfo_settimer(ln, ndi->retrans * hz / 1000);
    563 		psrc = nd6_llinfo_get_holdsrc(ln, &src);
    564 		LLE_FREE_LOCKED(ln);
    565 		ln = NULL;
    566 		nd6_ns_output(ifp, daddr6, taddr6, psrc, 0);
    567 	}
    568 
    569 out:
    570 	if (ln != NULL)
    571 		LLE_FREE_LOCKED(ln);
    572 #ifndef NET_MPSAFE
    573 	KERNEL_UNLOCK_ONE(NULL);
    574 	mutex_exit(softnet_lock);
    575 #endif
    576 }
    577 
    578 /*
    579  * ND6 timer routine to expire default route list and prefix list
    580  */
    581 static void
    582 nd6_timer_work(struct work *wk, void *arg)
    583 {
    584 	struct nd_defrouter *next_dr, *dr;
    585 	struct nd_prefix *next_pr, *pr;
    586 	struct in6_ifaddr *ia6, *nia6;
    587 	int s, bound;
    588 	struct psref psref;
    589 
    590 	callout_reset(&nd6_timer_ch, nd6_prune * hz,
    591 	    nd6_timer, NULL);
    592 
    593 #ifndef NET_MPSAFE
    594 	mutex_enter(softnet_lock);
    595 	KERNEL_LOCK(1, NULL);
    596 #endif
    597 
    598 	/* expire default router list */
    599 
    600 	ND6_WLOCK();
    601 	ND_DEFROUTER_LIST_FOREACH_SAFE(dr, next_dr) {
    602 		if (dr->expire && dr->expire < time_uptime) {
    603 			nd6_defrtrlist_del(dr, NULL);
    604 		}
    605 	}
    606 	ND6_UNLOCK();
    607 
    608 	/*
    609 	 * expire interface addresses.
    610 	 * in the past the loop was inside prefix expiry processing.
    611 	 * However, from a stricter speci-confrmance standpoint, we should
    612 	 * rather separate address lifetimes and prefix lifetimes.
    613 	 */
    614 	bound = curlwp_bind();
    615   addrloop:
    616 	s = pserialize_read_enter();
    617 	for (ia6 = IN6_ADDRLIST_READER_FIRST(); ia6; ia6 = nia6) {
    618 		nia6 = IN6_ADDRLIST_READER_NEXT(ia6);
    619 
    620 		ia6_acquire(ia6, &psref);
    621 		pserialize_read_exit(s);
    622 
    623 		/* check address lifetime */
    624 		if (IFA6_IS_INVALID(ia6)) {
    625 			int regen = 0;
    626 
    627 			/*
    628 			 * If the expiring address is temporary, try
    629 			 * regenerating a new one.  This would be useful when
    630 			 * we suspended a laptop PC, then turned it on after a
    631 			 * period that could invalidate all temporary
    632 			 * addresses.  Although we may have to restart the
    633 			 * loop (see below), it must be after purging the
    634 			 * address.  Otherwise, we'd see an infinite loop of
    635 			 * regeneration.
    636 			 */
    637 			if (ip6_use_tempaddr &&
    638 			    (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
    639 				if (regen_tmpaddr(ia6) == 0)
    640 					regen = 1;
    641 			}
    642 
    643 			ia6_release(ia6, &psref);
    644  			in6_purgeaddr(&ia6->ia_ifa);
    645 			ia6 = NULL;
    646 
    647 			if (regen)
    648 				goto addrloop; /* XXX: see below */
    649 		} else if (IFA6_IS_DEPRECATED(ia6)) {
    650 			int oldflags = ia6->ia6_flags;
    651 
    652 			if ((oldflags & IN6_IFF_DEPRECATED) == 0) {
    653 				ia6->ia6_flags |= IN6_IFF_DEPRECATED;
    654 				rt_newaddrmsg(RTM_NEWADDR,
    655 				    (struct ifaddr *)ia6, 0, NULL);
    656 			}
    657 
    658 			/*
    659 			 * If a temporary address has just become deprecated,
    660 			 * regenerate a new one if possible.
    661 			 */
    662 			if (ip6_use_tempaddr &&
    663 			    (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
    664 			    (oldflags & IN6_IFF_DEPRECATED) == 0) {
    665 
    666 				if (regen_tmpaddr(ia6) == 0) {
    667 					/*
    668 					 * A new temporary address is
    669 					 * generated.
    670 					 * XXX: this means the address chain
    671 					 * has changed while we are still in
    672 					 * the loop.  Although the change
    673 					 * would not cause disaster (because
    674 					 * it's not a deletion, but an
    675 					 * addition,) we'd rather restart the
    676 					 * loop just for safety.  Or does this
    677 					 * significantly reduce performance??
    678 					 */
    679 					ia6_release(ia6, &psref);
    680 					goto addrloop;
    681 				}
    682 			}
    683 		} else {
    684 			/*
    685 			 * A new RA might have made a deprecated address
    686 			 * preferred.
    687 			 */
    688 			if (ia6->ia6_flags & IN6_IFF_DEPRECATED) {
    689 				ia6->ia6_flags &= ~IN6_IFF_DEPRECATED;
    690 				rt_newaddrmsg(RTM_NEWADDR,
    691 				    (struct ifaddr *)ia6, 0, NULL);
    692 			}
    693 		}
    694 		s = pserialize_read_enter();
    695 		ia6_release(ia6, &psref);
    696 	}
    697 	pserialize_read_exit(s);
    698 	curlwp_bindx(bound);
    699 
    700 	/* expire prefix list */
    701 	ND6_WLOCK();
    702 	ND_PREFIX_LIST_FOREACH_SAFE(pr, next_pr) {
    703 		/*
    704 		 * check prefix lifetime.
    705 		 * since pltime is just for autoconf, pltime processing for
    706 		 * prefix is not necessary.
    707 		 */
    708 		if (pr->ndpr_vltime != ND6_INFINITE_LIFETIME &&
    709 		    time_uptime - pr->ndpr_lastupdate > pr->ndpr_vltime) {
    710 			/*
    711 			 * Just invalidate the prefix here. Removing it
    712 			 * will be done when purging an associated address.
    713 			 */
    714 			KASSERT(pr->ndpr_refcnt > 0);
    715 			nd6_invalidate_prefix(pr);
    716 		}
    717 	}
    718 	ND6_UNLOCK();
    719 
    720 #ifndef NET_MPSAFE
    721 	KERNEL_UNLOCK_ONE(NULL);
    722 	mutex_exit(softnet_lock);
    723 #endif
    724 }
    725 
    726 static void
    727 nd6_timer(void *ignored_arg)
    728 {
    729 
    730 	workqueue_enqueue(nd6_timer_wq, &nd6_timer_wk, NULL);
    731 }
    732 
    733 /* ia6: deprecated/invalidated temporary address */
    734 static int
    735 regen_tmpaddr(const struct in6_ifaddr *ia6)
    736 {
    737 	struct ifaddr *ifa;
    738 	struct ifnet *ifp;
    739 	struct in6_ifaddr *public_ifa6 = NULL;
    740 	int s;
    741 
    742 	ifp = ia6->ia_ifa.ifa_ifp;
    743 	s = pserialize_read_enter();
    744 	IFADDR_READER_FOREACH(ifa, ifp) {
    745 		struct in6_ifaddr *it6;
    746 
    747 		if (ifa->ifa_addr->sa_family != AF_INET6)
    748 			continue;
    749 
    750 		it6 = (struct in6_ifaddr *)ifa;
    751 
    752 		/* ignore no autoconf addresses. */
    753 		if ((it6->ia6_flags & IN6_IFF_AUTOCONF) == 0)
    754 			continue;
    755 
    756 		/* ignore autoconf addresses with different prefixes. */
    757 		if (it6->ia6_ndpr == NULL || it6->ia6_ndpr != ia6->ia6_ndpr)
    758 			continue;
    759 
    760 		/*
    761 		 * Now we are looking at an autoconf address with the same
    762 		 * prefix as ours.  If the address is temporary and is still
    763 		 * preferred, do not create another one.  It would be rare, but
    764 		 * could happen, for example, when we resume a laptop PC after
    765 		 * a long period.
    766 		 */
    767 		if ((it6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
    768 		    !IFA6_IS_DEPRECATED(it6)) {
    769 			public_ifa6 = NULL;
    770 			break;
    771 		}
    772 
    773 		/*
    774 		 * This is a public autoconf address that has the same prefix
    775 		 * as ours.  If it is preferred, keep it.  We can't break the
    776 		 * loop here, because there may be a still-preferred temporary
    777 		 * address with the prefix.
    778 		 */
    779 		if (!IFA6_IS_DEPRECATED(it6))
    780 			public_ifa6 = it6;
    781 	}
    782 
    783 	if (public_ifa6 != NULL) {
    784 		int e;
    785 		struct psref psref;
    786 
    787 		ia6_acquire(public_ifa6, &psref);
    788 		pserialize_read_exit(s);
    789 		/*
    790 		 * Random factor is introduced in the preferred lifetime, so
    791 		 * we do not need additional delay (3rd arg to in6_tmpifadd).
    792 		 */
    793 		ND6_WLOCK();
    794 		e = in6_tmpifadd(public_ifa6, 0, 0);
    795 		ND6_UNLOCK();
    796 		if (e != 0) {
    797 			ia6_release(public_ifa6, &psref);
    798 			log(LOG_NOTICE, "regen_tmpaddr: failed to create a new"
    799 			    " tmp addr, errno=%d\n", e);
    800 			return -1;
    801 		}
    802 		ia6_release(public_ifa6, &psref);
    803 		return 0;
    804 	}
    805 	pserialize_read_exit(s);
    806 
    807 	return -1;
    808 }
    809 
    810 bool
    811 nd6_accepts_rtadv(const struct nd_ifinfo *ndi)
    812 {
    813 	switch (ndi->flags & (ND6_IFF_ACCEPT_RTADV|ND6_IFF_OVERRIDE_RTADV)) {
    814 	case ND6_IFF_OVERRIDE_RTADV|ND6_IFF_ACCEPT_RTADV:
    815 		return true;
    816 	case ND6_IFF_ACCEPT_RTADV:
    817 		return ip6_accept_rtadv != 0;
    818 	case ND6_IFF_OVERRIDE_RTADV:
    819 	case 0:
    820 	default:
    821 		return false;
    822 	}
    823 }
    824 
    825 /*
    826  * Nuke neighbor cache/prefix/default router management table, right before
    827  * ifp goes away.
    828  */
    829 void
    830 nd6_purge(struct ifnet *ifp, struct in6_ifextra *ext)
    831 {
    832 	struct nd_defrouter *dr, *ndr;
    833 	struct nd_prefix *pr, *npr;
    834 
    835 	/*
    836 	 * During detach, the ND info might be already removed, but
    837 	 * then is explitly passed as argument.
    838 	 * Otherwise get it from ifp->if_afdata.
    839 	 */
    840 	if (ext == NULL)
    841 		ext = ifp->if_afdata[AF_INET6];
    842 	if (ext == NULL)
    843 		return;
    844 
    845 	ND6_WLOCK();
    846 	/*
    847 	 * Nuke default router list entries toward ifp.
    848 	 * We defer removal of default router list entries that is installed
    849 	 * in the routing table, in order to keep additional side effects as
    850 	 * small as possible.
    851 	 */
    852 	ND_DEFROUTER_LIST_FOREACH_SAFE(dr, ndr) {
    853 		if (dr->installed)
    854 			continue;
    855 
    856 		if (dr->ifp == ifp) {
    857 			KASSERT(ext != NULL);
    858 			nd6_defrtrlist_del(dr, ext);
    859 		}
    860 	}
    861 
    862 	ND_DEFROUTER_LIST_FOREACH_SAFE(dr, ndr) {
    863 		if (!dr->installed)
    864 			continue;
    865 
    866 		if (dr->ifp == ifp) {
    867 			KASSERT(ext != NULL);
    868 			nd6_defrtrlist_del(dr, ext);
    869 		}
    870 	}
    871 
    872 	/* Nuke prefix list entries toward ifp */
    873 	ND_PREFIX_LIST_FOREACH_SAFE(pr, npr) {
    874 		if (pr->ndpr_ifp == ifp) {
    875 			/*
    876 			 * All addresses referencing pr should be already freed.
    877 			 */
    878 			KASSERT(pr->ndpr_refcnt == 0);
    879 			nd6_prelist_remove(pr);
    880 		}
    881 	}
    882 
    883 	/* cancel default outgoing interface setting */
    884 	if (nd6_defifindex == ifp->if_index)
    885 		nd6_setdefaultiface(0);
    886 
    887 	/* XXX: too restrictive? */
    888 	if (!ip6_forwarding && ifp->if_afdata[AF_INET6]) {
    889 		struct nd_ifinfo *ndi = ND_IFINFO(ifp);
    890 		if (ndi && nd6_accepts_rtadv(ndi)) {
    891 			/* refresh default router list */
    892 			nd6_defrouter_select();
    893 		}
    894 	}
    895 	ND6_UNLOCK();
    896 
    897 	/*
    898 	 * We may not need to nuke the neighbor cache entries here
    899 	 * because the neighbor cache is kept in if_afdata[AF_INET6].
    900 	 * nd6_purge() is invoked by in6_ifdetach() which is called
    901 	 * from if_detach() where everything gets purged. However
    902 	 * in6_ifdetach is directly called from vlan(4), so we still
    903 	 * need to purge entries here.
    904 	 */
    905 	if (ext->lltable != NULL)
    906 		lltable_purge_entries(ext->lltable);
    907 }
    908 
    909 void
    910 nd6_assert_purged(struct ifnet *ifp)
    911 {
    912 	struct nd_defrouter *dr;
    913 	struct nd_prefix *pr;
    914 	char ip6buf[INET6_ADDRSTRLEN] __diagused;
    915 
    916 	ND6_RLOCK();
    917 	ND_DEFROUTER_LIST_FOREACH(dr) {
    918 		KASSERTMSG(dr->ifp != ifp,
    919 		    "defrouter %s remains on %s",
    920 		    IN6_PRINT(ip6buf, &dr->rtaddr), ifp->if_xname);
    921 	}
    922 
    923 	ND_PREFIX_LIST_FOREACH(pr) {
    924 		KASSERTMSG(pr->ndpr_ifp != ifp,
    925 		    "prefix %s/%d remains on %s",
    926 		    IN6_PRINT(ip6buf, &pr->ndpr_prefix.sin6_addr),
    927 		    pr->ndpr_plen, ifp->if_xname);
    928 	}
    929 	ND6_UNLOCK();
    930 }
    931 
    932 struct llentry *
    933 nd6_lookup(const struct in6_addr *addr6, const struct ifnet *ifp, bool wlock)
    934 {
    935 	struct sockaddr_in6 sin6;
    936 	struct llentry *ln;
    937 
    938 	sockaddr_in6_init(&sin6, addr6, 0, 0, 0);
    939 
    940 	IF_AFDATA_RLOCK(ifp);
    941 	ln = lla_lookup(LLTABLE6(ifp), wlock ? LLE_EXCLUSIVE : 0,
    942 	    sin6tosa(&sin6));
    943 	IF_AFDATA_RUNLOCK(ifp);
    944 
    945 	return ln;
    946 }
    947 
    948 struct llentry *
    949 nd6_create(const struct in6_addr *addr6, const struct ifnet *ifp)
    950 {
    951 	struct sockaddr_in6 sin6;
    952 	struct llentry *ln;
    953 	struct rtentry *rt;
    954 
    955 	sockaddr_in6_init(&sin6, addr6, 0, 0, 0);
    956 	rt = rtalloc1(sin6tosa(&sin6), 0);
    957 
    958 	IF_AFDATA_WLOCK(ifp);
    959 	ln = lla_create(LLTABLE6(ifp), LLE_EXCLUSIVE, sin6tosa(&sin6), rt);
    960 	IF_AFDATA_WUNLOCK(ifp);
    961 
    962 	if (rt != NULL)
    963 		rt_unref(rt);
    964 	if (ln != NULL)
    965 		ln->ln_state = ND6_LLINFO_NOSTATE;
    966 
    967 	return ln;
    968 }
    969 
    970 /*
    971  * Test whether a given IPv6 address is a neighbor or not, ignoring
    972  * the actual neighbor cache.  The neighbor cache is ignored in order
    973  * to not reenter the routing code from within itself.
    974  */
    975 static int
    976 nd6_is_new_addr_neighbor(const struct sockaddr_in6 *addr, struct ifnet *ifp)
    977 {
    978 	struct nd_prefix *pr;
    979 	struct ifaddr *dstaddr;
    980 	int s;
    981 
    982 	/*
    983 	 * A link-local address is always a neighbor.
    984 	 * XXX: a link does not necessarily specify a single interface.
    985 	 */
    986 	if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr)) {
    987 		struct sockaddr_in6 sin6_copy;
    988 		u_int32_t zone;
    989 
    990 		/*
    991 		 * We need sin6_copy since sa6_recoverscope() may modify the
    992 		 * content (XXX).
    993 		 */
    994 		sin6_copy = *addr;
    995 		if (sa6_recoverscope(&sin6_copy))
    996 			return 0; /* XXX: should be impossible */
    997 		if (in6_setscope(&sin6_copy.sin6_addr, ifp, &zone))
    998 			return 0;
    999 		if (sin6_copy.sin6_scope_id == zone)
   1000 			return 1;
   1001 		else
   1002 			return 0;
   1003 	}
   1004 
   1005 	/*
   1006 	 * If the address matches one of our addresses,
   1007 	 * it should be a neighbor.
   1008 	 * If the address matches one of our on-link prefixes, it should be a
   1009 	 * neighbor.
   1010 	 */
   1011 	ND6_RLOCK();
   1012 	ND_PREFIX_LIST_FOREACH(pr) {
   1013 		if (pr->ndpr_ifp != ifp)
   1014 			continue;
   1015 
   1016 		if (!(pr->ndpr_stateflags & NDPRF_ONLINK)) {
   1017 			struct rtentry *rt;
   1018 
   1019 			rt = rtalloc1(sin6tosa(&pr->ndpr_prefix), 0);
   1020 			if (rt == NULL)
   1021 				continue;
   1022 			/*
   1023 			 * This is the case where multiple interfaces
   1024 			 * have the same prefix, but only one is installed
   1025 			 * into the routing table and that prefix entry
   1026 			 * is not the one being examined here. In the case
   1027 			 * where RADIX_MPATH is enabled, multiple route
   1028 			 * entries (of the same rt_key value) will be
   1029 			 * installed because the interface addresses all
   1030 			 * differ.
   1031 			 */
   1032 			if (!IN6_ARE_ADDR_EQUAL(&pr->ndpr_prefix.sin6_addr,
   1033 			    &satocsin6(rt_getkey(rt))->sin6_addr)) {
   1034 				rt_unref(rt);
   1035 				continue;
   1036 			}
   1037 			rt_unref(rt);
   1038 		}
   1039 
   1040 		if (IN6_ARE_MASKED_ADDR_EQUAL(&pr->ndpr_prefix.sin6_addr,
   1041 		    &addr->sin6_addr, &pr->ndpr_mask)) {
   1042 			ND6_UNLOCK();
   1043 			return 1;
   1044 		}
   1045 	}
   1046 	ND6_UNLOCK();
   1047 
   1048 	/*
   1049 	 * If the address is assigned on the node of the other side of
   1050 	 * a p2p interface, the address should be a neighbor.
   1051 	 */
   1052 	s = pserialize_read_enter();
   1053 	dstaddr = ifa_ifwithdstaddr(sin6tocsa(addr));
   1054 	if (dstaddr != NULL) {
   1055 		if (dstaddr->ifa_ifp == ifp) {
   1056 			pserialize_read_exit(s);
   1057 			return 1;
   1058 		}
   1059 	}
   1060 	pserialize_read_exit(s);
   1061 
   1062 	/*
   1063 	 * If the default router list is empty, all addresses are regarded
   1064 	 * as on-link, and thus, as a neighbor.
   1065 	 */
   1066 	ND6_RLOCK();
   1067 	if (ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV &&
   1068 	    ND_DEFROUTER_LIST_EMPTY() && nd6_defifindex == ifp->if_index) {
   1069 		ND6_UNLOCK();
   1070 		return 1;
   1071 	}
   1072 	ND6_UNLOCK();
   1073 
   1074 	return 0;
   1075 }
   1076 
   1077 /*
   1078  * Detect if a given IPv6 address identifies a neighbor on a given link.
   1079  * XXX: should take care of the destination of a p2p link?
   1080  */
   1081 int
   1082 nd6_is_addr_neighbor(const struct sockaddr_in6 *addr, struct ifnet *ifp)
   1083 {
   1084 	struct nd_prefix *pr;
   1085 	struct llentry *ln;
   1086 	struct rtentry *rt;
   1087 
   1088 	/*
   1089 	 * A link-local address is always a neighbor.
   1090 	 * XXX: a link does not necessarily specify a single interface.
   1091 	 */
   1092 	if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr)) {
   1093 		struct sockaddr_in6 sin6_copy;
   1094 		u_int32_t zone;
   1095 
   1096 		/*
   1097 		 * We need sin6_copy since sa6_recoverscope() may modify the
   1098 		 * content (XXX).
   1099 		 */
   1100 		sin6_copy = *addr;
   1101 		if (sa6_recoverscope(&sin6_copy))
   1102 			return 0; /* XXX: should be impossible */
   1103 		if (in6_setscope(&sin6_copy.sin6_addr, ifp, &zone))
   1104 			return 0;
   1105 		if (sin6_copy.sin6_scope_id == zone)
   1106 			return 1;
   1107 		else
   1108 			return 0;
   1109 	}
   1110 
   1111 	/*
   1112 	 * If the address matches one of our on-link prefixes, it should be a
   1113 	 * neighbor.
   1114 	 */
   1115 	ND6_RLOCK();
   1116 	ND_PREFIX_LIST_FOREACH(pr) {
   1117 		if (pr->ndpr_ifp != ifp)
   1118 			continue;
   1119 
   1120 		if (!(pr->ndpr_stateflags & NDPRF_ONLINK))
   1121 			continue;
   1122 
   1123 		if (IN6_ARE_MASKED_ADDR_EQUAL(&pr->ndpr_prefix.sin6_addr,
   1124 		    &addr->sin6_addr, &pr->ndpr_mask)) {
   1125 			ND6_UNLOCK();
   1126 			return 1;
   1127 		}
   1128 	}
   1129 
   1130 	/*
   1131 	 * If the default router list is empty, all addresses are regarded
   1132 	 * as on-link, and thus, as a neighbor.
   1133 	 * XXX: we restrict the condition to hosts, because routers usually do
   1134 	 * not have the "default router list".
   1135 	 */
   1136 	if (!ip6_forwarding && ND_DEFROUTER_LIST_EMPTY() &&
   1137 	    nd6_defifindex == ifp->if_index) {
   1138 		ND6_UNLOCK();
   1139 		return 1;
   1140 	}
   1141 	ND6_UNLOCK();
   1142 
   1143 	if (nd6_is_new_addr_neighbor(addr, ifp))
   1144 		return 1;
   1145 
   1146 	/*
   1147 	 * Even if the address matches none of our addresses, it might be
   1148 	 * in the neighbor cache or a connected route.
   1149 	 */
   1150 	ln = nd6_lookup(&addr->sin6_addr, ifp, false);
   1151 	if (ln != NULL) {
   1152 		LLE_RUNLOCK(ln);
   1153 		return 1;
   1154 	}
   1155 
   1156 	rt = rtalloc1(sin6tocsa(addr), 0);
   1157 	if (rt == NULL)
   1158 		return 0;
   1159 
   1160 	if ((rt->rt_flags & RTF_CONNECTED) && (rt->rt_ifp == ifp
   1161 #if NBRIDGE > 0
   1162 	    || rt->rt_ifp->if_bridge == ifp->if_bridge
   1163 #endif
   1164 #if NCARP > 0
   1165 	    || (ifp->if_type == IFT_CARP && rt->rt_ifp == ifp->if_carpdev) ||
   1166 	    (rt->rt_ifp->if_type == IFT_CARP && rt->rt_ifp->if_carpdev == ifp)||
   1167 	    (ifp->if_type == IFT_CARP && rt->rt_ifp->if_type == IFT_CARP &&
   1168 	    rt->rt_ifp->if_carpdev == ifp->if_carpdev)
   1169 #endif
   1170 	    )) {
   1171 		rt_unref(rt);
   1172 		return 1;
   1173 	}
   1174 	rt_unref(rt);
   1175 
   1176 	return 0;
   1177 }
   1178 
   1179 /*
   1180  * Free an nd6 llinfo entry.
   1181  * Since the function would cause significant changes in the kernel, DO NOT
   1182  * make it global, unless you have a strong reason for the change, and are sure
   1183  * that the change is safe.
   1184  */
   1185 static void
   1186 nd6_free(struct llentry *ln, int gc)
   1187 {
   1188 	struct nd_defrouter *dr;
   1189 	struct ifnet *ifp;
   1190 	struct in6_addr *in6;
   1191 
   1192 	KASSERT(ln != NULL);
   1193 	LLE_WLOCK_ASSERT(ln);
   1194 
   1195 	ifp = ln->lle_tbl->llt_ifp;
   1196 	in6 = &ln->r_l3addr.addr6;
   1197 	/*
   1198 	 * we used to have pfctlinput(PRC_HOSTDEAD) here.
   1199 	 * even though it is not harmful, it was not really necessary.
   1200 	 */
   1201 
   1202 	if (!ip6_forwarding) {
   1203 		ND6_WLOCK();
   1204 		dr = nd6_defrouter_lookup(in6, ifp);
   1205 
   1206 		if (dr != NULL && dr->expire &&
   1207 		    ln->ln_state == ND6_LLINFO_STALE && gc) {
   1208 			/*
   1209 			 * If the reason for the deletion is just garbage
   1210 			 * collection, and the neighbor is an active default
   1211 			 * router, do not delete it.  Instead, reset the GC
   1212 			 * timer using the router's lifetime.
   1213 			 * Simply deleting the entry would affect default
   1214 			 * router selection, which is not necessarily a good
   1215 			 * thing, especially when we're using router preference
   1216 			 * values.
   1217 			 * XXX: the check for ln_state would be redundant,
   1218 			 *      but we intentionally keep it just in case.
   1219 			 */
   1220 			if (dr->expire > time_uptime)
   1221 				nd6_llinfo_settimer(ln,
   1222 				    (dr->expire - time_uptime) * hz);
   1223 			else
   1224 				nd6_llinfo_settimer(ln, nd6_gctimer * hz);
   1225 			ND6_UNLOCK();
   1226 			LLE_WUNLOCK(ln);
   1227 			return;
   1228 		}
   1229 
   1230 		if (ln->ln_router || dr) {
   1231 			/*
   1232 			 * We need to unlock to avoid a LOR with nd6_rt_flush()
   1233 			 * with the rnh and for the calls to
   1234 			 * nd6_pfxlist_onlink_check() and nd6_defrouter_select() in the
   1235 			 * block further down for calls into nd6_lookup().
   1236 			 * We still hold a ref.
   1237 			 */
   1238 			LLE_WUNLOCK(ln);
   1239 
   1240 			/*
   1241 			 * nd6_rt_flush must be called whether or not the neighbor
   1242 			 * is in the Default Router List.
   1243 			 * See a corresponding comment in nd6_na_input().
   1244 			 */
   1245 			nd6_rt_flush(in6, ifp);
   1246 		}
   1247 
   1248 		if (dr) {
   1249 			/*
   1250 			 * Unreachablity of a router might affect the default
   1251 			 * router selection and on-link detection of advertised
   1252 			 * prefixes.
   1253 			 */
   1254 
   1255 			/*
   1256 			 * Temporarily fake the state to choose a new default
   1257 			 * router and to perform on-link determination of
   1258 			 * prefixes correctly.
   1259 			 * Below the state will be set correctly,
   1260 			 * or the entry itself will be deleted.
   1261 			 */
   1262 			ln->ln_state = ND6_LLINFO_INCOMPLETE;
   1263 
   1264 			/*
   1265 			 * Since nd6_defrouter_select() does not affect the
   1266 			 * on-link determination and MIP6 needs the check
   1267 			 * before the default router selection, we perform
   1268 			 * the check now.
   1269 			 */
   1270 			nd6_pfxlist_onlink_check();
   1271 
   1272 			/*
   1273 			 * refresh default router list
   1274 			 */
   1275 			nd6_defrouter_select();
   1276 		}
   1277 
   1278 #ifdef __FreeBSD__
   1279 		/*
   1280 		 * If this entry was added by an on-link redirect, remove the
   1281 		 * corresponding host route.
   1282 		 */
   1283 		if (ln->la_flags & LLE_REDIRECT)
   1284 			nd6_free_redirect(ln);
   1285 #endif
   1286 		ND6_UNLOCK();
   1287 
   1288 		if (ln->ln_router || dr)
   1289 			LLE_WLOCK(ln);
   1290 	}
   1291 
   1292 	/*
   1293 	 * Save to unlock. We still hold an extra reference and will not
   1294 	 * free(9) in llentry_free() if someone else holds one as well.
   1295 	 */
   1296 	LLE_WUNLOCK(ln);
   1297 	IF_AFDATA_LOCK(ifp);
   1298 	LLE_WLOCK(ln);
   1299 
   1300 	lltable_free_entry(LLTABLE6(ifp), ln);
   1301 
   1302 	IF_AFDATA_UNLOCK(ifp);
   1303 }
   1304 
   1305 /*
   1306  * Upper-layer reachability hint for Neighbor Unreachability Detection.
   1307  *
   1308  * XXX cost-effective methods?
   1309  */
   1310 void
   1311 nd6_nud_hint(struct rtentry *rt)
   1312 {
   1313 	struct llentry *ln;
   1314 	struct ifnet *ifp;
   1315 
   1316 	if (rt == NULL)
   1317 		return;
   1318 
   1319 	ifp = rt->rt_ifp;
   1320 	ln = nd6_lookup(&(satocsin6(rt_getkey(rt)))->sin6_addr, ifp, true);
   1321 	if (ln == NULL)
   1322 		return;
   1323 
   1324 	if (ln->ln_state < ND6_LLINFO_REACHABLE)
   1325 		goto done;
   1326 
   1327 	/*
   1328 	 * if we get upper-layer reachability confirmation many times,
   1329 	 * it is possible we have false information.
   1330 	 */
   1331 	ln->ln_byhint++;
   1332 	if (ln->ln_byhint > nd6_maxnudhint)
   1333 		goto done;
   1334 
   1335 	ln->ln_state = ND6_LLINFO_REACHABLE;
   1336 	if (!ND6_LLINFO_PERMANENT(ln))
   1337 		nd6_llinfo_settimer(ln, ND_IFINFO(rt->rt_ifp)->reachable * hz);
   1338 
   1339 done:
   1340 	LLE_WUNLOCK(ln);
   1341 
   1342 	return;
   1343 }
   1344 
   1345 struct gc_args {
   1346 	int gc_entries;
   1347 	const struct in6_addr *skip_in6;
   1348 };
   1349 
   1350 static int
   1351 nd6_purge_entry(struct lltable *llt, struct llentry *ln, void *farg)
   1352 {
   1353 	struct gc_args *args = farg;
   1354 	int *n = &args->gc_entries;
   1355 	const struct in6_addr *skip_in6 = args->skip_in6;
   1356 
   1357 	if (*n <= 0)
   1358 		return 0;
   1359 
   1360 	if (ND6_LLINFO_PERMANENT(ln))
   1361 		return 0;
   1362 
   1363 	if (IN6_ARE_ADDR_EQUAL(&ln->r_l3addr.addr6, skip_in6))
   1364 		return 0;
   1365 
   1366 	LLE_WLOCK(ln);
   1367 	if (ln->ln_state > ND6_LLINFO_INCOMPLETE)
   1368 		ln->ln_state = ND6_LLINFO_STALE;
   1369 	else
   1370 		ln->ln_state = ND6_LLINFO_PURGE;
   1371 	nd6_llinfo_settimer(ln, 0);
   1372 	LLE_WUNLOCK(ln);
   1373 
   1374 	(*n)--;
   1375 	return 0;
   1376 }
   1377 
   1378 static void
   1379 nd6_gc_neighbors(struct lltable *llt, const struct in6_addr *in6)
   1380 {
   1381 
   1382 	if (ip6_neighborgcthresh >= 0 &&
   1383 	    lltable_get_entry_count(llt) >= ip6_neighborgcthresh) {
   1384 		struct gc_args gc_args = {10, in6};
   1385 		/*
   1386 		 * XXX entries that are "less recently used" should be
   1387 		 * freed first.
   1388 		 */
   1389 		lltable_foreach_lle(llt, nd6_purge_entry, &gc_args);
   1390 	}
   1391 }
   1392 
   1393 void
   1394 nd6_rtrequest(int req, struct rtentry *rt, const struct rt_addrinfo *info)
   1395 {
   1396 	struct sockaddr *gate = rt->rt_gateway;
   1397 	struct ifnet *ifp = rt->rt_ifp;
   1398 	uint8_t namelen = strlen(ifp->if_xname), addrlen = ifp->if_addrlen;
   1399 	struct ifaddr *ifa;
   1400 
   1401 	RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
   1402 
   1403 	if (req == RTM_LLINFO_UPD) {
   1404 		int rc;
   1405 		struct in6_addr *in6;
   1406 		struct in6_addr in6_all;
   1407 		int anycast;
   1408 
   1409 		if ((ifa = info->rti_ifa) == NULL)
   1410 			return;
   1411 
   1412 		in6 = &ifatoia6(ifa)->ia_addr.sin6_addr;
   1413 		anycast = ifatoia6(ifa)->ia6_flags & IN6_IFF_ANYCAST;
   1414 
   1415 		in6_all = in6addr_linklocal_allnodes;
   1416 		if ((rc = in6_setscope(&in6_all, ifa->ifa_ifp, NULL)) != 0) {
   1417 			log(LOG_ERR, "%s: failed to set scope %s "
   1418 			    "(errno=%d)\n", __func__, if_name(ifp), rc);
   1419 			return;
   1420 		}
   1421 
   1422 		/* XXX don't set Override for proxy addresses */
   1423 		nd6_na_output(ifa->ifa_ifp, &in6_all, in6,
   1424 		    (anycast ? 0 : ND_NA_FLAG_OVERRIDE)
   1425 #if 0
   1426 		    | (ip6_forwarding ? ND_NA_FLAG_ROUTER : 0)
   1427 #endif
   1428 		    , 1, NULL);
   1429 		return;
   1430 	}
   1431 
   1432 	if ((rt->rt_flags & RTF_GATEWAY) != 0)
   1433 		return;
   1434 
   1435 	if (nd6_need_cache(ifp) == 0 && (rt->rt_flags & RTF_HOST) == 0) {
   1436 		RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
   1437 		/*
   1438 		 * This is probably an interface direct route for a link
   1439 		 * which does not need neighbor caches (e.g. fe80::%lo0/64).
   1440 		 * We do not need special treatment below for such a route.
   1441 		 * Moreover, the RTF_LLINFO flag which would be set below
   1442 		 * would annoy the ndp(8) command.
   1443 		 */
   1444 		return;
   1445 	}
   1446 
   1447 	switch (req) {
   1448 	case RTM_ADD: {
   1449 		int s;
   1450 
   1451 		RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
   1452 		/*
   1453 		 * There is no backward compatibility :)
   1454 		 *
   1455 		 * if ((rt->rt_flags & RTF_HOST) == 0 &&
   1456 		 *     SIN(rt_mask(rt))->sin_addr.s_addr != 0xffffffff)
   1457 		 *	   rt->rt_flags |= RTF_CLONING;
   1458 		 */
   1459 		/* XXX should move to route.c? */
   1460 		if (rt->rt_flags & (RTF_CONNECTED | RTF_LOCAL)) {
   1461 			union {
   1462 				struct sockaddr sa;
   1463 				struct sockaddr_dl sdl;
   1464 				struct sockaddr_storage ss;
   1465 			} u;
   1466 			/*
   1467 			 * Case 1: This route should come from a route to
   1468 			 * interface (RTF_CLONING case) or the route should be
   1469 			 * treated as on-link but is currently not
   1470 			 * (RTF_LLINFO && ln == NULL case).
   1471 			 */
   1472 			if (sockaddr_dl_init(&u.sdl, sizeof(u.ss),
   1473 			    ifp->if_index, ifp->if_type,
   1474 			    NULL, namelen, NULL, addrlen) == NULL) {
   1475 				printf("%s.%d: sockaddr_dl_init(, %zu, ) "
   1476 				    "failed on %s\n", __func__, __LINE__,
   1477 				    sizeof(u.ss), if_name(ifp));
   1478 			}
   1479 			rt_setgate(rt, &u.sa);
   1480 			gate = rt->rt_gateway;
   1481 			RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
   1482 			if (gate == NULL) {
   1483 				log(LOG_ERR,
   1484 				    "%s: rt_setgate failed on %s\n", __func__,
   1485 				    if_name(ifp));
   1486 				break;
   1487 			}
   1488 
   1489 			RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
   1490 			if ((rt->rt_flags & RTF_CONNECTED) != 0)
   1491 				break;
   1492 		}
   1493 		RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
   1494 		/*
   1495 		 * In IPv4 code, we try to annonuce new RTF_ANNOUNCE entry here.
   1496 		 * We don't do that here since llinfo is not ready yet.
   1497 		 *
   1498 		 * There are also couple of other things to be discussed:
   1499 		 * - unsolicited NA code needs improvement beforehand
   1500 		 * - RFC2461 says we MAY send multicast unsolicited NA
   1501 		 *   (7.2.6 paragraph 4), however, it also says that we
   1502 		 *   SHOULD provide a mechanism to prevent multicast NA storm.
   1503 		 *   we don't have anything like it right now.
   1504 		 *   note that the mechanism needs a mutual agreement
   1505 		 *   between proxies, which means that we need to implement
   1506 		 *   a new protocol, or a new kludge.
   1507 		 * - from RFC2461 6.2.4, host MUST NOT send an unsolicited NA.
   1508 		 *   we need to check ip6forwarding before sending it.
   1509 		 *   (or should we allow proxy ND configuration only for
   1510 		 *   routers?  there's no mention about proxy ND from hosts)
   1511 		 */
   1512 #if 0
   1513 		/* XXX it does not work */
   1514 		if (rt->rt_flags & RTF_ANNOUNCE)
   1515 			nd6_na_output(ifp,
   1516 			      &satocsin6(rt_getkey(rt))->sin6_addr,
   1517 			      &satocsin6(rt_getkey(rt))->sin6_addr,
   1518 			      ip6_forwarding ? ND_NA_FLAG_ROUTER : 0,
   1519 			      1, NULL);
   1520 #endif
   1521 
   1522 		if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) == 0) {
   1523 			RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
   1524 			/*
   1525 			 * Address resolution isn't necessary for a point to
   1526 			 * point link, so we can skip this test for a p2p link.
   1527 			 */
   1528 			if (gate->sa_family != AF_LINK ||
   1529 			    gate->sa_len <
   1530 			    sockaddr_dl_measure(namelen, addrlen)) {
   1531 				log(LOG_DEBUG,
   1532 				    "nd6_rtrequest: bad gateway value: %s\n",
   1533 				    if_name(ifp));
   1534 				break;
   1535 			}
   1536 			satosdl(gate)->sdl_type = ifp->if_type;
   1537 			satosdl(gate)->sdl_index = ifp->if_index;
   1538 			RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
   1539 		}
   1540 		RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
   1541 
   1542 		/*
   1543 		 * When called from rt_ifa_addlocal, we cannot depend on that
   1544 		 * the address (rt_getkey(rt)) exits in the address list of the
   1545 		 * interface. So check RTF_LOCAL instead.
   1546 		 */
   1547 		if (rt->rt_flags & RTF_LOCAL) {
   1548 			if (nd6_useloopback)
   1549 				rt->rt_ifp = lo0ifp;	/* XXX */
   1550 			break;
   1551 		}
   1552 
   1553 		/*
   1554 		 * check if rt_getkey(rt) is an address assigned
   1555 		 * to the interface.
   1556 		 */
   1557 		s = pserialize_read_enter();
   1558 		ifa = (struct ifaddr *)in6ifa_ifpwithaddr(ifp,
   1559 		    &satocsin6(rt_getkey(rt))->sin6_addr);
   1560 		if (ifa != NULL) {
   1561 			if (nd6_useloopback) {
   1562 				rt->rt_ifp = lo0ifp;	/* XXX */
   1563 				/*
   1564 				 * Make sure rt_ifa be equal to the ifaddr
   1565 				 * corresponding to the address.
   1566 				 * We need this because when we refer
   1567 				 * rt_ifa->ia6_flags in ip6_input, we assume
   1568 				 * that the rt_ifa points to the address instead
   1569 				 * of the loopback address.
   1570 				 */
   1571 				if (ifa != rt->rt_ifa)
   1572 					rt_replace_ifa(rt, ifa);
   1573 			}
   1574 		} else if (rt->rt_flags & RTF_ANNOUNCE) {
   1575 			/* join solicited node multicast for proxy ND */
   1576 			if (ifp->if_flags & IFF_MULTICAST) {
   1577 				struct in6_addr llsol;
   1578 				int error;
   1579 
   1580 				llsol = satocsin6(rt_getkey(rt))->sin6_addr;
   1581 				llsol.s6_addr32[0] = htonl(0xff020000);
   1582 				llsol.s6_addr32[1] = 0;
   1583 				llsol.s6_addr32[2] = htonl(1);
   1584 				llsol.s6_addr8[12] = 0xff;
   1585 				if (in6_setscope(&llsol, ifp, NULL))
   1586 					goto out;
   1587 				if (!in6_addmulti(&llsol, ifp, &error, 0)) {
   1588 					char ip6buf[INET6_ADDRSTRLEN];
   1589 					nd6log(LOG_ERR, "%s: failed to join "
   1590 					    "%s (errno=%d)\n", if_name(ifp),
   1591 					    IN6_PRINT(ip6buf, &llsol), error);
   1592 				}
   1593 			}
   1594 		}
   1595 	out:
   1596 		pserialize_read_exit(s);
   1597 		/*
   1598 		 * If we have too many cache entries, initiate immediate
   1599 		 * purging for some entries.
   1600 		 */
   1601 		if (rt->rt_ifp != NULL)
   1602 			nd6_gc_neighbors(LLTABLE6(rt->rt_ifp), NULL);
   1603 		break;
   1604 	    }
   1605 
   1606 	case RTM_DELETE:
   1607 		/* leave from solicited node multicast for proxy ND */
   1608 		if ((rt->rt_flags & RTF_ANNOUNCE) != 0 &&
   1609 		    (ifp->if_flags & IFF_MULTICAST) != 0) {
   1610 			struct in6_addr llsol;
   1611 			struct in6_multi *in6m;
   1612 
   1613 			llsol = satocsin6(rt_getkey(rt))->sin6_addr;
   1614 			llsol.s6_addr32[0] = htonl(0xff020000);
   1615 			llsol.s6_addr32[1] = 0;
   1616 			llsol.s6_addr32[2] = htonl(1);
   1617 			llsol.s6_addr8[12] = 0xff;
   1618 			if (in6_setscope(&llsol, ifp, NULL) == 0) {
   1619 				in6m = in6_lookup_multi(&llsol, ifp);
   1620 				if (in6m)
   1621 					in6_delmulti(in6m);
   1622 			}
   1623 		}
   1624 		break;
   1625 	}
   1626 }
   1627 
   1628 int
   1629 nd6_ioctl(u_long cmd, void *data, struct ifnet *ifp)
   1630 {
   1631 	struct in6_drlist *drl = (struct in6_drlist *)data;
   1632 	struct in6_oprlist *oprl = (struct in6_oprlist *)data;
   1633 	struct in6_ndireq *ndi = (struct in6_ndireq *)data;
   1634 	struct in6_nbrinfo *nbi = (struct in6_nbrinfo *)data;
   1635 	struct in6_ndifreq *ndif = (struct in6_ndifreq *)data;
   1636 	struct nd_defrouter *dr;
   1637 	struct nd_prefix *pr;
   1638 	int i = 0, error = 0;
   1639 
   1640 	switch (cmd) {
   1641 	case SIOCGDRLST_IN6:
   1642 		/*
   1643 		 * obsolete API, use sysctl under net.inet6.icmp6
   1644 		 */
   1645 		memset(drl, 0, sizeof(*drl));
   1646 		ND6_RLOCK();
   1647 		ND_DEFROUTER_LIST_FOREACH(dr) {
   1648 			if (i >= DRLSTSIZ)
   1649 				break;
   1650 			drl->defrouter[i].rtaddr = dr->rtaddr;
   1651 			in6_clearscope(&drl->defrouter[i].rtaddr);
   1652 
   1653 			drl->defrouter[i].flags = dr->flags;
   1654 			drl->defrouter[i].rtlifetime = dr->rtlifetime;
   1655 			drl->defrouter[i].expire = dr->expire ?
   1656 			    time_mono_to_wall(dr->expire) : 0;
   1657 			drl->defrouter[i].if_index = dr->ifp->if_index;
   1658 			i++;
   1659 		}
   1660 		ND6_UNLOCK();
   1661 		break;
   1662 	case SIOCGPRLST_IN6:
   1663 		/*
   1664 		 * obsolete API, use sysctl under net.inet6.icmp6
   1665 		 *
   1666 		 * XXX the structure in6_prlist was changed in backward-
   1667 		 * incompatible manner.  in6_oprlist is used for SIOCGPRLST_IN6,
   1668 		 * in6_prlist is used for nd6_sysctl() - fill_prlist().
   1669 		 */
   1670 		/*
   1671 		 * XXX meaning of fields, especialy "raflags", is very
   1672 		 * differnet between RA prefix list and RR/static prefix list.
   1673 		 * how about separating ioctls into two?
   1674 		 */
   1675 		memset(oprl, 0, sizeof(*oprl));
   1676 		ND6_RLOCK();
   1677 		ND_PREFIX_LIST_FOREACH(pr) {
   1678 			struct nd_pfxrouter *pfr;
   1679 			int j;
   1680 
   1681 			if (i >= PRLSTSIZ)
   1682 				break;
   1683 			oprl->prefix[i].prefix = pr->ndpr_prefix.sin6_addr;
   1684 			oprl->prefix[i].raflags = pr->ndpr_raf;
   1685 			oprl->prefix[i].prefixlen = pr->ndpr_plen;
   1686 			oprl->prefix[i].vltime = pr->ndpr_vltime;
   1687 			oprl->prefix[i].pltime = pr->ndpr_pltime;
   1688 			oprl->prefix[i].if_index = pr->ndpr_ifp->if_index;
   1689 			if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME)
   1690 				oprl->prefix[i].expire = 0;
   1691 			else {
   1692 				time_t maxexpire;
   1693 
   1694 				/* XXX: we assume time_t is signed. */
   1695 				maxexpire = (-1) &
   1696 				    ~((time_t)1 <<
   1697 				    ((sizeof(maxexpire) * 8) - 1));
   1698 				if (pr->ndpr_vltime <
   1699 				    maxexpire - pr->ndpr_lastupdate) {
   1700 					time_t expire;
   1701 					expire = pr->ndpr_lastupdate +
   1702 					    pr->ndpr_vltime;
   1703 					oprl->prefix[i].expire = expire ?
   1704 					    time_mono_to_wall(expire) : 0;
   1705 				} else
   1706 					oprl->prefix[i].expire = maxexpire;
   1707 			}
   1708 
   1709 			j = 0;
   1710 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
   1711 				if (j < DRLSTSIZ) {
   1712 #define RTRADDR oprl->prefix[i].advrtr[j]
   1713 					RTRADDR = pfr->router->rtaddr;
   1714 					in6_clearscope(&RTRADDR);
   1715 #undef RTRADDR
   1716 				}
   1717 				j++;
   1718 			}
   1719 			oprl->prefix[i].advrtrs = j;
   1720 			oprl->prefix[i].origin = PR_ORIG_RA;
   1721 
   1722 			i++;
   1723 		}
   1724 		ND6_UNLOCK();
   1725 
   1726 		break;
   1727 	case OSIOCGIFINFO_IN6:
   1728 #define ND	ndi->ndi
   1729 		/* XXX: old ndp(8) assumes a positive value for linkmtu. */
   1730 		memset(&ND, 0, sizeof(ND));
   1731 		ND.linkmtu = IN6_LINKMTU(ifp);
   1732 		ND.maxmtu = ND_IFINFO(ifp)->maxmtu;
   1733 		ND.basereachable = ND_IFINFO(ifp)->basereachable;
   1734 		ND.reachable = ND_IFINFO(ifp)->reachable;
   1735 		ND.retrans = ND_IFINFO(ifp)->retrans;
   1736 		ND.flags = ND_IFINFO(ifp)->flags;
   1737 		ND.recalctm = ND_IFINFO(ifp)->recalctm;
   1738 		ND.chlim = ND_IFINFO(ifp)->chlim;
   1739 		break;
   1740 	case SIOCGIFINFO_IN6:
   1741 		ND = *ND_IFINFO(ifp);
   1742 		break;
   1743 	case SIOCSIFINFO_IN6:
   1744 		/*
   1745 		 * used to change host variables from userland.
   1746 		 * intented for a use on router to reflect RA configurations.
   1747 		 */
   1748 		/* 0 means 'unspecified' */
   1749 		if (ND.linkmtu != 0) {
   1750 			if (ND.linkmtu < IPV6_MMTU ||
   1751 			    ND.linkmtu > IN6_LINKMTU(ifp)) {
   1752 				error = EINVAL;
   1753 				break;
   1754 			}
   1755 			ND_IFINFO(ifp)->linkmtu = ND.linkmtu;
   1756 		}
   1757 
   1758 		if (ND.basereachable != 0) {
   1759 			int obasereachable = ND_IFINFO(ifp)->basereachable;
   1760 
   1761 			ND_IFINFO(ifp)->basereachable = ND.basereachable;
   1762 			if (ND.basereachable != obasereachable)
   1763 				ND_IFINFO(ifp)->reachable =
   1764 				    ND_COMPUTE_RTIME(ND.basereachable);
   1765 		}
   1766 		if (ND.retrans != 0)
   1767 			ND_IFINFO(ifp)->retrans = ND.retrans;
   1768 		if (ND.chlim != 0)
   1769 			ND_IFINFO(ifp)->chlim = ND.chlim;
   1770 		/* FALLTHROUGH */
   1771 	case SIOCSIFINFO_FLAGS:
   1772 	{
   1773 		struct ifaddr *ifa;
   1774 		struct in6_ifaddr *ia;
   1775 		int s;
   1776 
   1777 		if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) &&
   1778 		    !(ND.flags & ND6_IFF_IFDISABLED))
   1779 		{
   1780 			/*
   1781 			 * If the interface is marked as ND6_IFF_IFDISABLED and
   1782 			 * has a link-local address with IN6_IFF_DUPLICATED,
   1783 			 * do not clear ND6_IFF_IFDISABLED.
   1784 			 * See RFC 4862, section 5.4.5.
   1785 			 */
   1786 			int duplicated_linklocal = 0;
   1787 
   1788 			s = pserialize_read_enter();
   1789 			IFADDR_READER_FOREACH(ifa, ifp) {
   1790 				if (ifa->ifa_addr->sa_family != AF_INET6)
   1791 					continue;
   1792 				ia = (struct in6_ifaddr *)ifa;
   1793 				if ((ia->ia6_flags & IN6_IFF_DUPLICATED) &&
   1794 				    IN6_IS_ADDR_LINKLOCAL(IA6_IN6(ia)))
   1795 				{
   1796 					duplicated_linklocal = 1;
   1797 					break;
   1798 				}
   1799 			}
   1800 			pserialize_read_exit(s);
   1801 
   1802 			if (duplicated_linklocal) {
   1803 				ND.flags |= ND6_IFF_IFDISABLED;
   1804 				log(LOG_ERR, "Cannot enable an interface"
   1805 				    " with a link-local address marked"
   1806 				    " duplicate.\n");
   1807 			} else {
   1808 				ND_IFINFO(ifp)->flags &= ~ND6_IFF_IFDISABLED;
   1809 				if (ifp->if_flags & IFF_UP)
   1810 					in6_if_up(ifp);
   1811 			}
   1812 		} else if (!(ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) &&
   1813 		    (ND.flags & ND6_IFF_IFDISABLED)) {
   1814 			int bound = curlwp_bind();
   1815 			/* Mark all IPv6 addresses as tentative. */
   1816 
   1817 			ND_IFINFO(ifp)->flags |= ND6_IFF_IFDISABLED;
   1818 			s = pserialize_read_enter();
   1819 			IFADDR_READER_FOREACH(ifa, ifp) {
   1820 				struct psref psref;
   1821 				if (ifa->ifa_addr->sa_family != AF_INET6)
   1822 					continue;
   1823 				ifa_acquire(ifa, &psref);
   1824 				pserialize_read_exit(s);
   1825 
   1826 				nd6_dad_stop(ifa);
   1827 
   1828 				ia = (struct in6_ifaddr *)ifa;
   1829 				ia->ia6_flags |= IN6_IFF_TENTATIVE;
   1830 
   1831 				s = pserialize_read_enter();
   1832 				ifa_release(ifa, &psref);
   1833 			}
   1834 			pserialize_read_exit(s);
   1835 			curlwp_bindx(bound);
   1836 		}
   1837 
   1838 		if (ND.flags & ND6_IFF_AUTO_LINKLOCAL) {
   1839 			if (!(ND_IFINFO(ifp)->flags & ND6_IFF_AUTO_LINKLOCAL)) {
   1840 				/* auto_linklocal 0->1 transition */
   1841 
   1842 				ND_IFINFO(ifp)->flags |= ND6_IFF_AUTO_LINKLOCAL;
   1843 				in6_ifattach(ifp, NULL);
   1844 			} else if (!(ND.flags & ND6_IFF_IFDISABLED) &&
   1845 			    ifp->if_flags & IFF_UP)
   1846 			{
   1847 				/*
   1848 				 * When the IF already has
   1849 				 * ND6_IFF_AUTO_LINKLOCAL, no link-local
   1850 				 * address is assigned, and IFF_UP, try to
   1851 				 * assign one.
   1852 				 */
   1853 				int haslinklocal = 0;
   1854 
   1855 				s = pserialize_read_enter();
   1856 				IFADDR_READER_FOREACH(ifa, ifp) {
   1857 					if (ifa->ifa_addr->sa_family !=AF_INET6)
   1858 						continue;
   1859 					ia = (struct in6_ifaddr *)ifa;
   1860 					if (IN6_IS_ADDR_LINKLOCAL(IA6_IN6(ia))){
   1861 						haslinklocal = 1;
   1862 						break;
   1863 					}
   1864 				}
   1865 				pserialize_read_exit(s);
   1866 				if (!haslinklocal)
   1867 					in6_ifattach(ifp, NULL);
   1868 			}
   1869 		}
   1870 	}
   1871 		ND_IFINFO(ifp)->flags = ND.flags;
   1872 		break;
   1873 #undef ND
   1874 	case SIOCSNDFLUSH_IN6:	/* XXX: the ioctl name is confusing... */
   1875 		/* sync kernel routing table with the default router list */
   1876 		ND6_WLOCK();
   1877 		nd6_defrouter_reset();
   1878 		nd6_defrouter_select();
   1879 		ND6_UNLOCK();
   1880 		break;
   1881 	case SIOCSPFXFLUSH_IN6:
   1882 	{
   1883 		/* flush all the prefix advertised by routers */
   1884 		struct nd_prefix *pfx, *next;
   1885 
   1886 	restart:
   1887 		ND6_WLOCK();
   1888 		ND_PREFIX_LIST_FOREACH_SAFE(pfx, next) {
   1889 			struct in6_ifaddr *ia, *ia_next;
   1890 			int _s;
   1891 
   1892 			if (IN6_IS_ADDR_LINKLOCAL(&pfx->ndpr_prefix.sin6_addr))
   1893 				continue; /* XXX */
   1894 
   1895 			/* do we really have to remove addresses as well? */
   1896 			_s = pserialize_read_enter();
   1897 			for (ia = IN6_ADDRLIST_READER_FIRST(); ia;
   1898 			     ia = ia_next) {
   1899 				/* ia might be removed.  keep the next ptr. */
   1900 				ia_next = IN6_ADDRLIST_READER_NEXT(ia);
   1901 
   1902 				if ((ia->ia6_flags & IN6_IFF_AUTOCONF) == 0)
   1903 					continue;
   1904 
   1905 				if (ia->ia6_ndpr == pfx) {
   1906 					pserialize_read_exit(_s);
   1907 					ND6_UNLOCK();
   1908 					/* XXX NOMPSAFE? */
   1909 					/* in6_purgeaddr may destroy pfx. */
   1910 					in6_purgeaddr(&ia->ia_ifa);
   1911 					goto restart;
   1912 				}
   1913 			}
   1914 			pserialize_read_exit(_s);
   1915 
   1916 			KASSERT(pfx->ndpr_refcnt == 0);
   1917 			nd6_prelist_remove(pfx);
   1918 		}
   1919 		ND6_UNLOCK();
   1920 		break;
   1921 	}
   1922 	case SIOCSRTRFLUSH_IN6:
   1923 	{
   1924 		/* flush all the default routers */
   1925 		struct nd_defrouter *drtr, *next;
   1926 
   1927 		ND6_WLOCK();
   1928 		nd6_defrouter_reset();
   1929 		ND_DEFROUTER_LIST_FOREACH_SAFE(drtr, next) {
   1930 			nd6_defrtrlist_del(drtr, NULL);
   1931 		}
   1932 		nd6_defrouter_select();
   1933 		ND6_UNLOCK();
   1934 		break;
   1935 	}
   1936 	case SIOCGNBRINFO_IN6:
   1937 	{
   1938 		struct llentry *ln;
   1939 		struct in6_addr nb_addr = nbi->addr; /* make local for safety */
   1940 
   1941 		if ((error = in6_setscope(&nb_addr, ifp, NULL)) != 0)
   1942 			return error;
   1943 
   1944 		ln = nd6_lookup(&nb_addr, ifp, false);
   1945 		if (ln == NULL) {
   1946 			error = EINVAL;
   1947 			break;
   1948 		}
   1949 		nbi->state = ln->ln_state;
   1950 		nbi->asked = ln->ln_asked;
   1951 		nbi->isrouter = ln->ln_router;
   1952 		nbi->expire = ln->ln_expire ?
   1953 		    time_mono_to_wall(ln->ln_expire) : 0;
   1954 		LLE_RUNLOCK(ln);
   1955 
   1956 		break;
   1957 	}
   1958 	case SIOCGDEFIFACE_IN6:	/* XXX: should be implemented as a sysctl? */
   1959 		ndif->ifindex = nd6_defifindex;
   1960 		break;
   1961 	case SIOCSDEFIFACE_IN6:	/* XXX: should be implemented as a sysctl? */
   1962 		return nd6_setdefaultiface(ndif->ifindex);
   1963 	}
   1964 	return error;
   1965 }
   1966 
   1967 void
   1968 nd6_llinfo_release_pkts(struct llentry *ln, struct ifnet *ifp)
   1969 {
   1970 	struct mbuf *m_hold, *m_hold_next;
   1971 	struct sockaddr_in6 sin6;
   1972 
   1973 	LLE_WLOCK_ASSERT(ln);
   1974 
   1975 	sockaddr_in6_init(&sin6, &ln->r_l3addr.addr6, 0, 0, 0);
   1976 
   1977 	m_hold = ln->la_hold, ln->la_hold = NULL, ln->la_numheld = 0;
   1978 
   1979 	LLE_WUNLOCK(ln);
   1980 	for (; m_hold != NULL; m_hold = m_hold_next) {
   1981 		m_hold_next = m_hold->m_nextpkt;
   1982 		m_hold->m_nextpkt = NULL;
   1983 
   1984 		/*
   1985 		 * we assume ifp is not a p2p here, so
   1986 		 * just set the 2nd argument as the
   1987 		 * 1st one.
   1988 		 */
   1989 		ip6_if_output(ifp, ifp, m_hold, &sin6, NULL);
   1990 	}
   1991 	LLE_WLOCK(ln);
   1992 }
   1993 
   1994 /*
   1995  * Create neighbor cache entry and cache link-layer address,
   1996  * on reception of inbound ND6 packets.  (RS/RA/NS/redirect)
   1997  */
   1998 void
   1999 nd6_cache_lladdr(
   2000     struct ifnet *ifp,
   2001     struct in6_addr *from,
   2002     char *lladdr,
   2003     int lladdrlen,
   2004     int type,	/* ICMP6 type */
   2005     int code	/* type dependent information */
   2006 )
   2007 {
   2008 	struct nd_ifinfo *ndi = ND_IFINFO(ifp);
   2009 	struct llentry *ln = NULL;
   2010 	int is_newentry;
   2011 	int do_update;
   2012 	int olladdr;
   2013 	int llchange;
   2014 	int newstate = 0;
   2015 	uint16_t router = 0;
   2016 
   2017 	KASSERT(ifp != NULL);
   2018 	KASSERT(from != NULL);
   2019 
   2020 	/* nothing must be updated for unspecified address */
   2021 	if (IN6_IS_ADDR_UNSPECIFIED(from))
   2022 		return;
   2023 
   2024 	/*
   2025 	 * Validation about ifp->if_addrlen and lladdrlen must be done in
   2026 	 * the caller.
   2027 	 *
   2028 	 * XXX If the link does not have link-layer adderss, what should
   2029 	 * we do? (ifp->if_addrlen == 0)
   2030 	 * Spec says nothing in sections for RA, RS and NA.  There's small
   2031 	 * description on it in NS section (RFC 2461 7.2.3).
   2032 	 */
   2033 
   2034 	ln = nd6_lookup(from, ifp, true);
   2035 	if (ln == NULL) {
   2036 #if 0
   2037 		/* nothing must be done if there's no lladdr */
   2038 		if (!lladdr || !lladdrlen)
   2039 			return NULL;
   2040 #endif
   2041 
   2042 		ln = nd6_create(from, ifp);
   2043 		is_newentry = 1;
   2044 	} else {
   2045 		/* do nothing if static ndp is set */
   2046 		if (ln->la_flags & LLE_STATIC) {
   2047 			LLE_WUNLOCK(ln);
   2048 			return;
   2049 		}
   2050 		is_newentry = 0;
   2051 	}
   2052 
   2053 	if (ln == NULL)
   2054 		return;
   2055 
   2056 	olladdr = (ln->la_flags & LLE_VALID) ? 1 : 0;
   2057 	if (olladdr && lladdr) {
   2058 		llchange = memcmp(lladdr, &ln->ll_addr, ifp->if_addrlen);
   2059 	} else
   2060 		llchange = 0;
   2061 
   2062 	/*
   2063 	 * newentry olladdr  lladdr  llchange	(*=record)
   2064 	 *	0	n	n	--	(1)
   2065 	 *	0	y	n	--	(2)
   2066 	 *	0	n	y	--	(3) * STALE
   2067 	 *	0	y	y	n	(4) *
   2068 	 *	0	y	y	y	(5) * STALE
   2069 	 *	1	--	n	--	(6)   NOSTATE(= PASSIVE)
   2070 	 *	1	--	y	--	(7) * STALE
   2071 	 */
   2072 
   2073 	if (lladdr) {		/* (3-5) and (7) */
   2074 		/*
   2075 		 * Record source link-layer address
   2076 		 * XXX is it dependent to ifp->if_type?
   2077 		 */
   2078 		memcpy(&ln->ll_addr, lladdr, ifp->if_addrlen);
   2079 		ln->la_flags |= LLE_VALID;
   2080 	}
   2081 
   2082 	if (!is_newentry) {
   2083 		if ((!olladdr && lladdr) ||		/* (3) */
   2084 		    (olladdr && lladdr && llchange)) {	/* (5) */
   2085 			do_update = 1;
   2086 			newstate = ND6_LLINFO_STALE;
   2087 		} else					/* (1-2,4) */
   2088 			do_update = 0;
   2089 	} else {
   2090 		do_update = 1;
   2091 		if (lladdr == NULL)			/* (6) */
   2092 			newstate = ND6_LLINFO_NOSTATE;
   2093 		else					/* (7) */
   2094 			newstate = ND6_LLINFO_STALE;
   2095 	}
   2096 
   2097 	if (do_update) {
   2098 		/*
   2099 		 * Update the state of the neighbor cache.
   2100 		 */
   2101 		ln->ln_state = newstate;
   2102 
   2103 		if (ln->ln_state == ND6_LLINFO_STALE) {
   2104 			/*
   2105 			 * XXX: since nd6_output() below will cause
   2106 			 * state tansition to DELAY and reset the timer,
   2107 			 * we must set the timer now, although it is actually
   2108 			 * meaningless.
   2109 			 */
   2110 			nd6_llinfo_settimer(ln, nd6_gctimer * hz);
   2111 
   2112 			nd6_llinfo_release_pkts(ln, ifp);
   2113 		} else if (ln->ln_state == ND6_LLINFO_INCOMPLETE) {
   2114 			/* probe right away */
   2115 			nd6_llinfo_settimer((void *)ln, 0);
   2116 		}
   2117 	}
   2118 
   2119 	/*
   2120 	 * ICMP6 type dependent behavior.
   2121 	 *
   2122 	 * NS: clear IsRouter if new entry
   2123 	 * RS: clear IsRouter
   2124 	 * RA: set IsRouter if there's lladdr
   2125 	 * redir: clear IsRouter if new entry
   2126 	 *
   2127 	 * RA case, (1):
   2128 	 * The spec says that we must set IsRouter in the following cases:
   2129 	 * - If lladdr exist, set IsRouter.  This means (1-5).
   2130 	 * - If it is old entry (!newentry), set IsRouter.  This means (7).
   2131 	 * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
   2132 	 * A quetion arises for (1) case.  (1) case has no lladdr in the
   2133 	 * neighbor cache, this is similar to (6).
   2134 	 * This case is rare but we figured that we MUST NOT set IsRouter.
   2135 	 *
   2136 	 * newentry olladdr  lladdr  llchange	    NS  RS  RA	redir
   2137 	 *							D R
   2138 	 *	0	n	n	--	(1)	c   ?     s
   2139 	 *	0	y	n	--	(2)	c   s     s
   2140 	 *	0	n	y	--	(3)	c   s     s
   2141 	 *	0	y	y	n	(4)	c   s     s
   2142 	 *	0	y	y	y	(5)	c   s     s
   2143 	 *	1	--	n	--	(6) c	c 	c s
   2144 	 *	1	--	y	--	(7) c	c   s	c s
   2145 	 *
   2146 	 *					(c=clear s=set)
   2147 	 */
   2148 	switch (type & 0xff) {
   2149 	case ND_NEIGHBOR_SOLICIT:
   2150 		/*
   2151 		 * New entry must have is_router flag cleared.
   2152 		 */
   2153 		if (is_newentry)	/* (6-7) */
   2154 			ln->ln_router = 0;
   2155 		break;
   2156 	case ND_REDIRECT:
   2157 		/*
   2158 		 * If the icmp is a redirect to a better router, always set the
   2159 		 * is_router flag.  Otherwise, if the entry is newly created,
   2160 		 * clear the flag.  [RFC 2461, sec 8.3]
   2161 		 */
   2162 		if (code == ND_REDIRECT_ROUTER)
   2163 			ln->ln_router = 1;
   2164 		else if (is_newentry) /* (6-7) */
   2165 			ln->ln_router = 0;
   2166 		break;
   2167 	case ND_ROUTER_SOLICIT:
   2168 		/*
   2169 		 * is_router flag must always be cleared.
   2170 		 */
   2171 		ln->ln_router = 0;
   2172 		break;
   2173 	case ND_ROUTER_ADVERT:
   2174 		/*
   2175 		 * Mark an entry with lladdr as a router.
   2176 		 */
   2177 		if ((!is_newentry && (olladdr || lladdr)) ||	/* (2-5) */
   2178 		    (is_newentry && lladdr)) {			/* (7) */
   2179 			ln->ln_router = 1;
   2180 		}
   2181 		break;
   2182 	}
   2183 
   2184 #if 0
   2185 	/* XXX should we send rtmsg as it used to be? */
   2186 	if (do_update)
   2187 		rt_newmsg(RTM_CHANGE, rt);  /* tell user process */
   2188 #endif
   2189 
   2190 	if (ln != NULL) {
   2191 		router = ln->ln_router;
   2192 		LLE_WUNLOCK(ln);
   2193 	}
   2194 
   2195 	/*
   2196 	 * If we have too many cache entries, initiate immediate
   2197 	 * purging for some entries.
   2198 	 */
   2199 	if (is_newentry)
   2200 		nd6_gc_neighbors(LLTABLE6(ifp), &ln->r_l3addr.addr6);
   2201 
   2202 	/*
   2203 	 * When the link-layer address of a router changes, select the
   2204 	 * best router again.  In particular, when the neighbor entry is newly
   2205 	 * created, it might affect the selection policy.
   2206 	 * Question: can we restrict the first condition to the "is_newentry"
   2207 	 * case?
   2208 	 * XXX: when we hear an RA from a new router with the link-layer
   2209 	 * address option, nd6_defrouter_select() is called twice, since
   2210 	 * defrtrlist_update called the function as well.  However, I believe
   2211 	 * we can compromise the overhead, since it only happens the first
   2212 	 * time.
   2213 	 * XXX: although nd6_defrouter_select() should not have a bad effect
   2214 	 * for those are not autoconfigured hosts, we explicitly avoid such
   2215 	 * cases for safety.
   2216 	 */
   2217 	if (do_update && router && !ip6_forwarding &&
   2218 	    nd6_accepts_rtadv(ndi)) {
   2219 		ND6_WLOCK();
   2220 		nd6_defrouter_select();
   2221 		ND6_UNLOCK();
   2222 	}
   2223 }
   2224 
   2225 static void
   2226 nd6_slowtimo(void *ignored_arg)
   2227 {
   2228 	struct nd_ifinfo *nd6if;
   2229 	struct ifnet *ifp;
   2230 	int s;
   2231 
   2232 #ifndef NET_MPSAFE
   2233 	mutex_enter(softnet_lock);
   2234 	KERNEL_LOCK(1, NULL);
   2235 #endif
   2236 	callout_reset(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
   2237 	    nd6_slowtimo, NULL);
   2238 
   2239 	s = pserialize_read_enter();
   2240 	IFNET_READER_FOREACH(ifp) {
   2241 		nd6if = ND_IFINFO(ifp);
   2242 		if (nd6if->basereachable && /* already initialized */
   2243 		    (nd6if->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
   2244 			/*
   2245 			 * Since reachable time rarely changes by router
   2246 			 * advertisements, we SHOULD insure that a new random
   2247 			 * value gets recomputed at least once every few hours.
   2248 			 * (RFC 2461, 6.3.4)
   2249 			 */
   2250 			nd6if->recalctm = nd6_recalc_reachtm_interval;
   2251 			nd6if->reachable = ND_COMPUTE_RTIME(nd6if->basereachable);
   2252 		}
   2253 	}
   2254 	pserialize_read_exit(s);
   2255 
   2256 #ifndef NET_MPSAFE
   2257 	KERNEL_UNLOCK_ONE(NULL);
   2258 	mutex_exit(softnet_lock);
   2259 #endif
   2260 }
   2261 
   2262 /*
   2263  * Return 0 if a neighbor cache is found. Return EWOULDBLOCK if a cache is not
   2264  * found and trying to resolve a neighbor; in this case the mbuf is queued in
   2265  * the list. Otherwise return errno after freeing the mbuf.
   2266  */
   2267 int
   2268 nd6_resolve(struct ifnet *ifp, const struct rtentry *rt, struct mbuf *m,
   2269     const struct sockaddr *_dst, uint8_t *lldst, size_t dstsize)
   2270 {
   2271 	struct llentry *ln = NULL;
   2272 	bool created = false;
   2273 	const struct sockaddr_in6 *dst = satocsin6(_dst);
   2274 
   2275 	/* discard the packet if IPv6 operation is disabled on the interface */
   2276 	if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED)) {
   2277 		m_freem(m);
   2278 		return ENETDOWN; /* better error? */
   2279 	}
   2280 
   2281 	/*
   2282 	 * Address resolution or Neighbor Unreachability Detection
   2283 	 * for the next hop.
   2284 	 * At this point, the destination of the packet must be a unicast
   2285 	 * or an anycast address(i.e. not a multicast).
   2286 	 */
   2287 
   2288 	/* Look up the neighbor cache for the nexthop */
   2289 	ln = nd6_lookup(&dst->sin6_addr, ifp, false);
   2290 
   2291 	if (ln != NULL && (ln->la_flags & LLE_VALID) != 0) {
   2292 		KASSERT(ln->ln_state > ND6_LLINFO_INCOMPLETE);
   2293 		/* Fast path */
   2294 		memcpy(lldst, &ln->ll_addr, MIN(dstsize, ifp->if_addrlen));
   2295 		LLE_RUNLOCK(ln);
   2296 		return 0;
   2297 	}
   2298 	if (ln != NULL)
   2299 		LLE_RUNLOCK(ln);
   2300 
   2301 	/* Slow path */
   2302 	ln = nd6_lookup(&dst->sin6_addr, ifp, true);
   2303 	if (ln == NULL && nd6_is_addr_neighbor(dst, ifp))  {
   2304 		struct sockaddr_in6 sin6;
   2305 		/*
   2306 		 * Since nd6_is_addr_neighbor() internally calls nd6_lookup(),
   2307 		 * the condition below is not very efficient.  But we believe
   2308 		 * it is tolerable, because this should be a rare case.
   2309 		 */
   2310 		ln = nd6_create(&dst->sin6_addr, ifp);
   2311 		if (ln == NULL) {
   2312 			char ip6buf[INET6_ADDRSTRLEN];
   2313 			log(LOG_DEBUG,
   2314 			    "%s: can't allocate llinfo for %s "
   2315 			    "(ln=%p, rt=%p)\n", __func__,
   2316 			    IN6_PRINT(ip6buf, &dst->sin6_addr), ln, rt);
   2317 			m_freem(m);
   2318 			return ENOBUFS;
   2319 		}
   2320 
   2321 		sockaddr_in6_init(&sin6, &ln->r_l3addr.addr6, 0, 0, 0);
   2322 		rt_clonedmsg(sin6tosa(&sin6), ifp, rt);
   2323 
   2324 		created = true;
   2325 	}
   2326 
   2327 	if (ln == NULL) {
   2328 		m_freem(m);
   2329 		return ENETDOWN; /* better error? */
   2330 	}
   2331 
   2332 	LLE_WLOCK_ASSERT(ln);
   2333 
   2334 	/* We don't have to do link-layer address resolution on a p2p link. */
   2335 	if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
   2336 	    ln->ln_state < ND6_LLINFO_REACHABLE) {
   2337 		ln->ln_state = ND6_LLINFO_STALE;
   2338 		nd6_llinfo_settimer(ln, nd6_gctimer * hz);
   2339 	}
   2340 
   2341 	/*
   2342 	 * The first time we send a packet to a neighbor whose entry is
   2343 	 * STALE, we have to change the state to DELAY and a sets a timer to
   2344 	 * expire in DELAY_FIRST_PROBE_TIME seconds to ensure do
   2345 	 * neighbor unreachability detection on expiration.
   2346 	 * (RFC 2461 7.3.3)
   2347 	 */
   2348 	if (ln->ln_state == ND6_LLINFO_STALE) {
   2349 		ln->ln_asked = 0;
   2350 		ln->ln_state = ND6_LLINFO_DELAY;
   2351 		nd6_llinfo_settimer(ln, nd6_delay * hz);
   2352 	}
   2353 
   2354 	/*
   2355 	 * There is a neighbor cache entry, but no ethernet address
   2356 	 * response yet.  Append this latest packet to the end of the
   2357 	 * packet queue in the mbuf, unless the number of the packet
   2358 	 * does not exceed nd6_maxqueuelen.  When it exceeds nd6_maxqueuelen,
   2359 	 * the oldest packet in the queue will be removed.
   2360 	 */
   2361 	if (ln->ln_state == ND6_LLINFO_NOSTATE)
   2362 		ln->ln_state = ND6_LLINFO_INCOMPLETE;
   2363 	if (ln->ln_hold) {
   2364 		struct mbuf *m_hold;
   2365 		int i;
   2366 
   2367 		i = 0;
   2368 		for (m_hold = ln->ln_hold; m_hold; m_hold = m_hold->m_nextpkt) {
   2369 			i++;
   2370 			if (m_hold->m_nextpkt == NULL) {
   2371 				m_hold->m_nextpkt = m;
   2372 				break;
   2373 			}
   2374 		}
   2375 		while (i >= nd6_maxqueuelen) {
   2376 			m_hold = ln->ln_hold;
   2377 			ln->ln_hold = ln->ln_hold->m_nextpkt;
   2378 			m_freem(m_hold);
   2379 			i--;
   2380 		}
   2381 	} else {
   2382 		ln->ln_hold = m;
   2383 	}
   2384 
   2385 	/*
   2386 	 * If there has been no NS for the neighbor after entering the
   2387 	 * INCOMPLETE state, send the first solicitation.
   2388 	 */
   2389 	if (!ND6_LLINFO_PERMANENT(ln) && ln->ln_asked == 0) {
   2390 		struct in6_addr src, *psrc;
   2391 
   2392 		ln->ln_asked++;
   2393 		nd6_llinfo_settimer(ln, ND_IFINFO(ifp)->retrans * hz / 1000);
   2394 		psrc = nd6_llinfo_get_holdsrc(ln, &src);
   2395 		LLE_WUNLOCK(ln);
   2396 		ln = NULL;
   2397 		nd6_ns_output(ifp, NULL, &dst->sin6_addr, psrc, 0);
   2398 	} else {
   2399 		/* We did the lookup so we need to do the unlock here. */
   2400 		LLE_WUNLOCK(ln);
   2401 	}
   2402 
   2403 	if (created)
   2404 		nd6_gc_neighbors(LLTABLE6(ifp), &dst->sin6_addr);
   2405 
   2406 	return EWOULDBLOCK;
   2407 }
   2408 
   2409 int
   2410 nd6_need_cache(struct ifnet *ifp)
   2411 {
   2412 	/*
   2413 	 * XXX: we currently do not make neighbor cache on any interface
   2414 	 * other than ARCnet, Ethernet, FDDI and GIF.
   2415 	 *
   2416 	 * RFC2893 says:
   2417 	 * - unidirectional tunnels needs no ND
   2418 	 */
   2419 	switch (ifp->if_type) {
   2420 	case IFT_ARCNET:
   2421 	case IFT_ETHER:
   2422 	case IFT_FDDI:
   2423 	case IFT_IEEE1394:
   2424 	case IFT_CARP:
   2425 	case IFT_GIF:		/* XXX need more cases? */
   2426 	case IFT_PPP:
   2427 	case IFT_TUNNEL:
   2428 		return 1;
   2429 	default:
   2430 		return 0;
   2431 	}
   2432 }
   2433 
   2434 static void
   2435 clear_llinfo_pqueue(struct llentry *ln)
   2436 {
   2437 	struct mbuf *m_hold, *m_hold_next;
   2438 
   2439 	for (m_hold = ln->ln_hold; m_hold; m_hold = m_hold_next) {
   2440 		m_hold_next = m_hold->m_nextpkt;
   2441 		m_hold->m_nextpkt = NULL;
   2442 		m_freem(m_hold);
   2443 	}
   2444 
   2445 	ln->ln_hold = NULL;
   2446 	return;
   2447 }
   2448 
   2449 int
   2450 nd6_sysctl(
   2451     int name,
   2452     void *oldp,	/* syscall arg, need copyout */
   2453     size_t *oldlenp,
   2454     void *newp,	/* syscall arg, need copyin */
   2455     size_t newlen
   2456 )
   2457 {
   2458 	void *p;
   2459 	size_t ol;
   2460 	int error;
   2461 	size_t bufsize = 0;
   2462 
   2463 	error = 0;
   2464 
   2465 	if (newp)
   2466 		return EPERM;
   2467 	if (oldp && !oldlenp)
   2468 		return EINVAL;
   2469 	ol = oldlenp ? *oldlenp : 0;
   2470 
   2471 	if (oldp && *oldlenp > 0) {
   2472 		p = kmem_alloc(*oldlenp, KM_SLEEP);
   2473 		bufsize = *oldlenp;
   2474 	} else
   2475 		p = NULL;
   2476 	switch (name) {
   2477 	case ICMPV6CTL_ND6_DRLIST:
   2478 		error = fill_drlist(p, oldlenp, ol);
   2479 		if (!error && p != NULL && oldp != NULL)
   2480 			error = copyout(p, oldp, *oldlenp);
   2481 		break;
   2482 
   2483 	case ICMPV6CTL_ND6_PRLIST:
   2484 		error = fill_prlist(p, oldlenp, ol);
   2485 		if (!error && p != NULL && oldp != NULL)
   2486 			error = copyout(p, oldp, *oldlenp);
   2487 		break;
   2488 
   2489 	case ICMPV6CTL_ND6_MAXQLEN:
   2490 		break;
   2491 
   2492 	default:
   2493 		error = ENOPROTOOPT;
   2494 		break;
   2495 	}
   2496 	if (p)
   2497 		kmem_free(p, bufsize);
   2498 
   2499 	return error;
   2500 }
   2501 
   2502 static int
   2503 fill_drlist(void *oldp, size_t *oldlenp, size_t ol)
   2504 {
   2505 	int error = 0;
   2506 	struct in6_defrouter *d = NULL, *de = NULL;
   2507 	struct nd_defrouter *dr;
   2508 	size_t l;
   2509 
   2510 	if (oldp) {
   2511 		d = (struct in6_defrouter *)oldp;
   2512 		de = (struct in6_defrouter *)((char *)oldp + *oldlenp);
   2513 	}
   2514 	l = 0;
   2515 
   2516 	ND6_RLOCK();
   2517 	ND_DEFROUTER_LIST_FOREACH(dr) {
   2518 
   2519 		if (oldp && d + 1 <= de) {
   2520 			memset(d, 0, sizeof(*d));
   2521 			sockaddr_in6_init(&d->rtaddr, &dr->rtaddr, 0, 0, 0);
   2522 			if (sa6_recoverscope(&d->rtaddr)) {
   2523 				char ip6buf[INET6_ADDRSTRLEN];
   2524 				log(LOG_ERR,
   2525 				    "scope error in router list (%s)\n",
   2526 				    IN6_PRINT(ip6buf, &d->rtaddr.sin6_addr));
   2527 				/* XXX: press on... */
   2528 			}
   2529 			d->flags = dr->flags;
   2530 			d->rtlifetime = dr->rtlifetime;
   2531 			d->expire = dr->expire ?
   2532 			    time_mono_to_wall(dr->expire) : 0;
   2533 			d->if_index = dr->ifp->if_index;
   2534 		}
   2535 
   2536 		l += sizeof(*d);
   2537 		if (d)
   2538 			d++;
   2539 	}
   2540 	ND6_UNLOCK();
   2541 
   2542 	if (oldp) {
   2543 		if (l > ol)
   2544 			error = ENOMEM;
   2545 	}
   2546 	if (oldlenp)
   2547 		*oldlenp = l;	/* (void *)d - (void *)oldp */
   2548 
   2549 	return error;
   2550 }
   2551 
   2552 static int
   2553 fill_prlist(void *oldp, size_t *oldlenp, size_t ol)
   2554 {
   2555 	int error = 0;
   2556 	struct nd_prefix *pr;
   2557 	uint8_t *p = NULL, *ps = NULL;
   2558 	uint8_t *pe = NULL;
   2559 	size_t l;
   2560 	char ip6buf[INET6_ADDRSTRLEN];
   2561 
   2562 	if (oldp) {
   2563 		ps = p = (uint8_t*)oldp;
   2564 		pe = (uint8_t*)oldp + *oldlenp;
   2565 	}
   2566 	l = 0;
   2567 
   2568 	ND6_RLOCK();
   2569 	ND_PREFIX_LIST_FOREACH(pr) {
   2570 		u_short advrtrs;
   2571 		struct sockaddr_in6 sin6;
   2572 		struct nd_pfxrouter *pfr;
   2573 		struct in6_prefix pfx;
   2574 
   2575 		if (oldp && p + sizeof(struct in6_prefix) <= pe)
   2576 		{
   2577 			memset(&pfx, 0, sizeof(pfx));
   2578 			ps = p;
   2579 			pfx.prefix = pr->ndpr_prefix;
   2580 
   2581 			if (sa6_recoverscope(&pfx.prefix)) {
   2582 				log(LOG_ERR,
   2583 				    "scope error in prefix list (%s)\n",
   2584 				    IN6_PRINT(ip6buf, &pfx.prefix.sin6_addr));
   2585 				/* XXX: press on... */
   2586 			}
   2587 			pfx.raflags = pr->ndpr_raf;
   2588 			pfx.prefixlen = pr->ndpr_plen;
   2589 			pfx.vltime = pr->ndpr_vltime;
   2590 			pfx.pltime = pr->ndpr_pltime;
   2591 			pfx.if_index = pr->ndpr_ifp->if_index;
   2592 			if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME)
   2593 				pfx.expire = 0;
   2594 			else {
   2595 				time_t maxexpire;
   2596 
   2597 				/* XXX: we assume time_t is signed. */
   2598 				maxexpire = (-1) &
   2599 				    ~((time_t)1 <<
   2600 				    ((sizeof(maxexpire) * 8) - 1));
   2601 				if (pr->ndpr_vltime <
   2602 				    maxexpire - pr->ndpr_lastupdate) {
   2603 					pfx.expire = pr->ndpr_lastupdate +
   2604 						pr->ndpr_vltime;
   2605 				} else
   2606 					pfx.expire = maxexpire;
   2607 			}
   2608 			pfx.refcnt = pr->ndpr_refcnt;
   2609 			pfx.flags = pr->ndpr_stateflags;
   2610 			pfx.origin = PR_ORIG_RA;
   2611 
   2612 			p += sizeof(pfx); l += sizeof(pfx);
   2613 
   2614 			advrtrs = 0;
   2615 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
   2616 				if (p + sizeof(sin6) > pe) {
   2617 					advrtrs++;
   2618 					continue;
   2619 				}
   2620 
   2621 				sockaddr_in6_init(&sin6, &pfr->router->rtaddr,
   2622 					    0, 0, 0);
   2623 				if (sa6_recoverscope(&sin6)) {
   2624 					log(LOG_ERR,
   2625 					    "scope error in "
   2626 					    "prefix list (%s)\n",
   2627 					    IN6_PRINT(ip6buf,
   2628 					    &pfr->router->rtaddr));
   2629 				}
   2630 				advrtrs++;
   2631 				memcpy(p, &sin6, sizeof(sin6));
   2632 				p += sizeof(sin6);
   2633 				l += sizeof(sin6);
   2634 			}
   2635 			pfx.advrtrs = advrtrs;
   2636 			memcpy(ps, &pfx, sizeof(pfx));
   2637 		}
   2638 		else {
   2639 			l += sizeof(pfx);
   2640 			advrtrs = 0;
   2641 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
   2642 				advrtrs++;
   2643 				l += sizeof(sin6);
   2644 			}
   2645 		}
   2646 	}
   2647 	ND6_UNLOCK();
   2648 
   2649 	if (oldp) {
   2650 		*oldlenp = l;	/* (void *)d - (void *)oldp */
   2651 		if (l > ol)
   2652 			error = ENOMEM;
   2653 	} else
   2654 		*oldlenp = l;
   2655 
   2656 	return error;
   2657 }
   2658 
   2659 static int
   2660 nd6_setdefaultiface(int ifindex)
   2661 {
   2662 	ifnet_t *ifp;
   2663 	int error = 0;
   2664 	int s;
   2665 
   2666 	s = pserialize_read_enter();
   2667 	ifp = if_byindex(ifindex);
   2668 	if (ifp == NULL) {
   2669 		pserialize_read_exit(s);
   2670 		return EINVAL;
   2671 	}
   2672 	if (nd6_defifindex != ifindex) {
   2673 		nd6_defifindex = ifindex;
   2674 		nd6_defifp = nd6_defifindex > 0 ? ifp : NULL;
   2675 
   2676 		/*
   2677 		 * Our current implementation assumes one-to-one maping between
   2678 		 * interfaces and links, so it would be natural to use the
   2679 		 * default interface as the default link.
   2680 		 */
   2681 		scope6_setdefault(nd6_defifp);
   2682 	}
   2683 	pserialize_read_exit(s);
   2684 
   2685 	return (error);
   2686 }
   2687