Home | History | Annotate | Line # | Download | only in netinet6
nd6_rtr.c revision 1.130
      1 /*	$NetBSD: nd6_rtr.c,v 1.130 2017/01/16 07:33:36 ryo Exp $	*/
      2 /*	$KAME: nd6_rtr.c,v 1.95 2001/02/07 08:09:47 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_rtr.c,v 1.130 2017/01/16 07:33:36 ryo Exp $");
     35 
     36 #include <sys/param.h>
     37 #include <sys/systm.h>
     38 #include <sys/malloc.h>
     39 #include <sys/mbuf.h>
     40 #include <sys/socket.h>
     41 #include <sys/sockio.h>
     42 #include <sys/time.h>
     43 #include <sys/kernel.h>
     44 #include <sys/errno.h>
     45 #include <sys/ioctl.h>
     46 #include <sys/syslog.h>
     47 #include <sys/cprng.h>
     48 
     49 #include <net/if.h>
     50 #include <net/if_types.h>
     51 #include <net/if_dl.h>
     52 
     53 #include <netinet/in.h>
     54 #include <netinet6/in6_var.h>
     55 #include <netinet6/in6_ifattach.h>
     56 #include <netinet/ip6.h>
     57 #include <netinet6/ip6_var.h>
     58 #include <netinet6/nd6.h>
     59 #include <netinet/icmp6.h>
     60 #include <netinet6/icmp6_private.h>
     61 #include <netinet6/scope6_var.h>
     62 
     63 #include <net/net_osdep.h>
     64 
     65 static int rtpref(struct nd_defrouter *);
     66 static struct nd_defrouter *defrtrlist_update(struct nd_defrouter *);
     67 static int prelist_update(struct nd_prefixctl *, struct nd_defrouter *,
     68     struct mbuf *, int);
     69 static struct in6_ifaddr *in6_ifadd(struct nd_prefixctl *, int, struct psref *);
     70 static struct nd_pfxrouter *pfxrtr_lookup(struct nd_prefix *,
     71 	struct nd_defrouter *);
     72 static void pfxrtr_add(struct nd_prefix *, struct nd_defrouter *);
     73 static void pfxrtr_del(struct nd_pfxrouter *);
     74 static struct nd_pfxrouter *find_pfxlist_reachable_router
     75 	(struct nd_prefix *);
     76 
     77 static void defrouter_addreq(struct nd_defrouter *);
     78 static void defrouter_delreq(struct nd_defrouter *);
     79 
     80 static int in6_init_prefix_ltimes(struct nd_prefix *);
     81 static void in6_init_address_ltimes(struct nd_prefix *,
     82 	struct in6_addrlifetime *);
     83 static void purge_detached(struct ifnet *);
     84 
     85 static int rt6_deleteroute_matcher(struct rtentry *, void *);
     86 
     87 static int nd6_prelist_add(struct nd_prefixctl *, struct nd_defrouter *,
     88 	struct nd_prefix **);
     89 static int nd6_prefix_onlink(struct nd_prefix *);
     90 static int nd6_prefix_offlink(struct nd_prefix *);
     91 static struct nd_prefix *nd6_prefix_lookup(struct nd_prefixctl *);
     92 
     93 extern int nd6_recalc_reachtm_interval;
     94 
     95 int ip6_use_tempaddr = 0;
     96 
     97 int ip6_desync_factor;
     98 u_int32_t ip6_temp_preferred_lifetime = DEF_TEMP_PREFERRED_LIFETIME;
     99 u_int32_t ip6_temp_valid_lifetime = DEF_TEMP_VALID_LIFETIME;
    100 int ip6_temp_regen_advance = TEMPADDR_REGEN_ADVANCE;
    101 
    102 int nd6_numroutes = 0;
    103 
    104 /* RTPREF_MEDIUM has to be 0! */
    105 #define RTPREF_HIGH	1
    106 #define RTPREF_MEDIUM	0
    107 #define RTPREF_LOW	(-1)
    108 #define RTPREF_RESERVED	(-2)
    109 #define RTPREF_INVALID	(-3)	/* internal */
    110 
    111 static inline bool
    112 nd6_is_llinfo_probreach(struct nd_defrouter *dr)
    113 {
    114 	struct llentry *ln = NULL;
    115 
    116 	ln = nd6_lookup(&dr->rtaddr, dr->ifp, false);
    117 	if (ln == NULL)
    118 		return false;
    119 
    120 	if (!ND6_IS_LLINFO_PROBREACH(ln)) {
    121 		LLE_RUNLOCK(ln);
    122 		return false;
    123 	}
    124 
    125 	LLE_RUNLOCK(ln);
    126 	return true;
    127 }
    128 
    129 /*
    130  * Receive Router Solicitation Message - just for routers.
    131  * Router solicitation/advertisement is mostly managed by a userland program
    132  * (rtadvd) so here we have no function like nd6_ra_output().
    133  *
    134  * Based on RFC 2461
    135  */
    136 void
    137 nd6_rs_input(struct mbuf *m, int off, int icmp6len)
    138 {
    139 	struct ifnet *ifp;
    140 	struct nd_ifinfo *ndi;
    141 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
    142 	struct nd_router_solicit *nd_rs;
    143 	struct in6_addr saddr6 = ip6->ip6_src;
    144 	char *lladdr = NULL;
    145 	int lladdrlen = 0;
    146 	union nd_opts ndopts;
    147 	struct psref psref;
    148 	char ip6bufs[INET6_ADDRSTRLEN], ip6bufd[INET6_ADDRSTRLEN];
    149 
    150 	ifp = m_get_rcvif_psref(m, &psref);
    151 	if (ifp == NULL)
    152 		goto freeit;
    153 
    154 	ndi = ND_IFINFO(ifp);
    155 
    156 	/* If I'm not a router, ignore it. */
    157 	if (nd6_accepts_rtadv(ndi) || !ip6_forwarding)
    158 		goto freeit;
    159 
    160 	/* Sanity checks */
    161 	if (ip6->ip6_hlim != 255) {
    162 		nd6log(LOG_ERR, "invalid hlim (%d) from %s to %s on %s\n",
    163 		    ip6->ip6_hlim, ip6_sprintf(ip6bufs, &ip6->ip6_src),
    164 		    ip6_sprintf(ip6bufd, &ip6->ip6_dst), if_name(ifp));
    165 		goto bad;
    166 	}
    167 
    168 	/*
    169 	 * Don't update the neighbor cache, if src = ::.
    170 	 * This indicates that the src has no IP address assigned yet.
    171 	 */
    172 	if (IN6_IS_ADDR_UNSPECIFIED(&saddr6))
    173 		goto freeit;
    174 
    175 	IP6_EXTHDR_GET(nd_rs, struct nd_router_solicit *, m, off, icmp6len);
    176 	if (nd_rs == NULL) {
    177 		ICMP6_STATINC(ICMP6_STAT_TOOSHORT);
    178 		return;
    179 	}
    180 
    181 	icmp6len -= sizeof(*nd_rs);
    182 	nd6_option_init(nd_rs + 1, icmp6len, &ndopts);
    183 	if (nd6_options(&ndopts) < 0) {
    184 		nd6log(LOG_INFO, "invalid ND option, ignored\n");
    185 		/* nd6_options have incremented stats */
    186 		goto freeit;
    187 	}
    188 
    189 	if (ndopts.nd_opts_src_lladdr) {
    190 		lladdr = (char *)(ndopts.nd_opts_src_lladdr + 1);
    191 		lladdrlen = ndopts.nd_opts_src_lladdr->nd_opt_len << 3;
    192 	}
    193 
    194 	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
    195 		nd6log(LOG_INFO, "lladdrlen mismatch for %s "
    196 		    "(if %d, RS packet %d)\n",
    197 		    ip6_sprintf(ip6bufs, &saddr6),
    198 		    ifp->if_addrlen, lladdrlen - 2);
    199 		goto bad;
    200 	}
    201 
    202 	nd6_cache_lladdr(ifp, &saddr6, lladdr, lladdrlen, ND_ROUTER_SOLICIT, 0);
    203 
    204  freeit:
    205 	m_put_rcvif_psref(ifp, &psref);
    206 	m_freem(m);
    207 	return;
    208 
    209  bad:
    210 	ICMP6_STATINC(ICMP6_STAT_BADRS);
    211 	m_put_rcvif_psref(ifp, &psref);
    212 	m_freem(m);
    213 }
    214 
    215 /*
    216  * Receive Router Advertisement Message.
    217  *
    218  * Based on RFC 2461
    219  * TODO: on-link bit on prefix information
    220  * TODO: ND_RA_FLAG_{OTHER,MANAGED} processing
    221  */
    222 void
    223 nd6_ra_input(struct mbuf *m, int off, int icmp6len)
    224 {
    225 	struct ifnet *ifp;
    226 	struct nd_ifinfo *ndi;
    227 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
    228 	struct nd_router_advert *nd_ra;
    229 	struct in6_addr saddr6 = ip6->ip6_src;
    230 #if 0
    231 	struct in6_addr daddr6 = ip6->ip6_dst;
    232 	int flags; /* = nd_ra->nd_ra_flags_reserved; */
    233 	int is_managed = ((flags & ND_RA_FLAG_MANAGED) != 0);
    234 	int is_other = ((flags & ND_RA_FLAG_OTHER) != 0);
    235 #endif
    236 	int mcast = 0;
    237 	union nd_opts ndopts;
    238 	struct nd_defrouter *dr;
    239 	struct psref psref;
    240 	char ip6buf[INET6_ADDRSTRLEN], ip6buf2[INET6_ADDRSTRLEN];
    241 
    242 	ifp = m_get_rcvif_psref(m, &psref);
    243 	if (ifp == NULL)
    244 		goto freeit;
    245 
    246 	ndi = ND_IFINFO(ifp);
    247 	/*
    248 	 * We only accept RAs when
    249 	 * the system-wide variable allows the acceptance, and the
    250 	 * per-interface variable allows RAs on the receiving interface.
    251 	 */
    252 	if (!nd6_accepts_rtadv(ndi))
    253 		goto freeit;
    254 
    255 	if (ip6->ip6_hlim != 255) {
    256 		nd6log(LOG_ERR, "invalid hlim (%d) from %s to %s on %s\n",
    257 		    ip6->ip6_hlim, ip6_sprintf(ip6buf, &ip6->ip6_src),
    258 		    ip6_sprintf(ip6buf2, &ip6->ip6_dst), if_name(ifp));
    259 		goto bad;
    260 	}
    261 
    262 	if (!IN6_IS_ADDR_LINKLOCAL(&saddr6)) {
    263 		nd6log(LOG_ERR, "src %s is not link-local\n",
    264 		    ip6_sprintf(ip6buf, &saddr6));
    265 		goto bad;
    266 	}
    267 
    268 	IP6_EXTHDR_GET(nd_ra, struct nd_router_advert *, m, off, icmp6len);
    269 	if (nd_ra == NULL) {
    270 		ICMP6_STATINC(ICMP6_STAT_TOOSHORT);
    271 		m_put_rcvif_psref(ifp, &psref);
    272 		return;
    273 	}
    274 
    275 	icmp6len -= sizeof(*nd_ra);
    276 	nd6_option_init(nd_ra + 1, icmp6len, &ndopts);
    277 	if (nd6_options(&ndopts) < 0) {
    278 		nd6log(LOG_INFO, "invalid ND option, ignored\n");
    279 		/* nd6_options have incremented stats */
    280 		goto freeit;
    281 	}
    282 
    283     {
    284 	struct nd_defrouter drtr;
    285 	u_int32_t advreachable = nd_ra->nd_ra_reachable;
    286 
    287 	/* remember if this is a multicasted advertisement */
    288 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
    289 		mcast = 1;
    290 
    291 	memset(&drtr, 0, sizeof(drtr));
    292 	drtr.rtaddr = saddr6;
    293 	drtr.flags  = nd_ra->nd_ra_flags_reserved;
    294 	drtr.rtlifetime = ntohs(nd_ra->nd_ra_router_lifetime);
    295 	drtr.expire = time_uptime + drtr.rtlifetime;
    296 	drtr.ifp = ifp;
    297 	/* unspecified or not? (RFC 2461 6.3.4) */
    298 	if (advreachable) {
    299 		NTOHL(advreachable);
    300 		if (advreachable <= MAX_REACHABLE_TIME &&
    301 		    ndi->basereachable != advreachable) {
    302 			ndi->basereachable = advreachable;
    303 			ndi->reachable = ND_COMPUTE_RTIME(ndi->basereachable);
    304 			ndi->recalctm = nd6_recalc_reachtm_interval; /* reset */
    305 		}
    306 	}
    307 	if (nd_ra->nd_ra_retransmit)
    308 		ndi->retrans = ntohl(nd_ra->nd_ra_retransmit);
    309 	if (nd_ra->nd_ra_curhoplimit) {
    310 		if (ndi->chlim < nd_ra->nd_ra_curhoplimit)
    311 			ndi->chlim = nd_ra->nd_ra_curhoplimit;
    312 		else if (ndi->chlim != nd_ra->nd_ra_curhoplimit)
    313 			log(LOG_ERR, "nd_ra_input: lower CurHopLimit sent from "
    314 			   "%s on %s (current=%d, received=%d), ignored\n",
    315 			   ip6_sprintf(ip6buf, &ip6->ip6_src),
    316 			   if_name(ifp), ndi->chlim, nd_ra->nd_ra_curhoplimit);
    317 	}
    318 	ND6_WLOCK();
    319 	dr = defrtrlist_update(&drtr);
    320     }
    321 
    322 	/*
    323 	 * prefix
    324 	 */
    325 	if (ndopts.nd_opts_pi) {
    326 		struct nd_opt_hdr *pt;
    327 		struct nd_opt_prefix_info *pi = NULL;
    328 		struct nd_prefixctl prc;
    329 
    330 		for (pt = (struct nd_opt_hdr *)ndopts.nd_opts_pi;
    331 		     pt <= (struct nd_opt_hdr *)ndopts.nd_opts_pi_end;
    332 		     pt = (struct nd_opt_hdr *)((char *)pt +
    333 						(pt->nd_opt_len << 3))) {
    334 			if (pt->nd_opt_type != ND_OPT_PREFIX_INFORMATION)
    335 				continue;
    336 			pi = (struct nd_opt_prefix_info *)pt;
    337 
    338 			if (pi->nd_opt_pi_len != 4) {
    339 				nd6log(LOG_INFO, "invalid option "
    340 				    "len %d for prefix information option, "
    341 				    "ignored\n", pi->nd_opt_pi_len);
    342 				continue;
    343 			}
    344 
    345 			if (128 < pi->nd_opt_pi_prefix_len) {
    346 				nd6log(LOG_INFO, "invalid prefix "
    347 				    "len %d for prefix information option, "
    348 				    "ignored\n", pi->nd_opt_pi_prefix_len);
    349 				continue;
    350 			}
    351 
    352 			if (IN6_IS_ADDR_MULTICAST(&pi->nd_opt_pi_prefix)
    353 			 || IN6_IS_ADDR_LINKLOCAL(&pi->nd_opt_pi_prefix)) {
    354 				nd6log(LOG_INFO,
    355 				    "invalid prefix %s, ignored\n",
    356 				    ip6_sprintf(ip6buf, &pi->nd_opt_pi_prefix));
    357 				continue;
    358 			}
    359 
    360 			memset(&prc, 0, sizeof(prc));
    361 			sockaddr_in6_init(&prc.ndprc_prefix,
    362 			    &pi->nd_opt_pi_prefix, 0, 0, 0);
    363 			prc.ndprc_ifp = ifp;
    364 
    365 			prc.ndprc_raf_onlink = (pi->nd_opt_pi_flags_reserved &
    366 			    ND_OPT_PI_FLAG_ONLINK) ? 1 : 0;
    367 			prc.ndprc_raf_auto = (pi->nd_opt_pi_flags_reserved &
    368 			    ND_OPT_PI_FLAG_AUTO) ? 1 : 0;
    369 			prc.ndprc_plen = pi->nd_opt_pi_prefix_len;
    370 			prc.ndprc_vltime = ntohl(pi->nd_opt_pi_valid_time);
    371 			prc.ndprc_pltime = ntohl(pi->nd_opt_pi_preferred_time);
    372 
    373 			(void)prelist_update(&prc, dr, m, mcast);
    374 		}
    375 	}
    376 	ND6_UNLOCK();
    377 
    378 	/*
    379 	 * MTU
    380 	 */
    381 	if (ndopts.nd_opts_mtu && ndopts.nd_opts_mtu->nd_opt_mtu_len == 1) {
    382 		u_long mtu;
    383 		u_long maxmtu;
    384 
    385 		mtu = ntohl(ndopts.nd_opts_mtu->nd_opt_mtu_mtu);
    386 
    387 		/* lower bound */
    388 		if (mtu < IPV6_MMTU) {
    389 			nd6log(LOG_INFO, "bogus mtu option "
    390 			    "mtu=%lu sent from %s, ignoring\n",
    391 			    mtu, ip6_sprintf(ip6buf, &ip6->ip6_src));
    392 			goto skip;
    393 		}
    394 
    395 		/* upper bound */
    396 		maxmtu = (ndi->maxmtu && ndi->maxmtu < ifp->if_mtu)
    397 		    ? ndi->maxmtu : ifp->if_mtu;
    398 		if (mtu <= maxmtu) {
    399 			int change = (ndi->linkmtu != mtu);
    400 
    401 			ndi->linkmtu = mtu;
    402 			if (change) /* in6_maxmtu may change */
    403 				in6_setmaxmtu();
    404 		} else {
    405 			nd6log(LOG_INFO,
    406 			    "bogus mtu mtu=%lu sent from %s; "
    407 			    "exceeds maxmtu %lu, ignoring\n",
    408 			    mtu, ip6_sprintf(ip6buf, &ip6->ip6_src), maxmtu);
    409 		}
    410 	}
    411 
    412  skip:
    413 
    414 	/*
    415 	 * Source link layer address
    416 	 */
    417     {
    418 	char *lladdr = NULL;
    419 	int lladdrlen = 0;
    420 
    421 	if (ndopts.nd_opts_src_lladdr) {
    422 		lladdr = (char *)(ndopts.nd_opts_src_lladdr + 1);
    423 		lladdrlen = ndopts.nd_opts_src_lladdr->nd_opt_len << 3;
    424 	}
    425 
    426 	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
    427 		nd6log(LOG_INFO, "lladdrlen mismatch for %s "
    428 		    "(if %d, RA packet %d)\n", ip6_sprintf(ip6buf, &saddr6),
    429 		    ifp->if_addrlen, lladdrlen - 2);
    430 		goto bad;
    431 	}
    432 
    433 	nd6_cache_lladdr(ifp, &saddr6, lladdr, lladdrlen, ND_ROUTER_ADVERT, 0);
    434 
    435 	/*
    436 	 * Installing a link-layer address might change the state of the
    437 	 * router's neighbor cache, which might also affect our on-link
    438 	 * detection of adveritsed prefixes.
    439 	 */
    440 	ND6_WLOCK();
    441 	nd6_pfxlist_onlink_check();
    442 	ND6_UNLOCK();
    443     }
    444 
    445  freeit:
    446 	m_put_rcvif_psref(ifp, &psref);
    447 	m_freem(m);
    448 	return;
    449 
    450  bad:
    451 	ICMP6_STATINC(ICMP6_STAT_BADRA);
    452 	m_put_rcvif_psref(ifp, &psref);
    453 	m_freem(m);
    454 }
    455 
    456 /*
    457  * default router list processing sub routines
    458  */
    459 static void
    460 defrouter_addreq(struct nd_defrouter *newdr)
    461 {
    462 	union {
    463 		struct sockaddr_in6 sin6;
    464 		struct sockaddr sa;
    465 	} def, mask, gate;
    466 	int s;
    467 	int error;
    468 
    469 	memset(&def, 0, sizeof(def));
    470 	memset(&mask, 0, sizeof(mask));
    471 	memset(&gate, 0,sizeof(gate)); /* for safety */
    472 
    473 	def.sin6.sin6_len = mask.sin6.sin6_len = gate.sin6.sin6_len =
    474 	    sizeof(struct sockaddr_in6);
    475 	def.sin6.sin6_family = mask.sin6.sin6_family = gate.sin6.sin6_family = AF_INET6;
    476 	gate.sin6.sin6_addr = newdr->rtaddr;
    477 #ifndef SCOPEDROUTING
    478 	gate.sin6.sin6_scope_id = 0;	/* XXX */
    479 #endif
    480 
    481 	s = splsoftnet();
    482 	error = rtrequest_newmsg(RTM_ADD, &def.sa, &gate.sa, &mask.sa,
    483 	    RTF_GATEWAY);
    484 	if (error == 0) {
    485 		nd6_numroutes++;
    486 		newdr->installed = 1;
    487 	}
    488 	splx(s);
    489 	return;
    490 }
    491 
    492 struct nd_defrouter *
    493 nd6_defrouter_lookup(const struct in6_addr *addr, struct ifnet *ifp)
    494 {
    495 	struct nd_defrouter *dr;
    496 
    497 	ND6_ASSERT_LOCK();
    498 
    499 	ND_DEFROUTER_LIST_FOREACH(dr) {
    500 		if (dr->ifp == ifp && IN6_ARE_ADDR_EQUAL(addr, &dr->rtaddr))
    501 			break;
    502 	}
    503 
    504 	return dr;		/* search failed */
    505 }
    506 
    507 void
    508 nd6_defrtrlist_del(struct nd_defrouter *dr, struct in6_ifextra *ext)
    509 {
    510 	struct nd_defrouter *deldr = NULL;
    511 	struct nd_prefix *pr;
    512 	struct nd_ifinfo *ndi;
    513 
    514 	ND6_ASSERT_WLOCK();
    515 
    516 	if (ext == NULL)
    517 		ext = dr->ifp->if_afdata[AF_INET6];
    518 
    519 	/* detach already in progress, can not do anything */
    520 	if (ext == NULL)
    521 		return;
    522 
    523 	ndi = ext->nd_ifinfo;
    524 
    525 	/*
    526 	 * Flush all the routing table entries that use the router
    527 	 * as a next hop.
    528 	 */
    529 	/* XXX: better condition? */
    530 	if (!ip6_forwarding && nd6_accepts_rtadv(ndi))
    531 		nd6_rt_flush(&dr->rtaddr, dr->ifp);
    532 
    533 	if (dr->installed) {
    534 		deldr = dr;
    535 		defrouter_delreq(dr);
    536 	}
    537 	ND_DEFROUTER_LIST_REMOVE(dr);
    538 
    539 	/*
    540 	 * Also delete all the pointers to the router in each prefix lists.
    541 	 */
    542 	ND_PREFIX_LIST_FOREACH(pr) {
    543 		struct nd_pfxrouter *pfxrtr;
    544 		if ((pfxrtr = pfxrtr_lookup(pr, dr)) != NULL)
    545 			pfxrtr_del(pfxrtr);
    546 	}
    547 	nd6_pfxlist_onlink_check();
    548 
    549 	/*
    550 	 * If the router is the primary one, choose a new one.
    551 	 * Note that nd6_defrouter_select() will remove the current gateway
    552 	 * from the routing table.
    553 	 */
    554 	if (deldr)
    555 		nd6_defrouter_select();
    556 
    557 	ext->ndefrouters--;
    558 	if (ext->ndefrouters < 0) {
    559 		log(LOG_WARNING, "nd6_defrtrlist_del: negative count on %s\n",
    560 		    dr->ifp->if_xname);
    561 	}
    562 
    563 	free(dr, M_IP6NDP);
    564 }
    565 
    566 /*
    567  * Remove the default route for a given router.
    568  * This is just a subroutine function for nd6_defrouter_select(), and should
    569  * not be called from anywhere else.
    570  */
    571 static void
    572 defrouter_delreq(struct nd_defrouter *dr)
    573 {
    574 	union {
    575 		struct sockaddr_in6 sin6;
    576 		struct sockaddr sa;
    577 	} def, mask, gw;
    578 	int error;
    579 
    580 #ifdef DIAGNOSTIC
    581 	if (dr == NULL)
    582 		panic("dr == NULL in defrouter_delreq");
    583 #endif
    584 
    585 	memset(&def, 0, sizeof(def));
    586 	memset(&mask, 0, sizeof(mask));
    587 	memset(&gw, 0, sizeof(gw));	/* for safety */
    588 
    589 	def.sin6.sin6_len = mask.sin6.sin6_len = gw.sin6.sin6_len =
    590 	    sizeof(struct sockaddr_in6);
    591 	def.sin6.sin6_family = mask.sin6.sin6_family = gw.sin6.sin6_family = AF_INET6;
    592 	gw.sin6.sin6_addr = dr->rtaddr;
    593 #ifndef SCOPEDROUTING
    594 	gw.sin6.sin6_scope_id = 0;	/* XXX */
    595 #endif
    596 
    597 	error = rtrequest_newmsg(RTM_DELETE, &def.sa, &gw.sa, &mask.sa,
    598 	    RTF_GATEWAY);
    599 	if (error == 0)
    600 		nd6_numroutes--;
    601 
    602 	dr->installed = 0;
    603 }
    604 
    605 /*
    606  * remove all default routes from default router list
    607  */
    608 void
    609 nd6_defrouter_reset(void)
    610 {
    611 	struct nd_defrouter *dr;
    612 
    613 	ND6_ASSERT_WLOCK();
    614 
    615 	ND_DEFROUTER_LIST_FOREACH(dr)
    616 		defrouter_delreq(dr);
    617 
    618 	/*
    619 	 * XXX should we also nuke any default routers in the kernel, by
    620 	 * going through them by rtalloc1()?
    621 	 */
    622 }
    623 
    624 /*
    625  * Default Router Selection according to Section 6.3.6 of RFC 2461 and
    626  * draft-ietf-ipngwg-router-selection:
    627  * 1) Routers that are reachable or probably reachable should be preferred.
    628  *    If we have more than one (probably) reachable router, prefer ones
    629  *    with the highest router preference.
    630  * 2) When no routers on the list are known to be reachable or
    631  *    probably reachable, routers SHOULD be selected in a round-robin
    632  *    fashion, regardless of router preference values.
    633  * 3) If the Default Router List is empty, assume that all
    634  *    destinations are on-link.
    635  *
    636  * We assume nd_defrouter is sorted by router preference value.
    637  * Since the code below covers both with and without router preference cases,
    638  * we do not need to classify the cases by ifdef.
    639  *
    640  * At this moment, we do not try to install more than one default router,
    641  * even when the multipath routing is available, because we're not sure about
    642  * the benefits for stub hosts comparing to the risk of making the code
    643  * complicated and the possibility of introducing bugs.
    644  */
    645 void
    646 nd6_defrouter_select(void)
    647 {
    648 	struct nd_ifinfo *ndi;
    649 	struct nd_defrouter *dr, *selected_dr = NULL, *installed_dr = NULL;
    650 
    651 	ND6_ASSERT_WLOCK();
    652 
    653 	/*
    654 	 * This function should be called only when acting as an autoconfigured
    655 	 * host.  Although the remaining part of this function is not effective
    656 	 * if the node is not an autoconfigured host, we explicitly exclude
    657 	 * such cases here for safety.
    658 	 */
    659 	if (ip6_forwarding) {
    660 		nd6log(LOG_WARNING, "called unexpectedly (forwarding=%d, "
    661 		    "accept_rtadv=%d)\n", ip6_forwarding, ip6_accept_rtadv);
    662 		return;
    663 	}
    664 
    665 	/*
    666 	 * Let's handle easy case (3) first:
    667 	 * If default router list is empty, there's nothing to be done.
    668 	 */
    669 	if (ND_DEFROUTER_LIST_EMPTY())
    670 		return;
    671 
    672 	/*
    673 	 * Search for a (probably) reachable router from the list.
    674 	 * We just pick up the first reachable one (if any), assuming that
    675 	 * the ordering rule of the list described in defrtrlist_update().
    676 	 */
    677 	ND_DEFROUTER_LIST_FOREACH(dr) {
    678 		ndi = ND_IFINFO(dr->ifp);
    679 		if (nd6_accepts_rtadv(ndi))
    680 			continue;
    681 
    682 		if (selected_dr == NULL &&
    683 		    nd6_is_llinfo_probreach(dr))
    684 			selected_dr = dr;
    685 
    686 		if (dr->installed && !installed_dr)
    687 			installed_dr = dr;
    688 		else if (dr->installed && installed_dr) {
    689 			/* this should not happen.  warn for diagnosis. */
    690 			log(LOG_ERR, "nd6_defrouter_select: more than one router"
    691 			    " is installed\n");
    692 		}
    693 	}
    694 	/*
    695 	 * If none of the default routers was found to be reachable,
    696 	 * round-robin the list regardless of preference.
    697 	 * Otherwise, if we have an installed router, check if the selected
    698 	 * (reachable) router should really be preferred to the installed one.
    699 	 * We only prefer the new router when the old one is not reachable
    700 	 * or when the new one has a really higher preference value.
    701 	 */
    702 	if (selected_dr == NULL) {
    703 		if (installed_dr == NULL ||
    704 		    ND_DEFROUTER_LIST_NEXT(installed_dr) == NULL)
    705 			selected_dr = ND_DEFROUTER_LIST_FIRST();
    706 		else
    707 			selected_dr = ND_DEFROUTER_LIST_NEXT(installed_dr);
    708 	} else if (installed_dr &&
    709 	    nd6_is_llinfo_probreach(installed_dr) &&
    710 	    rtpref(selected_dr) <= rtpref(installed_dr)) {
    711 		selected_dr = installed_dr;
    712 	}
    713 
    714 	/*
    715 	 * If the selected router is different than the installed one,
    716 	 * remove the installed router and install the selected one.
    717 	 * Note that the selected router is never NULL here.
    718 	 */
    719 	if (installed_dr != selected_dr) {
    720 		if (installed_dr)
    721 			defrouter_delreq(installed_dr);
    722 		defrouter_addreq(selected_dr);
    723 	}
    724 
    725 	return;
    726 }
    727 
    728 /*
    729  * for default router selection
    730  * regards router-preference field as a 2-bit signed integer
    731  */
    732 static int
    733 rtpref(struct nd_defrouter *dr)
    734 {
    735 	switch (dr->flags & ND_RA_FLAG_RTPREF_MASK) {
    736 	case ND_RA_FLAG_RTPREF_HIGH:
    737 		return (RTPREF_HIGH);
    738 	case ND_RA_FLAG_RTPREF_MEDIUM:
    739 	case ND_RA_FLAG_RTPREF_RSV:
    740 		return (RTPREF_MEDIUM);
    741 	case ND_RA_FLAG_RTPREF_LOW:
    742 		return (RTPREF_LOW);
    743 	default:
    744 		/*
    745 		 * This case should never happen.  If it did, it would mean a
    746 		 * serious bug of kernel internal.  We thus always bark here.
    747 		 * Or, can we even panic?
    748 		 */
    749 		log(LOG_ERR, "rtpref: impossible RA flag %x\n", dr->flags);
    750 		return (RTPREF_INVALID);
    751 	}
    752 	/* NOTREACHED */
    753 }
    754 
    755 static struct nd_defrouter *
    756 defrtrlist_update(struct nd_defrouter *newdr)
    757 {
    758 	struct nd_defrouter *dr, *n, *ret = NULL;
    759 	struct in6_ifextra *ext = newdr->ifp->if_afdata[AF_INET6];
    760 
    761 	ND6_ASSERT_WLOCK();
    762 
    763 	if ((dr = nd6_defrouter_lookup(&newdr->rtaddr, newdr->ifp)) != NULL) {
    764 		/* entry exists */
    765 		if (newdr->rtlifetime == 0) {
    766 			nd6_defrtrlist_del(dr, ext);
    767 			dr = NULL;
    768 		} else {
    769 			int oldpref = rtpref(dr);
    770 
    771 			/* override */
    772 			dr->flags = newdr->flags; /* xxx flag check */
    773 			dr->rtlifetime = newdr->rtlifetime;
    774 			dr->expire = newdr->expire;
    775 
    776 			/*
    777 			 * If the preference does not change, there's no need
    778 			 * to sort the entries.
    779 			 */
    780 			if (rtpref(newdr) == oldpref) {
    781 				ret = dr;
    782 				goto out;
    783 			}
    784 
    785 			/*
    786 			 * preferred router may be changed, so relocate
    787 			 * this router.
    788 			 * XXX: calling TAILQ_REMOVE directly is a bad manner.
    789 			 * However, since nd6_defrtrlist_del() has many side
    790 			 * effects, we intentionally do so here.
    791 			 * nd6_defrouter_select() below will handle routing
    792 			 * changes later.
    793 			 */
    794 			ND_DEFROUTER_LIST_REMOVE(dr);
    795 			n = dr;
    796 			goto insert;
    797 		}
    798 		ret = dr;
    799 		goto out;
    800 	}
    801 
    802 	if (ip6_maxifdefrouters >= 0 && ext->ndefrouters >= ip6_maxifdefrouters)
    803 		goto out;
    804 
    805 	/* entry does not exist */
    806 	if (newdr->rtlifetime == 0)
    807 		goto out;
    808 
    809 	if (ip6_rtadv_maxroutes <= nd6_numroutes) {
    810 		ICMP6_STATINC(ICMP6_STAT_DROPPED_RAROUTE);
    811 		goto out;
    812 	}
    813 
    814 	n = (struct nd_defrouter *)malloc(sizeof(*n), M_IP6NDP, M_NOWAIT);
    815 	if (n == NULL)
    816 		goto out;
    817 	memset(n, 0, sizeof(*n));
    818 	*n = *newdr;
    819 
    820 insert:
    821 	/*
    822 	 * Insert the new router in the Default Router List;
    823 	 * The Default Router List should be in the descending order
    824 	 * of router-preferece.  Routers with the same preference are
    825 	 * sorted in the arriving time order.
    826 	 */
    827 
    828 	/* insert at the end of the group */
    829 	ND_DEFROUTER_LIST_FOREACH(dr) {
    830 		if (rtpref(n) > rtpref(dr))
    831 			break;
    832 	}
    833 	if (dr)
    834 		ND_DEFROUTER_LIST_INSERT_BEFORE(dr, n);
    835 	else
    836 		ND_DEFROUTER_LIST_INSERT_TAIL(n);
    837 
    838 	nd6_defrouter_select();
    839 
    840 	ext->ndefrouters++;
    841 
    842 	ret = n;
    843 out:
    844 	return ret;
    845 }
    846 
    847 static struct nd_pfxrouter *
    848 pfxrtr_lookup(struct nd_prefix *pr, struct nd_defrouter *dr)
    849 {
    850 	struct nd_pfxrouter *search;
    851 
    852 	ND6_ASSERT_LOCK();
    853 
    854 	LIST_FOREACH(search, &pr->ndpr_advrtrs, pfr_entry) {
    855 		if (search->router == dr)
    856 			break;
    857 	}
    858 
    859 	return (search);
    860 }
    861 
    862 static void
    863 pfxrtr_add(struct nd_prefix *pr, struct nd_defrouter *dr)
    864 {
    865 	struct nd_pfxrouter *newpfr;
    866 
    867 	ND6_ASSERT_WLOCK();
    868 
    869 	newpfr = malloc(sizeof(*newpfr), M_IP6NDP, M_NOWAIT|M_ZERO);
    870 	if (newpfr == NULL)
    871 		return;
    872 	newpfr->router = dr;
    873 
    874 	LIST_INSERT_HEAD(&pr->ndpr_advrtrs, newpfr, pfr_entry);
    875 
    876 	nd6_pfxlist_onlink_check();
    877 }
    878 
    879 static void
    880 pfxrtr_del(struct nd_pfxrouter *pfr)
    881 {
    882 	LIST_REMOVE(pfr, pfr_entry);
    883 	free(pfr, M_IP6NDP);
    884 }
    885 
    886 static struct nd_prefix *
    887 nd6_prefix_lookup(struct nd_prefixctl *key)
    888 {
    889 	struct nd_prefix *search;
    890 
    891 	ND_PREFIX_LIST_FOREACH(search) {
    892 		if (key->ndprc_ifp == search->ndpr_ifp &&
    893 		    key->ndprc_plen == search->ndpr_plen &&
    894 		    in6_are_prefix_equal(&key->ndprc_prefix.sin6_addr,
    895 		    &search->ndpr_prefix.sin6_addr, key->ndprc_plen)) {
    896 			break;
    897 		}
    898 	}
    899 
    900 	return (search);
    901 }
    902 
    903 static void
    904 purge_detached(struct ifnet *ifp)
    905 {
    906 	struct nd_prefix *pr, *pr_next;
    907 	struct in6_ifaddr *ia;
    908 	struct ifaddr *ifa, *ifa_next;
    909 
    910 restart:
    911 	ND6_ASSERT_WLOCK();
    912 
    913 	ND_PREFIX_LIST_FOREACH_SAFE(pr, pr_next) {
    914 		int s;
    915 
    916 		/*
    917 		 * This function is called when we need to make more room for
    918 		 * new prefixes rather than keeping old, possibly stale ones.
    919 		 * Detached prefixes would be a good candidate; if all routers
    920 		 * that advertised the prefix expired, the prefix is also
    921 		 * probably stale.
    922 		 */
    923 		if (pr->ndpr_ifp != ifp ||
    924 		    IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr) ||
    925 		    ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
    926 		    !LIST_EMPTY(&pr->ndpr_advrtrs)))
    927 			continue;
    928 
    929 		s = pserialize_read_enter();
    930 		for (ifa = IFADDR_READER_FIRST(ifp); ifa; ifa = ifa_next) {
    931 			ifa_next = IFADDR_READER_NEXT(ifa);
    932 			if (ifa->ifa_addr->sa_family != AF_INET6)
    933 				continue;
    934 			ia = (struct in6_ifaddr *)ifa;
    935 			if ((ia->ia6_flags & IN6_IFF_AUTOCONF) ==
    936 			    IN6_IFF_AUTOCONF && ia->ia6_ndpr == pr) {
    937 				pserialize_read_exit(s);
    938 				ND6_UNLOCK();
    939 
    940 				/* in6_purgeaddr may destroy pr. */
    941 				in6_purgeaddr(ifa);
    942 
    943 				ND6_WLOCK();
    944 				goto restart;
    945 			}
    946 		}
    947 		pserialize_read_exit(s);
    948 
    949 		KASSERT(pr->ndpr_refcnt == 0);
    950 		nd6_prelist_remove(pr);
    951 	}
    952 }
    953 
    954 static int
    955 nd6_prelist_add(struct nd_prefixctl *prc, struct nd_defrouter *dr,
    956 	struct nd_prefix **newp)
    957 {
    958 	struct nd_prefix *newpr = NULL;
    959 	int i, s;
    960 	int error;
    961 	struct in6_ifextra *ext = prc->ndprc_ifp->if_afdata[AF_INET6];
    962 
    963 	ND6_ASSERT_WLOCK();
    964 
    965 	if (ip6_maxifprefixes >= 0) {
    966 		if (ext->nprefixes >= ip6_maxifprefixes / 2)
    967 			purge_detached(prc->ndprc_ifp);
    968 		if (ext->nprefixes >= ip6_maxifprefixes)
    969 			return ENOMEM;
    970 	}
    971 
    972 	error = 0;
    973 	newpr = malloc(sizeof(*newpr), M_IP6NDP, M_NOWAIT|M_ZERO);
    974 	if (newpr == NULL)
    975 		return ENOMEM;
    976 	newpr->ndpr_ifp = prc->ndprc_ifp;
    977 	newpr->ndpr_prefix = prc->ndprc_prefix;
    978 	newpr->ndpr_plen = prc->ndprc_plen;
    979 	newpr->ndpr_vltime = prc->ndprc_vltime;
    980 	newpr->ndpr_pltime = prc->ndprc_pltime;
    981 	newpr->ndpr_flags = prc->ndprc_flags;
    982 	if ((error = in6_init_prefix_ltimes(newpr)) != 0) {
    983 		free(newpr, M_IP6NDP);
    984 		return(error);
    985 	}
    986 	newpr->ndpr_lastupdate = time_uptime;
    987 	if (newp != NULL)
    988 		*newp = newpr;
    989 
    990 	/* initialization */
    991 	LIST_INIT(&newpr->ndpr_advrtrs);
    992 	in6_prefixlen2mask(&newpr->ndpr_mask, newpr->ndpr_plen);
    993 	/* make prefix in the canonical form */
    994 	for (i = 0; i < 4; i++) {
    995 		newpr->ndpr_prefix.sin6_addr.s6_addr32[i] &=
    996 		    newpr->ndpr_mask.s6_addr32[i];
    997 	}
    998 
    999 	s = splsoftnet();
   1000 	/* link ndpr_entry to nd_prefix list */
   1001 	ND_PREFIX_LIST_INSERT_HEAD(newpr);
   1002 	splx(s);
   1003 
   1004 	/* ND_OPT_PI_FLAG_ONLINK processing */
   1005 	if (newpr->ndpr_raf_onlink) {
   1006 		int e;
   1007 
   1008 		if ((e = nd6_prefix_onlink(newpr)) != 0) {
   1009 			char ip6buf[INET6_ADDRSTRLEN];
   1010 			nd6log(LOG_ERR, "failed to make "
   1011 			    "the prefix %s/%d on-link on %s (errno=%d)\n",
   1012 			    ip6_sprintf(ip6buf, &prc->ndprc_prefix.sin6_addr),
   1013 			    prc->ndprc_plen, if_name(prc->ndprc_ifp), e);
   1014 			/* proceed anyway. XXX: is it correct? */
   1015 		}
   1016 	}
   1017 
   1018 	if (dr)
   1019 		pfxrtr_add(newpr, dr);
   1020 
   1021 	ext->nprefixes++;
   1022 
   1023 	return 0;
   1024 }
   1025 
   1026 void
   1027 nd6_prefix_unref(struct nd_prefix *pr)
   1028 {
   1029 
   1030 	ND6_WLOCK();
   1031 	pr->ndpr_refcnt--;
   1032 	if (pr->ndpr_refcnt == 0)
   1033 		nd6_prelist_remove(pr);
   1034 	ND6_UNLOCK();
   1035 }
   1036 
   1037 void
   1038 nd6_prelist_remove(struct nd_prefix *pr)
   1039 {
   1040 	struct nd_pfxrouter *pfr, *next;
   1041 	int e, s;
   1042 	struct in6_ifextra *ext = pr->ndpr_ifp->if_afdata[AF_INET6];
   1043 
   1044 	ND6_ASSERT_WLOCK();
   1045 	KASSERT(pr->ndpr_refcnt == 0);
   1046 
   1047 	/* make sure to invalidate the prefix until it is really freed. */
   1048 	pr->ndpr_vltime = 0;
   1049 	pr->ndpr_pltime = 0;
   1050 #if 0
   1051 	/*
   1052 	 * Though these flags are now meaningless, we'd rather keep the value
   1053 	 * not to confuse users when executing "ndp -p".
   1054 	 */
   1055 	pr->ndpr_raf_onlink = 0;
   1056 	pr->ndpr_raf_auto = 0;
   1057 #endif
   1058 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0 &&
   1059 	    (e = nd6_prefix_offlink(pr)) != 0) {
   1060 		char ip6buf[INET6_ADDRSTRLEN];
   1061 		nd6log(LOG_ERR,
   1062 		    "failed to make %s/%d offlink on %s, errno=%d\n",
   1063 		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
   1064 		    pr->ndpr_plen, if_name(pr->ndpr_ifp), e);
   1065 		/* what should we do? */
   1066 	}
   1067 
   1068 	s = splsoftnet();
   1069 	/* unlink ndpr_entry from nd_prefix list */
   1070 	ND_PREFIX_LIST_REMOVE(pr);
   1071 
   1072 	/* free list of routers that adversed the prefix */
   1073 	for (pfr = LIST_FIRST(&pr->ndpr_advrtrs); pfr != NULL; pfr = next) {
   1074 		next = LIST_NEXT(pfr, pfr_entry);
   1075 
   1076 		free(pfr, M_IP6NDP);
   1077 	}
   1078 
   1079 	if (ext) {
   1080 		ext->nprefixes--;
   1081 		if (ext->nprefixes < 0) {
   1082 			log(LOG_WARNING, "nd6_prelist_remove: negative count on "
   1083 			    "%s\n", pr->ndpr_ifp->if_xname);
   1084 		}
   1085 	}
   1086 	splx(s);
   1087 
   1088 	free(pr, M_IP6NDP);
   1089 
   1090 	nd6_pfxlist_onlink_check();
   1091 }
   1092 
   1093 static int
   1094 prelist_update(struct nd_prefixctl *newprc,
   1095 	struct nd_defrouter *dr, /* may be NULL */
   1096 	struct mbuf *m,
   1097 	int mcast)
   1098 {
   1099 	struct in6_ifaddr *ia6_match = NULL;
   1100 	struct ifaddr *ifa;
   1101 	struct ifnet *ifp = newprc->ndprc_ifp;
   1102 	struct nd_prefix *pr;
   1103 	int error = 0;
   1104 	int auth;
   1105 	struct in6_addrlifetime lt6_tmp;
   1106 	int ss;
   1107 	char ip6buf[INET6_ADDRSTRLEN];
   1108 
   1109 	ND6_ASSERT_WLOCK();
   1110 
   1111 	auth = 0;
   1112 	if (m) {
   1113 		/*
   1114 		 * Authenticity for NA consists authentication for
   1115 		 * both IP header and IP datagrams, doesn't it ?
   1116 		 */
   1117 #if defined(M_AUTHIPHDR) && defined(M_AUTHIPDGM)
   1118 		auth = (m->m_flags & M_AUTHIPHDR
   1119 		     && m->m_flags & M_AUTHIPDGM) ? 1 : 0;
   1120 #endif
   1121 	}
   1122 
   1123 	if ((pr = nd6_prefix_lookup(newprc)) != NULL) {
   1124 		/*
   1125 		 * nd6_prefix_lookup() ensures that pr and newprc have the same
   1126 		 * prefix on a same interface.
   1127 		 */
   1128 
   1129 		/*
   1130 		 * Update prefix information.  Note that the on-link (L) bit
   1131 		 * and the autonomous (A) bit should NOT be changed from 1
   1132 		 * to 0.
   1133 		 */
   1134 		if (newprc->ndprc_raf_onlink == 1)
   1135 			pr->ndpr_raf_onlink = 1;
   1136 		if (newprc->ndprc_raf_auto == 1)
   1137 			pr->ndpr_raf_auto = 1;
   1138 		if (newprc->ndprc_raf_onlink) {
   1139 			pr->ndpr_vltime = newprc->ndprc_vltime;
   1140 			pr->ndpr_pltime = newprc->ndprc_pltime;
   1141 			(void)in6_init_prefix_ltimes(pr); /* XXX error case? */
   1142 			pr->ndpr_lastupdate = time_uptime;
   1143 		}
   1144 
   1145 		if (newprc->ndprc_raf_onlink &&
   1146 		    (pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
   1147 			int e;
   1148 
   1149 			if ((e = nd6_prefix_onlink(pr)) != 0) {
   1150 				nd6log(LOG_ERR,
   1151 				    "failed to make "
   1152 				    "the prefix %s/%d on-link on %s "
   1153 				    "(errno=%d)\n",
   1154 				    ip6_sprintf(ip6buf,
   1155 				    &pr->ndpr_prefix.sin6_addr),
   1156 				    pr->ndpr_plen, if_name(pr->ndpr_ifp), e);
   1157 				/* proceed anyway. XXX: is it correct? */
   1158 			}
   1159 		}
   1160 
   1161 		if (dr && pfxrtr_lookup(pr, dr) == NULL)
   1162 			pfxrtr_add(pr, dr);
   1163 	} else {
   1164 		struct nd_prefix *newpr = NULL;
   1165 
   1166 		if (newprc->ndprc_vltime == 0)
   1167 			goto end;
   1168 		if (newprc->ndprc_raf_onlink == 0 && newprc->ndprc_raf_auto == 0)
   1169 			goto end;
   1170 
   1171 		if (ip6_rtadv_maxroutes <= nd6_numroutes) {
   1172 			ICMP6_STATINC(ICMP6_STAT_DROPPED_RAROUTE);
   1173 			goto end;
   1174 		}
   1175 
   1176 		error = nd6_prelist_add(newprc, dr, &newpr);
   1177 		if (error != 0 || newpr == NULL) {
   1178 			nd6log(LOG_NOTICE,
   1179 			    "nd6_prelist_add failed for %s/%d on %s "
   1180 			    "errno=%d, returnpr=%p\n",
   1181 			    ip6_sprintf(ip6buf, &newprc->ndprc_prefix.sin6_addr),
   1182 			    newprc->ndprc_plen, if_name(newprc->ndprc_ifp),
   1183 			    error, newpr);
   1184 			goto end; /* we should just give up in this case. */
   1185 		}
   1186 
   1187 		/*
   1188 		 * XXX: from the ND point of view, we can ignore a prefix
   1189 		 * with the on-link bit being zero.  However, we need a
   1190 		 * prefix structure for references from autoconfigured
   1191 		 * addresses.  Thus, we explicitly make sure that the prefix
   1192 		 * itself expires now.
   1193 		 */
   1194 		if (newpr->ndpr_raf_onlink == 0) {
   1195 			newpr->ndpr_vltime = 0;
   1196 			newpr->ndpr_pltime = 0;
   1197 			in6_init_prefix_ltimes(newpr);
   1198 		}
   1199 
   1200 		pr = newpr;
   1201 	}
   1202 
   1203 	/*
   1204 	 * Address autoconfiguration based on Section 5.5.3 of RFC 2462.
   1205 	 * Note that pr must be non NULL at this point.
   1206 	 */
   1207 
   1208 	/* 5.5.3 (a). Ignore the prefix without the A bit set. */
   1209 	if (!newprc->ndprc_raf_auto)
   1210 		goto end;
   1211 
   1212 	/*
   1213 	 * 5.5.3 (b). the link-local prefix should have been ignored in
   1214 	 * nd6_ra_input.
   1215 	 */
   1216 
   1217 	/* 5.5.3 (c). Consistency check on lifetimes: pltime <= vltime. */
   1218 	if (newprc->ndprc_pltime > newprc->ndprc_vltime) {
   1219 		error = EINVAL;	/* XXX: won't be used */
   1220 		goto end;
   1221 	}
   1222 
   1223 	/*
   1224 	 * 5.5.3 (d).  If the prefix advertised is not equal to the prefix of
   1225 	 * an address configured by stateless autoconfiguration already in the
   1226 	 * list of addresses associated with the interface, and the Valid
   1227 	 * Lifetime is not 0, form an address.  We first check if we have
   1228 	 * a matching prefix.
   1229 	 * Note: we apply a clarification in rfc2462bis-02 here.  We only
   1230 	 * consider autoconfigured addresses while RFC2462 simply said
   1231 	 * "address".
   1232 	 */
   1233 	ss = pserialize_read_enter();
   1234 	IFADDR_READER_FOREACH(ifa, ifp) {
   1235 		struct in6_ifaddr *ia6;
   1236 		u_int32_t remaininglifetime;
   1237 
   1238 		if (ifa->ifa_addr->sa_family != AF_INET6)
   1239 			continue;
   1240 
   1241 		ia6 = (struct in6_ifaddr *)ifa;
   1242 
   1243 		/*
   1244 		 * We only consider autoconfigured addresses as per rfc2462bis.
   1245 		 */
   1246 		if (!(ia6->ia6_flags & IN6_IFF_AUTOCONF))
   1247 			continue;
   1248 
   1249 		/*
   1250 		 * Spec is not clear here, but I believe we should concentrate
   1251 		 * on unicast (i.e. not anycast) addresses.
   1252 		 * XXX: other ia6_flags? detached or duplicated?
   1253 		 */
   1254 		if ((ia6->ia6_flags & IN6_IFF_ANYCAST) != 0)
   1255 			continue;
   1256 
   1257 		/*
   1258 		 * Ignore the address if it is not associated with a prefix
   1259 		 * or is associated with a prefix that is different from this
   1260 		 * one.  (pr is never NULL here)
   1261 		 */
   1262 		if (ia6->ia6_ndpr != pr)
   1263 			continue;
   1264 
   1265 		if (ia6_match == NULL) /* remember the first one */
   1266 			ia6_match = ia6;
   1267 
   1268 		/*
   1269 		 * An already autoconfigured address matched.  Now that we
   1270 		 * are sure there is at least one matched address, we can
   1271 		 * proceed to 5.5.3. (e): update the lifetimes according to the
   1272 		 * "two hours" rule and the privacy extension.
   1273 		 * We apply some clarifications in rfc2462bis:
   1274 		 * - use remaininglifetime instead of storedlifetime as a
   1275 		 *   variable name
   1276 		 * - remove the dead code in the "two-hour" rule
   1277 		 */
   1278 #define TWOHOUR		(120*60)
   1279 		lt6_tmp = ia6->ia6_lifetime;
   1280 		if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME)
   1281 			remaininglifetime = ND6_INFINITE_LIFETIME;
   1282 		else if (time_uptime - ia6->ia6_updatetime >
   1283 			 lt6_tmp.ia6t_vltime) {
   1284 			/*
   1285 			 * The case of "invalid" address.  We should usually
   1286 			 * not see this case.
   1287 			 */
   1288 			remaininglifetime = 0;
   1289 		} else
   1290 			remaininglifetime = lt6_tmp.ia6t_vltime -
   1291 			    (time_uptime - ia6->ia6_updatetime);
   1292 
   1293 		/* when not updating, keep the current stored lifetime. */
   1294 		lt6_tmp.ia6t_vltime = remaininglifetime;
   1295 
   1296 		if (TWOHOUR < newprc->ndprc_vltime ||
   1297 		    remaininglifetime < newprc->ndprc_vltime) {
   1298 			lt6_tmp.ia6t_vltime = newprc->ndprc_vltime;
   1299 		} else if (remaininglifetime <= TWOHOUR) {
   1300 			if (auth)
   1301 				lt6_tmp.ia6t_vltime = newprc->ndprc_vltime;
   1302 		} else {
   1303 			/*
   1304 			 * newprc->ndprc_vltime <= TWOHOUR &&
   1305 			 * TWOHOUR < remaininglifetime
   1306 			 */
   1307 			lt6_tmp.ia6t_vltime = TWOHOUR;
   1308 		}
   1309 
   1310 		/* The 2 hour rule is not imposed for preferred lifetime. */
   1311 		lt6_tmp.ia6t_pltime = newprc->ndprc_pltime;
   1312 
   1313 		in6_init_address_ltimes(pr, &lt6_tmp);
   1314 
   1315 		/*
   1316 		 * We need to treat lifetimes for temporary addresses
   1317 		 * differently, according to
   1318 		 * draft-ietf-ipv6-privacy-addrs-v2-01.txt 3.3 (1);
   1319 		 * we only update the lifetimes when they are in the maximum
   1320 		 * intervals.
   1321 		 */
   1322 		if ((ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
   1323 			u_int32_t maxvltime, maxpltime;
   1324 
   1325 			if (ip6_temp_valid_lifetime >
   1326 			    (u_int32_t)((time_uptime - ia6->ia6_createtime) +
   1327 			    ip6_desync_factor)) {
   1328 				maxvltime = ip6_temp_valid_lifetime -
   1329 				    (time_uptime - ia6->ia6_createtime) -
   1330 				    ip6_desync_factor;
   1331 			} else
   1332 				maxvltime = 0;
   1333 			if (ip6_temp_preferred_lifetime >
   1334 			    (u_int32_t)((time_uptime - ia6->ia6_createtime) +
   1335 			    ip6_desync_factor)) {
   1336 				maxpltime = ip6_temp_preferred_lifetime -
   1337 				    (time_uptime - ia6->ia6_createtime) -
   1338 				    ip6_desync_factor;
   1339 			} else
   1340 				maxpltime = 0;
   1341 
   1342 			if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME ||
   1343 			    lt6_tmp.ia6t_vltime > maxvltime) {
   1344 				lt6_tmp.ia6t_vltime = maxvltime;
   1345 			}
   1346 			if (lt6_tmp.ia6t_pltime == ND6_INFINITE_LIFETIME ||
   1347 			    lt6_tmp.ia6t_pltime > maxpltime) {
   1348 				lt6_tmp.ia6t_pltime = maxpltime;
   1349 			}
   1350 		}
   1351 
   1352 		ia6->ia6_lifetime = lt6_tmp;
   1353 		ia6->ia6_updatetime = time_uptime;
   1354 	}
   1355 	pserialize_read_exit(ss);
   1356 
   1357 	if (ia6_match == NULL && newprc->ndprc_vltime) {
   1358 		int ifidlen;
   1359 		struct in6_ifaddr *ia6;
   1360 		struct psref psref;
   1361 
   1362 		/*
   1363 		 * 5.5.3 (d) (continued)
   1364 		 * No address matched and the valid lifetime is non-zero.
   1365 		 * Create a new address.
   1366 		 */
   1367 
   1368 		/*
   1369 		 * Prefix Length check:
   1370 		 * If the sum of the prefix length and interface identifier
   1371 		 * length does not equal 128 bits, the Prefix Information
   1372 		 * option MUST be ignored.  The length of the interface
   1373 		 * identifier is defined in a separate link-type specific
   1374 		 * document.
   1375 		 */
   1376 		ifidlen = in6_if2idlen(ifp);
   1377 		if (ifidlen < 0) {
   1378 			/* this should not happen, so we always log it. */
   1379 			log(LOG_ERR, "%s: IFID undefined (%s)\n",
   1380 			    __func__, if_name(ifp));
   1381 			goto end;
   1382 		}
   1383 		if (ifidlen + pr->ndpr_plen != 128) {
   1384 			nd6log(LOG_INFO,
   1385 			    "invalid prefixlen %d for %s, ignored\n",
   1386 			    pr->ndpr_plen, if_name(ifp));
   1387 			goto end;
   1388 		}
   1389 
   1390 		if ((ia6 = in6_ifadd(newprc, mcast, &psref)) != NULL) {
   1391 			/*
   1392 			 * note that we should use pr (not newprc) for reference.
   1393 			 */
   1394 			pr->ndpr_refcnt++;
   1395 			ia6->ia6_ndpr = pr;
   1396 
   1397 			/* toggle onlink state if the address was assigned
   1398 			 * a prefix route. */
   1399 			if (ia6->ia_flags & IFA_ROUTE)
   1400 				pr->ndpr_stateflags |= NDPRF_ONLINK;
   1401 
   1402 			/*
   1403 			 * draft-ietf-ipngwg-temp-addresses-v2-00 3.3 (2).
   1404 			 * When a new public address is created as described
   1405 			 * in RFC2462, also create a new temporary address.
   1406 			 *
   1407 			 * draft-ietf-ipngwg-temp-addresses-v2-00 3.5.
   1408 			 * When an interface connects to a new link, a new
   1409 			 * randomized interface identifier should be generated
   1410 			 * immediately together with a new set of temporary
   1411 			 * addresses.  Thus, we specifiy 1 as the 2nd arg of
   1412 			 * in6_tmpifadd().
   1413 			 */
   1414 			if (ip6_use_tempaddr) {
   1415 				int e;
   1416 				if ((e = in6_tmpifadd(ia6, 1, 1)) != 0) {
   1417 					nd6log(LOG_NOTICE,
   1418 					    "failed to create a temporary "
   1419 					    "address, errno=%d\n", e);
   1420 				}
   1421 			}
   1422 			ia6_release(ia6, &psref);
   1423 
   1424 			/*
   1425 			 * A newly added address might affect the status
   1426 			 * of other addresses, so we check and update it.
   1427 			 * XXX: what if address duplication happens?
   1428 			 */
   1429 			nd6_pfxlist_onlink_check();
   1430 		} else {
   1431 			/* just set an error. do not bark here. */
   1432 			error = EADDRNOTAVAIL; /* XXX: might be unused. */
   1433 		}
   1434 	}
   1435 
   1436  end:
   1437 	return error;
   1438 }
   1439 
   1440 /*
   1441  * A supplement function used in the on-link detection below;
   1442  * detect if a given prefix has a (probably) reachable advertising router.
   1443  * XXX: lengthy function name...
   1444  */
   1445 static struct nd_pfxrouter *
   1446 find_pfxlist_reachable_router(struct nd_prefix *pr)
   1447 {
   1448 	struct nd_pfxrouter *pfxrtr;
   1449 
   1450 	for (pfxrtr = LIST_FIRST(&pr->ndpr_advrtrs); pfxrtr;
   1451 	     pfxrtr = LIST_NEXT(pfxrtr, pfr_entry)) {
   1452 		if (pfxrtr->router->ifp->if_flags & IFF_UP &&
   1453 		    pfxrtr->router->ifp->if_link_state != LINK_STATE_DOWN &&
   1454 		    nd6_is_llinfo_probreach(pfxrtr->router))
   1455 			break;	/* found */
   1456 	}
   1457 
   1458 	return (pfxrtr);
   1459 }
   1460 
   1461 /*
   1462  * Check if each prefix in the prefix list has at least one available router
   1463  * that advertised the prefix (a router is "available" if its neighbor cache
   1464  * entry is reachable or probably reachable).
   1465  * If the check fails, the prefix may be off-link, because, for example,
   1466  * we have moved from the network but the lifetime of the prefix has not
   1467  * expired yet.  So we should not use the prefix if there is another prefix
   1468  * that has an available router.
   1469  * But, if there is no prefix that has an available router, we still regards
   1470  * all the prefixes as on-link.  This is because we can't tell if all the
   1471  * routers are simply dead or if we really moved from the network and there
   1472  * is no router around us.
   1473  */
   1474 void
   1475 nd6_pfxlist_onlink_check(void)
   1476 {
   1477 	struct nd_prefix *pr;
   1478 	struct in6_ifaddr *ia;
   1479 	struct nd_defrouter *dr;
   1480 	struct nd_pfxrouter *pfxrtr = NULL;
   1481 	int s;
   1482 	char ip6buf[INET6_ADDRSTRLEN];
   1483 
   1484 	ND6_ASSERT_WLOCK();
   1485 
   1486 	/*
   1487 	 * Check if there is a prefix that has a reachable advertising
   1488 	 * router.
   1489 	 */
   1490 	ND_PREFIX_LIST_FOREACH(pr) {
   1491 		if (pr->ndpr_raf_onlink && find_pfxlist_reachable_router(pr))
   1492 			break;
   1493 	}
   1494 	/*
   1495 	 * If we have no such prefix, check whether we still have a router
   1496 	 * that does not advertise any prefixes.
   1497 	 */
   1498 	if (pr == NULL) {
   1499 		ND_DEFROUTER_LIST_FOREACH(dr) {
   1500 			struct nd_prefix *pr0;
   1501 
   1502 			ND_PREFIX_LIST_FOREACH(pr0) {
   1503 				if ((pfxrtr = pfxrtr_lookup(pr0, dr)) != NULL)
   1504 					break;
   1505 			}
   1506 			if (pfxrtr)
   1507 				break;
   1508 		}
   1509 	}
   1510 	if (pr != NULL || (!ND_DEFROUTER_LIST_EMPTY() && !pfxrtr)) {
   1511 		/*
   1512 		 * There is at least one prefix that has a reachable router,
   1513 		 * or at least a router which probably does not advertise
   1514 		 * any prefixes.  The latter would be the case when we move
   1515 		 * to a new link where we have a router that does not provide
   1516 		 * prefixes and we configure an address by hand.
   1517 		 * Detach prefixes which have no reachable advertising
   1518 		 * router, and attach other prefixes.
   1519 		 */
   1520 		ND_PREFIX_LIST_FOREACH(pr) {
   1521 			/* XXX: a link-local prefix should never be detached */
   1522 			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
   1523 				continue;
   1524 
   1525 			/*
   1526 			 * we aren't interested in prefixes without the L bit
   1527 			 * set.
   1528 			 */
   1529 			if (pr->ndpr_raf_onlink == 0)
   1530 				continue;
   1531 
   1532 			if ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
   1533 			    find_pfxlist_reachable_router(pr) == NULL)
   1534 				pr->ndpr_stateflags |= NDPRF_DETACHED;
   1535 			if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0 &&
   1536 			    find_pfxlist_reachable_router(pr) != 0)
   1537 				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
   1538 		}
   1539 	} else {
   1540 		/* there is no prefix that has a reachable router */
   1541 		ND_PREFIX_LIST_FOREACH(pr) {
   1542 			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
   1543 				continue;
   1544 
   1545 			if (pr->ndpr_raf_onlink == 0)
   1546 				continue;
   1547 
   1548 			if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0)
   1549 				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
   1550 		}
   1551 	}
   1552 
   1553 	/*
   1554 	 * Remove each interface route associated with a (just) detached
   1555 	 * prefix, and reinstall the interface route for a (just) attached
   1556 	 * prefix.  Note that all attempt of reinstallation does not
   1557 	 * necessarily success, when a same prefix is shared among multiple
   1558 	 * interfaces.  Such cases will be handled in nd6_prefix_onlink,
   1559 	 * so we don't have to care about them.
   1560 	 */
   1561 	ND_PREFIX_LIST_FOREACH(pr) {
   1562 		int e;
   1563 
   1564 		if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
   1565 			continue;
   1566 
   1567 		if (pr->ndpr_raf_onlink == 0)
   1568 			continue;
   1569 
   1570 		if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0 &&
   1571 		    (pr->ndpr_stateflags & NDPRF_ONLINK) != 0) {
   1572 			if ((e = nd6_prefix_offlink(pr)) != 0) {
   1573 				nd6log(LOG_ERR,
   1574 				    "failed to make %s/%d offlink, errno=%d\n",
   1575 				    ip6_sprintf(ip6buf,
   1576 				    &pr->ndpr_prefix.sin6_addr),
   1577 				    pr->ndpr_plen, e);
   1578 			}
   1579 		}
   1580 		if ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
   1581 		    (pr->ndpr_stateflags & NDPRF_ONLINK) == 0 &&
   1582 		    pr->ndpr_raf_onlink) {
   1583 			if ((e = nd6_prefix_onlink(pr)) != 0) {
   1584 				nd6log(LOG_ERR,
   1585 				    "failed to make %s/%d onlink, errno=%d\n",
   1586 				    ip6_sprintf(ip6buf,
   1587 				    &pr->ndpr_prefix.sin6_addr),
   1588 				    pr->ndpr_plen, e);
   1589 			}
   1590 		}
   1591 	}
   1592 
   1593 	/*
   1594 	 * Changes on the prefix status might affect address status as well.
   1595 	 * Make sure that all addresses derived from an attached prefix are
   1596 	 * attached, and that all addresses derived from a detached prefix are
   1597 	 * detached.  Note, however, that a manually configured address should
   1598 	 * always be attached.
   1599 	 * The precise detection logic is same as the one for prefixes.
   1600 	 */
   1601 	s = pserialize_read_enter();
   1602 	IN6_ADDRLIST_READER_FOREACH(ia) {
   1603 		if (!(ia->ia6_flags & IN6_IFF_AUTOCONF))
   1604 			continue;
   1605 
   1606 		if (ia->ia6_ndpr == NULL) {
   1607 			/*
   1608 			 * This can happen when we first configure the address
   1609 			 * (i.e. the address exists, but the prefix does not).
   1610 			 * XXX: complicated relationships...
   1611 			 */
   1612 			continue;
   1613 		}
   1614 
   1615 		if (find_pfxlist_reachable_router(ia->ia6_ndpr))
   1616 			break;
   1617 	}
   1618 	pserialize_read_exit(s);
   1619 
   1620 	if (ia) {
   1621 		int bound = curlwp_bind();
   1622 
   1623 		s = pserialize_read_enter();
   1624 		IN6_ADDRLIST_READER_FOREACH(ia) {
   1625 			struct ifaddr *ifa = (struct ifaddr *)ia;
   1626 			struct psref psref;
   1627 
   1628 			if ((ia->ia6_flags & IN6_IFF_AUTOCONF) == 0)
   1629 				continue;
   1630 
   1631 			if (ia->ia6_ndpr == NULL) /* XXX: see above. */
   1632 				continue;
   1633 
   1634 			ia6_acquire(ia, &psref);
   1635 			pserialize_read_exit(s);
   1636 
   1637 			if (find_pfxlist_reachable_router(ia->ia6_ndpr)) {
   1638 				if (ia->ia6_flags & IN6_IFF_DETACHED) {
   1639 					ia->ia6_flags &= ~IN6_IFF_DETACHED;
   1640 					ia->ia6_flags |= IN6_IFF_TENTATIVE;
   1641 					nd6_dad_start(ifa,
   1642 					    0);
   1643 					/* We will notify the routing socket
   1644 					 * of the DAD result, so no need to
   1645 					 * here */
   1646 				}
   1647 			} else {
   1648 				if ((ia->ia6_flags & IN6_IFF_DETACHED) == 0) {
   1649 					ia->ia6_flags |= IN6_IFF_DETACHED;
   1650 					rt_newaddrmsg(RTM_NEWADDR,
   1651 					    ifa, 0, NULL);
   1652 				}
   1653 			}
   1654 
   1655 			s = pserialize_read_enter();
   1656 			ia6_release(ia, &psref);
   1657 		}
   1658 		pserialize_read_exit(s);
   1659 		curlwp_bindx(bound);
   1660 	}
   1661 	else {
   1662 		int bound = curlwp_bind();
   1663 
   1664 		s = pserialize_read_enter();
   1665 		IN6_ADDRLIST_READER_FOREACH(ia) {
   1666 			if ((ia->ia6_flags & IN6_IFF_AUTOCONF) == 0)
   1667 				continue;
   1668 
   1669 			if (ia->ia6_flags & IN6_IFF_DETACHED) {
   1670 				struct ifaddr *ifa = (struct ifaddr *)ia;
   1671 				struct psref psref;
   1672 
   1673 				ia->ia6_flags &= ~IN6_IFF_DETACHED;
   1674 				ia->ia6_flags |= IN6_IFF_TENTATIVE;
   1675 
   1676 				ia6_acquire(ia, &psref);
   1677 				pserialize_read_exit(s);
   1678 
   1679 				/* Do we need a delay in this case? */
   1680 				nd6_dad_start(ifa, 0);
   1681 
   1682 				s = pserialize_read_enter();
   1683 				ia6_release(ia, &psref);
   1684 			}
   1685 		}
   1686 		pserialize_read_exit(s);
   1687 		curlwp_bindx(bound);
   1688 	}
   1689 }
   1690 
   1691 static int
   1692 nd6_prefix_onlink(struct nd_prefix *pr)
   1693 {
   1694 	struct ifaddr *ifa;
   1695 	struct ifnet *ifp = pr->ndpr_ifp;
   1696 	struct sockaddr_in6 mask6;
   1697 	struct nd_prefix *opr;
   1698 	u_long rtflags;
   1699 	int error = 0;
   1700 	struct psref psref;
   1701 	int bound;
   1702 	char ip6buf[INET6_ADDRSTRLEN];
   1703 	char ip6bufp[INET6_ADDRSTRLEN], ip6bufm[INET6_ADDRSTRLEN];
   1704 
   1705 	ND6_ASSERT_WLOCK();
   1706 
   1707 	/* sanity check */
   1708 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0) {
   1709 		nd6log(LOG_ERR, "%s/%d is already on-link\n",
   1710 		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
   1711 		    pr->ndpr_plen);
   1712 		return (EEXIST);
   1713 	}
   1714 
   1715 	/*
   1716 	 * Add the interface route associated with the prefix.  Before
   1717 	 * installing the route, check if there's the same prefix on another
   1718 	 * interface, and the prefix has already installed the interface route.
   1719 	 * Although such a configuration is expected to be rare, we explicitly
   1720 	 * allow it.
   1721 	 */
   1722 	ND_PREFIX_LIST_FOREACH(opr) {
   1723 		if (opr == pr)
   1724 			continue;
   1725 
   1726 		if ((opr->ndpr_stateflags & NDPRF_ONLINK) == 0)
   1727 			continue;
   1728 
   1729 		if (opr->ndpr_plen == pr->ndpr_plen &&
   1730 		    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
   1731 		    &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen))
   1732 			return (0);
   1733 	}
   1734 
   1735 	/*
   1736 	 * We prefer link-local addresses as the associated interface address.
   1737 	 */
   1738 	/* search for a link-local addr */
   1739 	bound = curlwp_bind();
   1740 	ifa = (struct ifaddr *)in6ifa_ifpforlinklocal_psref(ifp,
   1741 	    IN6_IFF_NOTREADY | IN6_IFF_ANYCAST, &psref);
   1742 	if (ifa == NULL) {
   1743 		int s = pserialize_read_enter();
   1744 		IFADDR_READER_FOREACH(ifa, ifp) {
   1745 			if (ifa->ifa_addr->sa_family == AF_INET6)
   1746 				break;
   1747 		}
   1748 		if (ifa != NULL)
   1749 			ifa_acquire(ifa, &psref);
   1750 		pserialize_read_exit(s);
   1751 		/* should we care about ia6_flags? */
   1752 	}
   1753 	if (ifa == NULL) {
   1754 		/*
   1755 		 * This can still happen, when, for example, we receive an RA
   1756 		 * containing a prefix with the L bit set and the A bit clear,
   1757 		 * after removing all IPv6 addresses on the receiving
   1758 		 * interface.  This should, of course, be rare though.
   1759 		 */
   1760 		nd6log(LOG_NOTICE, "failed to find any ifaddr"
   1761 		    " to add route for a prefix(%s/%d) on %s\n",
   1762 		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
   1763 		    pr->ndpr_plen, if_name(ifp));
   1764 		curlwp_bindx(bound);
   1765 		return (0);
   1766 	}
   1767 
   1768 	/*
   1769 	 * in6_ifinit() sets nd6_rtrequest to ifa_rtrequest for all ifaddrs.
   1770 	 * ifa->ifa_rtrequest = nd6_rtrequest;
   1771 	 */
   1772 	memset(&mask6, 0, sizeof(mask6));
   1773 	mask6.sin6_family = AF_INET6;
   1774 	mask6.sin6_len = sizeof(mask6);
   1775 	mask6.sin6_addr = pr->ndpr_mask;
   1776 	/* rtrequest() will probably set RTF_UP, but we're not sure. */
   1777 	rtflags = ifa->ifa_flags | RTF_UP;
   1778 	if (nd6_need_cache(ifp)) {
   1779 		/* explicitly set in case ifa_flags does not set the flag. */
   1780 		rtflags |= RTF_CONNECTED;
   1781 	} else {
   1782 		/*
   1783 		 * explicitly clear the cloning bit in case ifa_flags sets it.
   1784 		 */
   1785 		rtflags &= ~RTF_CONNECTED;
   1786 	}
   1787 	error = rtrequest_newmsg(RTM_ADD, sin6tosa(&pr->ndpr_prefix),
   1788 	    ifa->ifa_addr, sin6tosa(&mask6), rtflags);
   1789 	if (error == 0) {
   1790 		nd6_numroutes++;
   1791 		pr->ndpr_stateflags |= NDPRF_ONLINK;
   1792 	} else {
   1793 		nd6log(LOG_ERR, "failed to add route for a"
   1794 		    " prefix (%s/%d) on %s, gw=%s, mask=%s, flags=%lx "
   1795 		    "errno = %d\n",
   1796 		    ip6_sprintf(ip6bufp, &pr->ndpr_prefix.sin6_addr),
   1797 		    pr->ndpr_plen, if_name(ifp),
   1798 		    ip6_sprintf(ip6buf,
   1799 		    &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr),
   1800 		    ip6_sprintf(ip6bufm, &mask6.sin6_addr), rtflags, error);
   1801 	}
   1802 	ifa_release(ifa, &psref);
   1803 	curlwp_bindx(bound);
   1804 
   1805 	return (error);
   1806 }
   1807 
   1808 static int
   1809 nd6_prefix_offlink(struct nd_prefix *pr)
   1810 {
   1811 	int error = 0;
   1812 	struct ifnet *ifp = pr->ndpr_ifp;
   1813 	struct nd_prefix *opr;
   1814 	struct sockaddr_in6 sa6, mask6;
   1815 	char ip6buf[INET6_ADDRSTRLEN];
   1816 
   1817 	ND6_ASSERT_WLOCK();
   1818 
   1819 	/* sanity check */
   1820 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
   1821 		nd6log(LOG_ERR, "%s/%d is already off-link\n",
   1822 		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
   1823 		    pr->ndpr_plen);
   1824 		return (EEXIST);
   1825 	}
   1826 
   1827 	sockaddr_in6_init(&sa6, &pr->ndpr_prefix.sin6_addr, 0, 0, 0);
   1828 	sockaddr_in6_init(&mask6, &pr->ndpr_mask, 0, 0, 0);
   1829 	error = rtrequest_newmsg(RTM_DELETE, sin6tosa(&sa6), NULL,
   1830 	    sin6tosa(&mask6), 0);
   1831 	if (error == 0) {
   1832 		pr->ndpr_stateflags &= ~NDPRF_ONLINK;
   1833 		nd6_numroutes--;
   1834 
   1835 		/*
   1836 		 * There might be the same prefix on another interface,
   1837 		 * the prefix which could not be on-link just because we have
   1838 		 * the interface route (see comments in nd6_prefix_onlink).
   1839 		 * If there's one, try to make the prefix on-link on the
   1840 		 * interface.
   1841 		 */
   1842 		ND_PREFIX_LIST_FOREACH(opr) {
   1843 			if (opr == pr)
   1844 				continue;
   1845 
   1846 			if ((opr->ndpr_stateflags & NDPRF_ONLINK) != 0)
   1847 				continue;
   1848 
   1849 			/*
   1850 			 * KAME specific: detached prefixes should not be
   1851 			 * on-link.
   1852 			 */
   1853 			if ((opr->ndpr_stateflags & NDPRF_DETACHED) != 0)
   1854 				continue;
   1855 
   1856 			if (opr->ndpr_plen == pr->ndpr_plen &&
   1857 			    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
   1858 			    &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen)) {
   1859 				int e;
   1860 
   1861 				if ((e = nd6_prefix_onlink(opr)) != 0) {
   1862 					nd6log(LOG_ERR, "failed to "
   1863 					    "recover a prefix %s/%d from %s "
   1864 					    "to %s (errno = %d)\n",
   1865 					    ip6_sprintf(ip6buf,
   1866 					    &opr->ndpr_prefix.sin6_addr),
   1867 					    opr->ndpr_plen, if_name(ifp),
   1868 					    if_name(opr->ndpr_ifp), e);
   1869 				}
   1870 			}
   1871 		}
   1872 	} else {
   1873 		/* XXX: can we still set the NDPRF_ONLINK flag? */
   1874 		nd6log(LOG_ERR, "failed to delete route: "
   1875 		    "%s/%d on %s (errno = %d)\n",
   1876 		    ip6_sprintf(ip6buf, &sa6.sin6_addr), pr->ndpr_plen,
   1877 		    if_name(ifp),
   1878 		    error);
   1879 	}
   1880 
   1881 	return error;
   1882 }
   1883 
   1884 static struct in6_ifaddr *
   1885 in6_ifadd(struct nd_prefixctl *prc, int mcast, struct psref *psref)
   1886 {
   1887 	struct ifnet *ifp = prc->ndprc_ifp;
   1888 	struct ifaddr *ifa;
   1889 	struct in6_aliasreq ifra;
   1890 	struct in6_ifaddr *ia, *ib;
   1891 	int error, plen0;
   1892 	struct in6_addr mask;
   1893 	int prefixlen = prc->ndprc_plen;
   1894 	int updateflags;
   1895 	int s;
   1896 	char ip6buf[INET6_ADDRSTRLEN];
   1897 
   1898 	ND6_ASSERT_WLOCK();
   1899 
   1900 	in6_prefixlen2mask(&mask, prefixlen);
   1901 
   1902 	/*
   1903 	 * find a link-local address (will be interface ID).
   1904 	 * Is it really mandatory? Theoretically, a global or a site-local
   1905 	 * address can be configured without a link-local address, if we
   1906 	 * have a unique interface identifier...
   1907 	 *
   1908 	 * it is not mandatory to have a link-local address, we can generate
   1909 	 * interface identifier on the fly.  we do this because:
   1910 	 * (1) it should be the easiest way to find interface identifier.
   1911 	 * (2) RFC2462 5.4 suggesting the use of the same interface identifier
   1912 	 * for multiple addresses on a single interface, and possible shortcut
   1913 	 * of DAD.  we omitted DAD for this reason in the past.
   1914 	 * (3) a user can prevent autoconfiguration of global address
   1915 	 * by removing link-local address by hand (this is partly because we
   1916 	 * don't have other way to control the use of IPv6 on an interface.
   1917 	 * this has been our design choice - cf. NRL's "ifconfig auto").
   1918 	 * (4) it is easier to manage when an interface has addresses
   1919 	 * with the same interface identifier, than to have multiple addresses
   1920 	 * with different interface identifiers.
   1921 	 */
   1922 	s = pserialize_read_enter();
   1923 	ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp, 0); /* 0 is OK? */
   1924 	if (ifa)
   1925 		ib = (struct in6_ifaddr *)ifa;
   1926 	else {
   1927 		pserialize_read_exit(s);
   1928 		return NULL;
   1929 	}
   1930 
   1931 #if 0 /* don't care link local addr state, and always do DAD */
   1932 	/* if link-local address is not eligible, do not autoconfigure. */
   1933 	if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY) {
   1934 		printf("in6_ifadd: link-local address not ready\n");
   1935 		return NULL;
   1936 	}
   1937 #endif
   1938 
   1939 	/* prefixlen + ifidlen must be equal to 128 */
   1940 	plen0 = in6_mask2len(&ib->ia_prefixmask.sin6_addr, NULL);
   1941 	if (prefixlen != plen0) {
   1942 		nd6log(LOG_INFO, "wrong prefixlen for %s "
   1943 		    "(prefix=%d ifid=%d)\n",
   1944 		    if_name(ifp), prefixlen, 128 - plen0);
   1945 		pserialize_read_exit(s);
   1946 		return NULL;
   1947 	}
   1948 
   1949 	/* make ifaddr */
   1950 
   1951 	memset(&ifra, 0, sizeof(ifra));
   1952 	/*
   1953 	 * in6_update_ifa() does not use ifra_name, but we accurately set it
   1954 	 * for safety.
   1955 	 */
   1956 	strncpy(ifra.ifra_name, if_name(ifp), sizeof(ifra.ifra_name));
   1957 	sockaddr_in6_init(&ifra.ifra_addr, &prc->ndprc_prefix.sin6_addr, 0, 0, 0);
   1958 	/* prefix */
   1959 	ifra.ifra_addr.sin6_addr.s6_addr32[0] &= mask.s6_addr32[0];
   1960 	ifra.ifra_addr.sin6_addr.s6_addr32[1] &= mask.s6_addr32[1];
   1961 	ifra.ifra_addr.sin6_addr.s6_addr32[2] &= mask.s6_addr32[2];
   1962 	ifra.ifra_addr.sin6_addr.s6_addr32[3] &= mask.s6_addr32[3];
   1963 
   1964 	/* interface ID */
   1965 	ifra.ifra_addr.sin6_addr.s6_addr32[0] |=
   1966 	    (ib->ia_addr.sin6_addr.s6_addr32[0] & ~mask.s6_addr32[0]);
   1967 	ifra.ifra_addr.sin6_addr.s6_addr32[1] |=
   1968 	    (ib->ia_addr.sin6_addr.s6_addr32[1] & ~mask.s6_addr32[1]);
   1969 	ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
   1970 	    (ib->ia_addr.sin6_addr.s6_addr32[2] & ~mask.s6_addr32[2]);
   1971 	ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
   1972 	    (ib->ia_addr.sin6_addr.s6_addr32[3] & ~mask.s6_addr32[3]);
   1973 	pserialize_read_exit(s);
   1974 
   1975 	/* new prefix mask. */
   1976 	sockaddr_in6_init(&ifra.ifra_prefixmask, &mask, 0, 0, 0);
   1977 
   1978 	/* lifetimes */
   1979 	ifra.ifra_lifetime.ia6t_vltime = prc->ndprc_vltime;
   1980 	ifra.ifra_lifetime.ia6t_pltime = prc->ndprc_pltime;
   1981 
   1982 	/* XXX: scope zone ID? */
   1983 
   1984 	ifra.ifra_flags |= IN6_IFF_AUTOCONF; /* obey autoconf */
   1985 
   1986 	/*
   1987 	 * Make sure that we do not have this address already.  This should
   1988 	 * usually not happen, but we can still see this case, e.g., if we
   1989 	 * have manually configured the exact address to be configured.
   1990 	 */
   1991 	s = pserialize_read_enter();
   1992 	if (in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr) != NULL) {
   1993 		/* this should be rare enough to make an explicit log */
   1994 		log(LOG_INFO, "in6_ifadd: %s is already configured\n",
   1995 		    ip6_sprintf(ip6buf, &ifra.ifra_addr.sin6_addr));
   1996 		pserialize_read_exit(s);
   1997 		return (NULL);
   1998 	}
   1999 	pserialize_read_exit(s);
   2000 
   2001 	/*
   2002 	 * Allocate ifaddr structure, link into chain, etc.
   2003 	 * If we are going to create a new address upon receiving a multicasted
   2004 	 * RA, we need to impose a random delay before starting DAD.
   2005 	 * [draft-ietf-ipv6-rfc2462bis-02.txt, Section 5.4.2]
   2006 	 */
   2007 	updateflags = 0;
   2008 	if (mcast)
   2009 		updateflags |= IN6_IFAUPDATE_DADDELAY;
   2010 	if ((error = in6_update_ifa(ifp, &ifra, updateflags)) != 0) {
   2011 		nd6log(LOG_ERR, "failed to make ifaddr %s on %s (errno=%d)\n",
   2012 		    ip6_sprintf(ip6buf, &ifra.ifra_addr.sin6_addr), if_name(ifp),
   2013 		    error);
   2014 		return (NULL);	/* ifaddr must not have been allocated. */
   2015 	}
   2016 
   2017 	ia = in6ifa_ifpwithaddr_psref(ifp, &ifra.ifra_addr.sin6_addr, psref);
   2018 
   2019 	return (ia);		/* this is always non-NULL */
   2020 }
   2021 
   2022 int
   2023 in6_tmpifadd(
   2024 	const struct in6_ifaddr *ia0, /* corresponding public address */
   2025 	int forcegen,
   2026 	int dad_delay)
   2027 {
   2028 	struct ifnet *ifp = ia0->ia_ifa.ifa_ifp;
   2029 	struct in6_ifaddr *newia, *ia;
   2030 	struct in6_aliasreq ifra;
   2031 	int i, error;
   2032 	int trylimit = 3;	/* XXX: adhoc value */
   2033 	int updateflags;
   2034 	u_int32_t randid[2];
   2035 	u_int32_t vltime0, pltime0;
   2036 	int s;
   2037 
   2038 	ND6_ASSERT_WLOCK();
   2039 
   2040 	memset(&ifra, 0, sizeof(ifra));
   2041 	strncpy(ifra.ifra_name, if_name(ifp), sizeof(ifra.ifra_name));
   2042 	ifra.ifra_addr = ia0->ia_addr;
   2043 	/* copy prefix mask */
   2044 	ifra.ifra_prefixmask = ia0->ia_prefixmask;
   2045 	/* clear the old IFID */
   2046 	for (i = 0; i < 4; i++) {
   2047 		ifra.ifra_addr.sin6_addr.s6_addr32[i] &=
   2048 		    ifra.ifra_prefixmask.sin6_addr.s6_addr32[i];
   2049 	}
   2050 
   2051   again:
   2052 	if (in6_get_tmpifid(ifp, (u_int8_t *)randid,
   2053 	    (const u_int8_t *)&ia0->ia_addr.sin6_addr.s6_addr[8], forcegen)) {
   2054 		nd6log(LOG_NOTICE, "failed to find a good random IFID\n");
   2055 		return (EINVAL);
   2056 	}
   2057 	ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
   2058 	    (randid[0] & ~(ifra.ifra_prefixmask.sin6_addr.s6_addr32[2]));
   2059 	ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
   2060 	    (randid[1] & ~(ifra.ifra_prefixmask.sin6_addr.s6_addr32[3]));
   2061 
   2062 	/*
   2063 	 * in6_get_tmpifid() quite likely provided a unique interface ID.
   2064 	 * However, we may still have a chance to see collision, because
   2065 	 * there may be a time lag between generation of the ID and generation
   2066 	 * of the address.  So, we'll do one more sanity check.
   2067 	 */
   2068 	s = pserialize_read_enter();
   2069 	IN6_ADDRLIST_READER_FOREACH(ia) {
   2070 		if (IN6_ARE_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
   2071 		    &ifra.ifra_addr.sin6_addr)) {
   2072 			pserialize_read_exit(s);
   2073 			if (trylimit-- == 0) {
   2074 				/*
   2075 				 * Give up.  Something strange should have
   2076 				 * happened.
   2077 				 */
   2078 				nd6log(LOG_NOTICE,
   2079 				    "failed to find a unique random IFID\n");
   2080 				return (EEXIST);
   2081 			}
   2082 			forcegen = 1;
   2083 			goto again;
   2084 		}
   2085 	}
   2086 	pserialize_read_exit(s);
   2087 
   2088 	/*
   2089 	 * The Valid Lifetime is the lower of the Valid Lifetime of the
   2090          * public address or TEMP_VALID_LIFETIME.
   2091 	 * The Preferred Lifetime is the lower of the Preferred Lifetime
   2092          * of the public address or TEMP_PREFERRED_LIFETIME -
   2093          * DESYNC_FACTOR.
   2094 	 */
   2095 	if (ia0->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
   2096 		vltime0 = IFA6_IS_INVALID(ia0) ? 0 :
   2097 		    (ia0->ia6_lifetime.ia6t_vltime -
   2098 		    (time_uptime - ia0->ia6_updatetime));
   2099 		if (vltime0 > ip6_temp_valid_lifetime)
   2100 			vltime0 = ip6_temp_valid_lifetime;
   2101 	} else
   2102 		vltime0 = ip6_temp_valid_lifetime;
   2103 	if (ia0->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
   2104 		pltime0 = IFA6_IS_DEPRECATED(ia0) ? 0 :
   2105 		    (ia0->ia6_lifetime.ia6t_pltime -
   2106 		    (time_uptime - ia0->ia6_updatetime));
   2107 		if (pltime0 > ip6_temp_preferred_lifetime - ip6_desync_factor){
   2108 			pltime0 = ip6_temp_preferred_lifetime -
   2109 			    ip6_desync_factor;
   2110 		}
   2111 	} else
   2112 		pltime0 = ip6_temp_preferred_lifetime - ip6_desync_factor;
   2113 	ifra.ifra_lifetime.ia6t_vltime = vltime0;
   2114 	ifra.ifra_lifetime.ia6t_pltime = pltime0;
   2115 
   2116 	/*
   2117 	 * A temporary address is created only if this calculated Preferred
   2118 	 * Lifetime is greater than REGEN_ADVANCE time units.
   2119 	 */
   2120 	if (ifra.ifra_lifetime.ia6t_pltime <= ip6_temp_regen_advance)
   2121 		return (0);
   2122 
   2123 	/* XXX: scope zone ID? */
   2124 
   2125 	ifra.ifra_flags |= (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY);
   2126 
   2127 	/* allocate ifaddr structure, link into chain, etc. */
   2128 	updateflags = 0;
   2129 	if (dad_delay)
   2130 		updateflags |= IN6_IFAUPDATE_DADDELAY;
   2131 	if ((error = in6_update_ifa(ifp, &ifra, updateflags)) != 0)
   2132 		return (error);
   2133 
   2134 	s = pserialize_read_enter();
   2135 	newia = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr);
   2136 	if (newia == NULL) {	/* XXX: can it happen? */
   2137 		pserialize_read_exit(s);
   2138 		nd6log(LOG_ERR,
   2139 		    "ifa update succeeded, but we got no ifaddr\n");
   2140 		return (EINVAL); /* XXX */
   2141 	}
   2142 	newia->ia6_ndpr = ia0->ia6_ndpr;
   2143 	newia->ia6_ndpr->ndpr_refcnt++;
   2144 	pserialize_read_exit(s);
   2145 
   2146 	/*
   2147 	 * A newly added address might affect the status of other addresses.
   2148 	 * XXX: when the temporary address is generated with a new public
   2149 	 * address, the onlink check is redundant.  However, it would be safe
   2150 	 * to do the check explicitly everywhere a new address is generated,
   2151 	 * and, in fact, we surely need the check when we create a new
   2152 	 * temporary address due to deprecation of an old temporary address.
   2153 	 */
   2154 	nd6_pfxlist_onlink_check();
   2155 
   2156 	return (0);
   2157 }
   2158 
   2159 static int
   2160 in6_init_prefix_ltimes(struct nd_prefix *ndpr)
   2161 {
   2162 
   2163 	ND6_ASSERT_WLOCK();
   2164 
   2165 	/* check if preferred lifetime > valid lifetime.  RFC2462 5.5.3 (c) */
   2166 	if (ndpr->ndpr_pltime > ndpr->ndpr_vltime) {
   2167 		nd6log(LOG_INFO, "preferred lifetime"
   2168 		    "(%d) is greater than valid lifetime(%d)\n",
   2169 		    (u_int)ndpr->ndpr_pltime, (u_int)ndpr->ndpr_vltime);
   2170 		return (EINVAL);
   2171 	}
   2172 	if (ndpr->ndpr_pltime == ND6_INFINITE_LIFETIME)
   2173 		ndpr->ndpr_preferred = 0;
   2174 	else
   2175 		ndpr->ndpr_preferred = time_uptime + ndpr->ndpr_pltime;
   2176 	if (ndpr->ndpr_vltime == ND6_INFINITE_LIFETIME)
   2177 		ndpr->ndpr_expire = 0;
   2178 	else
   2179 		ndpr->ndpr_expire = time_uptime + ndpr->ndpr_vltime;
   2180 
   2181 	return 0;
   2182 }
   2183 
   2184 static void
   2185 in6_init_address_ltimes(struct nd_prefix *newpr,
   2186     struct in6_addrlifetime *lt6)
   2187 {
   2188 
   2189 	/* Valid lifetime must not be updated unless explicitly specified. */
   2190 	/* init ia6t_expire */
   2191 	if (lt6->ia6t_vltime == ND6_INFINITE_LIFETIME)
   2192 		lt6->ia6t_expire = 0;
   2193 	else {
   2194 		lt6->ia6t_expire = time_uptime;
   2195 		lt6->ia6t_expire += lt6->ia6t_vltime;
   2196 	}
   2197 
   2198 	/* init ia6t_preferred */
   2199 	if (lt6->ia6t_pltime == ND6_INFINITE_LIFETIME)
   2200 		lt6->ia6t_preferred = 0;
   2201 	else {
   2202 		lt6->ia6t_preferred = time_uptime;
   2203 		lt6->ia6t_preferred += lt6->ia6t_pltime;
   2204 	}
   2205 }
   2206 
   2207 /*
   2208  * Delete all the routing table entries that use the specified gateway.
   2209  * XXX: this function causes search through all entries of routing table, so
   2210  * it shouldn't be called when acting as a router.
   2211  */
   2212 void
   2213 nd6_rt_flush(struct in6_addr *gateway, struct ifnet *ifp)
   2214 {
   2215 	int s = splsoftnet();
   2216 
   2217 	/* We'll care only link-local addresses */
   2218 	if (!IN6_IS_ADDR_LINKLOCAL(gateway)) {
   2219 		splx(s);
   2220 		return;
   2221 	}
   2222 
   2223 	rt_delete_matched_entries(AF_INET6, rt6_deleteroute_matcher, gateway);
   2224 	splx(s);
   2225 }
   2226 
   2227 static int
   2228 rt6_deleteroute_matcher(struct rtentry *rt, void *arg)
   2229 {
   2230 	struct in6_addr *gate = (struct in6_addr *)arg;
   2231 
   2232 	if (rt->rt_gateway == NULL || rt->rt_gateway->sa_family != AF_INET6)
   2233 		return (0);
   2234 
   2235 	if (!IN6_ARE_ADDR_EQUAL(gate, &satosin6(rt->rt_gateway)->sin6_addr))
   2236 		return (0);
   2237 
   2238 	/*
   2239 	 * Do not delete a static route.
   2240 	 * XXX: this seems to be a bit ad-hoc. Should we consider the
   2241 	 * 'cloned' bit instead?
   2242 	 */
   2243 	if ((rt->rt_flags & RTF_STATIC) != 0)
   2244 		return (0);
   2245 
   2246 	/*
   2247 	 * We delete only host route. This means, in particular, we don't
   2248 	 * delete default route.
   2249 	 */
   2250 	if ((rt->rt_flags & RTF_HOST) == 0)
   2251 		return (0);
   2252 
   2253 	return 1;
   2254 }
   2255