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