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