Home | History | Annotate | Line # | Download | only in netinet6
      1 /*	$NetBSD: nd6.c,v 1.284 2025/06/05 06:31:07 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.284 2025/06/05 06:31:07 ozaki-r Exp $");
     35 
     36 #ifdef _KERNEL_OPT
     37 #include "opt_compat_netbsd.h"
     38 #include "opt_net_mpsafe.h"
     39 #endif
     40 
     41 #include "bridge.h"
     42 #include "carp.h"
     43 
     44 #include <sys/param.h>
     45 #include <sys/systm.h>
     46 #include <sys/callout.h>
     47 #include <sys/kmem.h>
     48 #include <sys/mbuf.h>
     49 #include <sys/socket.h>
     50 #include <sys/socketvar.h>
     51 #include <sys/sockio.h>
     52 #include <sys/time.h>
     53 #include <sys/kernel.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 #include <sys/compat_stub.h>
     61 
     62 #include <net/if.h>
     63 #include <net/if_dl.h>
     64 #include <net/if_llatbl.h>
     65 #include <net/if_types.h>
     66 #include <net/nd.h>
     67 #include <net/route.h>
     68 #include <net/if_ether.h>
     69 #include <net/if_arc.h>
     70 
     71 #include <netinet/in.h>
     72 #include <netinet6/in6_var.h>
     73 #include <netinet/ip6.h>
     74 #include <netinet6/ip6_var.h>
     75 #include <netinet6/scope6_var.h>
     76 #include <netinet6/nd6.h>
     77 #include <netinet6/in6_ifattach.h>
     78 #include <netinet/icmp6.h>
     79 #include <netinet6/icmp6_private.h>
     80 
     81 #include <compat/netinet6/in6_var.h>
     82 #include <compat/netinet6/nd6.h>
     83 
     84 #define ND6_SLOWTIMER_INTERVAL (60 * 60) /* 1 hour */
     85 #define ND6_RECALC_REACHTM_INTERVAL (60 * 120) /* 2 hours */
     86 
     87 /* timer values */
     88 int	nd6_prune	= 1;	/* walk list every 1 seconds */
     89 int	nd6_useloopback = 1;	/* use loopback interface for local traffic */
     90 
     91 /* preventing too many loops in ND option parsing */
     92 int nd6_maxndopt = 10;	/* max # of ND options allowed */
     93 
     94 #ifdef ND6_DEBUG
     95 int nd6_debug = 1;
     96 #else
     97 int nd6_debug = 0;
     98 #endif
     99 
    100 krwlock_t nd6_lock __cacheline_aligned;
    101 
    102 int nd6_recalc_reachtm_interval = ND6_RECALC_REACHTM_INTERVAL;
    103 
    104 static void nd6_slowtimo(void *);
    105 static void nd6_free(struct llentry *, int);
    106 static bool nd6_nud_enabled(struct ifnet *);
    107 static unsigned int nd6_llinfo_reachable(struct ifnet *);
    108 static unsigned int nd6_llinfo_retrans(struct ifnet *);
    109 static union l3addr *nd6_llinfo_holdsrc(struct llentry *, union l3addr *);
    110 static void nd6_llinfo_output(struct ifnet *, const union l3addr *,
    111     const union l3addr *, const uint8_t *, const union l3addr *);
    112 static void nd6_llinfo_missed(struct ifnet *, const union l3addr *,
    113     int16_t, struct mbuf *);
    114 static void nd6_timer(void *);
    115 static void nd6_timer_work(struct work *, void *);
    116 static struct nd_opt_hdr *nd6_option(union nd_opts *);
    117 
    118 static callout_t nd6_slowtimo_ch;
    119 static callout_t nd6_timer_ch;
    120 static struct workqueue	*nd6_timer_wq;
    121 static struct work	nd6_timer_wk;
    122 
    123 struct nd_domain nd6_nd_domain = {
    124 	.nd_family = AF_INET6,
    125 	.nd_delay = 5,		/* delay first probe time 5 second */
    126 	.nd_mmaxtries = 3,	/* maximum unicast query */
    127 	.nd_umaxtries = 3,	/* maximum multicast query */
    128 	.nd_retransmultiple = BACKOFF_MULTIPLE,
    129 	.nd_maxretrans = MAX_RETRANS_TIMER,
    130 	.nd_maxnudhint = 0,	/* max # of subsequent upper layer hints */
    131 	.nd_maxqueuelen = 1,	/* max # of packets in unresolved ND entries */
    132 	.nd_nud_enabled = nd6_nud_enabled,
    133 	.nd_reachable = nd6_llinfo_reachable,
    134 	.nd_retrans = nd6_llinfo_retrans,
    135 	.nd_holdsrc = nd6_llinfo_holdsrc,
    136 	.nd_output = nd6_llinfo_output,
    137 	.nd_missed = nd6_llinfo_missed,
    138 	.nd_free = nd6_free,
    139 };
    140 
    141 MALLOC_DEFINE(M_IP6NDP, "NDP", "IPv6 Neighbour Discovery");
    142 
    143 void
    144 nd6_init(void)
    145 {
    146 	int error;
    147 
    148 	nd_attach_domain(&nd6_nd_domain);
    149 	nd6_nbr_init();
    150 
    151 	rw_init(&nd6_lock);
    152 
    153 	callout_init(&nd6_slowtimo_ch, CALLOUT_MPSAFE);
    154 	callout_init(&nd6_timer_ch, CALLOUT_MPSAFE);
    155 
    156 	error = workqueue_create(&nd6_timer_wq, "nd6_timer",
    157 	    nd6_timer_work, NULL, PRI_SOFTNET, IPL_SOFTNET, WQ_MPSAFE);
    158 	if (error)
    159 		panic("%s: workqueue_create failed (%d)\n", __func__, error);
    160 
    161 	/* start timer */
    162 	callout_reset(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
    163 	    nd6_slowtimo, NULL);
    164 	callout_reset(&nd6_timer_ch, hz, nd6_timer, NULL);
    165 }
    166 
    167 struct nd_kifinfo *
    168 nd6_ifattach(struct ifnet *ifp)
    169 {
    170 	struct nd_kifinfo *nd;
    171 
    172 	nd = kmem_zalloc(sizeof(*nd), KM_SLEEP);
    173 
    174 	nd->chlim = IPV6_DEFHLIM;
    175 	nd->basereachable = REACHABLE_TIME;
    176 	nd->reachable = ND_COMPUTE_RTIME(nd->basereachable);
    177 	nd->retrans = RETRANS_TIMER;
    178 
    179 	nd->flags = ND6_IFF_PERFORMNUD;
    180 
    181 	/* A loopback interface always has ND6_IFF_AUTO_LINKLOCAL.
    182 	 * A bridge interface should not have ND6_IFF_AUTO_LINKLOCAL
    183 	 * because one of its members should. */
    184 	if ((ip6_auto_linklocal && ifp->if_type != IFT_BRIDGE) ||
    185 	    (ifp->if_flags & IFF_LOOPBACK))
    186 		nd->flags |= ND6_IFF_AUTO_LINKLOCAL;
    187 
    188 	return nd;
    189 }
    190 
    191 void
    192 nd6_ifdetach(struct ifnet *ifp, struct in6_ifextra *ext)
    193 {
    194 
    195 	/* Ensure all IPv6 addresses are purged before calling nd6_purge */
    196 	if_purgeaddrs(ifp, AF_INET6, in6_purgeaddr);
    197 	nd6_purge(ifp, ext);
    198 	kmem_free(ext->nd_ifinfo, sizeof(struct nd_kifinfo));
    199 }
    200 
    201 void
    202 nd6_option_init(void *opt, int icmp6len, union nd_opts *ndopts)
    203 {
    204 
    205 	memset(ndopts, 0, sizeof(*ndopts));
    206 	ndopts->nd_opts_search = (struct nd_opt_hdr *)opt;
    207 	ndopts->nd_opts_last
    208 		= (struct nd_opt_hdr *)(((u_char *)opt) + icmp6len);
    209 
    210 	if (icmp6len == 0) {
    211 		ndopts->nd_opts_done = 1;
    212 		ndopts->nd_opts_search = NULL;
    213 	}
    214 }
    215 
    216 /*
    217  * Take one ND option.
    218  */
    219 static struct nd_opt_hdr *
    220 nd6_option(union nd_opts *ndopts)
    221 {
    222 	struct nd_opt_hdr *nd_opt;
    223 	int olen;
    224 
    225 	KASSERT(ndopts != NULL);
    226 	KASSERT(ndopts->nd_opts_last != NULL);
    227 
    228 	if (ndopts->nd_opts_search == NULL)
    229 		return NULL;
    230 	if (ndopts->nd_opts_done)
    231 		return NULL;
    232 
    233 	nd_opt = ndopts->nd_opts_search;
    234 
    235 	/* make sure nd_opt_len is inside the buffer */
    236 	if ((void *)&nd_opt->nd_opt_len >= (void *)ndopts->nd_opts_last) {
    237 		memset(ndopts, 0, sizeof(*ndopts));
    238 		return NULL;
    239 	}
    240 
    241 	olen = nd_opt->nd_opt_len << 3;
    242 	if (olen == 0) {
    243 		/*
    244 		 * Message validation requires that all included
    245 		 * options have a length that is greater than zero.
    246 		 */
    247 		memset(ndopts, 0, sizeof(*ndopts));
    248 		return NULL;
    249 	}
    250 
    251 	ndopts->nd_opts_search = (struct nd_opt_hdr *)((char *)nd_opt + olen);
    252 	if (ndopts->nd_opts_search > ndopts->nd_opts_last) {
    253 		/* option overruns the end of buffer, invalid */
    254 		memset(ndopts, 0, sizeof(*ndopts));
    255 		return NULL;
    256 	} else if (ndopts->nd_opts_search == ndopts->nd_opts_last) {
    257 		/* reached the end of options chain */
    258 		ndopts->nd_opts_done = 1;
    259 		ndopts->nd_opts_search = NULL;
    260 	}
    261 	return nd_opt;
    262 }
    263 
    264 /*
    265  * Parse multiple ND options.
    266  * This function is much easier to use, for ND routines that do not need
    267  * multiple options of the same type.
    268  */
    269 int
    270 nd6_options(union nd_opts *ndopts)
    271 {
    272 	struct nd_opt_hdr *nd_opt;
    273 	int i = 0;
    274 
    275 	KASSERT(ndopts != NULL);
    276 	KASSERT(ndopts->nd_opts_last != NULL);
    277 
    278 	if (ndopts->nd_opts_search == NULL)
    279 		return 0;
    280 
    281 	while (1) {
    282 		nd_opt = nd6_option(ndopts);
    283 		if (nd_opt == NULL && ndopts->nd_opts_last == NULL) {
    284 			/*
    285 			 * Message validation requires that all included
    286 			 * options have a length that is greater than zero.
    287 			 */
    288 			ICMP6_STATINC(ICMP6_STAT_ND_BADOPT);
    289 			memset(ndopts, 0, sizeof(*ndopts));
    290 			return -1;
    291 		}
    292 
    293 		if (nd_opt == NULL)
    294 			goto skip1;
    295 
    296 		switch (nd_opt->nd_opt_type) {
    297 		case ND_OPT_SOURCE_LINKADDR:
    298 		case ND_OPT_TARGET_LINKADDR:
    299 		case ND_OPT_MTU:
    300 		case ND_OPT_REDIRECTED_HEADER:
    301 		case ND_OPT_NONCE:
    302 			if (ndopts->nd_opt_array[nd_opt->nd_opt_type]) {
    303 				nd6log(LOG_INFO,
    304 				    "duplicated ND6 option found (type=%d)\n",
    305 				    nd_opt->nd_opt_type);
    306 				/* XXX bark? */
    307 			} else {
    308 				ndopts->nd_opt_array[nd_opt->nd_opt_type]
    309 					= nd_opt;
    310 			}
    311 			break;
    312 		case ND_OPT_PREFIX_INFORMATION:
    313 			if (ndopts->nd_opt_array[nd_opt->nd_opt_type] == 0) {
    314 				ndopts->nd_opt_array[nd_opt->nd_opt_type]
    315 					= nd_opt;
    316 			}
    317 			ndopts->nd_opts_pi_end =
    318 				(struct nd_opt_prefix_info *)nd_opt;
    319 			break;
    320 		default:
    321 			/*
    322 			 * Unknown options must be silently ignored,
    323 			 * to accommodate future extension to the protocol.
    324 			 */
    325 			nd6log(LOG_DEBUG,
    326 			    "nd6_options: unsupported option %d - "
    327 			    "option ignored\n", nd_opt->nd_opt_type);
    328 		}
    329 
    330 skip1:
    331 		i++;
    332 		if (i > nd6_maxndopt) {
    333 			ICMP6_STATINC(ICMP6_STAT_ND_TOOMANYOPT);
    334 			nd6log(LOG_INFO, "too many loop in nd opt\n");
    335 			break;
    336 		}
    337 
    338 		if (ndopts->nd_opts_done)
    339 			break;
    340 	}
    341 
    342 	return 0;
    343 }
    344 
    345 /*
    346  * Gets source address of the first packet in hold queue
    347  * and stores it in @src.
    348  * Returns pointer to @src (if hold queue is not empty) or NULL.
    349  */
    350 static struct in6_addr *
    351 nd6_llinfo_get_holdsrc(struct llentry *ln, struct in6_addr *src)
    352 {
    353 	struct ip6_hdr *hip6;
    354 
    355 	if (ln == NULL || ln->ln_hold == NULL)
    356 		return NULL;
    357 
    358 	/*
    359 	 * assuming every packet in ln_hold has the same IP header
    360 	 */
    361 	hip6 = mtod(ln->ln_hold, struct ip6_hdr *);
    362 	/* XXX pullup? */
    363 	if (sizeof(*hip6) < ln->ln_hold->m_len)
    364 		*src = hip6->ip6_src;
    365 	else
    366 		src = NULL;
    367 
    368 	return src;
    369 }
    370 
    371 static union l3addr *
    372 nd6_llinfo_holdsrc(struct llentry *ln, union l3addr *src)
    373 {
    374 
    375 	if (nd6_llinfo_get_holdsrc(ln, &src->addr6) == NULL)
    376 		return NULL;
    377 	return src;
    378 }
    379 
    380 static void
    381 nd6_llinfo_output(struct ifnet *ifp, const union l3addr *daddr,
    382     const union l3addr *taddr, __unused const uint8_t *tlladdr,
    383     const union l3addr *hsrc)
    384 {
    385 
    386 	nd6_ns_output(ifp,
    387 	    daddr != NULL ? &daddr->addr6 : NULL,
    388 	    taddr != NULL ? &taddr->addr6 : NULL,
    389 	    hsrc != NULL ? &hsrc->addr6 : NULL, NULL);
    390 }
    391 
    392 static bool
    393 nd6_nud_enabled(struct ifnet *ifp)
    394 {
    395 	struct nd_kifinfo *ndi = ND_IFINFO(ifp);
    396 
    397 	return ndi->flags & ND6_IFF_PERFORMNUD;
    398 }
    399 
    400 static unsigned int
    401 nd6_llinfo_reachable(struct ifnet *ifp)
    402 {
    403 	struct nd_kifinfo *ndi = ND_IFINFO(ifp);
    404 
    405 	return ndi->reachable;
    406 }
    407 
    408 static unsigned int
    409 nd6_llinfo_retrans(struct ifnet *ifp)
    410 {
    411 	struct nd_kifinfo *ndi = ND_IFINFO(ifp);
    412 
    413 	return ndi->retrans;
    414 }
    415 
    416 static void
    417 nd6_llinfo_missed(struct ifnet *ifp, const union l3addr *taddr,
    418     int16_t type, struct mbuf *m)
    419 {
    420 	struct in6_addr mdaddr6 = zeroin6_addr;
    421 	struct sockaddr_in6 dsin6, tsin6;
    422 	struct sockaddr *sa;
    423 
    424 	if (m != NULL) {
    425 		if (type == ND_LLINFO_PROBE) {
    426 			struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
    427 
    428 			/* XXX pullup? */
    429 			if (sizeof(*ip6) < m->m_len)
    430 				mdaddr6 = ip6->ip6_src;
    431 			m_freem(m);
    432 		} else
    433 			icmp6_error2(m, ICMP6_DST_UNREACH,
    434 			    ICMP6_DST_UNREACH_ADDR, 0, ifp, &mdaddr6);
    435 	}
    436 	if (!IN6_IS_ADDR_UNSPECIFIED(&mdaddr6)) {
    437 		sockaddr_in6_init(&dsin6, &mdaddr6, 0, 0, 0);
    438 		sa = sin6tosa(&dsin6);
    439 	} else
    440 		sa = NULL;
    441 
    442 	sockaddr_in6_init(&tsin6, &taddr->addr6, 0, 0, 0);
    443 	rt_clonedmsg(RTM_MISS, sa, sin6tosa(&tsin6), NULL, ifp);
    444 }
    445 
    446 /*
    447  * ND6 timer routine to expire default route list and prefix list
    448  */
    449 static void
    450 nd6_timer_work(struct work *wk, void *arg)
    451 {
    452 	struct in6_ifaddr *ia6, *nia6;
    453 	int s, bound;
    454 	struct psref psref;
    455 
    456 	callout_reset(&nd6_timer_ch, nd6_prune * hz,
    457 	    nd6_timer, NULL);
    458 
    459 	SOFTNET_KERNEL_LOCK_UNLESS_NET_MPSAFE();
    460 
    461 	/* expire interface addresses */
    462 	bound = curlwp_bind();
    463 	s = pserialize_read_enter();
    464 	for (ia6 = IN6_ADDRLIST_READER_FIRST(); ia6; ia6 = nia6) {
    465 		nia6 = IN6_ADDRLIST_READER_NEXT(ia6);
    466 
    467 		ia6_acquire(ia6, &psref);
    468 		pserialize_read_exit(s);
    469 
    470 		/* check address lifetime */
    471 		if (IFA6_IS_INVALID(ia6)) {
    472 			struct ifnet *ifp;
    473 
    474 			ifp = ia6->ia_ifa.ifa_ifp;
    475 			IFNET_LOCK(ifp);
    476 			/*
    477 			 * Need to take the lock first to prevent if_detach
    478 			 * from running in6_purgeaddr concurrently.
    479 			 */
    480 			if (!if_is_deactivated(ifp)) {
    481 				ia6_release(ia6, &psref);
    482 				in6_purgeaddr(&ia6->ia_ifa);
    483 			} else {
    484 				/*
    485 				 * ifp is being destroyed, ia6 will be destroyed
    486 				 * by if_detach.
    487 				 */
    488 				ia6_release(ia6, &psref);
    489 			}
    490 			ia6 = NULL;
    491 			IFNET_UNLOCK(ifp);
    492 		} else if (IFA6_IS_DEPRECATED(ia6)) {
    493 			int oldflags = ia6->ia6_flags;
    494 
    495 			if ((oldflags & IN6_IFF_DEPRECATED) == 0) {
    496 				ia6->ia6_flags |= IN6_IFF_DEPRECATED;
    497 				rt_addrmsg(RTM_NEWADDR, (struct ifaddr *)ia6);
    498 			}
    499 		} else {
    500 			/*
    501 			 * A new RA might have made a deprecated address
    502 			 * preferred.
    503 			 */
    504 			if (ia6->ia6_flags & IN6_IFF_DEPRECATED) {
    505 				ia6->ia6_flags &= ~IN6_IFF_DEPRECATED;
    506 				rt_addrmsg(RTM_NEWADDR, (struct ifaddr *)ia6);
    507 			}
    508 		}
    509 		s = pserialize_read_enter();
    510 		ia6_release(ia6, &psref);
    511 	}
    512 	pserialize_read_exit(s);
    513 	curlwp_bindx(bound);
    514 
    515 	SOFTNET_KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
    516 }
    517 
    518 static void
    519 nd6_timer(void *ignored_arg)
    520 {
    521 
    522 	workqueue_enqueue(nd6_timer_wq, &nd6_timer_wk, NULL);
    523 }
    524 
    525 /*
    526  * Nuke neighbor cache/prefix/default router management table, right before
    527  * ifp goes away.
    528  */
    529 void
    530 nd6_purge(struct ifnet *ifp, struct in6_ifextra *ext)
    531 {
    532 
    533 	/*
    534 	 * During detach, the ND info might be already removed, but
    535 	 * then is explitly passed as argument.
    536 	 * Otherwise get it from ifp->if_afdata.
    537 	 */
    538 	if (ext == NULL)
    539 		ext = ifp->if_afdata[AF_INET6];
    540 	if (ext == NULL)
    541 		return;
    542 
    543 	/*
    544 	 * We may not need to nuke the neighbor cache entries here
    545 	 * because the neighbor cache is kept in if_afdata[AF_INET6].
    546 	 * nd6_purge() is invoked by in6_ifdetach() which is called
    547 	 * from if_detach() where everything gets purged. However
    548 	 * in6_ifdetach is directly called from vlan(4), so we still
    549 	 * need to purge entries here.
    550 	 */
    551 	if (ext->lltable != NULL)
    552 		lltable_purge_entries(ext->lltable);
    553 }
    554 
    555 struct llentry *
    556 nd6_lookup(const struct in6_addr *addr6, const struct ifnet *ifp, bool wlock)
    557 {
    558 	struct sockaddr_in6 sin6;
    559 	struct llentry *ln;
    560 
    561 	sockaddr_in6_init(&sin6, addr6, 0, 0, 0);
    562 
    563 	IF_AFDATA_RLOCK(ifp);
    564 	ln = lla_lookup(LLTABLE6(ifp), wlock ? LLE_EXCLUSIVE : 0,
    565 	    sin6tosa(&sin6));
    566 	IF_AFDATA_RUNLOCK(ifp);
    567 
    568 	return ln;
    569 }
    570 
    571 struct llentry *
    572 nd6_create(const struct in6_addr *addr6, const struct ifnet *ifp)
    573 {
    574 	struct sockaddr_in6 sin6;
    575 	struct llentry *ln;
    576 	struct rtentry *rt;
    577 
    578 	sockaddr_in6_init(&sin6, addr6, 0, 0, 0);
    579 	rt = rtalloc1(sin6tosa(&sin6), 0);
    580 
    581 	IF_AFDATA_WLOCK(ifp);
    582 	ln = lla_create(LLTABLE6(ifp), LLE_EXCLUSIVE, sin6tosa(&sin6), rt);
    583 	IF_AFDATA_WUNLOCK(ifp);
    584 
    585 	if (rt != NULL)
    586 		rt_unref(rt);
    587 	if (ln != NULL)
    588 		ln->ln_state = ND_LLINFO_NOSTATE;
    589 
    590 	return ln;
    591 }
    592 
    593 /*
    594  * Test whether a given IPv6 address is a neighbor or not, ignoring
    595  * the actual neighbor cache.  The neighbor cache is ignored in order
    596  * to not reenter the routing code from within itself.
    597  */
    598 static int
    599 nd6_is_new_addr_neighbor(const struct sockaddr_in6 *addr, struct ifnet *ifp)
    600 {
    601 	struct ifaddr *dstaddr;
    602 	int s;
    603 
    604 	/*
    605 	 * A link-local address is always a neighbor.
    606 	 * XXX: a link does not necessarily specify a single interface.
    607 	 */
    608 	if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr)) {
    609 		struct sockaddr_in6 sin6_copy;
    610 		u_int32_t zone;
    611 
    612 		/*
    613 		 * We need sin6_copy since sa6_recoverscope() may modify the
    614 		 * content (XXX).
    615 		 */
    616 		sin6_copy = *addr;
    617 		if (sa6_recoverscope(&sin6_copy))
    618 			return 0; /* XXX: should be impossible */
    619 		if (in6_setscope(&sin6_copy.sin6_addr, ifp, &zone))
    620 			return 0;
    621 		if (sin6_copy.sin6_scope_id == zone)
    622 			return 1;
    623 		else
    624 			return 0;
    625 	}
    626 
    627 	/*
    628 	 * If the address is assigned on the node of the other side of
    629 	 * a p2p interface, the address should be a neighbor.
    630 	 */
    631 	s = pserialize_read_enter();
    632 	dstaddr = ifa_ifwithdstaddr(sin6tocsa(addr));
    633 	if (dstaddr != NULL) {
    634 		if (dstaddr->ifa_ifp == ifp) {
    635 			pserialize_read_exit(s);
    636 			return 1;
    637 		}
    638 	}
    639 	pserialize_read_exit(s);
    640 
    641 	return 0;
    642 }
    643 
    644 /*
    645  * Detect if a given IPv6 address identifies a neighbor on a given link.
    646  * XXX: should take care of the destination of a p2p link?
    647  */
    648 int
    649 nd6_is_addr_neighbor(const struct sockaddr_in6 *addr, struct ifnet *ifp)
    650 {
    651 	struct llentry *ln;
    652 	struct rtentry *rt;
    653 
    654 	/*
    655 	 * A link-local address is always a neighbor.
    656 	 * XXX: a link does not necessarily specify a single interface.
    657 	 */
    658 	if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr)) {
    659 		struct sockaddr_in6 sin6_copy;
    660 		u_int32_t zone;
    661 
    662 		/*
    663 		 * We need sin6_copy since sa6_recoverscope() may modify the
    664 		 * content (XXX).
    665 		 */
    666 		sin6_copy = *addr;
    667 		if (sa6_recoverscope(&sin6_copy))
    668 			return 0; /* XXX: should be impossible */
    669 		if (in6_setscope(&sin6_copy.sin6_addr, ifp, &zone))
    670 			return 0;
    671 		if (sin6_copy.sin6_scope_id == zone)
    672 			return 1;
    673 		else
    674 			return 0;
    675 	}
    676 
    677 	if (nd6_is_new_addr_neighbor(addr, ifp))
    678 		return 1;
    679 
    680 	/*
    681 	 * Even if the address matches none of our addresses, it might be
    682 	 * in the neighbor cache or a connected route.
    683 	 */
    684 	ln = nd6_lookup(&addr->sin6_addr, ifp, false);
    685 	if (ln != NULL) {
    686 		LLE_RUNLOCK(ln);
    687 		return 1;
    688 	}
    689 
    690 	rt = rtalloc1(sin6tocsa(addr), 0);
    691 	if (rt == NULL)
    692 		return 0;
    693 
    694 	if ((rt->rt_flags & RTF_CONNECTED) && (rt->rt_ifp == ifp
    695 #if NBRIDGE > 0
    696 	    || rt->rt_ifp->if_bridge == ifp->if_bridge
    697 #endif
    698 #if NCARP > 0
    699 	    || (ifp->if_type == IFT_CARP && rt->rt_ifp == ifp->if_carpdev) ||
    700 	    (rt->rt_ifp->if_type == IFT_CARP && rt->rt_ifp->if_carpdev == ifp)||
    701 	    (ifp->if_type == IFT_CARP && rt->rt_ifp->if_type == IFT_CARP &&
    702 	    rt->rt_ifp->if_carpdev == ifp->if_carpdev)
    703 #endif
    704 	    )) {
    705 		rt_unref(rt);
    706 		return 1;
    707 	}
    708 	rt_unref(rt);
    709 
    710 	return 0;
    711 }
    712 
    713 /*
    714  * Free an nd6 llinfo entry.
    715  * Since the function would cause significant changes in the kernel, DO NOT
    716  * make it global, unless you have a strong reason for the change, and are sure
    717  * that the change is safe.
    718  */
    719 static void
    720 nd6_free(struct llentry *ln, int gc)
    721 {
    722 	struct ifnet *ifp;
    723 
    724 	KASSERT(ln != NULL);
    725 	LLE_WLOCK_ASSERT(ln);
    726 
    727 	/*
    728 	 * If the reason for the deletion is just garbage collection,
    729 	 * and the neighbor is an active router, do not delete it.
    730 	 * Instead, reset the GC timer using the router's lifetime.
    731 	 * XXX: the check for ln_state should be redundant,
    732 	 *      but we intentionally keep it just in case.
    733 	 */
    734 	if (!ip6_forwarding && ln->ln_router &&
    735 	    ln->ln_state == ND_LLINFO_STALE && gc)
    736 	{
    737 		nd_set_timer(ln, ND_TIMER_EXPIRE);
    738 		LLE_WUNLOCK(ln);
    739 		return;
    740 	}
    741 
    742 	ifp = ln->lle_tbl->llt_ifp;
    743 
    744 	if (ln->la_flags & LLE_VALID || gc) {
    745 		struct sockaddr_in6 sin6;
    746 		const char *lladdr;
    747 
    748 		sockaddr_in6_init(&sin6, &ln->r_l3addr.addr6, 0, 0, 0);
    749 		lladdr = ln->la_flags & LLE_VALID ?
    750 		    (const char *)&ln->ll_addr : NULL;
    751 		rt_clonedmsg(RTM_DELETE, NULL, sin6tosa(&sin6), lladdr, ifp);
    752 	}
    753 
    754 	/*
    755 	 * Save to unlock. We still hold an extra reference and will not
    756 	 * free(9) in llentry_free() if someone else holds one as well.
    757 	 */
    758 	LLE_WUNLOCK(ln);
    759 	IF_AFDATA_LOCK(ifp);
    760 	LLE_WLOCK(ln);
    761 
    762 	lltable_free_entry(LLTABLE6(ifp), ln);
    763 
    764 	IF_AFDATA_UNLOCK(ifp);
    765 }
    766 
    767 /*
    768  * Upper-layer reachability hint for Neighbor Unreachability Detection.
    769  *
    770  * XXX cost-effective methods?
    771  */
    772 void
    773 nd6_nud_hint(struct rtentry *rt)
    774 {
    775 	struct llentry *ln;
    776 	struct ifnet *ifp;
    777 
    778 	if (rt == NULL)
    779 		return;
    780 
    781 	ifp = rt->rt_ifp;
    782 	ln = nd6_lookup(&(satocsin6(rt_getkey(rt)))->sin6_addr, ifp, true);
    783 	nd_nud_hint(ln);
    784 }
    785 
    786 struct gc_args {
    787 	int gc_entries;
    788 	const struct in6_addr *skip_in6;
    789 };
    790 
    791 static int
    792 nd6_purge_entry(struct lltable *llt, struct llentry *ln, void *farg)
    793 {
    794 	struct gc_args *args = farg;
    795 	int *n = &args->gc_entries;
    796 	const struct in6_addr *skip_in6 = args->skip_in6;
    797 
    798 	if (*n <= 0)
    799 		return 0;
    800 
    801 	if (ND_IS_LLINFO_PERMANENT(ln))
    802 		return 0;
    803 
    804 	if (IN6_ARE_ADDR_EQUAL(&ln->r_l3addr.addr6, skip_in6))
    805 		return 0;
    806 
    807 	LLE_WLOCK(ln);
    808 	if (ln->ln_state > ND_LLINFO_INCOMPLETE)
    809 		ln->ln_state = ND_LLINFO_STALE;
    810 	else
    811 		ln->ln_state = ND_LLINFO_PURGE;
    812 	nd_set_timer(ln, ND_TIMER_IMMEDIATE);
    813 	LLE_WUNLOCK(ln);
    814 
    815 	(*n)--;
    816 	return 0;
    817 }
    818 
    819 static void
    820 nd6_gc_neighbors(struct lltable *llt, const struct in6_addr *in6)
    821 {
    822 
    823 	if (ip6_neighborgcthresh >= 0 &&
    824 	    lltable_get_entry_count(llt) >= ip6_neighborgcthresh) {
    825 		struct gc_args gc_args = {10, in6};
    826 		/*
    827 		 * XXX entries that are "less recently used" should be
    828 		 * freed first.
    829 		 */
    830 		lltable_foreach_lle(llt, nd6_purge_entry, &gc_args);
    831 	}
    832 }
    833 
    834 void
    835 nd6_rtrequest(int req, struct rtentry *rt, const struct rt_addrinfo *info)
    836 {
    837 	struct sockaddr *gate = rt->rt_gateway;
    838 	struct ifnet *ifp = rt->rt_ifp;
    839 	uint8_t namelen = strlen(ifp->if_xname), addrlen = ifp->if_addrlen;
    840 	struct ifaddr *ifa;
    841 
    842 	RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
    843 
    844 	if (req == RTM_LLINFO_UPD) {
    845 		int rc;
    846 		struct in6_addr *in6;
    847 		struct in6_addr in6_all;
    848 		int anycast;
    849 
    850 		if ((ifa = info->rti_ifa) == NULL)
    851 			return;
    852 
    853 		in6 = &ifatoia6(ifa)->ia_addr.sin6_addr;
    854 		anycast = ifatoia6(ifa)->ia6_flags & IN6_IFF_ANYCAST;
    855 
    856 		in6_all = in6addr_linklocal_allnodes;
    857 		if ((rc = in6_setscope(&in6_all, ifa->ifa_ifp, NULL)) != 0) {
    858 			log(LOG_ERR, "%s: failed to set scope %s "
    859 			    "(errno=%d)\n", __func__, if_name(ifp), rc);
    860 			return;
    861 		}
    862 
    863 		/* XXX don't set Override for proxy addresses */
    864 		nd6_na_output(ifa->ifa_ifp, &in6_all, in6,
    865 		    (anycast ? 0 : ND_NA_FLAG_OVERRIDE)
    866 #if 0
    867 		    | (ip6_forwarding ? ND_NA_FLAG_ROUTER : 0)
    868 #endif
    869 		    , 1, NULL);
    870 		return;
    871 	}
    872 
    873 	if ((rt->rt_flags & RTF_GATEWAY) != 0) {
    874 		if (req != RTM_ADD)
    875 			return;
    876 		/*
    877 		 * linklayers with particular MTU limitation.
    878 		 */
    879 		switch(ifp->if_type) {
    880 #if NARCNET > 0
    881 		case IFT_ARCNET:
    882 			if (rt->rt_rmx.rmx_mtu > ARC_PHDS_MAXMTU) /* RFC2497 */
    883 				rt->rt_rmx.rmx_mtu = ARC_PHDS_MAXMTU;
    884 			break;
    885 #endif
    886 		}
    887 		return;
    888 	}
    889 
    890 	if (nd6_need_cache(ifp) == 0 && (rt->rt_flags & RTF_HOST) == 0) {
    891 		RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
    892 		/*
    893 		 * This is probably an interface direct route for a link
    894 		 * which does not need neighbor caches (e.g. fe80::%lo0/64).
    895 		 * We do not need special treatment below for such a route.
    896 		 * Moreover, the RTF_LLINFO flag which would be set below
    897 		 * would annoy the ndp(8) command.
    898 		 */
    899 		return;
    900 	}
    901 
    902 	switch (req) {
    903 	case RTM_ADD: {
    904 		struct psref psref;
    905 
    906 		RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
    907 		/*
    908 		 * There is no backward compatibility :)
    909 		 *
    910 		 * if ((rt->rt_flags & RTF_HOST) == 0 &&
    911 		 *     SIN(rt_mask(rt))->sin_addr.s_addr != 0xffffffff)
    912 		 *	   rt->rt_flags |= RTF_CLONING;
    913 		 */
    914 		/* XXX should move to route.c? */
    915 		if (rt->rt_flags & (RTF_CONNECTED | RTF_LOCAL)) {
    916 			union {
    917 				struct sockaddr sa;
    918 				struct sockaddr_dl sdl;
    919 				struct sockaddr_storage ss;
    920 			} u;
    921 			/*
    922 			 * Case 1: This route should come from a route to
    923 			 * interface (RTF_CLONING case) or the route should be
    924 			 * treated as on-link but is currently not
    925 			 * (RTF_LLINFO && ln == NULL case).
    926 			 */
    927 			if (sockaddr_dl_init(&u.sdl, sizeof(u.ss),
    928 			    ifp->if_index, ifp->if_type,
    929 			    NULL, namelen, NULL, addrlen) == NULL) {
    930 				printf("%s.%d: sockaddr_dl_init(, %zu, ) "
    931 				    "failed on %s\n", __func__, __LINE__,
    932 				    sizeof(u.ss), if_name(ifp));
    933 			}
    934 			rt_setgate(rt, &u.sa);
    935 			gate = rt->rt_gateway;
    936 			RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
    937 			if (gate == NULL) {
    938 				log(LOG_ERR,
    939 				    "%s: rt_setgate failed on %s\n", __func__,
    940 				    if_name(ifp));
    941 				break;
    942 			}
    943 
    944 			RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
    945 			if ((rt->rt_flags & RTF_CONNECTED) != 0)
    946 				break;
    947 		}
    948 		RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
    949 		/*
    950 		 * In IPv4 code, we try to annonuce new RTF_ANNOUNCE entry here.
    951 		 * We don't do that here since llinfo is not ready yet.
    952 		 *
    953 		 * There are also couple of other things to be discussed:
    954 		 * - unsolicited NA code needs improvement beforehand
    955 		 * - RFC2461 says we MAY send multicast unsolicited NA
    956 		 *   (7.2.6 paragraph 4), however, it also says that we
    957 		 *   SHOULD provide a mechanism to prevent multicast NA storm.
    958 		 *   we don't have anything like it right now.
    959 		 *   note that the mechanism needs a mutual agreement
    960 		 *   between proxies, which means that we need to implement
    961 		 *   a new protocol, or a new kludge.
    962 		 * - from RFC2461 6.2.4, host MUST NOT send an unsolicited NA.
    963 		 *   we need to check ip6forwarding before sending it.
    964 		 *   (or should we allow proxy ND configuration only for
    965 		 *   routers?  there's no mention about proxy ND from hosts)
    966 		 */
    967 #if 0
    968 		/* XXX it does not work */
    969 		if (rt->rt_flags & RTF_ANNOUNCE)
    970 			nd6_na_output(ifp,
    971 			      &satocsin6(rt_getkey(rt))->sin6_addr,
    972 			      &satocsin6(rt_getkey(rt))->sin6_addr,
    973 			      ip6_forwarding ? ND_NA_FLAG_ROUTER : 0,
    974 			      1, NULL);
    975 #endif
    976 
    977 		if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) == 0) {
    978 			RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
    979 			/*
    980 			 * Address resolution isn't necessary for a point to
    981 			 * point link, so we can skip this test for a p2p link.
    982 			 */
    983 			if (gate->sa_family != AF_LINK ||
    984 			    gate->sa_len <
    985 			    sockaddr_dl_measure(namelen, addrlen)) {
    986 				log(LOG_DEBUG,
    987 				    "nd6_rtrequest: bad gateway value: %s\n",
    988 				    if_name(ifp));
    989 				break;
    990 			}
    991 			satosdl(gate)->sdl_type = ifp->if_type;
    992 			satosdl(gate)->sdl_index = ifp->if_index;
    993 			RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
    994 		}
    995 		RT_DPRINTF("rt_getkey(rt) = %p\n", rt_getkey(rt));
    996 
    997 		/*
    998 		 * When called from rt_ifa_addlocal, we cannot depend on that
    999 		 * the address (rt_getkey(rt)) exits in the address list of the
   1000 		 * interface. So check RTF_LOCAL instead.
   1001 		 */
   1002 		if (rt->rt_flags & RTF_LOCAL) {
   1003 			if (nd6_useloopback)
   1004 				rt->rt_ifp = lo0ifp;	/* XXX */
   1005 			break;
   1006 		}
   1007 
   1008 		/*
   1009 		 * check if rt_getkey(rt) is an address assigned
   1010 		 * to the interface.
   1011 		 */
   1012 		ifa = (struct ifaddr *)in6ifa_ifpwithaddr_psref(ifp,
   1013 		    &satocsin6(rt_getkey(rt))->sin6_addr, &psref);
   1014 		if (ifa != NULL) {
   1015 			if (nd6_useloopback) {
   1016 				rt->rt_ifp = lo0ifp;	/* XXX */
   1017 				/*
   1018 				 * Make sure rt_ifa be equal to the ifaddr
   1019 				 * corresponding to the address.
   1020 				 * We need this because when we refer
   1021 				 * rt_ifa->ia6_flags in ip6_input, we assume
   1022 				 * that the rt_ifa points to the address instead
   1023 				 * of the loopback address.
   1024 				 */
   1025 				if (!ISSET(info->rti_flags, RTF_DONTCHANGEIFA)
   1026 				    && ifa != rt->rt_ifa)
   1027 					rt_replace_ifa(rt, ifa);
   1028 			}
   1029 		} else if (rt->rt_flags & RTF_ANNOUNCE) {
   1030 			/* join solicited node multicast for proxy ND */
   1031 			if (ifp->if_flags & IFF_MULTICAST) {
   1032 				struct in6_addr llsol;
   1033 				int error;
   1034 
   1035 				llsol = satocsin6(rt_getkey(rt))->sin6_addr;
   1036 				llsol.s6_addr32[0] = htonl(0xff020000);
   1037 				llsol.s6_addr32[1] = 0;
   1038 				llsol.s6_addr32[2] = htonl(1);
   1039 				llsol.s6_addr8[12] = 0xff;
   1040 				if (in6_setscope(&llsol, ifp, NULL))
   1041 					goto out;
   1042 				if (!in6_addmulti(&llsol, ifp, &error, 0)) {
   1043 					char ip6buf[INET6_ADDRSTRLEN];
   1044 					nd6log(LOG_ERR, "%s: failed to join "
   1045 					    "%s (errno=%d)\n", if_name(ifp),
   1046 					    IN6_PRINT(ip6buf, &llsol), error);
   1047 				}
   1048 			}
   1049 		}
   1050 	out:
   1051 		ifa_release(ifa, &psref);
   1052 		/*
   1053 		 * If we have too many cache entries, initiate immediate
   1054 		 * purging for some entries.
   1055 		 */
   1056 		if (rt->rt_ifp != NULL)
   1057 			nd6_gc_neighbors(LLTABLE6(rt->rt_ifp), NULL);
   1058 		break;
   1059 	    }
   1060 
   1061 	case RTM_DELETE:
   1062 		/* leave from solicited node multicast for proxy ND */
   1063 		if ((rt->rt_flags & RTF_ANNOUNCE) != 0 &&
   1064 		    (ifp->if_flags & IFF_MULTICAST) != 0) {
   1065 			struct in6_addr llsol;
   1066 
   1067 			llsol = satocsin6(rt_getkey(rt))->sin6_addr;
   1068 			llsol.s6_addr32[0] = htonl(0xff020000);
   1069 			llsol.s6_addr32[1] = 0;
   1070 			llsol.s6_addr32[2] = htonl(1);
   1071 			llsol.s6_addr8[12] = 0xff;
   1072 			if (in6_setscope(&llsol, ifp, NULL) == 0)
   1073 				in6_lookup_and_delete_multi(&llsol, ifp);
   1074 		}
   1075 		break;
   1076 	}
   1077 }
   1078 
   1079 static void
   1080 nd6_setifflags(struct ifnet *ifp, uint32_t flags)
   1081 {
   1082 	struct nd_kifinfo *ndi = ND_IFINFO(ifp);
   1083 	struct ifaddr *ifa;
   1084 	struct in6_ifaddr *ia;
   1085 	int s;
   1086 
   1087 	if (ndi->flags & ND6_IFF_IFDISABLED && !(flags & ND6_IFF_IFDISABLED)) {
   1088 		/*
   1089 		 * If the interface is marked as ND6_IFF_IFDISABLED and
   1090 		 * has a link-local address with IN6_IFF_DUPLICATED,
   1091 		 * do not clear ND6_IFF_IFDISABLED.
   1092 		 * See RFC 4862, section 5.4.5.
   1093 		 */
   1094 		bool duplicated_linklocal = false;
   1095 
   1096 		s = pserialize_read_enter();
   1097 		IFADDR_READER_FOREACH(ifa, ifp) {
   1098 			if (ifa->ifa_addr->sa_family != AF_INET6)
   1099 				continue;
   1100 			ia = (struct in6_ifaddr *)ifa;
   1101 			if ((ia->ia6_flags & IN6_IFF_DUPLICATED) &&
   1102 			    IN6_IS_ADDR_LINKLOCAL(IA6_IN6(ia)))
   1103 			{
   1104 				duplicated_linklocal = true;
   1105 				break;
   1106 			}
   1107 		}
   1108 		pserialize_read_exit(s);
   1109 
   1110 		if (duplicated_linklocal) {
   1111 			flags |= ND6_IFF_IFDISABLED;
   1112 			log(LOG_ERR, "%s: Cannot enable an interface"
   1113 			    " with a link-local address marked"
   1114 			    " duplicate.\n", if_name(ifp));
   1115 		} else {
   1116 			ndi->flags &= ~ND6_IFF_IFDISABLED;
   1117 			if (ifp->if_flags & IFF_UP)
   1118 				in6_if_up(ifp);
   1119 		}
   1120 	} else if (!(ndi->flags & ND6_IFF_IFDISABLED) &&
   1121 	    (flags & ND6_IFF_IFDISABLED))
   1122 	{
   1123 		struct psref psref;
   1124 		int bound = curlwp_bind();
   1125 
   1126 		/* Mark all IPv6 addresses as tentative. */
   1127 
   1128 		ndi->flags |= ND6_IFF_IFDISABLED;
   1129 		s = pserialize_read_enter();
   1130 		IFADDR_READER_FOREACH(ifa, ifp) {
   1131 			if (ifa->ifa_addr->sa_family != AF_INET6)
   1132 				continue;
   1133 			ifa_acquire(ifa, &psref);
   1134 			pserialize_read_exit(s);
   1135 
   1136 			nd6_dad_stop(ifa);
   1137 
   1138 			ia = (struct in6_ifaddr *)ifa;
   1139 			ia->ia6_flags |= IN6_IFF_TENTATIVE;
   1140 
   1141 			s = pserialize_read_enter();
   1142 			ifa_release(ifa, &psref);
   1143 		}
   1144 		pserialize_read_exit(s);
   1145 		curlwp_bindx(bound);
   1146 	}
   1147 
   1148 	if (flags & ND6_IFF_AUTO_LINKLOCAL) {
   1149 		if (!(ndi->flags & ND6_IFF_AUTO_LINKLOCAL)) {
   1150 			/* auto_linklocal 0->1 transition */
   1151 
   1152 			ndi->flags |= ND6_IFF_AUTO_LINKLOCAL;
   1153 			in6_ifattach(ifp, NULL);
   1154 		} else if (!(flags & ND6_IFF_IFDISABLED) &&
   1155 		    ifp->if_flags & IFF_UP)
   1156 		{
   1157 			/*
   1158 			 * When the IF already has
   1159 			 * ND6_IFF_AUTO_LINKLOCAL, no link-local
   1160 			 * address is assigned, and IFF_UP, try to
   1161 			 * assign one.
   1162 			 */
   1163 			bool haslinklocal = 0;
   1164 
   1165 			s = pserialize_read_enter();
   1166 			ifa = in6ifa_first_lladdr(ifp);
   1167 			if (ifa != NULL)
   1168 				haslinklocal = true;
   1169 			pserialize_read_exit(s);
   1170 			if (!haslinklocal)
   1171 				in6_ifattach(ifp, NULL);
   1172 		}
   1173 	}
   1174 
   1175 	ndi->flags = flags;
   1176 }
   1177 
   1178 int
   1179 nd6_ioctl(u_long cmd, void *data, struct ifnet *ifp)
   1180 {
   1181 #ifdef OSIOCGIFINFO_IN6_90
   1182 	struct in6_ndireq90 *ondi = (struct in6_ndireq90 *)data;
   1183 	struct in6_ndifreq90 *ndif = (struct in6_ndifreq90 *)data;
   1184 #define OND	ondi->ndi
   1185 #endif
   1186 	struct in6_ndireq *ndi = (struct in6_ndireq *)data;
   1187 	struct in6_nbrinfo *nbi = (struct in6_nbrinfo *)data;
   1188 	struct nd_kifinfo *ifndi = ND_IFINFO(ifp);
   1189 	int error = 0;
   1190 #define ND     ndi->ndi
   1191 
   1192 	switch (cmd) {
   1193 #ifdef OSIOCSRTRFLUSH_IN6
   1194 	case OSIOCGDRLST_IN6:		/* FALLTHROUGH */
   1195 	case OSIOCGPRLST_IN6:		/* FALLTHROUGH */
   1196 	case OSIOCSNDFLUSH_IN6:		/* FALLTHROUGH */
   1197 	case OSIOCSPFXFLUSH_IN6:	/* FALLTHROUGH */
   1198 	case OSIOCSRTRFLUSH_IN6:	/* FALLTHROUGH */
   1199 		break;
   1200 	case OSIOCGDEFIFACE_IN6:
   1201 		ndif->ifindex = 0;
   1202 		break;
   1203 	case OSIOCSDEFIFACE_IN6:
   1204 		error = ENOTSUP;
   1205 		break;
   1206 #endif
   1207 #ifdef OSIOCGIFINFO_IN6
   1208 	case OSIOCGIFINFO_IN6:		/* FALLTHROUGH */
   1209 #endif
   1210 #ifdef OSIOCGIFINFO_IN6_90
   1211 	case OSIOCGIFINFO_IN6_90:
   1212 		memset(&OND, 0, sizeof(OND));
   1213 		OND.initialized = 1;
   1214 		OND.chlim = ifndi->chlim;
   1215 		OND.basereachable = ifndi->basereachable;
   1216 		OND.retrans = ifndi->retrans;
   1217 		OND.flags = ifndi->flags;
   1218 		break;
   1219 	case OSIOCSIFINFO_IN6_90:
   1220 		/* Allow userland to set Neighbor Unreachability Detection
   1221 		 * timers. */
   1222 		if (OND.chlim != 0)
   1223 			ifndi->chlim = OND.chlim;
   1224 		if (OND.basereachable != 0 &&
   1225 		    OND.basereachable != ifndi->basereachable)
   1226 		{
   1227 			ifndi->basereachable = OND.basereachable;
   1228 			ifndi->reachable = ND_COMPUTE_RTIME(OND.basereachable);
   1229 		}
   1230 		if (OND.retrans != 0)
   1231 			ifndi->retrans = OND.retrans;
   1232 		/* Retain the old behaviour .... */
   1233 		/* FALLTHROUGH */
   1234 	case OSIOCSIFINFO_FLAGS_90:
   1235 		nd6_setifflags(ifp, OND.flags);
   1236 		break;
   1237 #undef OND
   1238 #endif
   1239 	case SIOCGIFINFO_IN6:
   1240 		ND.chlim = ifndi->chlim;
   1241 		ND.basereachable = ifndi->basereachable;
   1242 		ND.retrans = ifndi->retrans;
   1243 		ND.flags = ifndi->flags;
   1244 		break;
   1245 	case SIOCSIFINFO_IN6:
   1246 		/* Allow userland to set Neighbor Unreachability Detection
   1247 		 * timers. */
   1248 		if (ND.chlim != 0)
   1249 			ifndi->chlim = ND.chlim;
   1250 		if (ND.basereachable != 0 &&
   1251 		    ND.basereachable != ifndi->basereachable)
   1252 		{
   1253 			ifndi->basereachable = ND.basereachable;
   1254 			ifndi->reachable = ND_COMPUTE_RTIME(ND.basereachable);
   1255 		}
   1256 		if (ND.retrans != 0)
   1257 			ifndi->retrans = ND.retrans;
   1258 		break;
   1259 	case SIOCSIFINFO_FLAGS:
   1260 		nd6_setifflags(ifp, ND.flags);
   1261 		break;
   1262 #undef ND
   1263 	case SIOCGNBRINFO_IN6:
   1264 	{
   1265 		struct llentry *ln;
   1266 		struct in6_addr nb_addr = nbi->addr; /* make local for safety */
   1267 
   1268 		if ((error = in6_setscope(&nb_addr, ifp, NULL)) != 0)
   1269 			return error;
   1270 
   1271 		ln = nd6_lookup(&nb_addr, ifp, false);
   1272 		if (ln == NULL) {
   1273 			error = EINVAL;
   1274 			break;
   1275 		}
   1276 		nbi->state = ln->ln_state;
   1277 		nbi->asked = ln->ln_asked;
   1278 		nbi->isrouter = ln->ln_router;
   1279 		nbi->expire = ln->ln_expire ?
   1280 		    time_mono_to_wall(ln->ln_expire) : 0;
   1281 		LLE_RUNLOCK(ln);
   1282 
   1283 		break;
   1284 	}
   1285 	}
   1286 	return error;
   1287 }
   1288 
   1289 void
   1290 nd6_llinfo_release_pkts(struct llentry *ln, struct ifnet *ifp)
   1291 {
   1292 	struct mbuf *m_hold, *m_hold_next;
   1293 	struct sockaddr_in6 sin6;
   1294 
   1295 	LLE_WLOCK_ASSERT(ln);
   1296 
   1297 	sockaddr_in6_init(&sin6, &ln->r_l3addr.addr6, 0, 0, 0);
   1298 
   1299 	m_hold = ln->la_hold, ln->la_hold = NULL, ln->la_numheld = 0;
   1300 
   1301 	LLE_ADDREF(ln);
   1302 	LLE_WUNLOCK(ln);
   1303 	for (; m_hold != NULL; m_hold = m_hold_next) {
   1304 		m_hold_next = m_hold->m_nextpkt;
   1305 		m_hold->m_nextpkt = NULL;
   1306 
   1307 		/*
   1308 		 * we assume ifp is not a p2p here, so
   1309 		 * just set the 2nd argument as the
   1310 		 * 1st one.
   1311 		 */
   1312 		ip6_if_output(ifp, ifp, m_hold, &sin6, NULL);
   1313 	}
   1314 	LLE_WLOCK(ln);
   1315 	LLE_REMREF(ln);
   1316 }
   1317 
   1318 /*
   1319  * Create neighbor cache entry and cache link-layer address,
   1320  * on reception of inbound ND6 packets.  (RS/RA/NS/redirect)
   1321  */
   1322 void
   1323 nd6_cache_lladdr(
   1324     struct ifnet *ifp,
   1325     struct in6_addr *from,
   1326     char *lladdr,
   1327     int lladdrlen,
   1328     int type,	/* ICMP6 type */
   1329     int code	/* type dependent information */
   1330 )
   1331 {
   1332 	struct llentry *ln = NULL;
   1333 	int is_newentry;
   1334 	int do_update;
   1335 	int olladdr;
   1336 	int llchange;
   1337 	int newstate = 0;
   1338 
   1339 	KASSERT(ifp != NULL);
   1340 	KASSERT(from != NULL);
   1341 
   1342 	/* nothing must be updated for unspecified address */
   1343 	if (IN6_IS_ADDR_UNSPECIFIED(from))
   1344 		return;
   1345 
   1346 	/*
   1347 	 * Validation about ifp->if_addrlen and lladdrlen must be done in
   1348 	 * the caller.
   1349 	 *
   1350 	 * XXX If the link does not have link-layer adderss, what should
   1351 	 * we do? (ifp->if_addrlen == 0)
   1352 	 * Spec says nothing in sections for RA, RS and NA.  There's small
   1353 	 * description on it in NS section (RFC 2461 7.2.3).
   1354 	 */
   1355 
   1356 	ln = nd6_lookup(from, ifp, true);
   1357 	if (ln == NULL) {
   1358 #if 0
   1359 		/* nothing must be done if there's no lladdr */
   1360 		if (!lladdr || !lladdrlen)
   1361 			return NULL;
   1362 #endif
   1363 
   1364 		ln = nd6_create(from, ifp);
   1365 		is_newentry = 1;
   1366 	} else {
   1367 		/* do nothing if static ndp is set */
   1368 		if (ln->la_flags & LLE_STATIC) {
   1369 			LLE_WUNLOCK(ln);
   1370 			return;
   1371 		}
   1372 		is_newentry = 0;
   1373 	}
   1374 
   1375 	if (ln == NULL)
   1376 		return;
   1377 
   1378 	olladdr = (ln->la_flags & LLE_VALID) ? 1 : 0;
   1379 	if (olladdr && lladdr) {
   1380 		llchange = memcmp(lladdr, &ln->ll_addr, ifp->if_addrlen);
   1381 	} else
   1382 		llchange = 0;
   1383 
   1384 	/*
   1385 	 * newentry olladdr  lladdr  llchange	(*=record)
   1386 	 *	0	n	n	--	(1)
   1387 	 *	0	y	n	--	(2)
   1388 	 *	0	n	y	--	(3) * STALE
   1389 	 *	0	y	y	n	(4) *
   1390 	 *	0	y	y	y	(5) * STALE
   1391 	 *	1	--	n	--	(6)   NOSTATE(= PASSIVE)
   1392 	 *	1	--	y	--	(7) * STALE
   1393 	 */
   1394 
   1395 	if (lladdr) {		/* (3-5) and (7) */
   1396 		/*
   1397 		 * Record source link-layer address
   1398 		 * XXX is it dependent to ifp->if_type?
   1399 		 */
   1400 		memcpy(&ln->ll_addr, lladdr, ifp->if_addrlen);
   1401 		ln->la_flags |= LLE_VALID;
   1402 	}
   1403 
   1404 	if (!is_newentry) {
   1405 		if ((!olladdr && lladdr) ||		/* (3) */
   1406 		    (olladdr && lladdr && llchange)) {	/* (5) */
   1407 			do_update = 1;
   1408 			newstate = ND_LLINFO_STALE;
   1409 		} else					/* (1-2,4) */
   1410 			do_update = 0;
   1411 	} else {
   1412 		do_update = 1;
   1413 		if (lladdr == NULL)			/* (6) */
   1414 			newstate = ND_LLINFO_NOSTATE;
   1415 		else					/* (7) */
   1416 			newstate = ND_LLINFO_STALE;
   1417 	}
   1418 
   1419 	if (do_update) {
   1420 		/*
   1421 		 * Update the state of the neighbor cache.
   1422 		 */
   1423 		ln->ln_state = newstate;
   1424 
   1425 		if (ln->ln_state == ND_LLINFO_STALE) {
   1426 			/*
   1427 			 * XXX: since nd6_output() below will cause
   1428 			 * state tansition to DELAY and reset the timer,
   1429 			 * we must set the timer now, although it is actually
   1430 			 * meaningless.
   1431 			 */
   1432 			nd_set_timer(ln, ND_TIMER_GC);
   1433 
   1434 			nd6_llinfo_release_pkts(ln, ifp);
   1435 		} else if (ln->ln_state == ND_LLINFO_INCOMPLETE) {
   1436 			/* probe right away */
   1437 			nd_set_timer(ln, ND_TIMER_IMMEDIATE);
   1438 		}
   1439 	}
   1440 
   1441 	/*
   1442 	 * ICMP6 type dependent behavior.
   1443 	 *
   1444 	 * NS: clear IsRouter if new entry
   1445 	 * RS: clear IsRouter
   1446 	 * RA: set IsRouter if there's lladdr
   1447 	 * redir: clear IsRouter if new entry
   1448 	 *
   1449 	 * RA case, (1):
   1450 	 * The spec says that we must set IsRouter in the following cases:
   1451 	 * - If lladdr exist, set IsRouter.  This means (1-5).
   1452 	 * - If it is old entry (!newentry), set IsRouter.  This means (7).
   1453 	 * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
   1454 	 * A question arises for (1) case.  (1) case has no lladdr in the
   1455 	 * neighbor cache, this is similar to (6).
   1456 	 * This case is rare but we figured that we MUST NOT set IsRouter.
   1457 	 *
   1458 	 * newentry olladdr  lladdr  llchange	    NS  RS  RA	redir
   1459 	 *							D R
   1460 	 *	0	n	n	--	(1)	c   ?     s
   1461 	 *	0	y	n	--	(2)	c   s     s
   1462 	 *	0	n	y	--	(3)	c   s     s
   1463 	 *	0	y	y	n	(4)	c   s     s
   1464 	 *	0	y	y	y	(5)	c   s     s
   1465 	 *	1	--	n	--	(6) c	c 	c s
   1466 	 *	1	--	y	--	(7) c	c   s	c s
   1467 	 *
   1468 	 *					(c=clear s=set)
   1469 	 */
   1470 	switch (type & 0xff) {
   1471 	case ND_NEIGHBOR_SOLICIT:
   1472 		/*
   1473 		 * New entry must have is_router flag cleared.
   1474 		 */
   1475 		if (is_newentry)	/* (6-7) */
   1476 			ln->ln_router = 0;
   1477 		break;
   1478 	case ND_REDIRECT:
   1479 		/*
   1480 		 * If the icmp is a redirect to a better router, always set the
   1481 		 * is_router flag.  Otherwise, if the entry is newly created,
   1482 		 * clear the flag.  [RFC 2461, sec 8.3]
   1483 		 */
   1484 		if (code == ND_REDIRECT_ROUTER)
   1485 			ln->ln_router = 1;
   1486 		else if (is_newentry) /* (6-7) */
   1487 			ln->ln_router = 0;
   1488 		break;
   1489 	case ND_ROUTER_SOLICIT:
   1490 		/*
   1491 		 * is_router flag must always be cleared.
   1492 		 */
   1493 		ln->ln_router = 0;
   1494 		break;
   1495 	case ND_ROUTER_ADVERT:
   1496 		/*
   1497 		 * Mark an entry with lladdr as a router.
   1498 		 */
   1499 		if ((!is_newentry && (olladdr || lladdr)) ||	/* (2-5) */
   1500 		    (is_newentry && lladdr)) {			/* (7) */
   1501 			ln->ln_router = 1;
   1502 		}
   1503 		break;
   1504 	}
   1505 
   1506 	if (do_update && lladdr != NULL) {
   1507 		struct sockaddr_in6 sin6;
   1508 
   1509 		sockaddr_in6_init(&sin6, from, 0, 0, 0);
   1510 		rt_clonedmsg(is_newentry ? RTM_ADD : RTM_CHANGE,
   1511 		    NULL, sin6tosa(&sin6), lladdr, ifp);
   1512 	}
   1513 
   1514 	if (ln != NULL)
   1515 		LLE_WUNLOCK(ln);
   1516 
   1517 	/*
   1518 	 * If we have too many cache entries, initiate immediate
   1519 	 * purging for some entries.
   1520 	 */
   1521 	if (is_newentry)
   1522 		nd6_gc_neighbors(LLTABLE6(ifp), &ln->r_l3addr.addr6);
   1523 }
   1524 
   1525 static void
   1526 nd6_slowtimo(void *ignored_arg)
   1527 {
   1528 	struct nd_kifinfo *ndi;
   1529 	struct ifnet *ifp;
   1530 	struct psref psref;
   1531 	int s;
   1532 
   1533 	SOFTNET_KERNEL_LOCK_UNLESS_NET_MPSAFE();
   1534 	callout_reset(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
   1535 	    nd6_slowtimo, NULL);
   1536 
   1537 	s = pserialize_read_enter();
   1538 	IFNET_READER_FOREACH(ifp) {
   1539 		ndi = ND_IFINFO(ifp);
   1540 		if (ndi->basereachable && /* already initialized */
   1541 		    (ndi->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
   1542 			if_acquire(ifp, &psref);
   1543 			pserialize_read_exit(s);
   1544 			/*
   1545 			 * Since reachable time rarely changes by router
   1546 			 * advertisements, we SHOULD insure that a new random
   1547 			 * value gets recomputed at least once every few hours.
   1548 			 * (RFC 2461, 6.3.4)
   1549 			 */
   1550 			ndi->recalctm = nd6_recalc_reachtm_interval;
   1551 			ndi->reachable = ND_COMPUTE_RTIME(ndi->basereachable);
   1552 			s = pserialize_read_enter();
   1553 			if_release(ifp, &psref);
   1554 		}
   1555 	}
   1556 	pserialize_read_exit(s);
   1557 
   1558 	SOFTNET_KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
   1559 }
   1560 
   1561 /*
   1562  * Return 0 if a neighbor cache is found. Return EWOULDBLOCK if a cache is not
   1563  * found and trying to resolve a neighbor; in this case the mbuf is queued in
   1564  * the list. Otherwise return errno after freeing the mbuf.
   1565  */
   1566 int
   1567 nd6_resolve(struct ifnet *ifp, const struct rtentry *rt, struct mbuf *m,
   1568     const struct sockaddr *_dst, uint8_t *lldst, size_t dstsize)
   1569 {
   1570 	struct llentry *ln = NULL;
   1571 	bool created = false;
   1572 	const struct sockaddr_in6 *dst = satocsin6(_dst);
   1573 	int error;
   1574 	struct nd_kifinfo *ndi = ND_IFINFO(ifp);
   1575 
   1576 	/* discard the packet if IPv6 operation is disabled on the interface */
   1577 	if (ndi->flags & ND6_IFF_IFDISABLED) {
   1578 		m_freem(m);
   1579 		return ENETDOWN; /* better error? */
   1580 	}
   1581 
   1582 	/*
   1583 	 * Address resolution or Neighbor Unreachability Detection
   1584 	 * for the next hop.
   1585 	 * At this point, the destination of the packet must be a unicast
   1586 	 * or an anycast address(i.e. not a multicast).
   1587 	 */
   1588 
   1589 	/* Look up the neighbor cache for the nexthop */
   1590 	ln = nd6_lookup(&dst->sin6_addr, ifp, false);
   1591 
   1592 	if (ln != NULL && (ln->la_flags & LLE_VALID) != 0 &&
   1593 	    /* Only STALE needs to go the slow path to change its state. */
   1594 	    (ln->ln_state == ND_LLINFO_REACHABLE ||
   1595 	     ln->ln_state == ND_LLINFO_DELAY ||
   1596 	     ln->ln_state == ND_LLINFO_PROBE)) {
   1597 		/* Fast path */
   1598 		memcpy(lldst, &ln->ll_addr, MIN(dstsize, ifp->if_addrlen));
   1599 		LLE_RUNLOCK(ln);
   1600 		return 0;
   1601 	}
   1602 	if (ln != NULL)
   1603 		LLE_RUNLOCK(ln);
   1604 
   1605 	/* Slow path */
   1606 	ln = nd6_lookup(&dst->sin6_addr, ifp, true);
   1607 	if (ln == NULL && nd6_is_addr_neighbor(dst, ifp))  {
   1608 		/*
   1609 		 * Since nd6_is_addr_neighbor() internally calls nd6_lookup(),
   1610 		 * the condition below is not very efficient.  But we believe
   1611 		 * it is tolerable, because this should be a rare case.
   1612 		 */
   1613 		ln = nd6_create(&dst->sin6_addr, ifp);
   1614 		if (ln == NULL) {
   1615 			char ip6buf[INET6_ADDRSTRLEN];
   1616 			log(LOG_DEBUG,
   1617 			    "%s: can't allocate llinfo for %s "
   1618 			    "(ln=%p, rt=%p)\n", __func__,
   1619 			    IN6_PRINT(ip6buf, &dst->sin6_addr), ln, rt);
   1620 			m_freem(m);
   1621 			return ENOBUFS;
   1622 		}
   1623 		created = true;
   1624 	}
   1625 
   1626 	if (ln == NULL) {
   1627 		m_freem(m);
   1628 		return ENETDOWN; /* better error? */
   1629 	}
   1630 
   1631 	error = nd_resolve(ln, rt, m, lldst, dstsize);
   1632 
   1633 	if (created)
   1634 		nd6_gc_neighbors(LLTABLE6(ifp), &dst->sin6_addr);
   1635 
   1636 	return error;
   1637 }
   1638 
   1639 int
   1640 nd6_need_cache(struct ifnet *ifp)
   1641 {
   1642 	/*
   1643 	 * XXX: we currently do not make neighbor cache on any interface
   1644 	 * other than ARCnet, Ethernet, and GIF.
   1645 	 *
   1646 	 * RFC2893 says:
   1647 	 * - unidirectional tunnels needs no ND
   1648 	 */
   1649 	switch (ifp->if_type) {
   1650 	case IFT_ARCNET:
   1651 	case IFT_ETHER:
   1652 	case IFT_IEEE1394:
   1653 	case IFT_CARP:
   1654 	case IFT_GIF:		/* XXX need more cases? */
   1655 	case IFT_IPSEC:
   1656 	case IFT_PPP:
   1657 	case IFT_TUNNEL:
   1658 		return 1;
   1659 	default:
   1660 		return 0;
   1661 	}
   1662 }
   1663 
   1664 int
   1665 nd6_sysctl(
   1666     int name,
   1667     void *oldp,	/* syscall arg, need copyout */
   1668     size_t *oldlenp,
   1669     void *newp,	/* syscall arg, need copyin */
   1670     size_t newlen
   1671 )
   1672 {
   1673 	int error;
   1674 
   1675 	if (newp)
   1676 		return EPERM;
   1677 
   1678 	switch (name) {
   1679 
   1680 /* call the nd6 compat_90 hook to validate the nd6-related names */
   1681 	case OICMPV6CTL_ND6_DRLIST: /* FALLTHROUGH */
   1682 	case OICMPV6CTL_ND6_PRLIST:
   1683 		MODULE_HOOK_CALL(net_inet6_nd_90_hook, (name), ENOPROTOOPT,
   1684 		    error);
   1685 		if (error == 0)
   1686 			*oldlenp = 0;
   1687 		return error;
   1688 
   1689 	case ICMPV6CTL_ND6_MAXQLEN:
   1690 		return 0;
   1691 	default:
   1692 		return ENOPROTOOPT;
   1693 	}
   1694 }
   1695