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