Home | History | Annotate | Line # | Download | only in netinet6
nd6.c revision 1.226
      1 /*	$NetBSD: nd6.c,v 1.226 2017/01/16 15:44:47 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.226 2017/01/16 15:44:47 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/malloc.h>
     47 #include <sys/mbuf.h>
     48 #include <sys/socket.h>
     49 #include <sys/socketvar.h>
     50 #include <sys/sockio.h>
     51 #include <sys/time.h>
     52 #include <sys/kernel.h>
     53 #include <sys/errno.h>
     54 #include <sys/ioctl.h>
     55 #include <sys/syslog.h>
     56 #include <sys/queue.h>
     57 #include <sys/cprng.h>
     58 #include <sys/workqueue.h>
     59 
     60 #include <net/if.h>
     61 #include <net/if_dl.h>
     62 #include <net/if_llatbl.h>
     63 #include <net/if_types.h>
     64 #include <net/route.h>
     65 #include <net/if_ether.h>
     66 #include <net/if_fddi.h>
     67 #include <net/if_arc.h>
     68 
     69 #include <netinet/in.h>
     70 #include <netinet6/in6_var.h>
     71 #include <netinet/ip6.h>
     72 #include <netinet6/ip6_var.h>
     73 #include <netinet6/scope6_var.h>
     74 #include <netinet6/nd6.h>
     75 #include <netinet6/in6_ifattach.h>
     76 #include <netinet/icmp6.h>
     77 #include <netinet6/icmp6_private.h>
     78 
     79 #include <net/net_osdep.h>
     80 
     81 #define ND6_SLOWTIMER_INTERVAL (60 * 60) /* 1 hour */
     82 #define ND6_RECALC_REACHTM_INTERVAL (60 * 120) /* 2 hours */
     83 
     84 /* timer values */
     85 int	nd6_prune	= 1;	/* walk list every 1 seconds */
     86 int	nd6_delay	= 5;	/* delay first probe time 5 second */
     87 int	nd6_umaxtries	= 3;	/* maximum unicast query */
     88 int	nd6_mmaxtries	= 3;	/* maximum multicast query */
     89 int	nd6_useloopback = 1;	/* use loopback interface for local traffic */
     90 int	nd6_gctimer	= (60 * 60 * 24); /* 1 day: garbage collection timer */
     91 
     92 /* preventing too many loops in ND option parsing */
     93 int nd6_maxndopt = 10;	/* max # of ND options allowed */
     94 
     95 int nd6_maxnudhint = 0;	/* max # of subsequent upper layer hints */
     96 
     97 int nd6_maxqueuelen = 1; /* max # of packets cached in unresolved ND entries */
     98 
     99 #ifdef ND6_DEBUG
    100 int nd6_debug = 1;
    101 #else
    102 int nd6_debug = 0;
    103 #endif
    104 
    105 krwlock_t nd6_lock __cacheline_aligned;
    106 
    107 struct nd_drhead nd_defrouter;
    108 struct nd_prhead nd_prefix = { 0 };
    109 
    110 int nd6_recalc_reachtm_interval = ND6_RECALC_REACHTM_INTERVAL;
    111 
    112 static void nd6_setmtu0(struct ifnet *, struct nd_ifinfo *);
    113 static void nd6_slowtimo(void *);
    114 static int regen_tmpaddr(const struct in6_ifaddr *);
    115 static void nd6_free(struct llentry *, int);
    116 static void nd6_llinfo_timer(void *);
    117 static void nd6_timer(void *);
    118 static void nd6_timer_work(struct work *, void *);
    119 static void clear_llinfo_pqueue(struct llentry *);
    120 static struct nd_opt_hdr *nd6_option(union nd_opts *);
    121 
    122 static callout_t nd6_slowtimo_ch;
    123 static callout_t nd6_timer_ch;
    124 static struct workqueue	*nd6_timer_wq;
    125 static struct work	nd6_timer_wk;
    126 
    127 static int fill_drlist(void *, size_t *, size_t);
    128 static int fill_prlist(void *, size_t *, size_t);
    129 
    130 static struct ifnet *nd6_defifp;
    131 static int nd6_defifindex;
    132 
    133 static int nd6_setdefaultiface(int);
    134 
    135 MALLOC_DEFINE(M_IP6NDP, "NDP", "IPv6 Neighbour Discovery");
    136 
    137 void
    138 nd6_init(void)
    139 {
    140 	int error;
    141 
    142 	rw_init(&nd6_lock);
    143 
    144 	/* initialization of the default router list */
    145 	ND_DEFROUTER_LIST_INIT();
    146 
    147 	callout_init(&nd6_slowtimo_ch, CALLOUT_MPSAFE);
    148 	callout_init(&nd6_timer_ch, CALLOUT_MPSAFE);
    149 
    150 	error = workqueue_create(&nd6_timer_wq, "nd6_timer",
    151 	    nd6_timer_work, NULL, PRI_SOFTNET, IPL_SOFTNET, WQ_MPSAFE);
    152 	if (error)
    153 		panic("%s: workqueue_create failed (%d)\n", __func__, error);
    154 
    155 	/* start timer */
    156 	callout_reset(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
    157 	    nd6_slowtimo, NULL);
    158 	callout_reset(&nd6_timer_ch, hz, nd6_timer, NULL);
    159 }
    160 
    161 struct nd_ifinfo *
    162 nd6_ifattach(struct ifnet *ifp)
    163 {
    164 	struct nd_ifinfo *nd;
    165 
    166 	nd = (struct nd_ifinfo *)malloc(sizeof(*nd), M_IP6NDP, M_WAITOK|M_ZERO);
    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 	free(ext->nd_ifinfo, M_IP6NDP);
    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 	LLE_WLOCK(ln);
    454 	if ((ln->la_flags & LLE_LINKED) == 0)
    455 		goto out;
    456 	if (ln->ln_ntick > 0) {
    457 		nd6_llinfo_settimer(ln, ln->ln_ntick);
    458 		goto out;
    459 	}
    460 
    461 	if (callout_pending(&ln->la_timer)) {
    462 		/*
    463 		 * Here we are a bit odd here in the treatment of
    464 		 * active/pending. If the pending bit is set, it got
    465 		 * rescheduled before I ran. The active
    466 		 * bit we ignore, since if it was stopped
    467 		 * in ll_tablefree() and was currently running
    468 		 * it would have return 0 so the code would
    469 		 * not have deleted it since the callout could
    470 		 * not be stopped so we want to go through
    471 		 * with the delete here now. If the callout
    472 		 * was restarted, the pending bit will be back on and
    473 		 * we just want to bail since the callout_reset would
    474 		 * return 1 and our reference would have been removed
    475 		 * by nd6_llinfo_settimer above since canceled
    476 		 * would have been 1.
    477 		 */
    478 		goto out;
    479 	}
    480 
    481 	ifp = ln->lle_tbl->llt_ifp;
    482 
    483 	KASSERT(ifp != NULL);
    484 
    485 	ndi = ND_IFINFO(ifp);
    486 
    487 	switch (ln->ln_state) {
    488 	case ND6_LLINFO_INCOMPLETE:
    489 		if (ln->ln_asked < nd6_mmaxtries) {
    490 			ln->ln_asked++;
    491 			send_ns = true;
    492 		} else {
    493 			struct mbuf *m = ln->ln_hold;
    494 			if (m) {
    495 				struct mbuf *m0;
    496 
    497 				/*
    498 				 * assuming every packet in ln_hold has
    499 				 * the same IP header
    500 				 */
    501 				m0 = m->m_nextpkt;
    502 				m->m_nextpkt = NULL;
    503 				ln->ln_hold = m0;
    504 				clear_llinfo_pqueue(ln);
    505  			}
    506 			nd6_free(ln, 0);
    507 			ln = NULL;
    508 			if (m != NULL) {
    509 #ifndef NET_MPSAFE
    510 				mutex_enter(softnet_lock);
    511 				KERNEL_LOCK(1, NULL);
    512 #endif
    513 				icmp6_error2(m, ICMP6_DST_UNREACH,
    514 				    ICMP6_DST_UNREACH_ADDR, 0, ifp);
    515 #ifndef NET_MPSAFE
    516 				KERNEL_UNLOCK_ONE(NULL);
    517 				mutex_exit(softnet_lock);
    518 #endif
    519 			}
    520 		}
    521 		break;
    522 	case ND6_LLINFO_REACHABLE:
    523 		if (!ND6_LLINFO_PERMANENT(ln)) {
    524 			ln->ln_state = ND6_LLINFO_STALE;
    525 			nd6_llinfo_settimer(ln, nd6_gctimer * hz);
    526 		}
    527 		break;
    528 
    529 	case ND6_LLINFO_PURGE:
    530 	case ND6_LLINFO_STALE:
    531 		/* Garbage Collection(RFC 2461 5.3) */
    532 		if (!ND6_LLINFO_PERMANENT(ln)) {
    533 			nd6_free(ln, 1);
    534 			ln = NULL;
    535 		}
    536 		break;
    537 
    538 	case ND6_LLINFO_DELAY:
    539 		if (ndi && (ndi->flags & ND6_IFF_PERFORMNUD) != 0) {
    540 			/* We need NUD */
    541 			ln->ln_asked = 1;
    542 			ln->ln_state = ND6_LLINFO_PROBE;
    543 			daddr6 = &ln->r_l3addr.addr6;
    544 			send_ns = true;
    545 		} else {
    546 			ln->ln_state = ND6_LLINFO_STALE; /* XXX */
    547 			nd6_llinfo_settimer(ln, nd6_gctimer * hz);
    548 		}
    549 		break;
    550 	case ND6_LLINFO_PROBE:
    551 		if (ln->ln_asked < nd6_umaxtries) {
    552 			ln->ln_asked++;
    553 			daddr6 = &ln->r_l3addr.addr6;
    554 			send_ns = true;
    555 		} else {
    556 			nd6_free(ln, 0);
    557 			ln = NULL;
    558 		}
    559 		break;
    560 	}
    561 
    562 	if (send_ns) {
    563 		struct in6_addr src, *psrc;
    564 		const struct in6_addr *taddr6 = &ln->r_l3addr.addr6;
    565 
    566 		nd6_llinfo_settimer(ln, ndi->retrans * hz / 1000);
    567 		psrc = nd6_llinfo_get_holdsrc(ln, &src);
    568 		LLE_FREE_LOCKED(ln);
    569 		ln = NULL;
    570 #ifndef NET_MPSAFE
    571 		mutex_enter(softnet_lock);
    572 		KERNEL_LOCK(1, NULL);
    573 #endif
    574 		nd6_ns_output(ifp, daddr6, taddr6, psrc, 0);
    575 #ifndef NET_MPSAFE
    576 		KERNEL_UNLOCK_ONE(NULL);
    577 		mutex_exit(softnet_lock);
    578 #endif
    579 	}
    580 
    581 out:
    582 	if (ln != NULL)
    583 		LLE_FREE_LOCKED(ln);
    584 }
    585 
    586 /*
    587  * ND6 timer routine to expire default route list and prefix list
    588  */
    589 static void
    590 nd6_timer_work(struct work *wk, void *arg)
    591 {
    592 	struct nd_defrouter *next_dr, *dr;
    593 	struct nd_prefix *next_pr, *pr;
    594 	struct in6_ifaddr *ia6, *nia6;
    595 	int s, bound;
    596 	struct psref psref;
    597 
    598 	callout_reset(&nd6_timer_ch, nd6_prune * hz,
    599 	    nd6_timer, NULL);
    600 
    601 #ifndef NET_MPSAFE
    602 	mutex_enter(softnet_lock);
    603 	KERNEL_LOCK(1, NULL);
    604 #endif
    605 
    606 	/* expire default router list */
    607 
    608 	ND6_WLOCK();
    609 	ND_DEFROUTER_LIST_FOREACH_SAFE(dr, next_dr) {
    610 		if (dr->expire && dr->expire < time_uptime) {
    611 			nd6_defrtrlist_del(dr, NULL);
    612 		}
    613 	}
    614 	ND6_UNLOCK();
    615 
    616 	/*
    617 	 * expire interface addresses.
    618 	 * in the past the loop was inside prefix expiry processing.
    619 	 * However, from a stricter speci-confrmance standpoint, we should
    620 	 * rather separate address lifetimes and prefix lifetimes.
    621 	 */
    622 	bound = curlwp_bind();
    623   addrloop:
    624 	s = pserialize_read_enter();
    625 	for (ia6 = IN6_ADDRLIST_READER_FIRST(); ia6; ia6 = nia6) {
    626 		nia6 = IN6_ADDRLIST_READER_NEXT(ia6);
    627 
    628 		ia6_acquire(ia6, &psref);
    629 		pserialize_read_exit(s);
    630 
    631 		/* check address lifetime */
    632 		if (IFA6_IS_INVALID(ia6)) {
    633 			int regen = 0;
    634 
    635 			/*
    636 			 * If the expiring address is temporary, try
    637 			 * regenerating a new one.  This would be useful when
    638 			 * we suspended a laptop PC, then turned it on after a
    639 			 * period that could invalidate all temporary
    640 			 * addresses.  Although we may have to restart the
    641 			 * loop (see below), it must be after purging the
    642 			 * address.  Otherwise, we'd see an infinite loop of
    643 			 * regeneration.
    644 			 */
    645 			if (ip6_use_tempaddr &&
    646 			    (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
    647 				if (regen_tmpaddr(ia6) == 0)
    648 					regen = 1;
    649 			}
    650 
    651 			ia6_release(ia6, &psref);
    652  			in6_purgeaddr(&ia6->ia_ifa);
    653 			ia6 = NULL;
    654 
    655 			if (regen)
    656 				goto addrloop; /* XXX: see below */
    657 		} else if (IFA6_IS_DEPRECATED(ia6)) {
    658 			int oldflags = ia6->ia6_flags;
    659 
    660 			if ((oldflags & IN6_IFF_DEPRECATED) == 0) {
    661 				ia6->ia6_flags |= IN6_IFF_DEPRECATED;
    662 				rt_newaddrmsg(RTM_NEWADDR,
    663 				    (struct ifaddr *)ia6, 0, NULL);
    664 			}
    665 
    666 			/*
    667 			 * If a temporary address has just become deprecated,
    668 			 * regenerate a new one if possible.
    669 			 */
    670 			if (ip6_use_tempaddr &&
    671 			    (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
    672 			    (oldflags & IN6_IFF_DEPRECATED) == 0) {
    673 
    674 				if (regen_tmpaddr(ia6) == 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_newaddrmsg(RTM_NEWADDR,
    699 				    (struct ifaddr *)ia6, 0, NULL);
    700 			}
    701 		}
    702 		s = pserialize_read_enter();
    703 		ia6_release(ia6, &psref);
    704 	}
    705 	pserialize_read_exit(s);
    706 	curlwp_bindx(bound);
    707 
    708 	/* expire prefix list */
    709 	ND6_WLOCK();
    710 	ND_PREFIX_LIST_FOREACH_SAFE(pr, next_pr) {
    711 		/*
    712 		 * check prefix lifetime.
    713 		 * since pltime is just for autoconf, pltime processing for
    714 		 * prefix is not necessary.
    715 		 */
    716 		if (pr->ndpr_vltime != ND6_INFINITE_LIFETIME &&
    717 		    time_uptime - pr->ndpr_lastupdate > pr->ndpr_vltime) {
    718 
    719 			/*
    720 			 * address expiration and prefix expiration are
    721 			 * separate.  NEVER perform in6_purgeaddr here.
    722 			 */
    723 
    724 			nd6_prelist_remove(pr);
    725 		}
    726 	}
    727 	ND6_UNLOCK();
    728 
    729 #ifndef NET_MPSAFE
    730 	KERNEL_UNLOCK_ONE(NULL);
    731 	mutex_exit(softnet_lock);
    732 #endif
    733 }
    734 
    735 static void
    736 nd6_timer(void *ignored_arg)
    737 {
    738 
    739 	workqueue_enqueue(nd6_timer_wq, &nd6_timer_wk, NULL);
    740 }
    741 
    742 /* ia6: deprecated/invalidated temporary address */
    743 static int
    744 regen_tmpaddr(const struct in6_ifaddr *ia6)
    745 {
    746 	struct ifaddr *ifa;
    747 	struct ifnet *ifp;
    748 	struct in6_ifaddr *public_ifa6 = NULL;
    749 	int s;
    750 
    751 	ifp = ia6->ia_ifa.ifa_ifp;
    752 	s = pserialize_read_enter();
    753 	IFADDR_READER_FOREACH(ifa, ifp) {
    754 		struct in6_ifaddr *it6;
    755 
    756 		if (ifa->ifa_addr->sa_family != AF_INET6)
    757 			continue;
    758 
    759 		it6 = (struct in6_ifaddr *)ifa;
    760 
    761 		/* ignore no autoconf addresses. */
    762 		if ((it6->ia6_flags & IN6_IFF_AUTOCONF) == 0)
    763 			continue;
    764 
    765 		/* ignore autoconf addresses with different prefixes. */
    766 		if (it6->ia6_ndpr == NULL || it6->ia6_ndpr != ia6->ia6_ndpr)
    767 			continue;
    768 
    769 		/*
    770 		 * Now we are looking at an autoconf address with the same
    771 		 * prefix as ours.  If the address is temporary and is still
    772 		 * preferred, do not create another one.  It would be rare, but
    773 		 * could happen, for example, when we resume a laptop PC after
    774 		 * a long period.
    775 		 */
    776 		if ((it6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
    777 		    !IFA6_IS_DEPRECATED(it6)) {
    778 			public_ifa6 = NULL;
    779 			break;
    780 		}
    781 
    782 		/*
    783 		 * This is a public autoconf address that has the same prefix
    784 		 * as ours.  If it is preferred, keep it.  We can't break the
    785 		 * loop here, because there may be a still-preferred temporary
    786 		 * address with the prefix.
    787 		 */
    788 		if (!IFA6_IS_DEPRECATED(it6))
    789 			public_ifa6 = it6;
    790 	}
    791 
    792 	if (public_ifa6 != NULL) {
    793 		int e;
    794 		struct psref psref;
    795 
    796 		ia6_acquire(public_ifa6, &psref);
    797 		pserialize_read_exit(s);
    798 		/*
    799 		 * Random factor is introduced in the preferred lifetime, so
    800 		 * we do not need additional delay (3rd arg to in6_tmpifadd).
    801 		 */
    802 		ND6_WLOCK();
    803 		e = in6_tmpifadd(public_ifa6, 0, 0);
    804 		ND6_UNLOCK();
    805 		if (e != 0) {
    806 			ia6_release(public_ifa6, &psref);
    807 			log(LOG_NOTICE, "regen_tmpaddr: failed to create a new"
    808 			    " tmp addr, errno=%d\n", e);
    809 			return -1;
    810 		}
    811 		ia6_release(public_ifa6, &psref);
    812 		return 0;
    813 	}
    814 	pserialize_read_exit(s);
    815 
    816 	return -1;
    817 }
    818 
    819 bool
    820 nd6_accepts_rtadv(const struct nd_ifinfo *ndi)
    821 {
    822 	switch (ndi->flags & (ND6_IFF_ACCEPT_RTADV|ND6_IFF_OVERRIDE_RTADV)) {
    823 	case ND6_IFF_OVERRIDE_RTADV|ND6_IFF_ACCEPT_RTADV:
    824 		return true;
    825 	case ND6_IFF_ACCEPT_RTADV:
    826 		return ip6_accept_rtadv != 0;
    827 	case ND6_IFF_OVERRIDE_RTADV:
    828 	case 0:
    829 	default:
    830 		return false;
    831 	}
    832 }
    833 
    834 /*
    835  * Nuke neighbor cache/prefix/default router management table, right before
    836  * ifp goes away.
    837  */
    838 void
    839 nd6_purge(struct ifnet *ifp, struct in6_ifextra *ext)
    840 {
    841 	struct nd_defrouter *dr, *ndr;
    842 	struct nd_prefix *pr, *npr;
    843 
    844 	/*
    845 	 * During detach, the ND info might be already removed, but
    846 	 * then is explitly passed as argument.
    847 	 * Otherwise get it from ifp->if_afdata.
    848 	 */
    849 	if (ext == NULL)
    850 		ext = ifp->if_afdata[AF_INET6];
    851 	if (ext == NULL)
    852 		return;
    853 
    854 	ND6_WLOCK();
    855 	/*
    856 	 * Nuke default router list entries toward ifp.
    857 	 * We defer removal of default router list entries that is installed
    858 	 * in the routing table, in order to keep additional side effects as
    859 	 * small as possible.
    860 	 */
    861 	ND_DEFROUTER_LIST_FOREACH_SAFE(dr, ndr) {
    862 		if (dr->installed)
    863 			continue;
    864 
    865 		if (dr->ifp == ifp) {
    866 			KASSERT(ext != NULL);
    867 			nd6_defrtrlist_del(dr, ext);
    868 		}
    869 	}
    870 
    871 	ND_DEFROUTER_LIST_FOREACH_SAFE(dr, ndr) {
    872 		if (!dr->installed)
    873 			continue;
    874 
    875 		if (dr->ifp == ifp) {
    876 			KASSERT(ext != NULL);
    877 			nd6_defrtrlist_del(dr, ext);
    878 		}
    879 	}
    880 
    881 	/* Nuke prefix list entries toward ifp */
    882 	ND_PREFIX_LIST_FOREACH_SAFE(pr, npr) {
    883 		if (pr->ndpr_ifp == ifp) {
    884 			/*
    885 			 * All addresses referencing pr should be already freed.
    886 			 */
    887 			KASSERT(pr->ndpr_refcnt == 0);
    888 			nd6_prelist_remove(pr);
    889 		}
    890 	}
    891 
    892 	/* cancel default outgoing interface setting */
    893 	if (nd6_defifindex == ifp->if_index)
    894 		nd6_setdefaultiface(0);
    895 
    896 	/* XXX: too restrictive? */
    897 	if (!ip6_forwarding && ifp->if_afdata[AF_INET6]) {
    898 		struct nd_ifinfo *ndi = ND_IFINFO(ifp);
    899 		if (ndi && nd6_accepts_rtadv(ndi)) {
    900 			/* refresh default router list */
    901 			nd6_defrouter_select();
    902 		}
    903 	}
    904 	ND6_UNLOCK();
    905 
    906 	/*
    907 	 * We may not need to nuke the neighbor cache entries here
    908 	 * because the neighbor cache is kept in if_afdata[AF_INET6].
    909 	 * nd6_purge() is invoked by in6_ifdetach() which is called
    910 	 * from if_detach() where everything gets purged. However
    911 	 * in6_ifdetach is directly called from vlan(4), so we still
    912 	 * need to purge entries here.
    913 	 */
    914 	if (ext->lltable != NULL)
    915 		lltable_purge_entries(ext->lltable);
    916 }
    917 
    918 void
    919 nd6_assert_purged(struct ifnet *ifp)
    920 {
    921 	struct nd_defrouter *dr;
    922 	struct nd_prefix *pr;
    923 	char ip6buf[INET6_ADDRSTRLEN] __diagused;
    924 
    925 	ND6_RLOCK();
    926 	ND_DEFROUTER_LIST_FOREACH(dr) {
    927 		KASSERTMSG(dr->ifp != ifp,
    928 		    "defrouter %s remains on %s",
    929 		    IN6_PRINT(ip6buf, &dr->rtaddr), ifp->if_xname);
    930 	}
    931 
    932 	ND_PREFIX_LIST_FOREACH(pr) {
    933 		KASSERTMSG(pr->ndpr_ifp != ifp,
    934 		    "prefix %s/%d remains on %s",
    935 		    IN6_PRINT(ip6buf, &pr->ndpr_prefix.sin6_addr),
    936 		    pr->ndpr_plen, ifp->if_xname);
    937 	}
    938 	ND6_UNLOCK();
    939 }
    940 
    941 struct llentry *
    942 nd6_lookup(const struct in6_addr *addr6, const struct ifnet *ifp, bool wlock)
    943 {
    944 	struct sockaddr_in6 sin6;
    945 	struct llentry *ln;
    946 
    947 	sockaddr_in6_init(&sin6, addr6, 0, 0, 0);
    948 
    949 	IF_AFDATA_RLOCK(ifp);
    950 	ln = lla_lookup(LLTABLE6(ifp), wlock ? LLE_EXCLUSIVE : 0,
    951 	    sin6tosa(&sin6));
    952 	IF_AFDATA_RUNLOCK(ifp);
    953 
    954 	return ln;
    955 }
    956 
    957 struct llentry *
    958 nd6_create(const struct in6_addr *addr6, const struct ifnet *ifp)
    959 {
    960 	struct sockaddr_in6 sin6;
    961 	struct llentry *ln;
    962 
    963 	sockaddr_in6_init(&sin6, addr6, 0, 0, 0);
    964 
    965 	IF_AFDATA_WLOCK(ifp);
    966 	ln = lla_create(LLTABLE6(ifp), LLE_EXCLUSIVE,
    967 	    sin6tosa(&sin6));
    968 	IF_AFDATA_WUNLOCK(ifp);
    969 
    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 		int s;
   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 		s = pserialize_read_enter();
   1564 		ifa = (struct ifaddr *)in6ifa_ifpwithaddr(ifp,
   1565 		    &satocsin6(rt_getkey(rt))->sin6_addr);
   1566 		if (ifa != NULL) {
   1567 			if (nd6_useloopback) {
   1568 				rt->rt_ifp = lo0ifp;	/* XXX */
   1569 				/*
   1570 				 * Make sure rt_ifa be equal to the ifaddr
   1571 				 * corresponding to the address.
   1572 				 * We need this because when we refer
   1573 				 * rt_ifa->ia6_flags in ip6_input, we assume
   1574 				 * that the rt_ifa points to the address instead
   1575 				 * of the loopback address.
   1576 				 */
   1577 				if (ifa != rt->rt_ifa)
   1578 					rt_replace_ifa(rt, ifa);
   1579 			}
   1580 		} else if (rt->rt_flags & RTF_ANNOUNCE) {
   1581 			/* join solicited node multicast for proxy ND */
   1582 			if (ifp->if_flags & IFF_MULTICAST) {
   1583 				struct in6_addr llsol;
   1584 				int error;
   1585 
   1586 				llsol = satocsin6(rt_getkey(rt))->sin6_addr;
   1587 				llsol.s6_addr32[0] = htonl(0xff020000);
   1588 				llsol.s6_addr32[1] = 0;
   1589 				llsol.s6_addr32[2] = htonl(1);
   1590 				llsol.s6_addr8[12] = 0xff;
   1591 				if (in6_setscope(&llsol, ifp, NULL))
   1592 					goto out;
   1593 				if (!in6_addmulti(&llsol, ifp, &error, 0)) {
   1594 					char ip6buf[INET6_ADDRSTRLEN];
   1595 					nd6log(LOG_ERR, "%s: failed to join "
   1596 					    "%s (errno=%d)\n", if_name(ifp),
   1597 					    IN6_PRINT(ip6buf, &llsol), error);
   1598 				}
   1599 			}
   1600 		}
   1601 	out:
   1602 		pserialize_read_exit(s);
   1603 		/*
   1604 		 * If we have too many cache entries, initiate immediate
   1605 		 * purging for some entries.
   1606 		 */
   1607 		if (rt->rt_ifp != NULL)
   1608 			nd6_gc_neighbors(LLTABLE6(rt->rt_ifp), NULL);
   1609 		break;
   1610 	    }
   1611 
   1612 	case RTM_DELETE:
   1613 		/* leave from solicited node multicast for proxy ND */
   1614 		if ((rt->rt_flags & RTF_ANNOUNCE) != 0 &&
   1615 		    (ifp->if_flags & IFF_MULTICAST) != 0) {
   1616 			struct in6_addr llsol;
   1617 			struct in6_multi *in6m;
   1618 
   1619 			llsol = satocsin6(rt_getkey(rt))->sin6_addr;
   1620 			llsol.s6_addr32[0] = htonl(0xff020000);
   1621 			llsol.s6_addr32[1] = 0;
   1622 			llsol.s6_addr32[2] = htonl(1);
   1623 			llsol.s6_addr8[12] = 0xff;
   1624 			if (in6_setscope(&llsol, ifp, NULL) == 0) {
   1625 				IN6_LOOKUP_MULTI(llsol, ifp, in6m);
   1626 				if (in6m)
   1627 					in6_delmulti(in6m);
   1628 			}
   1629 		}
   1630 		break;
   1631 	}
   1632 }
   1633 
   1634 int
   1635 nd6_ioctl(u_long cmd, void *data, struct ifnet *ifp)
   1636 {
   1637 	struct in6_drlist *drl = (struct in6_drlist *)data;
   1638 	struct in6_oprlist *oprl = (struct in6_oprlist *)data;
   1639 	struct in6_ndireq *ndi = (struct in6_ndireq *)data;
   1640 	struct in6_nbrinfo *nbi = (struct in6_nbrinfo *)data;
   1641 	struct in6_ndifreq *ndif = (struct in6_ndifreq *)data;
   1642 	struct nd_defrouter *dr;
   1643 	struct nd_prefix *pr;
   1644 	int i = 0, error = 0;
   1645 
   1646 	switch (cmd) {
   1647 	case SIOCGDRLST_IN6:
   1648 		/*
   1649 		 * obsolete API, use sysctl under net.inet6.icmp6
   1650 		 */
   1651 		memset(drl, 0, sizeof(*drl));
   1652 		ND6_RLOCK();
   1653 		ND_DEFROUTER_LIST_FOREACH(dr) {
   1654 			if (i >= DRLSTSIZ)
   1655 				break;
   1656 			drl->defrouter[i].rtaddr = dr->rtaddr;
   1657 			in6_clearscope(&drl->defrouter[i].rtaddr);
   1658 
   1659 			drl->defrouter[i].flags = dr->flags;
   1660 			drl->defrouter[i].rtlifetime = dr->rtlifetime;
   1661 			drl->defrouter[i].expire = dr->expire ?
   1662 			    time_mono_to_wall(dr->expire) : 0;
   1663 			drl->defrouter[i].if_index = dr->ifp->if_index;
   1664 			i++;
   1665 		}
   1666 		ND6_UNLOCK();
   1667 		break;
   1668 	case SIOCGPRLST_IN6:
   1669 		/*
   1670 		 * obsolete API, use sysctl under net.inet6.icmp6
   1671 		 *
   1672 		 * XXX the structure in6_prlist was changed in backward-
   1673 		 * incompatible manner.  in6_oprlist is used for SIOCGPRLST_IN6,
   1674 		 * in6_prlist is used for nd6_sysctl() - fill_prlist().
   1675 		 */
   1676 		/*
   1677 		 * XXX meaning of fields, especialy "raflags", is very
   1678 		 * differnet between RA prefix list and RR/static prefix list.
   1679 		 * how about separating ioctls into two?
   1680 		 */
   1681 		memset(oprl, 0, sizeof(*oprl));
   1682 		ND6_RLOCK();
   1683 		ND_PREFIX_LIST_FOREACH(pr) {
   1684 			struct nd_pfxrouter *pfr;
   1685 			int j;
   1686 
   1687 			if (i >= PRLSTSIZ)
   1688 				break;
   1689 			oprl->prefix[i].prefix = pr->ndpr_prefix.sin6_addr;
   1690 			oprl->prefix[i].raflags = pr->ndpr_raf;
   1691 			oprl->prefix[i].prefixlen = pr->ndpr_plen;
   1692 			oprl->prefix[i].vltime = pr->ndpr_vltime;
   1693 			oprl->prefix[i].pltime = pr->ndpr_pltime;
   1694 			oprl->prefix[i].if_index = pr->ndpr_ifp->if_index;
   1695 			if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME)
   1696 				oprl->prefix[i].expire = 0;
   1697 			else {
   1698 				time_t maxexpire;
   1699 
   1700 				/* XXX: we assume time_t is signed. */
   1701 				maxexpire = (-1) &
   1702 				    ~((time_t)1 <<
   1703 				    ((sizeof(maxexpire) * 8) - 1));
   1704 				if (pr->ndpr_vltime <
   1705 				    maxexpire - pr->ndpr_lastupdate) {
   1706 					time_t expire;
   1707 					expire = pr->ndpr_lastupdate +
   1708 					    pr->ndpr_vltime;
   1709 					oprl->prefix[i].expire = expire ?
   1710 					    time_mono_to_wall(expire) : 0;
   1711 				} else
   1712 					oprl->prefix[i].expire = maxexpire;
   1713 			}
   1714 
   1715 			j = 0;
   1716 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
   1717 				if (j < DRLSTSIZ) {
   1718 #define RTRADDR oprl->prefix[i].advrtr[j]
   1719 					RTRADDR = pfr->router->rtaddr;
   1720 					in6_clearscope(&RTRADDR);
   1721 #undef RTRADDR
   1722 				}
   1723 				j++;
   1724 			}
   1725 			oprl->prefix[i].advrtrs = j;
   1726 			oprl->prefix[i].origin = PR_ORIG_RA;
   1727 
   1728 			i++;
   1729 		}
   1730 		ND6_UNLOCK();
   1731 
   1732 		break;
   1733 	case OSIOCGIFINFO_IN6:
   1734 #define ND	ndi->ndi
   1735 		/* XXX: old ndp(8) assumes a positive value for linkmtu. */
   1736 		memset(&ND, 0, sizeof(ND));
   1737 		ND.linkmtu = IN6_LINKMTU(ifp);
   1738 		ND.maxmtu = ND_IFINFO(ifp)->maxmtu;
   1739 		ND.basereachable = ND_IFINFO(ifp)->basereachable;
   1740 		ND.reachable = ND_IFINFO(ifp)->reachable;
   1741 		ND.retrans = ND_IFINFO(ifp)->retrans;
   1742 		ND.flags = ND_IFINFO(ifp)->flags;
   1743 		ND.recalctm = ND_IFINFO(ifp)->recalctm;
   1744 		ND.chlim = ND_IFINFO(ifp)->chlim;
   1745 		break;
   1746 	case SIOCGIFINFO_IN6:
   1747 		ND = *ND_IFINFO(ifp);
   1748 		break;
   1749 	case SIOCSIFINFO_IN6:
   1750 		/*
   1751 		 * used to change host variables from userland.
   1752 		 * intented for a use on router to reflect RA configurations.
   1753 		 */
   1754 		/* 0 means 'unspecified' */
   1755 		if (ND.linkmtu != 0) {
   1756 			if (ND.linkmtu < IPV6_MMTU ||
   1757 			    ND.linkmtu > IN6_LINKMTU(ifp)) {
   1758 				error = EINVAL;
   1759 				break;
   1760 			}
   1761 			ND_IFINFO(ifp)->linkmtu = ND.linkmtu;
   1762 		}
   1763 
   1764 		if (ND.basereachable != 0) {
   1765 			int obasereachable = ND_IFINFO(ifp)->basereachable;
   1766 
   1767 			ND_IFINFO(ifp)->basereachable = ND.basereachable;
   1768 			if (ND.basereachable != obasereachable)
   1769 				ND_IFINFO(ifp)->reachable =
   1770 				    ND_COMPUTE_RTIME(ND.basereachable);
   1771 		}
   1772 		if (ND.retrans != 0)
   1773 			ND_IFINFO(ifp)->retrans = ND.retrans;
   1774 		if (ND.chlim != 0)
   1775 			ND_IFINFO(ifp)->chlim = ND.chlim;
   1776 		/* FALLTHROUGH */
   1777 	case SIOCSIFINFO_FLAGS:
   1778 	{
   1779 		struct ifaddr *ifa;
   1780 		struct in6_ifaddr *ia;
   1781 		int s;
   1782 
   1783 		if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) &&
   1784 		    !(ND.flags & ND6_IFF_IFDISABLED))
   1785 		{
   1786 			/*
   1787 			 * If the interface is marked as ND6_IFF_IFDISABLED and
   1788 			 * has a link-local address with IN6_IFF_DUPLICATED,
   1789 			 * do not clear ND6_IFF_IFDISABLED.
   1790 			 * See RFC 4862, section 5.4.5.
   1791 			 */
   1792 			int duplicated_linklocal = 0;
   1793 
   1794 			s = pserialize_read_enter();
   1795 			IFADDR_READER_FOREACH(ifa, ifp) {
   1796 				if (ifa->ifa_addr->sa_family != AF_INET6)
   1797 					continue;
   1798 				ia = (struct in6_ifaddr *)ifa;
   1799 				if ((ia->ia6_flags & IN6_IFF_DUPLICATED) &&
   1800 				    IN6_IS_ADDR_LINKLOCAL(IA6_IN6(ia)))
   1801 				{
   1802 					duplicated_linklocal = 1;
   1803 					break;
   1804 				}
   1805 			}
   1806 			pserialize_read_exit(s);
   1807 
   1808 			if (duplicated_linklocal) {
   1809 				ND.flags |= ND6_IFF_IFDISABLED;
   1810 				log(LOG_ERR, "Cannot enable an interface"
   1811 				    " with a link-local address marked"
   1812 				    " duplicate.\n");
   1813 			} else {
   1814 				ND_IFINFO(ifp)->flags &= ~ND6_IFF_IFDISABLED;
   1815 				if (ifp->if_flags & IFF_UP)
   1816 					in6_if_up(ifp);
   1817 			}
   1818 		} else if (!(ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) &&
   1819 		    (ND.flags & ND6_IFF_IFDISABLED)) {
   1820 			int bound = curlwp_bind();
   1821 			/* Mark all IPv6 addresses as tentative. */
   1822 
   1823 			ND_IFINFO(ifp)->flags |= ND6_IFF_IFDISABLED;
   1824 			s = pserialize_read_enter();
   1825 			IFADDR_READER_FOREACH(ifa, ifp) {
   1826 				struct psref psref;
   1827 				if (ifa->ifa_addr->sa_family != AF_INET6)
   1828 					continue;
   1829 				ifa_acquire(ifa, &psref);
   1830 				pserialize_read_exit(s);
   1831 
   1832 				nd6_dad_stop(ifa);
   1833 
   1834 				ia = (struct in6_ifaddr *)ifa;
   1835 				ia->ia6_flags |= IN6_IFF_TENTATIVE;
   1836 
   1837 				s = pserialize_read_enter();
   1838 				ifa_release(ifa, &psref);
   1839 			}
   1840 			pserialize_read_exit(s);
   1841 			curlwp_bindx(bound);
   1842 		}
   1843 
   1844 		if (ND.flags & ND6_IFF_AUTO_LINKLOCAL) {
   1845 			if (!(ND_IFINFO(ifp)->flags & ND6_IFF_AUTO_LINKLOCAL)) {
   1846 				/* auto_linklocal 0->1 transition */
   1847 
   1848 				ND_IFINFO(ifp)->flags |= ND6_IFF_AUTO_LINKLOCAL;
   1849 				in6_ifattach(ifp, NULL);
   1850 			} else if (!(ND.flags & ND6_IFF_IFDISABLED) &&
   1851 			    ifp->if_flags & IFF_UP)
   1852 			{
   1853 				/*
   1854 				 * When the IF already has
   1855 				 * ND6_IFF_AUTO_LINKLOCAL, no link-local
   1856 				 * address is assigned, and IFF_UP, try to
   1857 				 * assign one.
   1858 				 */
   1859 				int haslinklocal = 0;
   1860 
   1861 				s = pserialize_read_enter();
   1862 				IFADDR_READER_FOREACH(ifa, ifp) {
   1863 					if (ifa->ifa_addr->sa_family !=AF_INET6)
   1864 						continue;
   1865 					ia = (struct in6_ifaddr *)ifa;
   1866 					if (IN6_IS_ADDR_LINKLOCAL(IA6_IN6(ia))){
   1867 						haslinklocal = 1;
   1868 						break;
   1869 					}
   1870 				}
   1871 				pserialize_read_exit(s);
   1872 				if (!haslinklocal)
   1873 					in6_ifattach(ifp, NULL);
   1874 			}
   1875 		}
   1876 	}
   1877 		ND_IFINFO(ifp)->flags = ND.flags;
   1878 		break;
   1879 #undef ND
   1880 	case SIOCSNDFLUSH_IN6:	/* XXX: the ioctl name is confusing... */
   1881 		/* sync kernel routing table with the default router list */
   1882 		ND6_WLOCK();
   1883 		nd6_defrouter_reset();
   1884 		nd6_defrouter_select();
   1885 		ND6_UNLOCK();
   1886 		break;
   1887 	case SIOCSPFXFLUSH_IN6:
   1888 	{
   1889 		/* flush all the prefix advertised by routers */
   1890 		struct nd_prefix *pfx, *next;
   1891 
   1892 	restart:
   1893 		ND6_WLOCK();
   1894 		ND_PREFIX_LIST_FOREACH_SAFE(pfx, next) {
   1895 			struct in6_ifaddr *ia, *ia_next;
   1896 			int _s;
   1897 
   1898 			if (IN6_IS_ADDR_LINKLOCAL(&pfx->ndpr_prefix.sin6_addr))
   1899 				continue; /* XXX */
   1900 
   1901 			/* do we really have to remove addresses as well? */
   1902 			_s = pserialize_read_enter();
   1903 			for (ia = IN6_ADDRLIST_READER_FIRST(); ia;
   1904 			     ia = ia_next) {
   1905 				/* ia might be removed.  keep the next ptr. */
   1906 				ia_next = IN6_ADDRLIST_READER_NEXT(ia);
   1907 
   1908 				if ((ia->ia6_flags & IN6_IFF_AUTOCONF) == 0)
   1909 					continue;
   1910 
   1911 				if (ia->ia6_ndpr == pfx) {
   1912 					pserialize_read_exit(_s);
   1913 					ND6_UNLOCK();
   1914 					/* XXX NOMPSAFE? */
   1915 					/* in6_purgeaddr may destroy pfx. */
   1916 					in6_purgeaddr(&ia->ia_ifa);
   1917 					goto restart;
   1918 				}
   1919 			}
   1920 			pserialize_read_exit(_s);
   1921 
   1922 			KASSERT(pfx->ndpr_refcnt == 0);
   1923 			nd6_prelist_remove(pfx);
   1924 		}
   1925 		ND6_UNLOCK();
   1926 		break;
   1927 	}
   1928 	case SIOCSRTRFLUSH_IN6:
   1929 	{
   1930 		/* flush all the default routers */
   1931 		struct nd_defrouter *drtr, *next;
   1932 
   1933 		ND6_WLOCK();
   1934 		nd6_defrouter_reset();
   1935 		ND_DEFROUTER_LIST_FOREACH_SAFE(drtr, next) {
   1936 			nd6_defrtrlist_del(drtr, NULL);
   1937 		}
   1938 		nd6_defrouter_select();
   1939 		ND6_UNLOCK();
   1940 		break;
   1941 	}
   1942 	case SIOCGNBRINFO_IN6:
   1943 	{
   1944 		struct llentry *ln;
   1945 		struct in6_addr nb_addr = nbi->addr; /* make local for safety */
   1946 
   1947 		if ((error = in6_setscope(&nb_addr, ifp, NULL)) != 0)
   1948 			return error;
   1949 
   1950 		ln = nd6_lookup(&nb_addr, ifp, false);
   1951 		if (ln == NULL) {
   1952 			error = EINVAL;
   1953 			break;
   1954 		}
   1955 		nbi->state = ln->ln_state;
   1956 		nbi->asked = ln->ln_asked;
   1957 		nbi->isrouter = ln->ln_router;
   1958 		nbi->expire = ln->ln_expire ?
   1959 		    time_mono_to_wall(ln->ln_expire) : 0;
   1960 		LLE_RUNLOCK(ln);
   1961 
   1962 		break;
   1963 	}
   1964 	case SIOCGDEFIFACE_IN6:	/* XXX: should be implemented as a sysctl? */
   1965 		ndif->ifindex = nd6_defifindex;
   1966 		break;
   1967 	case SIOCSDEFIFACE_IN6:	/* XXX: should be implemented as a sysctl? */
   1968 		return nd6_setdefaultiface(ndif->ifindex);
   1969 	}
   1970 	return error;
   1971 }
   1972 
   1973 void
   1974 nd6_llinfo_release_pkts(struct llentry *ln, struct ifnet *ifp)
   1975 {
   1976 	struct mbuf *m_hold, *m_hold_next;
   1977 	struct sockaddr_in6 sin6;
   1978 
   1979 	LLE_WLOCK_ASSERT(ln);
   1980 
   1981 	sockaddr_in6_init(&sin6, &ln->r_l3addr.addr6, 0, 0, 0);
   1982 
   1983 	m_hold = ln->la_hold, ln->la_hold = NULL, ln->la_numheld = 0;
   1984 
   1985 	LLE_WUNLOCK(ln);
   1986 	for (; m_hold != NULL; m_hold = m_hold_next) {
   1987 		m_hold_next = m_hold->m_nextpkt;
   1988 		m_hold->m_nextpkt = NULL;
   1989 
   1990 		/*
   1991 		 * we assume ifp is not a p2p here, so
   1992 		 * just set the 2nd argument as the
   1993 		 * 1st one.
   1994 		 */
   1995 		nd6_output(ifp, ifp, m_hold, &sin6, NULL);
   1996 	}
   1997 	LLE_WLOCK(ln);
   1998 }
   1999 
   2000 /*
   2001  * Create neighbor cache entry and cache link-layer address,
   2002  * on reception of inbound ND6 packets.  (RS/RA/NS/redirect)
   2003  */
   2004 void
   2005 nd6_cache_lladdr(
   2006     struct ifnet *ifp,
   2007     struct in6_addr *from,
   2008     char *lladdr,
   2009     int lladdrlen,
   2010     int type,	/* ICMP6 type */
   2011     int code	/* type dependent information */
   2012 )
   2013 {
   2014 	struct nd_ifinfo *ndi = ND_IFINFO(ifp);
   2015 	struct llentry *ln = NULL;
   2016 	int is_newentry;
   2017 	int do_update;
   2018 	int olladdr;
   2019 	int llchange;
   2020 	int newstate = 0;
   2021 	uint16_t router = 0;
   2022 
   2023 	KASSERT(ifp != NULL);
   2024 	KASSERT(from != NULL);
   2025 
   2026 	/* nothing must be updated for unspecified address */
   2027 	if (IN6_IS_ADDR_UNSPECIFIED(from))
   2028 		return;
   2029 
   2030 	/*
   2031 	 * Validation about ifp->if_addrlen and lladdrlen must be done in
   2032 	 * the caller.
   2033 	 *
   2034 	 * XXX If the link does not have link-layer adderss, what should
   2035 	 * we do? (ifp->if_addrlen == 0)
   2036 	 * Spec says nothing in sections for RA, RS and NA.  There's small
   2037 	 * description on it in NS section (RFC 2461 7.2.3).
   2038 	 */
   2039 
   2040 	ln = nd6_lookup(from, ifp, true);
   2041 	if (ln == NULL) {
   2042 #if 0
   2043 		/* nothing must be done if there's no lladdr */
   2044 		if (!lladdr || !lladdrlen)
   2045 			return NULL;
   2046 #endif
   2047 
   2048 		ln = nd6_create(from, ifp);
   2049 		is_newentry = 1;
   2050 	} else {
   2051 		/* do nothing if static ndp is set */
   2052 		if (ln->la_flags & LLE_STATIC) {
   2053 			LLE_WUNLOCK(ln);
   2054 			return;
   2055 		}
   2056 		is_newentry = 0;
   2057 	}
   2058 
   2059 	if (ln == NULL)
   2060 		return;
   2061 
   2062 	olladdr = (ln->la_flags & LLE_VALID) ? 1 : 0;
   2063 	if (olladdr && lladdr) {
   2064 		llchange = memcmp(lladdr, &ln->ll_addr, ifp->if_addrlen);
   2065 	} else
   2066 		llchange = 0;
   2067 
   2068 	/*
   2069 	 * newentry olladdr  lladdr  llchange	(*=record)
   2070 	 *	0	n	n	--	(1)
   2071 	 *	0	y	n	--	(2)
   2072 	 *	0	n	y	--	(3) * STALE
   2073 	 *	0	y	y	n	(4) *
   2074 	 *	0	y	y	y	(5) * STALE
   2075 	 *	1	--	n	--	(6)   NOSTATE(= PASSIVE)
   2076 	 *	1	--	y	--	(7) * STALE
   2077 	 */
   2078 
   2079 	if (lladdr) {		/* (3-5) and (7) */
   2080 		/*
   2081 		 * Record source link-layer address
   2082 		 * XXX is it dependent to ifp->if_type?
   2083 		 */
   2084 		memcpy(&ln->ll_addr, lladdr, ifp->if_addrlen);
   2085 		ln->la_flags |= LLE_VALID;
   2086 	}
   2087 
   2088 	if (!is_newentry) {
   2089 		if ((!olladdr && lladdr) ||		/* (3) */
   2090 		    (olladdr && lladdr && llchange)) {	/* (5) */
   2091 			do_update = 1;
   2092 			newstate = ND6_LLINFO_STALE;
   2093 		} else					/* (1-2,4) */
   2094 			do_update = 0;
   2095 	} else {
   2096 		do_update = 1;
   2097 		if (lladdr == NULL)			/* (6) */
   2098 			newstate = ND6_LLINFO_NOSTATE;
   2099 		else					/* (7) */
   2100 			newstate = ND6_LLINFO_STALE;
   2101 	}
   2102 
   2103 	if (do_update) {
   2104 		/*
   2105 		 * Update the state of the neighbor cache.
   2106 		 */
   2107 		ln->ln_state = newstate;
   2108 
   2109 		if (ln->ln_state == ND6_LLINFO_STALE) {
   2110 			/*
   2111 			 * XXX: since nd6_output() below will cause
   2112 			 * state tansition to DELAY and reset the timer,
   2113 			 * we must set the timer now, although it is actually
   2114 			 * meaningless.
   2115 			 */
   2116 			nd6_llinfo_settimer(ln, nd6_gctimer * hz);
   2117 
   2118 			nd6_llinfo_release_pkts(ln, ifp);
   2119 		} else if (ln->ln_state == ND6_LLINFO_INCOMPLETE) {
   2120 			/* probe right away */
   2121 			nd6_llinfo_settimer((void *)ln, 0);
   2122 		}
   2123 	}
   2124 
   2125 	/*
   2126 	 * ICMP6 type dependent behavior.
   2127 	 *
   2128 	 * NS: clear IsRouter if new entry
   2129 	 * RS: clear IsRouter
   2130 	 * RA: set IsRouter if there's lladdr
   2131 	 * redir: clear IsRouter if new entry
   2132 	 *
   2133 	 * RA case, (1):
   2134 	 * The spec says that we must set IsRouter in the following cases:
   2135 	 * - If lladdr exist, set IsRouter.  This means (1-5).
   2136 	 * - If it is old entry (!newentry), set IsRouter.  This means (7).
   2137 	 * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
   2138 	 * A quetion arises for (1) case.  (1) case has no lladdr in the
   2139 	 * neighbor cache, this is similar to (6).
   2140 	 * This case is rare but we figured that we MUST NOT set IsRouter.
   2141 	 *
   2142 	 * newentry olladdr  lladdr  llchange	    NS  RS  RA	redir
   2143 	 *							D R
   2144 	 *	0	n	n	--	(1)	c   ?     s
   2145 	 *	0	y	n	--	(2)	c   s     s
   2146 	 *	0	n	y	--	(3)	c   s     s
   2147 	 *	0	y	y	n	(4)	c   s     s
   2148 	 *	0	y	y	y	(5)	c   s     s
   2149 	 *	1	--	n	--	(6) c	c 	c s
   2150 	 *	1	--	y	--	(7) c	c   s	c s
   2151 	 *
   2152 	 *					(c=clear s=set)
   2153 	 */
   2154 	switch (type & 0xff) {
   2155 	case ND_NEIGHBOR_SOLICIT:
   2156 		/*
   2157 		 * New entry must have is_router flag cleared.
   2158 		 */
   2159 		if (is_newentry)	/* (6-7) */
   2160 			ln->ln_router = 0;
   2161 		break;
   2162 	case ND_REDIRECT:
   2163 		/*
   2164 		 * If the icmp is a redirect to a better router, always set the
   2165 		 * is_router flag.  Otherwise, if the entry is newly created,
   2166 		 * clear the flag.  [RFC 2461, sec 8.3]
   2167 		 */
   2168 		if (code == ND_REDIRECT_ROUTER)
   2169 			ln->ln_router = 1;
   2170 		else if (is_newentry) /* (6-7) */
   2171 			ln->ln_router = 0;
   2172 		break;
   2173 	case ND_ROUTER_SOLICIT:
   2174 		/*
   2175 		 * is_router flag must always be cleared.
   2176 		 */
   2177 		ln->ln_router = 0;
   2178 		break;
   2179 	case ND_ROUTER_ADVERT:
   2180 		/*
   2181 		 * Mark an entry with lladdr as a router.
   2182 		 */
   2183 		if ((!is_newentry && (olladdr || lladdr)) ||	/* (2-5) */
   2184 		    (is_newentry && lladdr)) {			/* (7) */
   2185 			ln->ln_router = 1;
   2186 		}
   2187 		break;
   2188 	}
   2189 
   2190 #if 0
   2191 	/* XXX should we send rtmsg as it used to be? */
   2192 	if (do_update)
   2193 		rt_newmsg(RTM_CHANGE, rt);  /* tell user process */
   2194 #endif
   2195 
   2196 	if (ln != NULL) {
   2197 		router = ln->ln_router;
   2198 		LLE_WUNLOCK(ln);
   2199 	}
   2200 
   2201 	/*
   2202 	 * If we have too many cache entries, initiate immediate
   2203 	 * purging for some entries.
   2204 	 */
   2205 	if (is_newentry)
   2206 		nd6_gc_neighbors(LLTABLE6(ifp), &ln->r_l3addr.addr6);
   2207 
   2208 	/*
   2209 	 * When the link-layer address of a router changes, select the
   2210 	 * best router again.  In particular, when the neighbor entry is newly
   2211 	 * created, it might affect the selection policy.
   2212 	 * Question: can we restrict the first condition to the "is_newentry"
   2213 	 * case?
   2214 	 * XXX: when we hear an RA from a new router with the link-layer
   2215 	 * address option, nd6_defrouter_select() is called twice, since
   2216 	 * defrtrlist_update called the function as well.  However, I believe
   2217 	 * we can compromise the overhead, since it only happens the first
   2218 	 * time.
   2219 	 * XXX: although nd6_defrouter_select() should not have a bad effect
   2220 	 * for those are not autoconfigured hosts, we explicitly avoid such
   2221 	 * cases for safety.
   2222 	 */
   2223 	if (do_update && router && !ip6_forwarding &&
   2224 	    nd6_accepts_rtadv(ndi)) {
   2225 		ND6_WLOCK();
   2226 		nd6_defrouter_select();
   2227 		ND6_UNLOCK();
   2228 	}
   2229 }
   2230 
   2231 static void
   2232 nd6_slowtimo(void *ignored_arg)
   2233 {
   2234 	struct nd_ifinfo *nd6if;
   2235 	struct ifnet *ifp;
   2236 	int s;
   2237 
   2238 #ifndef NET_MPSAFE
   2239 	mutex_enter(softnet_lock);
   2240 	KERNEL_LOCK(1, NULL);
   2241 #endif
   2242 	callout_reset(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
   2243 	    nd6_slowtimo, NULL);
   2244 
   2245 	s = pserialize_read_enter();
   2246 	IFNET_READER_FOREACH(ifp) {
   2247 		nd6if = ND_IFINFO(ifp);
   2248 		if (nd6if->basereachable && /* already initialized */
   2249 		    (nd6if->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
   2250 			/*
   2251 			 * Since reachable time rarely changes by router
   2252 			 * advertisements, we SHOULD insure that a new random
   2253 			 * value gets recomputed at least once every few hours.
   2254 			 * (RFC 2461, 6.3.4)
   2255 			 */
   2256 			nd6if->recalctm = nd6_recalc_reachtm_interval;
   2257 			nd6if->reachable = ND_COMPUTE_RTIME(nd6if->basereachable);
   2258 		}
   2259 	}
   2260 	pserialize_read_exit(s);
   2261 
   2262 #ifndef NET_MPSAFE
   2263 	KERNEL_UNLOCK_ONE(NULL);
   2264 	mutex_exit(softnet_lock);
   2265 #endif
   2266 }
   2267 
   2268 int
   2269 nd6_output(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m,
   2270     const struct sockaddr_in6 *dst, struct rtentry *rt)
   2271 {
   2272 #define senderr(e) { error = (e); goto bad;}
   2273 	struct llentry *ln = NULL;
   2274 	int error = 0;
   2275 	bool created = false;
   2276 
   2277 	if (rt != NULL) {
   2278 		error = rt_check_reject_route(rt, ifp);
   2279 		if (error != 0) {
   2280 			m_freem(m);
   2281 			return error;
   2282 		}
   2283 	}
   2284 
   2285 	if (IN6_IS_ADDR_MULTICAST(&dst->sin6_addr))
   2286 		goto sendpkt;
   2287 
   2288 	if (nd6_need_cache(ifp) == 0)
   2289 		goto sendpkt;
   2290 
   2291 	if (rt != NULL && (rt->rt_flags & RTF_GATEWAY) != 0) {
   2292 		struct sockaddr_in6 *gw6 = satosin6(rt->rt_gateway);
   2293 		int s;
   2294 
   2295 		/* XXX remain the check to keep the original behavior. */
   2296 		/*
   2297 		 * We skip link-layer address resolution and NUD
   2298 		 * if the gateway is not a neighbor from ND point
   2299 		 * of view, regardless of the value of nd_ifinfo.flags.
   2300 		 * The second condition is a bit tricky; we skip
   2301 		 * if the gateway is our own address, which is
   2302 		 * sometimes used to install a route to a p2p link.
   2303 		 */
   2304 		s = pserialize_read_enter();
   2305 		if (!nd6_is_addr_neighbor(gw6, ifp) ||
   2306 		    in6ifa_ifpwithaddr(ifp, &gw6->sin6_addr)) {
   2307 			/*
   2308 			 * We allow this kind of tricky route only
   2309 			 * when the outgoing interface is p2p.
   2310 			 * XXX: we may need a more generic rule here.
   2311 			 */
   2312 			if ((ifp->if_flags & IFF_POINTOPOINT) == 0) {
   2313 				pserialize_read_exit(s);
   2314 				senderr(EHOSTUNREACH);
   2315 			}
   2316 
   2317 			pserialize_read_exit(s);
   2318 			goto sendpkt;
   2319 		}
   2320 		pserialize_read_exit(s);
   2321 	}
   2322 
   2323 	/*
   2324 	 * Address resolution or Neighbor Unreachability Detection
   2325 	 * for the next hop.
   2326 	 * At this point, the destination of the packet must be a unicast
   2327 	 * or an anycast address(i.e. not a multicast).
   2328 	 */
   2329 
   2330 	/* Look up the neighbor cache for the nexthop */
   2331 	ln = nd6_lookup(&dst->sin6_addr, ifp, true);
   2332 	if ((ln == NULL) && nd6_is_addr_neighbor(dst, ifp))  {
   2333 		/*
   2334 		 * Since nd6_is_addr_neighbor() internally calls nd6_lookup(),
   2335 		 * the condition below is not very efficient.  But we believe
   2336 		 * it is tolerable, because this should be a rare case.
   2337 		 */
   2338 		ln = nd6_create(&dst->sin6_addr, ifp);
   2339 		if (ln != NULL)
   2340 			created = true;
   2341 	}
   2342 
   2343 	if (ln == NULL) {
   2344 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0 &&
   2345 		    !(ND_IFINFO(ifp)->flags & ND6_IFF_PERFORMNUD)) {
   2346 			char ip6buf[INET6_ADDRSTRLEN];
   2347 			log(LOG_DEBUG,
   2348 			    "nd6_output: can't allocate llinfo for %s "
   2349 			    "(ln=%p, rt=%p)\n",
   2350 			    IN6_PRINT(ip6buf, &dst->sin6_addr), ln, rt);
   2351 			senderr(EIO);	/* XXX: good error? */
   2352 		}
   2353 		goto sendpkt;	/* send anyway */
   2354 	}
   2355 
   2356 	LLE_WLOCK_ASSERT(ln);
   2357 
   2358 	/* We don't have to do link-layer address resolution on a p2p link. */
   2359 	if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
   2360 	    ln->ln_state < ND6_LLINFO_REACHABLE) {
   2361 		ln->ln_state = ND6_LLINFO_STALE;
   2362 		nd6_llinfo_settimer(ln, nd6_gctimer * hz);
   2363 	}
   2364 
   2365 	/*
   2366 	 * The first time we send a packet to a neighbor whose entry is
   2367 	 * STALE, we have to change the state to DELAY and a sets a timer to
   2368 	 * expire in DELAY_FIRST_PROBE_TIME seconds to ensure do
   2369 	 * neighbor unreachability detection on expiration.
   2370 	 * (RFC 2461 7.3.3)
   2371 	 */
   2372 	if (ln->ln_state == ND6_LLINFO_STALE) {
   2373 		ln->ln_asked = 0;
   2374 		ln->ln_state = ND6_LLINFO_DELAY;
   2375 		nd6_llinfo_settimer(ln, nd6_delay * hz);
   2376 	}
   2377 
   2378 	/*
   2379 	 * If the neighbor cache entry has a state other than INCOMPLETE
   2380 	 * (i.e. its link-layer address is already resolved), just
   2381 	 * send the packet.
   2382 	 */
   2383 	if (ln->ln_state > ND6_LLINFO_INCOMPLETE)
   2384 		goto sendpkt;
   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 	error = 0;
   2436 	goto exit;
   2437 
   2438   sendpkt:
   2439 	/* discard the packet if IPv6 operation is disabled on the interface */
   2440 	if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED)) {
   2441 		error = ENETDOWN; /* better error? */
   2442 		goto bad;
   2443 	}
   2444 
   2445 	if (ln != NULL)
   2446 		LLE_WUNLOCK(ln);
   2447 
   2448 	if ((ifp->if_flags & IFF_LOOPBACK) != 0)
   2449 		error = if_output_lock(ifp, origifp, m, sin6tocsa(dst), rt);
   2450 	else
   2451 		error = if_output_lock(ifp, ifp, m, sin6tocsa(dst), rt);
   2452 	goto exit;
   2453 
   2454   bad:
   2455 	if (m != NULL)
   2456 		m_freem(m);
   2457   exit:
   2458 	if (created)
   2459 		nd6_gc_neighbors(LLTABLE6(ifp), &dst->sin6_addr);
   2460 
   2461 	return error;
   2462 #undef senderr
   2463 }
   2464 
   2465 int
   2466 nd6_need_cache(struct ifnet *ifp)
   2467 {
   2468 	/*
   2469 	 * XXX: we currently do not make neighbor cache on any interface
   2470 	 * other than ARCnet, Ethernet, FDDI and GIF.
   2471 	 *
   2472 	 * RFC2893 says:
   2473 	 * - unidirectional tunnels needs no ND
   2474 	 */
   2475 	switch (ifp->if_type) {
   2476 	case IFT_ARCNET:
   2477 	case IFT_ETHER:
   2478 	case IFT_FDDI:
   2479 	case IFT_IEEE1394:
   2480 	case IFT_CARP:
   2481 	case IFT_GIF:		/* XXX need more cases? */
   2482 	case IFT_PPP:
   2483 	case IFT_TUNNEL:
   2484 		return 1;
   2485 	default:
   2486 		return 0;
   2487 	}
   2488 }
   2489 
   2490 /*
   2491  * Add pernament ND6 link-layer record for given
   2492  * interface address.
   2493  *
   2494  * Very similar to IPv4 arp_ifinit(), but:
   2495  * 1) IPv6 DAD is performed in different place
   2496  * 2) It is called by IPv6 protocol stack in contrast to
   2497  * arp_ifinit() which is typically called in SIOCSIFADDR
   2498  * driver ioctl handler.
   2499  *
   2500  */
   2501 int
   2502 nd6_add_ifa_lle(struct in6_ifaddr *ia)
   2503 {
   2504 	struct ifnet *ifp;
   2505 	struct llentry *ln;
   2506 
   2507 	ifp = ia->ia_ifa.ifa_ifp;
   2508 	if (nd6_need_cache(ifp) == 0)
   2509 		return 0;
   2510 	ia->ia_ifa.ifa_rtrequest = nd6_rtrequest;
   2511 	ia->ia_ifa.ifa_flags |= RTF_CONNECTED;
   2512 
   2513 	IF_AFDATA_WLOCK(ifp);
   2514 	ln = lla_create(LLTABLE6(ifp), LLE_IFADDR | LLE_EXCLUSIVE,
   2515 	    sin6tosa(&ia->ia_addr));
   2516 	IF_AFDATA_WUNLOCK(ifp);
   2517 	if (ln == NULL)
   2518 		return ENOBUFS;
   2519 
   2520 	ln->la_expire = 0;  /* for IPv6 this means permanent */
   2521 	ln->ln_state = ND6_LLINFO_REACHABLE;
   2522 
   2523 	LLE_WUNLOCK(ln);
   2524 	return 0;
   2525 }
   2526 
   2527 /*
   2528  * Removes ALL lle records for interface address prefix.
   2529  * XXXME: That's probably not we really want to do, we need
   2530  * to remove address record only and keep other records
   2531  * until we determine if given prefix is really going
   2532  * to be removed.
   2533  */
   2534 void
   2535 nd6_rem_ifa_lle(struct in6_ifaddr *ia)
   2536 {
   2537 	struct sockaddr_in6 mask, addr;
   2538 
   2539 	memcpy(&addr, &ia->ia_addr, sizeof(ia->ia_addr));
   2540 	memcpy(&mask, &ia->ia_prefixmask, sizeof(ia->ia_prefixmask));
   2541 	lltable_prefix_free(AF_INET6, sin6tosa(&addr), sin6tosa(&mask),
   2542 	    LLE_STATIC);
   2543 }
   2544 
   2545 int
   2546 nd6_storelladdr(const struct ifnet *ifp, const struct rtentry *rt,
   2547     struct mbuf *m, const struct sockaddr *dst, uint8_t *lldst,
   2548     size_t dstsize)
   2549 {
   2550 	struct llentry *ln;
   2551 
   2552 	if (m->m_flags & M_MCAST) {
   2553 		switch (ifp->if_type) {
   2554 		case IFT_ETHER:
   2555 		case IFT_FDDI:
   2556 			ETHER_MAP_IPV6_MULTICAST(&satocsin6(dst)->sin6_addr,
   2557 			    lldst);
   2558 			return 1;
   2559 		case IFT_IEEE1394:
   2560 			memcpy(lldst, ifp->if_broadcastaddr,
   2561 			    MIN(dstsize, ifp->if_addrlen));
   2562 			return 1;
   2563 		case IFT_ARCNET:
   2564 			*lldst = 0;
   2565 			return 1;
   2566 		default:
   2567 			m_freem(m);
   2568 			return 0;
   2569 		}
   2570 	}
   2571 
   2572 	/*
   2573 	 * the entry should have been created in nd6_store_lladdr
   2574 	 */
   2575 	ln = nd6_lookup(&satocsin6(dst)->sin6_addr, ifp, false);
   2576 	if ((ln == NULL) || !(ln->la_flags & LLE_VALID)) {
   2577 		if (ln != NULL)
   2578 			LLE_RUNLOCK(ln);
   2579 		/* this could happen, if we could not allocate memory */
   2580 		m_freem(m);
   2581 		return 0;
   2582 	}
   2583 
   2584 	/* XXX llentry should have addrlen? */
   2585 #if 0
   2586 	sdl = satocsdl(rt->rt_gateway);
   2587 	if (sdl->sdl_alen == 0 || sdl->sdl_alen > dstsize) {
   2588 		char sbuf[INET6_ADDRSTRLEN];
   2589 		char dbuf[LINK_ADDRSTRLEN];
   2590 		/* this should be impossible, but we bark here for debugging */
   2591 		printf("%s: sdl_alen == %" PRIu8 ", if=%s, dst=%s, sdl=%s\n",
   2592 		    __func__, sdl->sdl_alen, if_name(ifp),
   2593 		    IN6_PRINT(sbuf, &satocsin6(dst)->sin6_addr),
   2594 		    DL_PRINT(dbuf, &sdl->sdl_addr));
   2595 		m_freem(m);
   2596 		return 0;
   2597 	}
   2598 #endif
   2599 
   2600 	memcpy(lldst, &ln->ll_addr, MIN(dstsize, ifp->if_addrlen));
   2601 
   2602 	LLE_RUNLOCK(ln);
   2603 
   2604 	return 1;
   2605 }
   2606 
   2607 static void
   2608 clear_llinfo_pqueue(struct llentry *ln)
   2609 {
   2610 	struct mbuf *m_hold, *m_hold_next;
   2611 
   2612 	for (m_hold = ln->ln_hold; m_hold; m_hold = m_hold_next) {
   2613 		m_hold_next = m_hold->m_nextpkt;
   2614 		m_hold->m_nextpkt = NULL;
   2615 		m_freem(m_hold);
   2616 	}
   2617 
   2618 	ln->ln_hold = NULL;
   2619 	return;
   2620 }
   2621 
   2622 int
   2623 nd6_sysctl(
   2624     int name,
   2625     void *oldp,	/* syscall arg, need copyout */
   2626     size_t *oldlenp,
   2627     void *newp,	/* syscall arg, need copyin */
   2628     size_t newlen
   2629 )
   2630 {
   2631 	void *p;
   2632 	size_t ol;
   2633 	int error;
   2634 
   2635 	error = 0;
   2636 
   2637 	if (newp)
   2638 		return EPERM;
   2639 	if (oldp && !oldlenp)
   2640 		return EINVAL;
   2641 	ol = oldlenp ? *oldlenp : 0;
   2642 
   2643 	if (oldp) {
   2644 		p = malloc(*oldlenp, M_TEMP, M_WAITOK);
   2645 		if (p == NULL)
   2646 			return ENOMEM;
   2647 	} else
   2648 		p = NULL;
   2649 	switch (name) {
   2650 	case ICMPV6CTL_ND6_DRLIST:
   2651 		error = fill_drlist(p, oldlenp, ol);
   2652 		if (!error && p != NULL && oldp != NULL)
   2653 			error = copyout(p, oldp, *oldlenp);
   2654 		break;
   2655 
   2656 	case ICMPV6CTL_ND6_PRLIST:
   2657 		error = fill_prlist(p, oldlenp, ol);
   2658 		if (!error && p != NULL && oldp != NULL)
   2659 			error = copyout(p, oldp, *oldlenp);
   2660 		break;
   2661 
   2662 	case ICMPV6CTL_ND6_MAXQLEN:
   2663 		break;
   2664 
   2665 	default:
   2666 		error = ENOPROTOOPT;
   2667 		break;
   2668 	}
   2669 	if (p)
   2670 		free(p, M_TEMP);
   2671 
   2672 	return error;
   2673 }
   2674 
   2675 static int
   2676 fill_drlist(void *oldp, size_t *oldlenp, size_t ol)
   2677 {
   2678 	int error = 0;
   2679 	struct in6_defrouter *d = NULL, *de = NULL;
   2680 	struct nd_defrouter *dr;
   2681 	size_t l;
   2682 
   2683 	if (oldp) {
   2684 		d = (struct in6_defrouter *)oldp;
   2685 		de = (struct in6_defrouter *)((char *)oldp + *oldlenp);
   2686 	}
   2687 	l = 0;
   2688 
   2689 	ND6_RLOCK();
   2690 	ND_DEFROUTER_LIST_FOREACH(dr) {
   2691 
   2692 		if (oldp && d + 1 <= de) {
   2693 			memset(d, 0, sizeof(*d));
   2694 			sockaddr_in6_init(&d->rtaddr, &dr->rtaddr, 0, 0, 0);
   2695 			if (sa6_recoverscope(&d->rtaddr)) {
   2696 				char ip6buf[INET6_ADDRSTRLEN];
   2697 				log(LOG_ERR,
   2698 				    "scope error in router list (%s)\n",
   2699 				    IN6_PRINT(ip6buf, &d->rtaddr.sin6_addr));
   2700 				/* XXX: press on... */
   2701 			}
   2702 			d->flags = dr->flags;
   2703 			d->rtlifetime = dr->rtlifetime;
   2704 			d->expire = dr->expire ?
   2705 			    time_mono_to_wall(dr->expire) : 0;
   2706 			d->if_index = dr->ifp->if_index;
   2707 		}
   2708 
   2709 		l += sizeof(*d);
   2710 		if (d)
   2711 			d++;
   2712 	}
   2713 	ND6_UNLOCK();
   2714 
   2715 	if (oldp) {
   2716 		if (l > ol)
   2717 			error = ENOMEM;
   2718 	}
   2719 	if (oldlenp)
   2720 		*oldlenp = l;	/* (void *)d - (void *)oldp */
   2721 
   2722 	return error;
   2723 }
   2724 
   2725 static int
   2726 fill_prlist(void *oldp, size_t *oldlenp, size_t ol)
   2727 {
   2728 	int error = 0;
   2729 	struct nd_prefix *pr;
   2730 	uint8_t *p = NULL, *ps = NULL;
   2731 	uint8_t *pe = NULL;
   2732 	size_t l;
   2733 	char ip6buf[INET6_ADDRSTRLEN];
   2734 
   2735 	if (oldp) {
   2736 		ps = p = (uint8_t*)oldp;
   2737 		pe = (uint8_t*)oldp + *oldlenp;
   2738 	}
   2739 	l = 0;
   2740 
   2741 	ND6_RLOCK();
   2742 	ND_PREFIX_LIST_FOREACH(pr) {
   2743 		u_short advrtrs;
   2744 		struct sockaddr_in6 sin6;
   2745 		struct nd_pfxrouter *pfr;
   2746 		struct in6_prefix pfx;
   2747 
   2748 		if (oldp && p + sizeof(struct in6_prefix) <= pe)
   2749 		{
   2750 			memset(&pfx, 0, sizeof(pfx));
   2751 			ps = p;
   2752 			pfx.prefix = pr->ndpr_prefix;
   2753 
   2754 			if (sa6_recoverscope(&pfx.prefix)) {
   2755 				log(LOG_ERR,
   2756 				    "scope error in prefix list (%s)\n",
   2757 				    IN6_PRINT(ip6buf, &pfx.prefix.sin6_addr));
   2758 				/* XXX: press on... */
   2759 			}
   2760 			pfx.raflags = pr->ndpr_raf;
   2761 			pfx.prefixlen = pr->ndpr_plen;
   2762 			pfx.vltime = pr->ndpr_vltime;
   2763 			pfx.pltime = pr->ndpr_pltime;
   2764 			pfx.if_index = pr->ndpr_ifp->if_index;
   2765 			if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME)
   2766 				pfx.expire = 0;
   2767 			else {
   2768 				time_t maxexpire;
   2769 
   2770 				/* XXX: we assume time_t is signed. */
   2771 				maxexpire = (-1) &
   2772 				    ~((time_t)1 <<
   2773 				    ((sizeof(maxexpire) * 8) - 1));
   2774 				if (pr->ndpr_vltime <
   2775 				    maxexpire - pr->ndpr_lastupdate) {
   2776 					pfx.expire = pr->ndpr_lastupdate +
   2777 						pr->ndpr_vltime;
   2778 				} else
   2779 					pfx.expire = maxexpire;
   2780 			}
   2781 			pfx.refcnt = pr->ndpr_refcnt;
   2782 			pfx.flags = pr->ndpr_stateflags;
   2783 			pfx.origin = PR_ORIG_RA;
   2784 
   2785 			p += sizeof(pfx); l += sizeof(pfx);
   2786 
   2787 			advrtrs = 0;
   2788 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
   2789 				if (p + sizeof(sin6) > pe) {
   2790 					advrtrs++;
   2791 					continue;
   2792 				}
   2793 
   2794 				sockaddr_in6_init(&sin6, &pfr->router->rtaddr,
   2795 					    0, 0, 0);
   2796 				if (sa6_recoverscope(&sin6)) {
   2797 					log(LOG_ERR,
   2798 					    "scope error in "
   2799 					    "prefix list (%s)\n",
   2800 					    IN6_PRINT(ip6buf,
   2801 					    &pfr->router->rtaddr));
   2802 				}
   2803 				advrtrs++;
   2804 				memcpy(p, &sin6, sizeof(sin6));
   2805 				p += sizeof(sin6);
   2806 				l += sizeof(sin6);
   2807 			}
   2808 			pfx.advrtrs = advrtrs;
   2809 			memcpy(ps, &pfx, sizeof(pfx));
   2810 		}
   2811 		else {
   2812 			l += sizeof(pfx);
   2813 			advrtrs = 0;
   2814 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
   2815 				advrtrs++;
   2816 				l += sizeof(sin6);
   2817 			}
   2818 		}
   2819 	}
   2820 	ND6_UNLOCK();
   2821 
   2822 	if (oldp) {
   2823 		*oldlenp = l;	/* (void *)d - (void *)oldp */
   2824 		if (l > ol)
   2825 			error = ENOMEM;
   2826 	} else
   2827 		*oldlenp = l;
   2828 
   2829 	return error;
   2830 }
   2831 
   2832 static int
   2833 nd6_setdefaultiface(int ifindex)
   2834 {
   2835 	ifnet_t *ifp;
   2836 	int error = 0;
   2837 	int s;
   2838 
   2839 	s = pserialize_read_enter();
   2840 	ifp = if_byindex(ifindex);
   2841 	if (ifp == NULL) {
   2842 		pserialize_read_exit(s);
   2843 		return EINVAL;
   2844 	}
   2845 	if (nd6_defifindex != ifindex) {
   2846 		nd6_defifindex = ifindex;
   2847 		nd6_defifp = nd6_defifindex > 0 ? ifp : NULL;
   2848 
   2849 		/*
   2850 		 * Our current implementation assumes one-to-one maping between
   2851 		 * interfaces and links, so it would be natural to use the
   2852 		 * default interface as the default link.
   2853 		 */
   2854 		scope6_setdefault(nd6_defifp);
   2855 	}
   2856 	pserialize_read_exit(s);
   2857 
   2858 	return (error);
   2859 }
   2860