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