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