Home | History | Annotate | Line # | Download | only in netinet6
nd6.c revision 1.222
      1 /*	$NetBSD: nd6.c,v 1.222 2016/12/21 08:47:02 ozaki-r Exp $	*/
      2 /*	$KAME: nd6.c,v 1.279 2002/06/08 11:16:51 itojun Exp $	*/
      3 
      4 /*
      5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
      6  * All rights reserved.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  * 3. Neither the name of the project nor the names of its contributors
     17  *    may be used to endorse or promote products derived from this software
     18  *    without specific prior written permission.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     30  * SUCH DAMAGE.
     31  */
     32 
     33 #include <sys/cdefs.h>
     34 __KERNEL_RCSID(0, "$NetBSD: nd6.c,v 1.222 2016/12/21 08:47:02 ozaki-r Exp $");
     35 
     36 #ifdef _KERNEL_OPT
     37 #include "opt_net_mpsafe.h"
     38 #endif
     39 
     40 #include "bridge.h"
     41 #include "carp.h"
     42 
     43 #include <sys/param.h>
     44 #include <sys/systm.h>
     45 #include <sys/callout.h>
     46 #include <sys/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/protosw.h>
     54 #include <sys/errno.h>
     55 #include <sys/ioctl.h>
     56 #include <sys/syslog.h>
     57 #include <sys/queue.h>
     58 #include <sys/cprng.h>
     59 #include <sys/workqueue.h>
     60 
     61 #include <net/if.h>
     62 #include <net/if_dl.h>
     63 #include <net/if_llatbl.h>
     64 #include <net/if_types.h>
     65 #include <net/route.h>
     66 #include <net/if_ether.h>
     67 #include <net/if_fddi.h>
     68 #include <net/if_arc.h>
     69 
     70 #include <netinet/in.h>
     71 #include <netinet6/in6_var.h>
     72 #include <netinet/ip6.h>
     73 #include <netinet6/ip6_var.h>
     74 #include <netinet6/scope6_var.h>
     75 #include <netinet6/nd6.h>
     76 #include <netinet6/in6_ifattach.h>
     77 #include <netinet/icmp6.h>
     78 #include <netinet6/icmp6_private.h>
     79 
     80 #include <net/net_osdep.h>
     81 
     82 #define ND6_SLOWTIMER_INTERVAL (60 * 60) /* 1 hour */
     83 #define ND6_RECALC_REACHTM_INTERVAL (60 * 120) /* 2 hours */
     84 
     85 /* timer values */
     86 int	nd6_prune	= 1;	/* walk list every 1 seconds */
     87 int	nd6_delay	= 5;	/* delay first probe time 5 second */
     88 int	nd6_umaxtries	= 3;	/* maximum unicast query */
     89 int	nd6_mmaxtries	= 3;	/* maximum multicast query */
     90 int	nd6_useloopback = 1;	/* use loopback interface for local traffic */
     91 int	nd6_gctimer	= (60 * 60 * 24); /* 1 day: garbage collection timer */
     92 
     93 /* preventing too many loops in ND option parsing */
     94 int nd6_maxndopt = 10;	/* max # of ND options allowed */
     95 
     96 int nd6_maxnudhint = 0;	/* max # of subsequent upper layer hints */
     97 
     98 int nd6_maxqueuelen = 1; /* max # of packets cached in unresolved ND entries */
     99 
    100 #ifdef ND6_DEBUG
    101 int nd6_debug = 1;
    102 #else
    103 int nd6_debug = 0;
    104 #endif
    105 
    106 krwlock_t nd6_lock __cacheline_aligned;
    107 
    108 struct nd_drhead nd_defrouter;
    109 struct nd_prhead nd_prefix = { 0 };
    110 
    111 int nd6_recalc_reachtm_interval = ND6_RECALC_REACHTM_INTERVAL;
    112 
    113 static void nd6_setmtu0(struct ifnet *, struct nd_ifinfo *);
    114 static void nd6_slowtimo(void *);
    115 static int regen_tmpaddr(const struct in6_ifaddr *);
    116 static void nd6_free(struct llentry *, int);
    117 static void nd6_llinfo_timer(void *);
    118 static void nd6_timer(void *);
    119 static void nd6_timer_work(struct work *, void *);
    120 static void clear_llinfo_pqueue(struct llentry *);
    121 static struct nd_opt_hdr *nd6_option(union nd_opts *);
    122 
    123 static callout_t nd6_slowtimo_ch;
    124 static callout_t nd6_timer_ch;
    125 static struct workqueue	*nd6_timer_wq;
    126 static struct work	nd6_timer_wk;
    127 
    128 static int fill_drlist(void *, size_t *, size_t);
    129 static int fill_prlist(void *, size_t *, size_t);
    130 
    131 static struct ifnet *nd6_defifp;
    132 static int nd6_defifindex;
    133 
    134 static int nd6_setdefaultiface(int);
    135 
    136 MALLOC_DEFINE(M_IP6NDP, "NDP", "IPv6 Neighbour Discovery");
    137 
    138 void
    139 nd6_init(void)
    140 {
    141 	int error;
    142 
    143 	rw_init(&nd6_lock);
    144 
    145 	/* initialization of the default router list */
    146 	ND_DEFROUTER_LIST_INIT();
    147 
    148 	callout_init(&nd6_slowtimo_ch, CALLOUT_MPSAFE);
    149 	callout_init(&nd6_timer_ch, CALLOUT_MPSAFE);
    150 
    151 	error = workqueue_create(&nd6_timer_wq, "nd6_timer",
    152 	    nd6_timer_work, NULL, PRI_SOFTNET, IPL_SOFTNET, WQ_MPSAFE);
    153 	if (error)
    154 		panic("%s: workqueue_create failed (%d)\n", __func__, error);
    155 
    156 	/* start timer */
    157 	callout_reset(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
    158 	    nd6_slowtimo, NULL);
    159 	callout_reset(&nd6_timer_ch, hz, nd6_timer, NULL);
    160 }
    161 
    162 struct nd_ifinfo *
    163 nd6_ifattach(struct ifnet *ifp)
    164 {
    165 	struct nd_ifinfo *nd;
    166 
    167 	nd = (struct nd_ifinfo *)malloc(sizeof(*nd), M_IP6NDP, M_WAITOK|M_ZERO);
    168 
    169 	nd->initialized = 1;
    170 
    171 	nd->chlim = IPV6_DEFHLIM;
    172 	nd->basereachable = REACHABLE_TIME;
    173 	nd->reachable = ND_COMPUTE_RTIME(nd->basereachable);
    174 	nd->retrans = RETRANS_TIMER;
    175 
    176 	nd->flags = ND6_IFF_PERFORMNUD | ND6_IFF_ACCEPT_RTADV;
    177 
    178 	/* A loopback interface always has ND6_IFF_AUTO_LINKLOCAL.
    179 	 * A bridge interface should not have ND6_IFF_AUTO_LINKLOCAL
    180 	 * because one of its members should. */
    181 	if ((ip6_auto_linklocal && ifp->if_type != IFT_BRIDGE) ||
    182 	    (ifp->if_flags & IFF_LOOPBACK))
    183 		nd->flags |= ND6_IFF_AUTO_LINKLOCAL;
    184 
    185 	/* A loopback interface does not need to accept RTADV.
    186 	 * A bridge interface should not accept RTADV
    187 	 * because one of its members should. */
    188 	if (ip6_accept_rtadv &&
    189 	    !(ifp->if_flags & IFF_LOOPBACK) &&
    190 	    !(ifp->if_type != IFT_BRIDGE))
    191 		nd->flags |= ND6_IFF_ACCEPT_RTADV;
    192 
    193 	/* XXX: we cannot call nd6_setmtu since ifp is not fully initialized */
    194 	nd6_setmtu0(ifp, nd);
    195 
    196 	return nd;
    197 }
    198 
    199 void
    200 nd6_ifdetach(struct ifnet *ifp, struct in6_ifextra *ext)
    201 {
    202 
    203 	/* Ensure all IPv6 addresses are purged before calling nd6_purge */
    204 	if_purgeaddrs(ifp, AF_INET6, in6_purgeaddr);
    205 	nd6_purge(ifp, ext);
    206 	free(ext->nd_ifinfo, M_IP6NDP);
    207 }
    208 
    209 void
    210 nd6_setmtu(struct ifnet *ifp)
    211 {
    212 	nd6_setmtu0(ifp, ND_IFINFO(ifp));
    213 }
    214 
    215 void
    216 nd6_setmtu0(struct ifnet *ifp, struct nd_ifinfo *ndi)
    217 {
    218 	u_int32_t omaxmtu;
    219 
    220 	omaxmtu = ndi->maxmtu;
    221 
    222 	switch (ifp->if_type) {
    223 	case IFT_ARCNET:
    224 		ndi->maxmtu = MIN(ARC_PHDS_MAXMTU, ifp->if_mtu); /* RFC2497 */
    225 		break;
    226 	case IFT_FDDI:
    227 		ndi->maxmtu = MIN(FDDIIPMTU, ifp->if_mtu);
    228 		break;
    229 	default:
    230 		ndi->maxmtu = ifp->if_mtu;
    231 		break;
    232 	}
    233 
    234 	/*
    235 	 * Decreasing the interface MTU under IPV6 minimum MTU may cause
    236 	 * undesirable situation.  We thus notify the operator of the change
    237 	 * explicitly.  The check for omaxmtu is necessary to restrict the
    238 	 * log to the case of changing the MTU, not initializing it.
    239 	 */
    240 	if (omaxmtu >= IPV6_MMTU && ndi->maxmtu < IPV6_MMTU) {
    241 		log(LOG_NOTICE, "nd6_setmtu0: new link MTU on %s (%lu) is too"
    242 		    " small for IPv6 which needs %lu\n",
    243 		    if_name(ifp), (unsigned long)ndi->maxmtu, (unsigned long)
    244 		    IPV6_MMTU);
    245 	}
    246 
    247 	if (ndi->maxmtu > in6_maxmtu)
    248 		in6_setmaxmtu(); /* check all interfaces just in case */
    249 }
    250 
    251 void
    252 nd6_option_init(void *opt, int icmp6len, union nd_opts *ndopts)
    253 {
    254 
    255 	memset(ndopts, 0, sizeof(*ndopts));
    256 	ndopts->nd_opts_search = (struct nd_opt_hdr *)opt;
    257 	ndopts->nd_opts_last
    258 		= (struct nd_opt_hdr *)(((u_char *)opt) + icmp6len);
    259 
    260 	if (icmp6len == 0) {
    261 		ndopts->nd_opts_done = 1;
    262 		ndopts->nd_opts_search = NULL;
    263 	}
    264 }
    265 
    266 /*
    267  * Take one ND option.
    268  */
    269 static struct nd_opt_hdr *
    270 nd6_option(union nd_opts *ndopts)
    271 {
    272 	struct nd_opt_hdr *nd_opt;
    273 	int olen;
    274 
    275 	KASSERT(ndopts != NULL);
    276 	KASSERT(ndopts->nd_opts_last != NULL);
    277 
    278 	if (ndopts->nd_opts_search == NULL)
    279 		return NULL;
    280 	if (ndopts->nd_opts_done)
    281 		return NULL;
    282 
    283 	nd_opt = ndopts->nd_opts_search;
    284 
    285 	/* make sure nd_opt_len is inside the buffer */
    286 	if ((void *)&nd_opt->nd_opt_len >= (void *)ndopts->nd_opts_last) {
    287 		memset(ndopts, 0, sizeof(*ndopts));
    288 		return NULL;
    289 	}
    290 
    291 	olen = nd_opt->nd_opt_len << 3;
    292 	if (olen == 0) {
    293 		/*
    294 		 * Message validation requires that all included
    295 		 * options have a length that is greater than zero.
    296 		 */
    297 		memset(ndopts, 0, sizeof(*ndopts));
    298 		return NULL;
    299 	}
    300 
    301 	ndopts->nd_opts_search = (struct nd_opt_hdr *)((char *)nd_opt + olen);
    302 	if (ndopts->nd_opts_search > ndopts->nd_opts_last) {
    303 		/* option overruns the end of buffer, invalid */
    304 		memset(ndopts, 0, sizeof(*ndopts));
    305 		return NULL;
    306 	} else if (ndopts->nd_opts_search == ndopts->nd_opts_last) {
    307 		/* reached the end of options chain */
    308 		ndopts->nd_opts_done = 1;
    309 		ndopts->nd_opts_search = NULL;
    310 	}
    311 	return nd_opt;
    312 }
    313 
    314 /*
    315  * Parse multiple ND options.
    316  * This function is much easier to use, for ND routines that do not need
    317  * multiple options of the same type.
    318  */
    319 int
    320 nd6_options(union nd_opts *ndopts)
    321 {
    322 	struct nd_opt_hdr *nd_opt;
    323 	int i = 0;
    324 
    325 	KASSERT(ndopts != NULL);
    326 	KASSERT(ndopts->nd_opts_last != NULL);
    327 
    328 	if (ndopts->nd_opts_search == NULL)
    329 		return 0;
    330 
    331 	while (1) {
    332 		nd_opt = nd6_option(ndopts);
    333 		if (nd_opt == NULL && ndopts->nd_opts_last == NULL) {
    334 			/*
    335 			 * Message validation requires that all included
    336 			 * options have a length that is greater than zero.
    337 			 */
    338 			ICMP6_STATINC(ICMP6_STAT_ND_BADOPT);
    339 			memset(ndopts, 0, sizeof(*ndopts));
    340 			return -1;
    341 		}
    342 
    343 		if (nd_opt == NULL)
    344 			goto skip1;
    345 
    346 		switch (nd_opt->nd_opt_type) {
    347 		case ND_OPT_SOURCE_LINKADDR:
    348 		case ND_OPT_TARGET_LINKADDR:
    349 		case ND_OPT_MTU:
    350 		case ND_OPT_REDIRECTED_HEADER:
    351 			if (ndopts->nd_opt_array[nd_opt->nd_opt_type]) {
    352 				nd6log(LOG_INFO,
    353 				    "duplicated ND6 option found (type=%d)\n",
    354 				    nd_opt->nd_opt_type);
    355 				/* XXX bark? */
    356 			} else {
    357 				ndopts->nd_opt_array[nd_opt->nd_opt_type]
    358 					= nd_opt;
    359 			}
    360 			break;
    361 		case ND_OPT_PREFIX_INFORMATION:
    362 			if (ndopts->nd_opt_array[nd_opt->nd_opt_type] == 0) {
    363 				ndopts->nd_opt_array[nd_opt->nd_opt_type]
    364 					= nd_opt;
    365 			}
    366 			ndopts->nd_opts_pi_end =
    367 				(struct nd_opt_prefix_info *)nd_opt;
    368 			break;
    369 		default:
    370 			/*
    371 			 * Unknown options must be silently ignored,
    372 			 * to accommodate future extension to the protocol.
    373 			 */
    374 			nd6log(LOG_DEBUG,
    375 			    "nd6_options: unsupported option %d - "
    376 			    "option ignored\n", nd_opt->nd_opt_type);
    377 		}
    378 
    379 skip1:
    380 		i++;
    381 		if (i > nd6_maxndopt) {
    382 			ICMP6_STATINC(ICMP6_STAT_ND_TOOMANYOPT);
    383 			nd6log(LOG_INFO, "too many loop in nd opt\n");
    384 			break;
    385 		}
    386 
    387 		if (ndopts->nd_opts_done)
    388 			break;
    389 	}
    390 
    391 	return 0;
    392 }
    393 
    394 /*
    395  * ND6 timer routine to handle ND6 entries
    396  */
    397 void
    398 nd6_llinfo_settimer(struct llentry *ln, time_t xtick)
    399 {
    400 
    401 	CTASSERT(sizeof(time_t) > sizeof(int));
    402 	LLE_WLOCK_ASSERT(ln);
    403 
    404 	KASSERT(xtick >= 0);
    405 
    406 	ln->ln_expire = time_uptime + xtick / hz;
    407 	LLE_ADDREF(ln);
    408 	if (xtick > INT_MAX) {
    409 		ln->ln_ntick = xtick - INT_MAX;
    410 		callout_reset(&ln->ln_timer_ch, INT_MAX,
    411 		    nd6_llinfo_timer, ln);
    412 	} else {
    413 		ln->ln_ntick = 0;
    414 		callout_reset(&ln->ln_timer_ch, xtick,
    415 		    nd6_llinfo_timer, ln);
    416 	}
    417 }
    418 
    419 /*
    420  * Gets source address of the first packet in hold queue
    421  * and stores it in @src.
    422  * Returns pointer to @src (if hold queue is not empty) or NULL.
    423  */
    424 static struct in6_addr *
    425 nd6_llinfo_get_holdsrc(struct llentry *ln, struct in6_addr *src)
    426 {
    427 	struct ip6_hdr *hip6;
    428 
    429 	if (ln == NULL || ln->ln_hold == NULL)
    430 		return NULL;
    431 
    432 	/*
    433 	 * assuming every packet in ln_hold has the same IP header
    434 	 */
    435 	hip6 = mtod(ln->ln_hold, struct ip6_hdr *);
    436 	/* XXX pullup? */
    437 	if (sizeof(*hip6) < ln->ln_hold->m_len)
    438 		*src = hip6->ip6_src;
    439 	else
    440 		src = NULL;
    441 
    442 	return src;
    443 }
    444 
    445 static void
    446 nd6_llinfo_timer(void *arg)
    447 {
    448 	struct llentry *ln = arg;
    449 	struct ifnet *ifp;
    450 	struct nd_ifinfo *ndi = NULL;
    451 	bool send_ns = false;
    452 	const struct in6_addr *daddr6 = NULL;
    453 
    454 	LLE_WLOCK(ln);
    455 	if ((ln->la_flags & LLE_LINKED) == 0)
    456 		goto out;
    457 	if (ln->ln_ntick > 0) {
    458 		nd6_llinfo_settimer(ln, ln->ln_ntick);
    459 		goto out;
    460 	}
    461 
    462 	if (callout_pending(&ln->la_timer)) {
    463 		/*
    464 		 * Here we are a bit odd here in the treatment of
    465 		 * active/pending. If the pending bit is set, it got
    466 		 * rescheduled before I ran. The active
    467 		 * bit we ignore, since if it was stopped
    468 		 * in ll_tablefree() and was currently running
    469 		 * it would have return 0 so the code would
    470 		 * not have deleted it since the callout could
    471 		 * not be stopped so we want to go through
    472 		 * with the delete here now. If the callout
    473 		 * was restarted, the pending bit will be back on and
    474 		 * we just want to bail since the callout_reset would
    475 		 * return 1 and our reference would have been removed
    476 		 * by nd6_llinfo_settimer above since canceled
    477 		 * would have been 1.
    478 		 */
    479 		goto out;
    480 	}
    481 
    482 	ifp = ln->lle_tbl->llt_ifp;
    483 
    484 	KASSERT(ifp != NULL);
    485 
    486 	ndi = ND_IFINFO(ifp);
    487 
    488 	switch (ln->ln_state) {
    489 	case ND6_LLINFO_INCOMPLETE:
    490 		if (ln->ln_asked < nd6_mmaxtries) {
    491 			ln->ln_asked++;
    492 			send_ns = true;
    493 		} else {
    494 			struct mbuf *m = ln->ln_hold;
    495 			if (m) {
    496 				struct mbuf *m0;
    497 
    498 				/*
    499 				 * assuming every packet in ln_hold has
    500 				 * the same IP header
    501 				 */
    502 				m0 = m->m_nextpkt;
    503 				m->m_nextpkt = NULL;
    504 				ln->ln_hold = m0;
    505 				clear_llinfo_pqueue(ln);
    506  			}
    507 			nd6_free(ln, 0);
    508 			ln = NULL;
    509 			if (m != NULL) {
    510 #ifndef NET_MPSAFE
    511 				mutex_enter(softnet_lock);
    512 				KERNEL_LOCK(1, NULL);
    513 #endif
    514 				icmp6_error2(m, ICMP6_DST_UNREACH,
    515 				    ICMP6_DST_UNREACH_ADDR, 0, ifp);
    516 #ifndef NET_MPSAFE
    517 				KERNEL_UNLOCK_ONE(NULL);
    518 				mutex_exit(softnet_lock);
    519 #endif
    520 			}
    521 		}
    522 		break;
    523 	case ND6_LLINFO_REACHABLE:
    524 		if (!ND6_LLINFO_PERMANENT(ln)) {
    525 			ln->ln_state = ND6_LLINFO_STALE;
    526 			nd6_llinfo_settimer(ln, nd6_gctimer * hz);
    527 		}
    528 		break;
    529 
    530 	case ND6_LLINFO_PURGE:
    531 	case ND6_LLINFO_STALE:
    532 		/* Garbage Collection(RFC 2461 5.3) */
    533 		if (!ND6_LLINFO_PERMANENT(ln)) {
    534 			nd6_free(ln, 1);
    535 			ln = NULL;
    536 		}
    537 		break;
    538 
    539 	case ND6_LLINFO_DELAY:
    540 		if (ndi && (ndi->flags & ND6_IFF_PERFORMNUD) != 0) {
    541 			/* We need NUD */
    542 			ln->ln_asked = 1;
    543 			ln->ln_state = ND6_LLINFO_PROBE;
    544 			daddr6 = &ln->r_l3addr.addr6;
    545 			send_ns = true;
    546 		} else {
    547 			ln->ln_state = ND6_LLINFO_STALE; /* XXX */
    548 			nd6_llinfo_settimer(ln, nd6_gctimer * hz);
    549 		}
    550 		break;
    551 	case ND6_LLINFO_PROBE:
    552 		if (ln->ln_asked < nd6_umaxtries) {
    553 			ln->ln_asked++;
    554 			daddr6 = &ln->r_l3addr.addr6;
    555 			send_ns = true;
    556 		} else {
    557 			nd6_free(ln, 0);
    558 			ln = NULL;
    559 		}
    560 		break;
    561 	}
    562 
    563 	if (send_ns) {
    564 		struct in6_addr src, *psrc;
    565 		const struct in6_addr *taddr6 = &ln->r_l3addr.addr6;
    566 
    567 		nd6_llinfo_settimer(ln, ndi->retrans * hz / 1000);
    568 		psrc = nd6_llinfo_get_holdsrc(ln, &src);
    569 		LLE_FREE_LOCKED(ln);
    570 		ln = NULL;
    571 #ifndef NET_MPSAFE
    572 		mutex_enter(softnet_lock);
    573 		KERNEL_LOCK(1, NULL);
    574 #endif
    575 		nd6_ns_output(ifp, daddr6, taddr6, psrc, 0);
    576 #ifndef NET_MPSAFE
    577 		KERNEL_UNLOCK_ONE(NULL);
    578 		mutex_exit(softnet_lock);
    579 #endif
    580 	}
    581 
    582 out:
    583 	if (ln != NULL)
    584 		LLE_FREE_LOCKED(ln);
    585 }
    586 
    587 /*
    588  * ND6 timer routine to expire default route list and prefix list
    589  */
    590 static void
    591 nd6_timer_work(struct work *wk, void *arg)
    592 {
    593 	struct nd_defrouter *next_dr, *dr;
    594 	struct nd_prefix *next_pr, *pr;
    595 	struct in6_ifaddr *ia6, *nia6;
    596 	int s, bound;
    597 	struct psref psref;
    598 
    599 	callout_reset(&nd6_timer_ch, nd6_prune * hz,
    600 	    nd6_timer, NULL);
    601 
    602 #ifndef NET_MPSAFE
    603 	mutex_enter(softnet_lock);
    604 	KERNEL_LOCK(1, NULL);
    605 #endif
    606 
    607 	/* expire default router list */
    608 
    609 	ND6_WLOCK();
    610 	ND_DEFROUTER_LIST_FOREACH_SAFE(dr, next_dr) {
    611 		if (dr->expire && dr->expire < time_uptime) {
    612 			nd6_defrtrlist_del(dr, NULL);
    613 		}
    614 	}
    615 	ND6_UNLOCK();
    616 
    617 	/*
    618 	 * expire interface addresses.
    619 	 * in the past the loop was inside prefix expiry processing.
    620 	 * However, from a stricter speci-confrmance standpoint, we should
    621 	 * rather separate address lifetimes and prefix lifetimes.
    622 	 */
    623 	bound = curlwp_bind();
    624   addrloop:
    625 	s = pserialize_read_enter();
    626 	for (ia6 = IN6_ADDRLIST_READER_FIRST(); ia6; ia6 = nia6) {
    627 		nia6 = IN6_ADDRLIST_READER_NEXT(ia6);
    628 
    629 		ia6_acquire(ia6, &psref);
    630 		pserialize_read_exit(s);
    631 
    632 		/* check address lifetime */
    633 		if (IFA6_IS_INVALID(ia6)) {
    634 			int regen = 0;
    635 
    636 			/*
    637 			 * If the expiring address is temporary, try
    638 			 * regenerating a new one.  This would be useful when
    639 			 * we suspended a laptop PC, then turned it on after a
    640 			 * period that could invalidate all temporary
    641 			 * addresses.  Although we may have to restart the
    642 			 * loop (see below), it must be after purging the
    643 			 * address.  Otherwise, we'd see an infinite loop of
    644 			 * regeneration.
    645 			 */
    646 			if (ip6_use_tempaddr &&
    647 			    (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
    648 				if (regen_tmpaddr(ia6) == 0)
    649 					regen = 1;
    650 			}
    651 
    652 			ia6_release(ia6, &psref);
    653  			in6_purgeaddr(&ia6->ia_ifa);
    654 			ia6 = NULL;
    655 
    656 			if (regen)
    657 				goto addrloop; /* XXX: see below */
    658 		} else if (IFA6_IS_DEPRECATED(ia6)) {
    659 			int oldflags = ia6->ia6_flags;
    660 
    661 			if ((oldflags & IN6_IFF_DEPRECATED) == 0) {
    662 				ia6->ia6_flags |= IN6_IFF_DEPRECATED;
    663 				rt_newaddrmsg(RTM_NEWADDR,
    664 				    (struct ifaddr *)ia6, 0, NULL);
    665 			}
    666 
    667 			/*
    668 			 * If a temporary address has just become deprecated,
    669 			 * regenerate a new one if possible.
    670 			 */
    671 			if (ip6_use_tempaddr &&
    672 			    (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
    673 			    (oldflags & IN6_IFF_DEPRECATED) == 0) {
    674 
    675 				if (regen_tmpaddr(ia6) == 0) {
    676 					/*
    677 					 * A new temporary address is
    678 					 * generated.
    679 					 * XXX: this means the address chain
    680 					 * has changed while we are still in
    681 					 * the loop.  Although the change
    682 					 * would not cause disaster (because
    683 					 * it's not a deletion, but an
    684 					 * addition,) we'd rather restart the
    685 					 * loop just for safety.  Or does this
    686 					 * significantly reduce performance??
    687 					 */
    688 					ia6_release(ia6, &psref);
    689 					goto addrloop;
    690 				}
    691 			}
    692 		} else {
    693 			/*
    694 			 * A new RA might have made a deprecated address
    695 			 * preferred.
    696 			 */
    697 			if (ia6->ia6_flags & IN6_IFF_DEPRECATED) {
    698 				ia6->ia6_flags &= ~IN6_IFF_DEPRECATED;
    699 				rt_newaddrmsg(RTM_NEWADDR,
    700 				    (struct ifaddr *)ia6, 0, NULL);
    701 			}
    702 		}
    703 		s = pserialize_read_enter();
    704 		ia6_release(ia6, &psref);
    705 	}
    706 	pserialize_read_exit(s);
    707 	curlwp_bindx(bound);
    708 
    709 	/* expire prefix list */
    710 	ND6_WLOCK();
    711 	ND_PREFIX_LIST_FOREACH_SAFE(pr, next_pr) {
    712 		/*
    713 		 * check prefix lifetime.
    714 		 * since pltime is just for autoconf, pltime processing for
    715 		 * prefix is not necessary.
    716 		 */
    717 		if (pr->ndpr_vltime != ND6_INFINITE_LIFETIME &&
    718 		    time_uptime - pr->ndpr_lastupdate > pr->ndpr_vltime) {
    719 
    720 			/*
    721 			 * address expiration and prefix expiration are
    722 			 * separate.  NEVER perform in6_purgeaddr here.
    723 			 */
    724 
    725 			nd6_prelist_remove(pr);
    726 		}
    727 	}
    728 	ND6_UNLOCK();
    729 
    730 #ifndef NET_MPSAFE
    731 	KERNEL_UNLOCK_ONE(NULL);
    732 	mutex_exit(softnet_lock);
    733 #endif
    734 }
    735 
    736 static void
    737 nd6_timer(void *ignored_arg)
    738 {
    739 
    740 	workqueue_enqueue(nd6_timer_wq, &nd6_timer_wk, NULL);
    741 }
    742 
    743 /* ia6: deprecated/invalidated temporary address */
    744 static int
    745 regen_tmpaddr(const struct in6_ifaddr *ia6)
    746 {
    747 	struct ifaddr *ifa;
    748 	struct ifnet *ifp;
    749 	struct in6_ifaddr *public_ifa6 = NULL;
    750 	int s;
    751 
    752 	ifp = ia6->ia_ifa.ifa_ifp;
    753 	s = pserialize_read_enter();
    754 	IFADDR_READER_FOREACH(ifa, ifp) {
    755 		struct in6_ifaddr *it6;
    756 
    757 		if (ifa->ifa_addr->sa_family != AF_INET6)
    758 			continue;
    759 
    760 		it6 = (struct in6_ifaddr *)ifa;
    761 
    762 		/* ignore no autoconf addresses. */
    763 		if ((it6->ia6_flags & IN6_IFF_AUTOCONF) == 0)
    764 			continue;
    765 
    766 		/* ignore autoconf addresses with different prefixes. */
    767 		if (it6->ia6_ndpr == NULL || it6->ia6_ndpr != ia6->ia6_ndpr)
    768 			continue;
    769 
    770 		/*
    771 		 * Now we are looking at an autoconf address with the same
    772 		 * prefix as ours.  If the address is temporary and is still
    773 		 * preferred, do not create another one.  It would be rare, but
    774 		 * could happen, for example, when we resume a laptop PC after
    775 		 * a long period.
    776 		 */
    777 		if ((it6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
    778 		    !IFA6_IS_DEPRECATED(it6)) {
    779 			public_ifa6 = NULL;
    780 			break;
    781 		}
    782 
    783 		/*
    784 		 * This is a public autoconf address that has the same prefix
    785 		 * as ours.  If it is preferred, keep it.  We can't break the
    786 		 * loop here, because there may be a still-preferred temporary
    787 		 * address with the prefix.
    788 		 */
    789 		if (!IFA6_IS_DEPRECATED(it6))
    790 			public_ifa6 = it6;
    791 	}
    792 
    793 	if (public_ifa6 != NULL) {
    794 		int e;
    795 		struct psref psref;
    796 
    797 		ia6_acquire(public_ifa6, &psref);
    798 		pserialize_read_exit(s);
    799 		/*
    800 		 * Random factor is introduced in the preferred lifetime, so
    801 		 * we do not need additional delay (3rd arg to in6_tmpifadd).
    802 		 */
    803 		ND6_WLOCK();
    804 		e = in6_tmpifadd(public_ifa6, 0, 0);
    805 		ND6_UNLOCK();
    806 		if (e != 0) {
    807 			ia6_release(public_ifa6, &psref);
    808 			log(LOG_NOTICE, "regen_tmpaddr: failed to create a new"
    809 			    " tmp addr, errno=%d\n", e);
    810 			return -1;
    811 		}
    812 		ia6_release(public_ifa6, &psref);
    813 		return 0;
    814 	}
    815 	pserialize_read_exit(s);
    816 
    817 	return -1;
    818 }
    819 
    820 bool
    821 nd6_accepts_rtadv(const struct nd_ifinfo *ndi)
    822 {
    823 	switch (ndi->flags & (ND6_IFF_ACCEPT_RTADV|ND6_IFF_OVERRIDE_RTADV)) {
    824 	case ND6_IFF_OVERRIDE_RTADV|ND6_IFF_ACCEPT_RTADV:
    825 		return true;
    826 	case ND6_IFF_ACCEPT_RTADV:
    827 		return ip6_accept_rtadv != 0;
    828 	case ND6_IFF_OVERRIDE_RTADV:
    829 	case 0:
    830 	default:
    831 		return false;
    832 	}
    833 }
    834 
    835 /*
    836  * Nuke neighbor cache/prefix/default router management table, right before
    837  * ifp goes away.
    838  */
    839 void
    840 nd6_purge(struct ifnet *ifp, struct in6_ifextra *ext)
    841 {
    842 	struct nd_defrouter *dr, *ndr;
    843 	struct nd_prefix *pr, *npr;
    844 
    845 	/*
    846 	 * During detach, the ND info might be already removed, but
    847 	 * then is explitly passed as argument.
    848 	 * Otherwise get it from ifp->if_afdata.
    849 	 */
    850 	if (ext == NULL)
    851 		ext = ifp->if_afdata[AF_INET6];
    852 	if (ext == NULL)
    853 		return;
    854 
    855 	ND6_WLOCK();
    856 	/*
    857 	 * Nuke default router list entries toward ifp.
    858 	 * We defer removal of default router list entries that is installed
    859 	 * in the routing table, in order to keep additional side effects as
    860 	 * small as possible.
    861 	 */
    862 	ND_DEFROUTER_LIST_FOREACH_SAFE(dr, ndr) {
    863 		if (dr->installed)
    864 			continue;
    865 
    866 		if (dr->ifp == ifp) {
    867 			KASSERT(ext != NULL);
    868 			nd6_defrtrlist_del(dr, ext);
    869 		}
    870 	}
    871 
    872 	ND_DEFROUTER_LIST_FOREACH_SAFE(dr, ndr) {
    873 		if (!dr->installed)
    874 			continue;
    875 
    876 		if (dr->ifp == ifp) {
    877 			KASSERT(ext != NULL);
    878 			nd6_defrtrlist_del(dr, ext);
    879 		}
    880 	}
    881 
    882 	/* Nuke prefix list entries toward ifp */
    883 	ND_PREFIX_LIST_FOREACH_SAFE(pr, npr) {
    884 		if (pr->ndpr_ifp == ifp) {
    885 			/*
    886 			 * All addresses referencing pr should be already freed.
    887 			 */
    888 			KASSERT(pr->ndpr_refcnt == 0);
    889 			nd6_prelist_remove(pr);
    890 		}
    891 	}
    892 
    893 	/* cancel default outgoing interface setting */
    894 	if (nd6_defifindex == ifp->if_index)
    895 		nd6_setdefaultiface(0);
    896 
    897 	/* XXX: too restrictive? */
    898 	if (!ip6_forwarding && ifp->if_afdata[AF_INET6]) {
    899 		struct nd_ifinfo *ndi = ND_IFINFO(ifp);
    900 		if (ndi && nd6_accepts_rtadv(ndi)) {
    901 			/* refresh default router list */
    902 			nd6_defrouter_select();
    903 		}
    904 	}
    905 	ND6_UNLOCK();
    906 
    907 	/*
    908 	 * We may not need to nuke the neighbor cache entries here
    909 	 * because the neighbor cache is kept in if_afdata[AF_INET6].
    910 	 * nd6_purge() is invoked by in6_ifdetach() which is called
    911 	 * from if_detach() where everything gets purged. However
    912 	 * in6_ifdetach is directly called from vlan(4), so we still
    913 	 * need to purge entries here.
    914 	 */
    915 	if (ext->lltable != NULL)
    916 		lltable_purge_entries(ext->lltable);
    917 }
    918 
    919 void
    920 nd6_assert_purged(struct ifnet *ifp)
    921 {
    922 	struct nd_defrouter *dr;
    923 	struct nd_prefix *pr;
    924 
    925 	ND6_RLOCK();
    926 	ND_DEFROUTER_LIST_FOREACH(dr) {
    927 		KASSERTMSG(dr->ifp != ifp,
    928 		    "defrouter %s remains on %s",
    929 		    ip6_sprintf(&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 		    ip6_sprintf(&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_AFDATA_UNLOCK_ASSERT(ifp);
   1150 	if (nd6_is_new_addr_neighbor(addr, ifp))
   1151 		return 1;
   1152 
   1153 	/*
   1154 	 * Even if the address matches none of our addresses, it might be
   1155 	 * in the neighbor cache or a connected route.
   1156 	 */
   1157 	ln = nd6_lookup(&addr->sin6_addr, ifp, false);
   1158 	if (ln != NULL) {
   1159 		LLE_RUNLOCK(ln);
   1160 		return 1;
   1161 	}
   1162 
   1163 	rt = rtalloc1(sin6tocsa(addr), 0);
   1164 	if (rt == NULL)
   1165 		return 0;
   1166 
   1167 	if ((rt->rt_flags & RTF_CONNECTED) && (rt->rt_ifp == ifp
   1168 #if NBRIDGE > 0
   1169 	    || rt->rt_ifp->if_bridge == ifp->if_bridge
   1170 #endif
   1171 #if NCARP > 0
   1172 	    || (ifp->if_type == IFT_CARP && rt->rt_ifp == ifp->if_carpdev) ||
   1173 	    (rt->rt_ifp->if_type == IFT_CARP && rt->rt_ifp->if_carpdev == ifp)||
   1174 	    (ifp->if_type == IFT_CARP && rt->rt_ifp->if_type == IFT_CARP &&
   1175 	    rt->rt_ifp->if_carpdev == ifp->if_carpdev)
   1176 #endif
   1177 	    )) {
   1178 		rt_unref(rt);
   1179 		return 1;
   1180 	}
   1181 	rt_unref(rt);
   1182 
   1183 	return 0;
   1184 }
   1185 
   1186 /*
   1187  * Free an nd6 llinfo entry.
   1188  * Since the function would cause significant changes in the kernel, DO NOT
   1189  * make it global, unless you have a strong reason for the change, and are sure
   1190  * that the change is safe.
   1191  */
   1192 static void
   1193 nd6_free(struct llentry *ln, int gc)
   1194 {
   1195 	struct nd_defrouter *dr;
   1196 	struct ifnet *ifp;
   1197 	struct in6_addr *in6;
   1198 
   1199 	KASSERT(ln != NULL);
   1200 	LLE_WLOCK_ASSERT(ln);
   1201 
   1202 	ifp = ln->lle_tbl->llt_ifp;
   1203 	in6 = &ln->r_l3addr.addr6;
   1204 	/*
   1205 	 * we used to have pfctlinput(PRC_HOSTDEAD) here.
   1206 	 * even though it is not harmful, it was not really necessary.
   1207 	 */
   1208 
   1209 	if (!ip6_forwarding) {
   1210 		ND6_WLOCK();
   1211 		dr = nd6_defrouter_lookup(in6, ifp);
   1212 
   1213 		if (dr != NULL && dr->expire &&
   1214 		    ln->ln_state == ND6_LLINFO_STALE && gc) {
   1215 			/*
   1216 			 * If the reason for the deletion is just garbage
   1217 			 * collection, and the neighbor is an active default
   1218 			 * router, do not delete it.  Instead, reset the GC
   1219 			 * timer using the router's lifetime.
   1220 			 * Simply deleting the entry would affect default
   1221 			 * router selection, which is not necessarily a good
   1222 			 * thing, especially when we're using router preference
   1223 			 * values.
   1224 			 * XXX: the check for ln_state would be redundant,
   1225 			 *      but we intentionally keep it just in case.
   1226 			 */
   1227 			if (dr->expire > time_uptime)
   1228 				nd6_llinfo_settimer(ln,
   1229 				    (dr->expire - time_uptime) * hz);
   1230 			else
   1231 				nd6_llinfo_settimer(ln, nd6_gctimer * hz);
   1232 			ND6_UNLOCK();
   1233 			LLE_WUNLOCK(ln);
   1234 			return;
   1235 		}
   1236 
   1237 		if (ln->ln_router || dr) {
   1238 			/*
   1239 			 * We need to unlock to avoid a LOR with nd6_rt_flush()
   1240 			 * with the rnh and for the calls to
   1241 			 * nd6_pfxlist_onlink_check() and nd6_defrouter_select() in the
   1242 			 * block further down for calls into nd6_lookup().
   1243 			 * We still hold a ref.
   1244 			 */
   1245 			LLE_WUNLOCK(ln);
   1246 
   1247 			/*
   1248 			 * nd6_rt_flush must be called whether or not the neighbor
   1249 			 * is in the Default Router List.
   1250 			 * See a corresponding comment in nd6_na_input().
   1251 			 */
   1252 			nd6_rt_flush(in6, ifp);
   1253 		}
   1254 
   1255 		if (dr) {
   1256 			/*
   1257 			 * Unreachablity of a router might affect the default
   1258 			 * router selection and on-link detection of advertised
   1259 			 * prefixes.
   1260 			 */
   1261 
   1262 			/*
   1263 			 * Temporarily fake the state to choose a new default
   1264 			 * router and to perform on-link determination of
   1265 			 * prefixes correctly.
   1266 			 * Below the state will be set correctly,
   1267 			 * or the entry itself will be deleted.
   1268 			 */
   1269 			ln->ln_state = ND6_LLINFO_INCOMPLETE;
   1270 
   1271 			/*
   1272 			 * Since nd6_defrouter_select() does not affect the
   1273 			 * on-link determination and MIP6 needs the check
   1274 			 * before the default router selection, we perform
   1275 			 * the check now.
   1276 			 */
   1277 			nd6_pfxlist_onlink_check();
   1278 
   1279 			/*
   1280 			 * refresh default router list
   1281 			 */
   1282 			nd6_defrouter_select();
   1283 		}
   1284 
   1285 #ifdef __FreeBSD__
   1286 		/*
   1287 		 * If this entry was added by an on-link redirect, remove the
   1288 		 * corresponding host route.
   1289 		 */
   1290 		if (ln->la_flags & LLE_REDIRECT)
   1291 			nd6_free_redirect(ln);
   1292 #endif
   1293 		ND6_UNLOCK();
   1294 
   1295 		if (ln->ln_router || dr)
   1296 			LLE_WLOCK(ln);
   1297 	}
   1298 
   1299 	/*
   1300 	 * Save to unlock. We still hold an extra reference and will not
   1301 	 * free(9) in llentry_free() if someone else holds one as well.
   1302 	 */
   1303 	LLE_WUNLOCK(ln);
   1304 	IF_AFDATA_LOCK(ifp);
   1305 	LLE_WLOCK(ln);
   1306 
   1307 	lltable_free_entry(LLTABLE6(ifp), ln);
   1308 
   1309 	IF_AFDATA_UNLOCK(ifp);
   1310 }
   1311 
   1312 /*
   1313  * Upper-layer reachability hint for Neighbor Unreachability Detection.
   1314  *
   1315  * XXX cost-effective methods?
   1316  */
   1317 void
   1318 nd6_nud_hint(struct rtentry *rt)
   1319 {
   1320 	struct llentry *ln;
   1321 	struct ifnet *ifp;
   1322 
   1323 	if (rt == NULL)
   1324 		return;
   1325 
   1326 	ifp = rt->rt_ifp;
   1327 	ln = nd6_lookup(&(satocsin6(rt_getkey(rt)))->sin6_addr, ifp, true);
   1328 	if (ln == NULL)
   1329 		return;
   1330 
   1331 	if (ln->ln_state < ND6_LLINFO_REACHABLE)
   1332 		goto done;
   1333 
   1334 	/*
   1335 	 * if we get upper-layer reachability confirmation many times,
   1336 	 * it is possible we have false information.
   1337 	 */
   1338 	ln->ln_byhint++;
   1339 	if (ln->ln_byhint > nd6_maxnudhint)
   1340 		goto done;
   1341 
   1342 	ln->ln_state = ND6_LLINFO_REACHABLE;
   1343 	if (!ND6_LLINFO_PERMANENT(ln))
   1344 		nd6_llinfo_settimer(ln, ND_IFINFO(rt->rt_ifp)->reachable * hz);
   1345 
   1346 done:
   1347 	LLE_WUNLOCK(ln);
   1348 
   1349 	return;
   1350 }
   1351 
   1352 struct gc_args {
   1353 	int gc_entries;
   1354 	const struct in6_addr *skip_in6;
   1355 };
   1356 
   1357 static int
   1358 nd6_purge_entry(struct lltable *llt, struct llentry *ln, void *farg)
   1359 {
   1360 	struct gc_args *args = farg;
   1361 	int *n = &args->gc_entries;
   1362 	const struct in6_addr *skip_in6 = args->skip_in6;
   1363 
   1364 	if (*n <= 0)
   1365 		return 0;
   1366 
   1367 	if (ND6_LLINFO_PERMANENT(ln))
   1368 		return 0;
   1369 
   1370 	if (IN6_ARE_ADDR_EQUAL(&ln->r_l3addr.addr6, skip_in6))
   1371 		return 0;
   1372 
   1373 	LLE_WLOCK(ln);
   1374 	if (ln->ln_state > ND6_LLINFO_INCOMPLETE)
   1375 		ln->ln_state = ND6_LLINFO_STALE;
   1376 	else
   1377 		ln->ln_state = ND6_LLINFO_PURGE;
   1378 	nd6_llinfo_settimer(ln, 0);
   1379 	LLE_WUNLOCK(ln);
   1380 
   1381 	(*n)--;
   1382 	return 0;
   1383 }
   1384 
   1385 static void
   1386 nd6_gc_neighbors(struct lltable *llt, const struct in6_addr *in6)
   1387 {
   1388 
   1389 	if (ip6_neighborgcthresh >= 0 &&
   1390 	    lltable_get_entry_count(llt) >= ip6_neighborgcthresh) {
   1391 		struct gc_args gc_args = {10, in6};
   1392 		/*
   1393 		 * XXX entries that are "less recently used" should be
   1394 		 * freed first.
   1395 		 */
   1396 		lltable_foreach_lle(llt, nd6_purge_entry, &gc_args);
   1397 	}
   1398 }
   1399 
   1400 void
   1401 nd6_rtrequest(int req, struct rtentry *rt, const struct rt_addrinfo *info)
   1402 {
   1403 	struct sockaddr *gate = rt->rt_gateway;
   1404 	struct ifnet *ifp = rt->rt_ifp;
   1405 	uint8_t namelen = strlen(ifp->if_xname), addrlen = ifp->if_addrlen;
   1406 	struct ifaddr *ifa;
   1407 
   1408 	RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
   1409 
   1410 	if (req == RTM_LLINFO_UPD) {
   1411 		int rc;
   1412 		struct in6_addr *in6;
   1413 		struct in6_addr in6_all;
   1414 		int anycast;
   1415 
   1416 		if ((ifa = info->rti_ifa) == NULL)
   1417 			return;
   1418 
   1419 		in6 = &ifatoia6(ifa)->ia_addr.sin6_addr;
   1420 		anycast = ifatoia6(ifa)->ia6_flags & IN6_IFF_ANYCAST;
   1421 
   1422 		in6_all = in6addr_linklocal_allnodes;
   1423 		if ((rc = in6_setscope(&in6_all, ifa->ifa_ifp, NULL)) != 0) {
   1424 			log(LOG_ERR, "%s: failed to set scope %s "
   1425 			    "(errno=%d)\n", __func__, if_name(ifp), rc);
   1426 			return;
   1427 		}
   1428 
   1429 		/* XXX don't set Override for proxy addresses */
   1430 		nd6_na_output(ifa->ifa_ifp, &in6_all, in6,
   1431 		    (anycast ? 0 : ND_NA_FLAG_OVERRIDE)
   1432 #if 0
   1433 		    | (ip6_forwarding ? ND_NA_FLAG_ROUTER : 0)
   1434 #endif
   1435 		    , 1, NULL);
   1436 		return;
   1437 	}
   1438 
   1439 	if ((rt->rt_flags & RTF_GATEWAY) != 0)
   1440 		return;
   1441 
   1442 	if (nd6_need_cache(ifp) == 0 && (rt->rt_flags & RTF_HOST) == 0) {
   1443 		RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
   1444 		/*
   1445 		 * This is probably an interface direct route for a link
   1446 		 * which does not need neighbor caches (e.g. fe80::%lo0/64).
   1447 		 * We do not need special treatment below for such a route.
   1448 		 * Moreover, the RTF_LLINFO flag which would be set below
   1449 		 * would annoy the ndp(8) command.
   1450 		 */
   1451 		return;
   1452 	}
   1453 
   1454 	switch (req) {
   1455 	case RTM_ADD: {
   1456 		int s;
   1457 
   1458 		RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
   1459 		/*
   1460 		 * There is no backward compatibility :)
   1461 		 *
   1462 		 * if ((rt->rt_flags & RTF_HOST) == 0 &&
   1463 		 *     SIN(rt_mask(rt))->sin_addr.s_addr != 0xffffffff)
   1464 		 *	   rt->rt_flags |= RTF_CLONING;
   1465 		 */
   1466 		/* XXX should move to route.c? */
   1467 		if (rt->rt_flags & (RTF_CONNECTED | RTF_LOCAL)) {
   1468 			union {
   1469 				struct sockaddr sa;
   1470 				struct sockaddr_dl sdl;
   1471 				struct sockaddr_storage ss;
   1472 			} u;
   1473 			/*
   1474 			 * Case 1: This route should come from a route to
   1475 			 * interface (RTF_CLONING case) or the route should be
   1476 			 * treated as on-link but is currently not
   1477 			 * (RTF_LLINFO && ln == NULL case).
   1478 			 */
   1479 			if (sockaddr_dl_init(&u.sdl, sizeof(u.ss),
   1480 			    ifp->if_index, ifp->if_type,
   1481 			    NULL, namelen, NULL, addrlen) == NULL) {
   1482 				printf("%s.%d: sockaddr_dl_init(, %zu, ) "
   1483 				    "failed on %s\n", __func__, __LINE__,
   1484 				    sizeof(u.ss), if_name(ifp));
   1485 			}
   1486 			rt_setgate(rt, &u.sa);
   1487 			gate = rt->rt_gateway;
   1488 			RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
   1489 			if (gate == NULL) {
   1490 				log(LOG_ERR,
   1491 				    "%s: rt_setgate failed on %s\n", __func__,
   1492 				    if_name(ifp));
   1493 				break;
   1494 			}
   1495 
   1496 			RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
   1497 			if ((rt->rt_flags & RTF_CONNECTED) != 0)
   1498 				break;
   1499 		}
   1500 		RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
   1501 		/*
   1502 		 * In IPv4 code, we try to annonuce new RTF_ANNOUNCE entry here.
   1503 		 * We don't do that here since llinfo is not ready yet.
   1504 		 *
   1505 		 * There are also couple of other things to be discussed:
   1506 		 * - unsolicited NA code needs improvement beforehand
   1507 		 * - RFC2461 says we MAY send multicast unsolicited NA
   1508 		 *   (7.2.6 paragraph 4), however, it also says that we
   1509 		 *   SHOULD provide a mechanism to prevent multicast NA storm.
   1510 		 *   we don't have anything like it right now.
   1511 		 *   note that the mechanism needs a mutual agreement
   1512 		 *   between proxies, which means that we need to implement
   1513 		 *   a new protocol, or a new kludge.
   1514 		 * - from RFC2461 6.2.4, host MUST NOT send an unsolicited NA.
   1515 		 *   we need to check ip6forwarding before sending it.
   1516 		 *   (or should we allow proxy ND configuration only for
   1517 		 *   routers?  there's no mention about proxy ND from hosts)
   1518 		 */
   1519 #if 0
   1520 		/* XXX it does not work */
   1521 		if (rt->rt_flags & RTF_ANNOUNCE)
   1522 			nd6_na_output(ifp,
   1523 			      &satocsin6(rt_getkey(rt))->sin6_addr,
   1524 			      &satocsin6(rt_getkey(rt))->sin6_addr,
   1525 			      ip6_forwarding ? ND_NA_FLAG_ROUTER : 0,
   1526 			      1, NULL);
   1527 #endif
   1528 
   1529 		if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) == 0) {
   1530 			RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
   1531 			/*
   1532 			 * Address resolution isn't necessary for a point to
   1533 			 * point link, so we can skip this test for a p2p link.
   1534 			 */
   1535 			if (gate->sa_family != AF_LINK ||
   1536 			    gate->sa_len <
   1537 			    sockaddr_dl_measure(namelen, addrlen)) {
   1538 				log(LOG_DEBUG,
   1539 				    "nd6_rtrequest: bad gateway value: %s\n",
   1540 				    if_name(ifp));
   1541 				break;
   1542 			}
   1543 			satosdl(gate)->sdl_type = ifp->if_type;
   1544 			satosdl(gate)->sdl_index = ifp->if_index;
   1545 			RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
   1546 		}
   1547 		RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
   1548 
   1549 		/*
   1550 		 * When called from rt_ifa_addlocal, we cannot depend on that
   1551 		 * the address (rt_getkey(rt)) exits in the address list of the
   1552 		 * interface. So check RTF_LOCAL instead.
   1553 		 */
   1554 		if (rt->rt_flags & RTF_LOCAL) {
   1555 			if (nd6_useloopback)
   1556 				rt->rt_ifp = lo0ifp;	/* XXX */
   1557 			break;
   1558 		}
   1559 
   1560 		/*
   1561 		 * check if rt_getkey(rt) is an address assigned
   1562 		 * to the interface.
   1563 		 */
   1564 		s = pserialize_read_enter();
   1565 		ifa = (struct ifaddr *)in6ifa_ifpwithaddr(ifp,
   1566 		    &satocsin6(rt_getkey(rt))->sin6_addr);
   1567 		if (ifa != NULL) {
   1568 			if (nd6_useloopback) {
   1569 				rt->rt_ifp = lo0ifp;	/* XXX */
   1570 				/*
   1571 				 * Make sure rt_ifa be equal to the ifaddr
   1572 				 * corresponding to the address.
   1573 				 * We need this because when we refer
   1574 				 * rt_ifa->ia6_flags in ip6_input, we assume
   1575 				 * that the rt_ifa points to the address instead
   1576 				 * of the loopback address.
   1577 				 */
   1578 				if (ifa != rt->rt_ifa)
   1579 					rt_replace_ifa(rt, ifa);
   1580 			}
   1581 		} else if (rt->rt_flags & RTF_ANNOUNCE) {
   1582 			/* join solicited node multicast for proxy ND */
   1583 			if (ifp->if_flags & IFF_MULTICAST) {
   1584 				struct in6_addr llsol;
   1585 				int error;
   1586 
   1587 				llsol = satocsin6(rt_getkey(rt))->sin6_addr;
   1588 				llsol.s6_addr32[0] = htonl(0xff020000);
   1589 				llsol.s6_addr32[1] = 0;
   1590 				llsol.s6_addr32[2] = htonl(1);
   1591 				llsol.s6_addr8[12] = 0xff;
   1592 				if (in6_setscope(&llsol, ifp, NULL))
   1593 					goto out;
   1594 				if (!in6_addmulti(&llsol, ifp, &error, 0)) {
   1595 					nd6log(LOG_ERR, "%s: failed to join "
   1596 					    "%s (errno=%d)\n", if_name(ifp),
   1597 					    ip6_sprintf(&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 			log(LOG_DEBUG,
   2347 			    "nd6_output: can't allocate llinfo for %s "
   2348 			    "(ln=%p, rt=%p)\n",
   2349 			    ip6_sprintf(&dst->sin6_addr), ln, rt);
   2350 			senderr(EIO);	/* XXX: good error? */
   2351 		}
   2352 		goto sendpkt;	/* send anyway */
   2353 	}
   2354 
   2355 	LLE_WLOCK_ASSERT(ln);
   2356 
   2357 	/* We don't have to do link-layer address resolution on a p2p link. */
   2358 	if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
   2359 	    ln->ln_state < ND6_LLINFO_REACHABLE) {
   2360 		ln->ln_state = ND6_LLINFO_STALE;
   2361 		nd6_llinfo_settimer(ln, nd6_gctimer * hz);
   2362 	}
   2363 
   2364 	/*
   2365 	 * The first time we send a packet to a neighbor whose entry is
   2366 	 * STALE, we have to change the state to DELAY and a sets a timer to
   2367 	 * expire in DELAY_FIRST_PROBE_TIME seconds to ensure do
   2368 	 * neighbor unreachability detection on expiration.
   2369 	 * (RFC 2461 7.3.3)
   2370 	 */
   2371 	if (ln->ln_state == ND6_LLINFO_STALE) {
   2372 		ln->ln_asked = 0;
   2373 		ln->ln_state = ND6_LLINFO_DELAY;
   2374 		nd6_llinfo_settimer(ln, nd6_delay * hz);
   2375 	}
   2376 
   2377 	/*
   2378 	 * If the neighbor cache entry has a state other than INCOMPLETE
   2379 	 * (i.e. its link-layer address is already resolved), just
   2380 	 * send the packet.
   2381 	 */
   2382 	if (ln->ln_state > ND6_LLINFO_INCOMPLETE)
   2383 		goto sendpkt;
   2384 
   2385 	/*
   2386 	 * There is a neighbor cache entry, but no ethernet address
   2387 	 * response yet.  Append this latest packet to the end of the
   2388 	 * packet queue in the mbuf, unless the number of the packet
   2389 	 * does not exceed nd6_maxqueuelen.  When it exceeds nd6_maxqueuelen,
   2390 	 * the oldest packet in the queue will be removed.
   2391 	 */
   2392 	if (ln->ln_state == ND6_LLINFO_NOSTATE)
   2393 		ln->ln_state = ND6_LLINFO_INCOMPLETE;
   2394 	if (ln->ln_hold) {
   2395 		struct mbuf *m_hold;
   2396 		int i;
   2397 
   2398 		i = 0;
   2399 		for (m_hold = ln->ln_hold; m_hold; m_hold = m_hold->m_nextpkt) {
   2400 			i++;
   2401 			if (m_hold->m_nextpkt == NULL) {
   2402 				m_hold->m_nextpkt = m;
   2403 				break;
   2404 			}
   2405 		}
   2406 		while (i >= nd6_maxqueuelen) {
   2407 			m_hold = ln->ln_hold;
   2408 			ln->ln_hold = ln->ln_hold->m_nextpkt;
   2409 			m_freem(m_hold);
   2410 			i--;
   2411 		}
   2412 	} else {
   2413 		ln->ln_hold = m;
   2414 	}
   2415 
   2416 	/*
   2417 	 * If there has been no NS for the neighbor after entering the
   2418 	 * INCOMPLETE state, send the first solicitation.
   2419 	 */
   2420 	if (!ND6_LLINFO_PERMANENT(ln) && ln->ln_asked == 0) {
   2421 		struct in6_addr src, *psrc;
   2422 
   2423 		ln->ln_asked++;
   2424 		nd6_llinfo_settimer(ln, ND_IFINFO(ifp)->retrans * hz / 1000);
   2425 		psrc = nd6_llinfo_get_holdsrc(ln, &src);
   2426 		LLE_WUNLOCK(ln);
   2427 		ln = NULL;
   2428 		nd6_ns_output(ifp, NULL, &dst->sin6_addr, psrc, 0);
   2429 	} else {
   2430 		/* We did the lookup so we need to do the unlock here. */
   2431 		LLE_WUNLOCK(ln);
   2432 	}
   2433 
   2434 	error = 0;
   2435 	goto exit;
   2436 
   2437   sendpkt:
   2438 	/* discard the packet if IPv6 operation is disabled on the interface */
   2439 	if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED)) {
   2440 		error = ENETDOWN; /* better error? */
   2441 		goto bad;
   2442 	}
   2443 
   2444 	if (ln != NULL)
   2445 		LLE_WUNLOCK(ln);
   2446 
   2447 	if ((ifp->if_flags & IFF_LOOPBACK) != 0)
   2448 		error = if_output_lock(ifp, origifp, m, sin6tocsa(dst), rt);
   2449 	else
   2450 		error = if_output_lock(ifp, ifp, m, sin6tocsa(dst), rt);
   2451 	goto exit;
   2452 
   2453   bad:
   2454 	if (m != NULL)
   2455 		m_freem(m);
   2456   exit:
   2457 	if (created)
   2458 		nd6_gc_neighbors(LLTABLE6(ifp), &dst->sin6_addr);
   2459 
   2460 	return error;
   2461 #undef senderr
   2462 }
   2463 
   2464 int
   2465 nd6_need_cache(struct ifnet *ifp)
   2466 {
   2467 	/*
   2468 	 * XXX: we currently do not make neighbor cache on any interface
   2469 	 * other than ARCnet, Ethernet, FDDI and GIF.
   2470 	 *
   2471 	 * RFC2893 says:
   2472 	 * - unidirectional tunnels needs no ND
   2473 	 */
   2474 	switch (ifp->if_type) {
   2475 	case IFT_ARCNET:
   2476 	case IFT_ETHER:
   2477 	case IFT_FDDI:
   2478 	case IFT_IEEE1394:
   2479 	case IFT_CARP:
   2480 	case IFT_GIF:		/* XXX need more cases? */
   2481 	case IFT_PPP:
   2482 	case IFT_TUNNEL:
   2483 		return 1;
   2484 	default:
   2485 		return 0;
   2486 	}
   2487 }
   2488 
   2489 /*
   2490  * Add pernament ND6 link-layer record for given
   2491  * interface address.
   2492  *
   2493  * Very similar to IPv4 arp_ifinit(), but:
   2494  * 1) IPv6 DAD is performed in different place
   2495  * 2) It is called by IPv6 protocol stack in contrast to
   2496  * arp_ifinit() which is typically called in SIOCSIFADDR
   2497  * driver ioctl handler.
   2498  *
   2499  */
   2500 int
   2501 nd6_add_ifa_lle(struct in6_ifaddr *ia)
   2502 {
   2503 	struct ifnet *ifp;
   2504 	struct llentry *ln;
   2505 
   2506 	ifp = ia->ia_ifa.ifa_ifp;
   2507 	if (nd6_need_cache(ifp) == 0)
   2508 		return 0;
   2509 	ia->ia_ifa.ifa_rtrequest = nd6_rtrequest;
   2510 	ia->ia_ifa.ifa_flags |= RTF_CONNECTED;
   2511 
   2512 	IF_AFDATA_WLOCK(ifp);
   2513 	ln = lla_create(LLTABLE6(ifp), LLE_IFADDR | LLE_EXCLUSIVE,
   2514 	    sin6tosa(&ia->ia_addr));
   2515 	IF_AFDATA_WUNLOCK(ifp);
   2516 	if (ln == NULL)
   2517 		return ENOBUFS;
   2518 
   2519 	ln->la_expire = 0;  /* for IPv6 this means permanent */
   2520 	ln->ln_state = ND6_LLINFO_REACHABLE;
   2521 
   2522 	LLE_WUNLOCK(ln);
   2523 	return 0;
   2524 }
   2525 
   2526 /*
   2527  * Removes ALL lle records for interface address prefix.
   2528  * XXXME: That's probably not we really want to do, we need
   2529  * to remove address record only and keep other records
   2530  * until we determine if given prefix is really going
   2531  * to be removed.
   2532  */
   2533 void
   2534 nd6_rem_ifa_lle(struct in6_ifaddr *ia)
   2535 {
   2536 	struct sockaddr_in6 mask, addr;
   2537 
   2538 	memcpy(&addr, &ia->ia_addr, sizeof(ia->ia_addr));
   2539 	memcpy(&mask, &ia->ia_prefixmask, sizeof(ia->ia_prefixmask));
   2540 	lltable_prefix_free(AF_INET6, sin6tosa(&addr), sin6tosa(&mask),
   2541 	    LLE_STATIC);
   2542 }
   2543 
   2544 int
   2545 nd6_storelladdr(const struct ifnet *ifp, const struct rtentry *rt,
   2546     struct mbuf *m, const struct sockaddr *dst, uint8_t *lldst,
   2547     size_t dstsize)
   2548 {
   2549 	struct llentry *ln;
   2550 
   2551 	if (m->m_flags & M_MCAST) {
   2552 		switch (ifp->if_type) {
   2553 		case IFT_ETHER:
   2554 		case IFT_FDDI:
   2555 			ETHER_MAP_IPV6_MULTICAST(&satocsin6(dst)->sin6_addr,
   2556 			    lldst);
   2557 			return 1;
   2558 		case IFT_IEEE1394:
   2559 			memcpy(lldst, ifp->if_broadcastaddr,
   2560 			    MIN(dstsize, ifp->if_addrlen));
   2561 			return 1;
   2562 		case IFT_ARCNET:
   2563 			*lldst = 0;
   2564 			return 1;
   2565 		default:
   2566 			m_freem(m);
   2567 			return 0;
   2568 		}
   2569 	}
   2570 
   2571 	/*
   2572 	 * the entry should have been created in nd6_store_lladdr
   2573 	 */
   2574 	ln = nd6_lookup(&satocsin6(dst)->sin6_addr, ifp, false);
   2575 	if ((ln == NULL) || !(ln->la_flags & LLE_VALID)) {
   2576 		if (ln != NULL)
   2577 			LLE_RUNLOCK(ln);
   2578 		/* this could happen, if we could not allocate memory */
   2579 		m_freem(m);
   2580 		return 0;
   2581 	}
   2582 
   2583 	/* XXX llentry should have addrlen? */
   2584 #if 0
   2585 	sdl = satocsdl(rt->rt_gateway);
   2586 	if (sdl->sdl_alen == 0 || sdl->sdl_alen > dstsize) {
   2587 		char sbuf[INET6_ADDRSTRLEN];
   2588 		char dbuf[LINK_ADDRSTRLEN];
   2589 		/* this should be impossible, but we bark here for debugging */
   2590 		printf("%s: sdl_alen == %" PRIu8 ", if=%s, dst=%s, sdl=%s\n",
   2591 		    __func__, sdl->sdl_alen, if_name(ifp),
   2592 		    IN6_PRINT(sbuf, &satocsin6(dst)->sin6_addr),
   2593 		    DL_PRINT(dbuf, &sdl->sdl_addr));
   2594 		m_freem(m);
   2595 		return 0;
   2596 	}
   2597 #endif
   2598 
   2599 	memcpy(lldst, &ln->ll_addr, MIN(dstsize, ifp->if_addrlen));
   2600 
   2601 	LLE_RUNLOCK(ln);
   2602 
   2603 	return 1;
   2604 }
   2605 
   2606 static void
   2607 clear_llinfo_pqueue(struct llentry *ln)
   2608 {
   2609 	struct mbuf *m_hold, *m_hold_next;
   2610 
   2611 	for (m_hold = ln->ln_hold; m_hold; m_hold = m_hold_next) {
   2612 		m_hold_next = m_hold->m_nextpkt;
   2613 		m_hold->m_nextpkt = NULL;
   2614 		m_freem(m_hold);
   2615 	}
   2616 
   2617 	ln->ln_hold = NULL;
   2618 	return;
   2619 }
   2620 
   2621 int
   2622 nd6_sysctl(
   2623     int name,
   2624     void *oldp,	/* syscall arg, need copyout */
   2625     size_t *oldlenp,
   2626     void *newp,	/* syscall arg, need copyin */
   2627     size_t newlen
   2628 )
   2629 {
   2630 	void *p;
   2631 	size_t ol;
   2632 	int error;
   2633 
   2634 	error = 0;
   2635 
   2636 	if (newp)
   2637 		return EPERM;
   2638 	if (oldp && !oldlenp)
   2639 		return EINVAL;
   2640 	ol = oldlenp ? *oldlenp : 0;
   2641 
   2642 	if (oldp) {
   2643 		p = malloc(*oldlenp, M_TEMP, M_WAITOK);
   2644 		if (p == NULL)
   2645 			return ENOMEM;
   2646 	} else
   2647 		p = NULL;
   2648 	switch (name) {
   2649 	case ICMPV6CTL_ND6_DRLIST:
   2650 		error = fill_drlist(p, oldlenp, ol);
   2651 		if (!error && p != NULL && oldp != NULL)
   2652 			error = copyout(p, oldp, *oldlenp);
   2653 		break;
   2654 
   2655 	case ICMPV6CTL_ND6_PRLIST:
   2656 		error = fill_prlist(p, oldlenp, ol);
   2657 		if (!error && p != NULL && oldp != NULL)
   2658 			error = copyout(p, oldp, *oldlenp);
   2659 		break;
   2660 
   2661 	case ICMPV6CTL_ND6_MAXQLEN:
   2662 		break;
   2663 
   2664 	default:
   2665 		error = ENOPROTOOPT;
   2666 		break;
   2667 	}
   2668 	if (p)
   2669 		free(p, M_TEMP);
   2670 
   2671 	return error;
   2672 }
   2673 
   2674 static int
   2675 fill_drlist(void *oldp, size_t *oldlenp, size_t ol)
   2676 {
   2677 	int error = 0;
   2678 	struct in6_defrouter *d = NULL, *de = NULL;
   2679 	struct nd_defrouter *dr;
   2680 	size_t l;
   2681 
   2682 	if (oldp) {
   2683 		d = (struct in6_defrouter *)oldp;
   2684 		de = (struct in6_defrouter *)((char *)oldp + *oldlenp);
   2685 	}
   2686 	l = 0;
   2687 
   2688 	ND6_RLOCK();
   2689 	ND_DEFROUTER_LIST_FOREACH(dr) {
   2690 
   2691 		if (oldp && d + 1 <= de) {
   2692 			memset(d, 0, sizeof(*d));
   2693 			sockaddr_in6_init(&d->rtaddr, &dr->rtaddr, 0, 0, 0);
   2694 			if (sa6_recoverscope(&d->rtaddr)) {
   2695 				log(LOG_ERR,
   2696 				    "scope error in router list (%s)\n",
   2697 				    ip6_sprintf(&d->rtaddr.sin6_addr));
   2698 				/* XXX: press on... */
   2699 			}
   2700 			d->flags = dr->flags;
   2701 			d->rtlifetime = dr->rtlifetime;
   2702 			d->expire = dr->expire ?
   2703 			    time_mono_to_wall(dr->expire) : 0;
   2704 			d->if_index = dr->ifp->if_index;
   2705 		}
   2706 
   2707 		l += sizeof(*d);
   2708 		if (d)
   2709 			d++;
   2710 	}
   2711 	ND6_UNLOCK();
   2712 
   2713 	if (oldp) {
   2714 		if (l > ol)
   2715 			error = ENOMEM;
   2716 	}
   2717 	if (oldlenp)
   2718 		*oldlenp = l;	/* (void *)d - (void *)oldp */
   2719 
   2720 	return error;
   2721 }
   2722 
   2723 static int
   2724 fill_prlist(void *oldp, size_t *oldlenp, size_t ol)
   2725 {
   2726 	int error = 0;
   2727 	struct nd_prefix *pr;
   2728 	uint8_t *p = NULL, *ps = NULL;
   2729 	uint8_t *pe = NULL;
   2730 	size_t l;
   2731 
   2732 	if (oldp) {
   2733 		ps = p = (uint8_t*)oldp;
   2734 		pe = (uint8_t*)oldp + *oldlenp;
   2735 	}
   2736 	l = 0;
   2737 
   2738 	ND6_RLOCK();
   2739 	ND_PREFIX_LIST_FOREACH(pr) {
   2740 		u_short advrtrs;
   2741 		struct sockaddr_in6 sin6;
   2742 		struct nd_pfxrouter *pfr;
   2743 		struct in6_prefix pfx;
   2744 
   2745 		if (oldp && p + sizeof(struct in6_prefix) <= pe)
   2746 		{
   2747 			memset(&pfx, 0, sizeof(pfx));
   2748 			ps = p;
   2749 			pfx.prefix = pr->ndpr_prefix;
   2750 
   2751 			if (sa6_recoverscope(&pfx.prefix)) {
   2752 				log(LOG_ERR,
   2753 				    "scope error in prefix list (%s)\n",
   2754 				    ip6_sprintf(&pfx.prefix.sin6_addr));
   2755 				/* XXX: press on... */
   2756 			}
   2757 			pfx.raflags = pr->ndpr_raf;
   2758 			pfx.prefixlen = pr->ndpr_plen;
   2759 			pfx.vltime = pr->ndpr_vltime;
   2760 			pfx.pltime = pr->ndpr_pltime;
   2761 			pfx.if_index = pr->ndpr_ifp->if_index;
   2762 			if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME)
   2763 				pfx.expire = 0;
   2764 			else {
   2765 				time_t maxexpire;
   2766 
   2767 				/* XXX: we assume time_t is signed. */
   2768 				maxexpire = (-1) &
   2769 				    ~((time_t)1 <<
   2770 				    ((sizeof(maxexpire) * 8) - 1));
   2771 				if (pr->ndpr_vltime <
   2772 				    maxexpire - pr->ndpr_lastupdate) {
   2773 					pfx.expire = pr->ndpr_lastupdate +
   2774 						pr->ndpr_vltime;
   2775 				} else
   2776 					pfx.expire = maxexpire;
   2777 			}
   2778 			pfx.refcnt = pr->ndpr_refcnt;
   2779 			pfx.flags = pr->ndpr_stateflags;
   2780 			pfx.origin = PR_ORIG_RA;
   2781 
   2782 			p += sizeof(pfx); l += sizeof(pfx);
   2783 
   2784 			advrtrs = 0;
   2785 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
   2786 				if (p + sizeof(sin6) > pe) {
   2787 					advrtrs++;
   2788 					continue;
   2789 				}
   2790 
   2791 				sockaddr_in6_init(&sin6, &pfr->router->rtaddr,
   2792 				    0, 0, 0);
   2793 				if (sa6_recoverscope(&sin6)) {
   2794 					log(LOG_ERR,
   2795 					    "scope error in "
   2796 					    "prefix list (%s)\n",
   2797 					    ip6_sprintf(&pfr->router->rtaddr));
   2798 				}
   2799 				advrtrs++;
   2800 				memcpy(p, &sin6, sizeof(sin6));
   2801 				p += sizeof(sin6);
   2802 				l += sizeof(sin6);
   2803 			}
   2804 			pfx.advrtrs = advrtrs;
   2805 			memcpy(ps, &pfx, sizeof(pfx));
   2806 		}
   2807 		else {
   2808 			l += sizeof(pfx);
   2809 			advrtrs = 0;
   2810 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
   2811 				advrtrs++;
   2812 				l += sizeof(sin6);
   2813 			}
   2814 		}
   2815 	}
   2816 	ND6_UNLOCK();
   2817 
   2818 	if (oldp) {
   2819 		*oldlenp = l;	/* (void *)d - (void *)oldp */
   2820 		if (l > ol)
   2821 			error = ENOMEM;
   2822 	} else
   2823 		*oldlenp = l;
   2824 
   2825 	return error;
   2826 }
   2827 
   2828 static int
   2829 nd6_setdefaultiface(int ifindex)
   2830 {
   2831 	ifnet_t *ifp;
   2832 	int error = 0;
   2833 	int s;
   2834 
   2835 	s = pserialize_read_enter();
   2836 	ifp = if_byindex(ifindex);
   2837 	if (ifp == NULL) {
   2838 		pserialize_read_exit(s);
   2839 		return EINVAL;
   2840 	}
   2841 	if (nd6_defifindex != ifindex) {
   2842 		nd6_defifindex = ifindex;
   2843 		nd6_defifp = nd6_defifindex > 0 ? ifp : NULL;
   2844 
   2845 		/*
   2846 		 * Our current implementation assumes one-to-one maping between
   2847 		 * interfaces and links, so it would be natural to use the
   2848 		 * default interface as the default link.
   2849 		 */
   2850 		scope6_setdefault(nd6_defifp);
   2851 	}
   2852 	pserialize_read_exit(s);
   2853 
   2854 	return (error);
   2855 }
   2856