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