xref: /dragonfly/sys/netinet6/nd6_rtr.c (revision 6a3cbbc2)
1 /*	$FreeBSD: src/sys/netinet6/nd6_rtr.c,v 1.2.2.5 2003/04/05 10:28:53 ume Exp $	*/
2 /*	$KAME: nd6_rtr.c,v 1.111 2001/04/27 01:37:15 jinmei 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 "opt_inet.h"
34 #include "opt_inet6.h"
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/syslog.h>
46 #include <sys/queue.h>
47 #include <sys/globaldata.h>
48 #include <sys/mutex.h>
49 
50 #include <sys/mutex2.h>
51 
52 #include <net/if.h>
53 #include <net/if_types.h>
54 #include <net/if_dl.h>
55 #include <net/route.h>
56 #include <net/radix.h>
57 
58 #include <netinet/in.h>
59 #include <netinet6/in6_var.h>
60 #include <netinet6/in6_ifattach.h>
61 #include <netinet/ip6.h>
62 #include <netinet6/ip6_var.h>
63 #include <netinet6/nd6.h>
64 #include <netinet/icmp6.h>
65 #include <netinet6/scope6_var.h>
66 
67 #include <net/net_osdep.h>
68 
69 #define SDL(s)	((struct sockaddr_dl *)s)
70 
71 static struct nd_defrouter *defrtrlist_update (struct nd_defrouter *);
72 static struct in6_ifaddr *in6_ifadd (struct nd_prefix *,
73 	struct in6_addr *);
74 static struct nd_pfxrouter *pfxrtr_lookup (struct nd_prefix *,
75 	struct nd_defrouter *);
76 static void pfxrtr_add (struct nd_prefix *, struct nd_defrouter *);
77 static void pfxrtr_del (struct nd_pfxrouter *);
78 static struct nd_pfxrouter *find_pfxlist_reachable_router
79 	(struct nd_prefix *);
80 static void defrouter_addifreq (struct ifnet *);
81 
82 static void in6_init_address_ltimes(struct nd_prefix *ndpr,
83 	struct in6_addrlifetime *lt6);
84 
85 static int rt6_deleteroute (struct radix_node *, void *);
86 
87 extern int nd6_recalc_reachtm_interval;
88 
89 static struct ifnet *nd6_defifp;
90 int nd6_defifindex;
91 
92 int ip6_use_tempaddr = 0;
93 
94 int ip6_desync_factor;
95 u_int32_t ip6_temp_preferred_lifetime = DEF_TEMP_PREFERRED_LIFETIME;
96 u_int32_t ip6_temp_valid_lifetime = DEF_TEMP_VALID_LIFETIME;
97 /*
98  * shorter lifetimes for debugging purposes.
99 int ip6_temp_preferred_lifetime = 800;
100 static int ip6_temp_valid_lifetime = 1800;
101 */
102 int ip6_temp_regen_advance = TEMPADDR_REGEN_ADVANCE;
103 
104 /*
105  * Receive Router Solicitation Message - just for routers.
106  * Router solicitation/advertisement is mostly managed by userland program
107  * (rtadvd) so here we have no function like nd6_ra_output().
108  *
109  * Based on RFC 2461
110  */
111 void
112 nd6_rs_input(struct mbuf *m, int off, int icmp6len)
113 {
114 	struct ifnet *ifp = m->m_pkthdr.rcvif;
115 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
116 	struct nd_router_solicit *nd_rs;
117 	struct in6_addr saddr6 = ip6->ip6_src;
118 	char *lladdr = NULL;
119 	int lladdrlen = 0;
120 #if 0
121 	struct sockaddr_dl *sdl = NULL;
122 	struct llinfo_nd6 *ln = NULL;
123 	struct rtentry *rt = NULL;
124 	int is_newentry;
125 #endif
126 	union nd_opts ndopts;
127 
128 	/* If I'm not a router, ignore it. */
129 	if (ip6_accept_rtadv != 0 || ip6_forwarding != 1)
130 		goto freeit;
131 
132 	/* Sanity checks */
133 	if (ip6->ip6_hlim != 255) {
134 		nd6log((LOG_ERR,
135 		    "nd6_rs_input: invalid hlim (%d) from %s to %s on %s\n",
136 		    ip6->ip6_hlim, ip6_sprintf(&ip6->ip6_src),
137 		    ip6_sprintf(&ip6->ip6_dst), if_name(ifp)));
138 		goto bad;
139 	}
140 
141 	/*
142 	 * Don't update the neighbor cache, if src = ::.
143 	 * This indicates that the src has no IP address assigned yet.
144 	 */
145 	if (IN6_IS_ADDR_UNSPECIFIED(&saddr6))
146 		goto freeit;
147 
148 #ifndef PULLDOWN_TEST
149 	IP6_EXTHDR_CHECK(m, off, icmp6len,);
150 	nd_rs = (struct nd_router_solicit *)((caddr_t)ip6 + off);
151 #else
152 	IP6_EXTHDR_GET(nd_rs, struct nd_router_solicit *, m, off, icmp6len);
153 	if (nd_rs == NULL) {
154 		icmp6stat.icp6s_tooshort++;
155 		return;
156 	}
157 #endif
158 
159 	icmp6len -= sizeof(*nd_rs);
160 	nd6_option_init(nd_rs + 1, icmp6len, &ndopts);
161 	if (nd6_options(&ndopts) < 0) {
162 		nd6log((LOG_INFO,
163 		    "nd6_rs_input: invalid ND option, ignored\n"));
164 		/* nd6_options have incremented stats */
165 		goto freeit;
166 	}
167 
168 	if (ndopts.nd_opts_src_lladdr) {
169 		lladdr = (char *)(ndopts.nd_opts_src_lladdr + 1);
170 		lladdrlen = ndopts.nd_opts_src_lladdr->nd_opt_len << 3;
171 	}
172 
173 	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
174 		nd6log((LOG_INFO,
175 		    "nd6_rs_input: lladdrlen mismatch for %s "
176 		    "(if %d, RS packet %d)\n",
177 		    ip6_sprintf(&saddr6), ifp->if_addrlen, lladdrlen - 2));
178 		goto bad;
179 	}
180 
181 	nd6_cache_lladdr(ifp, &saddr6, lladdr, lladdrlen, ND_ROUTER_SOLICIT, 0);
182 
183 freeit:
184 	m_freem(m);
185 	return;
186 
187 bad:
188 	icmp6stat.icp6s_badrs++;
189 	m_freem(m);
190 }
191 
192 /*
193  * Receive Router Advertisement Message.
194  *
195  * Based on RFC 2461
196  * TODO: on-link bit on prefix information
197  * TODO: ND_RA_FLAG_{OTHER,MANAGED} processing
198  */
199 void
200 nd6_ra_input(struct mbuf *m, int off, int icmp6len)
201 {
202 	struct ifnet *ifp = m->m_pkthdr.rcvif;
203 	struct nd_ifinfo *ndi = ND_IFINFO(ifp);
204 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
205 	struct nd_router_advert *nd_ra;
206 	struct in6_addr saddr6 = ip6->ip6_src;
207 #if 0
208 	struct in6_addr daddr6 = ip6->ip6_dst;
209 	int flags; /* = nd_ra->nd_ra_flags_reserved; */
210 	int is_managed = ((flags & ND_RA_FLAG_MANAGED) != 0);
211 	int is_other = ((flags & ND_RA_FLAG_OTHER) != 0);
212 #endif
213 	union nd_opts ndopts;
214 	struct nd_defrouter *dr;
215 
216 	/*
217 	 * We only accept RAs only when
218 	 * the system-wide variable allows the acceptance, and
219 	 * per-interface variable allows RAs on the receiving interface.
220 	 */
221 	if (ip6_accept_rtadv == 0)
222 		goto freeit;
223 	if (!(ndi->flags & ND6_IFF_ACCEPT_RTADV))
224 		goto freeit;
225 
226 	if (ip6->ip6_hlim != 255) {
227 		nd6log((LOG_ERR,
228 		    "nd6_ra_input: invalid hlim (%d) from %s to %s on %s\n",
229 		    ip6->ip6_hlim, ip6_sprintf(&ip6->ip6_src),
230 		    ip6_sprintf(&ip6->ip6_dst), if_name(ifp)));
231 		goto bad;
232 	}
233 
234 	if (!IN6_IS_ADDR_LINKLOCAL(&saddr6)) {
235 		nd6log((LOG_ERR,
236 		    "nd6_ra_input: src %s is not link-local\n",
237 		    ip6_sprintf(&saddr6)));
238 		goto bad;
239 	}
240 
241 #ifndef PULLDOWN_TEST
242 	IP6_EXTHDR_CHECK(m, off, icmp6len,);
243 	nd_ra = (struct nd_router_advert *)((caddr_t)ip6 + off);
244 #else
245 	IP6_EXTHDR_GET(nd_ra, struct nd_router_advert *, m, off, icmp6len);
246 	if (nd_ra == NULL) {
247 		icmp6stat.icp6s_tooshort++;
248 		return;
249 	}
250 #endif
251 
252 	icmp6len -= sizeof(*nd_ra);
253 	nd6_option_init(nd_ra + 1, icmp6len, &ndopts);
254 	if (nd6_options(&ndopts) < 0) {
255 		nd6log((LOG_INFO,
256 		    "nd6_ra_input: invalid ND option, ignored\n"));
257 		/* nd6_options have incremented stats */
258 		goto freeit;
259 	}
260 
261     {
262 	struct nd_defrouter dr0;
263 	u_int32_t advreachable = nd_ra->nd_ra_reachable;
264 
265 	dr0.rtaddr = saddr6;
266 	dr0.flags  = nd_ra->nd_ra_flags_reserved;
267 	dr0.rtlifetime = ntohs(nd_ra->nd_ra_router_lifetime);
268 	dr0.expire = time_uptime + dr0.rtlifetime;
269 	dr0.ifp = ifp;
270 	dr0.advint = 0;		/* Mobile IPv6 */
271 	dr0.advint_expire = 0;	/* Mobile IPv6 */
272 	dr0.advints_lost = 0;	/* Mobile IPv6 */
273 	/* unspecified or not? (RFC 2461 6.3.4) */
274 	if (advreachable) {
275 		advreachable = ntohl(advreachable);
276 		if (advreachable <= MAX_REACHABLE_TIME &&
277 		    ndi->basereachable != advreachable) {
278 			ndi->basereachable = advreachable;
279 			ndi->reachable = ND_COMPUTE_RTIME(ndi->basereachable);
280 			ndi->recalctm = nd6_recalc_reachtm_interval; /* reset */
281 		}
282 	}
283 	if (nd_ra->nd_ra_retransmit)
284 		ndi->retrans = ntohl(nd_ra->nd_ra_retransmit);
285 	if (nd_ra->nd_ra_curhoplimit)
286 		ndi->chlim = nd_ra->nd_ra_curhoplimit;
287 	dr = defrtrlist_update(&dr0);
288     }
289 
290 	/*
291 	 * prefix
292 	 */
293 	if (ndopts.nd_opts_pi) {
294 		struct nd_opt_hdr *pt;
295 		struct nd_opt_prefix_info *pi = NULL;
296 		struct nd_prefix pr;
297 
298 		for (pt = (struct nd_opt_hdr *)ndopts.nd_opts_pi;
299 		     pt <= (struct nd_opt_hdr *)ndopts.nd_opts_pi_end;
300 		     pt = (struct nd_opt_hdr *)((caddr_t)pt +
301 						(pt->nd_opt_len << 3))) {
302 			if (pt->nd_opt_type != ND_OPT_PREFIX_INFORMATION)
303 				continue;
304 			pi = (struct nd_opt_prefix_info *)pt;
305 
306 			if (pi->nd_opt_pi_len != 4) {
307 				nd6log((LOG_INFO,
308 				    "nd6_ra_input: invalid option "
309 				    "len %d for prefix information option, "
310 				    "ignored\n", pi->nd_opt_pi_len));
311 				continue;
312 			}
313 
314 			if (128 < pi->nd_opt_pi_prefix_len) {
315 				nd6log((LOG_INFO,
316 				    "nd6_ra_input: invalid prefix "
317 				    "len %d for prefix information option, "
318 				    "ignored\n", pi->nd_opt_pi_prefix_len));
319 				continue;
320 			}
321 
322 			if (IN6_IS_ADDR_MULTICAST(&pi->nd_opt_pi_prefix)
323 			 || IN6_IS_ADDR_LINKLOCAL(&pi->nd_opt_pi_prefix)) {
324 				nd6log((LOG_INFO,
325 				    "nd6_ra_input: invalid prefix "
326 				    "%s, ignored\n",
327 				    ip6_sprintf(&pi->nd_opt_pi_prefix)));
328 				continue;
329 			}
330 
331 			bzero(&pr, sizeof(pr));
332 			pr.ndpr_prefix.sin6_family = AF_INET6;
333 			pr.ndpr_prefix.sin6_len = sizeof(pr.ndpr_prefix);
334 			pr.ndpr_prefix.sin6_addr = pi->nd_opt_pi_prefix;
335 			pr.ndpr_ifp = (struct ifnet *)m->m_pkthdr.rcvif;
336 
337 			pr.ndpr_raf_onlink = (pi->nd_opt_pi_flags_reserved &
338 			    ND_OPT_PI_FLAG_ONLINK) ? 1 : 0;
339 			pr.ndpr_raf_auto = (pi->nd_opt_pi_flags_reserved &
340 			    ND_OPT_PI_FLAG_AUTO) ? 1 : 0;
341 			pr.ndpr_plen = pi->nd_opt_pi_prefix_len;
342 			pr.ndpr_vltime = ntohl(pi->nd_opt_pi_valid_time);
343 			pr.ndpr_pltime = ntohl(pi->nd_opt_pi_preferred_time);
344 			if (in6_init_prefix_ltimes(&pr))
345 				continue; /* prefix lifetime init failed */
346 			prelist_update(&pr, dr, m);
347 		}
348 	}
349 
350 	/*
351 	 * MTU
352 	 */
353 	if (ndopts.nd_opts_mtu && ndopts.nd_opts_mtu->nd_opt_mtu_len == 1) {
354 		u_long mtu, maxmtu;
355 
356 		mtu = ntohl(ndopts.nd_opts_mtu->nd_opt_mtu_mtu);
357 
358 		/* lower bound */
359 		if (mtu < IPV6_MMTU) {
360 			nd6log((LOG_INFO, "nd6_ra_input: bogus mtu option "
361 			    "mtu=%ld sent from %s, ignoring\n",
362 			    mtu, ip6_sprintf(&ip6->ip6_src)));
363 			goto skip;
364 		}
365 
366 		/* upper bound */
367 		maxmtu = (ndi->maxmtu && ndi->maxmtu < ifp->if_mtu) ?
368 		    ndi->maxmtu : ifp->if_mtu;
369 		if (mtu <= maxmtu) {
370 		        int change = (ndi->linkmtu != mtu);
371 
372 		        ndi->linkmtu = mtu;
373 		        if (change) /* in6_maxmtu may change */
374 		                in6_setmaxmtu();
375 		} else {
376 			nd6log((LOG_INFO, "nd6_ra_input: bogus mtu "
377 			    "mtu=%lu sent from %s; "
378 			    "exceeds maxmtu %lu, ignoring\n",
379 			    mtu, ip6_sprintf(&ip6->ip6_src), maxmtu));
380 		}
381 	}
382 
383 skip:
384 
385 	/*
386 	 * Source link layer address
387 	 */
388     {
389 	char *lladdr = NULL;
390 	int lladdrlen = 0;
391 
392 	if (ndopts.nd_opts_src_lladdr) {
393 		lladdr = (char *)(ndopts.nd_opts_src_lladdr + 1);
394 		lladdrlen = ndopts.nd_opts_src_lladdr->nd_opt_len << 3;
395 	}
396 
397 	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
398 		nd6log((LOG_INFO,
399 		    "nd6_ra_input: lladdrlen mismatch for %s "
400 		    "(if %d, RA packet %d)\n",
401 		    ip6_sprintf(&saddr6), ifp->if_addrlen, lladdrlen - 2));
402 		goto bad;
403 	}
404 
405 	nd6_cache_lladdr(ifp, &saddr6, lladdr, lladdrlen, ND_ROUTER_ADVERT, 0);
406 
407 	/*
408 	 * Installing a link-layer address might change the state of the
409 	 * router's neighbor cache, which might also affect our on-link
410 	 * detection of adveritsed prefixes.
411 	 */
412 	pfxlist_onlink_check();
413     }
414 
415 freeit:
416 	m_freem(m);
417 	return;
418 
419 bad:
420 	icmp6stat.icp6s_badra++;
421 	m_freem(m);
422 }
423 
424 /*
425  * default router list proccessing sub routines
426  */
427 
428 #if 0
429 /* tell the change to user processes watching the routing socket. */
430 static void
431 nd6_rtmsg(int cmd, struct rtentry *rt)
432 {
433 	struct rt_addrinfo info;
434 
435 	bzero((caddr_t)&info, sizeof(info));
436 	info.rti_info[RTAX_DST] = rt_key(rt);
437 	info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
438 	info.rti_info[RTAX_NETMASK] = rt_mask(rt);
439 	if (TAILQ_EMPTY(&rt->rt_ifp->if_addrheads[mycpuid])) {
440 		info.rti_info[RTAX_IFP] = NULL;
441 	} else {
442 		info.rti_info[RTAX_IFP] =
443 		(struct sockaddr *)
444 		TAILQ_FIRST(&rt->rt_ifp->if_addrheads[mycpuid])->ifa;
445 	}
446 	info.rti_info[RTAX_IFA] = rt->rt_ifa->ifa_addr;
447 
448 	rt_missmsg(cmd, &info, rt->rt_flags, 0);
449 }
450 #endif
451 
452 void
453 defrouter_addreq(struct nd_defrouter *new)
454 {
455 	struct sockaddr_in6 def, mask, gate;
456 
457 	bzero(&def, sizeof(def));
458 	bzero(&mask, sizeof(mask));
459 	bzero(&gate, sizeof(gate));
460 
461 	def.sin6_len = mask.sin6_len = gate.sin6_len =
462 	    sizeof(struct sockaddr_in6);
463 	def.sin6_family = mask.sin6_family = gate.sin6_family = AF_INET6;
464 	gate.sin6_addr = new->rtaddr;
465 
466 	rtrequest_global(RTM_ADD, (struct sockaddr *)&def,
467 	    (struct sockaddr *)&gate, (struct sockaddr *)&mask, RTF_GATEWAY);
468 	return;
469 }
470 
471 /* Add a route to a given interface as default */
472 static void
473 defrouter_addifreq(struct ifnet *ifp)
474 {
475 	struct sockaddr_in6 def, mask;
476 	struct ifaddr *ifa;
477 	int error, flags;
478 
479 	bzero(&def, sizeof(def));
480 	bzero(&mask, sizeof(mask));
481 
482 	def.sin6_len = mask.sin6_len = sizeof(struct sockaddr_in6);
483 	def.sin6_family = mask.sin6_family = AF_INET6;
484 
485 	/*
486 	 * Search for an ifaddr beloging to the specified interface.
487 	 * XXX: An IPv6 address are required to be assigned on the interface.
488 	 */
489 	if ((ifa = ifaof_ifpforaddr((struct sockaddr *)&def, ifp)) == NULL) {
490 		nd6log((LOG_ERR,	/* better error? */
491 		    "defrouter_addifreq: failed to find an ifaddr "
492 		    "to install a route to interface %s\n",
493 		    if_name(ifp)));
494 		return;
495 	}
496 
497 	flags = ifa->ifa_flags;
498 	error = rtrequest_global(RTM_ADD, (struct sockaddr *)&def,
499 	    ifa->ifa_addr, (struct sockaddr *)&mask, flags);
500 	if (error != 0) {
501 		nd6log((LOG_ERR,
502 		    "defrouter_addifreq: failed to install a route to "
503 		    "interface %s (errno = %d)\n",
504 		    if_name(ifp), error));
505 	}
506 }
507 
508 struct nd_defrouter *
509 defrouter_lookup(struct in6_addr *addr, struct ifnet *ifp)
510 {
511 	struct nd_defrouter *dr;
512 
513 	for (dr = TAILQ_FIRST(&nd_defrouter); dr;
514 	     dr = TAILQ_NEXT(dr, dr_entry)) {
515 		if (dr->ifp == ifp && IN6_ARE_ADDR_EQUAL(addr, &dr->rtaddr))
516 			return (dr);
517 	}
518 
519 	return (NULL);		/* search failed */
520 }
521 
522 void
523 defrouter_delreq(struct nd_defrouter *dr, int dofree)
524 {
525 	struct sockaddr_in6 def, mask, gate;
526 
527 	bzero(&def, sizeof(def));
528 	bzero(&mask, sizeof(mask));
529 	bzero(&gate, sizeof(gate));
530 
531 	def.sin6_len = mask.sin6_len = gate.sin6_len =
532 	    sizeof(struct sockaddr_in6);
533 	def.sin6_family = mask.sin6_family = gate.sin6_family = AF_INET6;
534 	gate.sin6_addr = dr->rtaddr;
535 
536 	rtrequest_global(RTM_DELETE, (struct sockaddr *)&def,
537 	    (struct sockaddr *)&gate, (struct sockaddr *)&mask, RTF_GATEWAY);
538 	if (dofree)		/* XXX: necessary? */
539 		kfree(dr, M_IP6NDP);
540 }
541 
542 void
543 defrtrlist_del(struct nd_defrouter *dr)
544 {
545 	struct nd_defrouter *deldr = NULL;
546 	struct nd_prefix *pr;
547 
548 	/*
549 	 * Flush all the routing table entries that use the router
550 	 * as a next hop.
551 	 */
552 	if (!ip6_forwarding && ip6_accept_rtadv) /* XXX: better condition? */
553 		rt6_flush(&dr->rtaddr, dr->ifp);
554 
555 	if (dr == TAILQ_FIRST(&nd_defrouter))
556 		deldr = dr;	/* The router is primary. */
557 
558 	TAILQ_REMOVE(&nd_defrouter, dr, dr_entry);
559 
560 	/*
561 	 * Also delete all the pointers to the router in each prefix lists.
562 	 */
563 	for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
564 		struct nd_pfxrouter *pfxrtr;
565 		if ((pfxrtr = pfxrtr_lookup(pr, dr)) != NULL)
566 			pfxrtr_del(pfxrtr);
567 	}
568 	pfxlist_onlink_check();
569 
570 	/*
571 	 * If the router is the primary one, choose a new one.
572 	 * Note that defrouter_select() will remove the current gateway
573 	 * from the routing table.
574 	 */
575 	if (deldr)
576 		defrouter_select();
577 
578 	kfree(dr, M_IP6NDP);
579 }
580 
581 /*
582  * Default Router Selection according to Section 6.3.6 of RFC 2461:
583  * 1) Routers that are reachable or probably reachable should be
584  *    preferred.
585  * 2) When no routers on the list are known to be reachable or
586  *    probably reachable, routers SHOULD be selected in a round-robin
587  *    fashion.
588  * 3) If the Default Router List is empty, assume that all
589  *    destinations are on-link.
590  */
591 void
592 defrouter_select(void)
593 {
594 	struct nd_defrouter *dr, anydr;
595 	struct rtentry *rt = NULL;
596 	struct llinfo_nd6 *ln = NULL;
597 
598 	mtx_lock(&nd6_mtx);
599 
600 	/*
601 	 * Search for a (probably) reachable router from the list.
602 	 */
603 	for (dr = TAILQ_FIRST(&nd_defrouter); dr;
604 	     dr = TAILQ_NEXT(dr, dr_entry)) {
605 		if ((rt = nd6_lookup(&dr->rtaddr, 0, dr->ifp)) &&
606 		    (ln = (struct llinfo_nd6 *)rt->rt_llinfo) &&
607 		    ND6_IS_LLINFO_PROBREACH(ln)) {
608 			/* Got it, and move it to the head */
609 			TAILQ_REMOVE(&nd_defrouter, dr, dr_entry);
610 			TAILQ_INSERT_HEAD(&nd_defrouter, dr, dr_entry);
611 			break;
612 		}
613 	}
614 
615 	if ((dr = TAILQ_FIRST(&nd_defrouter))) {
616 		/*
617 		 * De-install the previous default gateway and install
618 		 * a new one.
619 		 * Note that if there is no reachable router in the list,
620 		 * the head entry will be used anyway.
621 		 * XXX: do we have to check the current routing table entry?
622 		 */
623 		bzero(&anydr, sizeof(anydr));
624 		defrouter_delreq(&anydr, 0);
625 		defrouter_addreq(dr);
626 	}
627 	else {
628 		/*
629 		 * The Default Router List is empty, so install the default
630 		 * route to an inteface.
631 		 * XXX: The specification does not say this mechanism should
632 		 * be restricted to hosts, but this would be not useful
633 		 * (even harmful) for routers.
634 		 */
635 		if (!ip6_forwarding) {
636 			/*
637 			 * De-install the current default route
638 			 * in advance.
639 			 */
640 			bzero(&anydr, sizeof(anydr));
641 			defrouter_delreq(&anydr, 0);
642 			if (nd6_defifp) {
643 				/*
644 				 * Install a route to the default interface
645 				 * as default route.
646 				 * XXX: we enable this for host only, because
647 				 * this may override a default route installed
648 				 * a user process (e.g. routing daemon) in a
649 				 * router case.
650 				 */
651 				defrouter_addifreq(nd6_defifp);
652 			} else {
653 				nd6log((LOG_INFO, "defrouter_select: "
654 				    "there's no default router and no default"
655 				    " interface\n"));
656 			}
657 		}
658 	}
659 	mtx_unlock(&nd6_mtx);
660 	return;
661 }
662 
663 static struct nd_defrouter *
664 defrtrlist_update(struct nd_defrouter *new)
665 {
666 	struct nd_defrouter *dr, *n;
667 
668 	mtx_lock(&nd6_mtx);
669 
670 	if ((dr = defrouter_lookup(&new->rtaddr, new->ifp)) != NULL) {
671 		/* entry exists */
672 		if (new->rtlifetime == 0) {
673 			defrtrlist_del(dr);
674 			dr = NULL;
675 		} else {
676 			/* override */
677 			dr->flags = new->flags; /* xxx flag check */
678 			dr->rtlifetime = new->rtlifetime;
679 			dr->expire = new->expire;
680 		}
681 		mtx_unlock(&nd6_mtx);
682 		return (dr);
683 	}
684 
685 	/* entry does not exist */
686 	if (new->rtlifetime == 0) {
687 		mtx_unlock(&nd6_mtx);
688 		return (NULL);
689 	}
690 
691 	n = (struct nd_defrouter *)kmalloc(sizeof(*n), M_IP6NDP,
692 	    M_NOWAIT | M_ZERO);
693 	if (n == NULL) {
694 		mtx_unlock(&nd6_mtx);
695 		return (NULL);
696 	}
697 	*n = *new;
698 
699 	/*
700 	 * Insert the new router at the end of the Default Router List.
701 	 * If there is no other router, install it anyway. Otherwise,
702 	 * just continue to use the current default router.
703 	 */
704 	TAILQ_INSERT_TAIL(&nd_defrouter, n, dr_entry);
705 	if (TAILQ_FIRST(&nd_defrouter) == n)
706 		defrouter_select();
707 	mtx_unlock(&nd6_mtx);
708 	return (n);
709 }
710 
711 static struct nd_pfxrouter *
712 pfxrtr_lookup(struct nd_prefix *pr, struct nd_defrouter *dr)
713 {
714 	struct nd_pfxrouter *search;
715 
716 	for (search = pr->ndpr_advrtrs.lh_first; search; search = search->pfr_next) {
717 		if (search->router == dr)
718 			break;
719 	}
720 
721 	return (search);
722 }
723 
724 static void
725 pfxrtr_add(struct nd_prefix *pr, struct nd_defrouter *dr)
726 {
727 	struct nd_pfxrouter *new;
728 
729 	new = kmalloc(sizeof(*new), M_IP6NDP, M_INTWAIT | M_ZERO);
730 	new->router = dr;
731 
732 	LIST_INSERT_HEAD(&pr->ndpr_advrtrs, new, pfr_entry);
733 
734 	pfxlist_onlink_check();
735 }
736 
737 static void
738 pfxrtr_del(struct nd_pfxrouter *pfr)
739 {
740 	LIST_REMOVE(pfr, pfr_entry);
741 	kfree(pfr, M_IP6NDP);
742 }
743 
744 struct nd_prefix *
745 nd6_prefix_lookup(struct nd_prefix *pr)
746 {
747 	struct nd_prefix *search;
748 
749 	for (search = nd_prefix.lh_first; search; search = search->ndpr_next) {
750 		if (pr->ndpr_ifp == search->ndpr_ifp &&
751 		    pr->ndpr_plen == search->ndpr_plen &&
752 		    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
753 		    &search->ndpr_prefix.sin6_addr, pr->ndpr_plen))
754 			break;
755 	}
756 
757 	return (search);
758 }
759 
760 int
761 nd6_prelist_add(struct nd_prefix *pr, struct nd_defrouter *dr,
762 		struct nd_prefix **newp)
763 {
764 	struct nd_prefix *new = NULL;
765 	int i;
766 
767 	new = kmalloc(sizeof(*new), M_IP6NDP, M_INTWAIT);
768 	*new = *pr;
769 	if (newp != NULL)
770 		*newp = new;
771 
772 	/* initialization */
773 	LIST_INIT(&new->ndpr_advrtrs);
774 	in6_prefixlen2mask(&new->ndpr_mask, new->ndpr_plen);
775 	/* make prefix in the canonical form */
776 	for (i = 0; i < 4; i++) {
777 		new->ndpr_prefix.sin6_addr.s6_addr32[i] &=
778 		    new->ndpr_mask.s6_addr32[i];
779 	}
780 
781 	mtx_lock(&nd6_mtx);
782 	/* link ndpr_entry to nd_prefix list */
783 	LIST_INSERT_HEAD(&nd_prefix, new, ndpr_entry);
784 	mtx_unlock(&nd6_mtx);
785 
786 	/* ND_OPT_PI_FLAG_ONLINK processing */
787 	if (new->ndpr_raf_onlink) {
788 		int e;
789 
790 		if ((e = nd6_prefix_onlink(new)) != 0) {
791 			nd6log((LOG_ERR, "nd6_prelist_add: failed to make "
792 			    "the prefix %s/%d on-link on %s (errno=%d)\n",
793 			    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
794 			    pr->ndpr_plen, if_name(pr->ndpr_ifp), e));
795 			/* proceed anyway. XXX: is it correct? */
796 		}
797 	}
798 
799 	if (dr)
800 		pfxrtr_add(new, dr);
801 
802 	return 0;
803 }
804 
805 void
806 prelist_remove(struct nd_prefix *pr)
807 {
808 	struct nd_pfxrouter *pfr, *next;
809 	int e;
810 
811 	/* make sure to invalidate the prefix until it is really freed. */
812 	pr->ndpr_vltime = 0;
813 	pr->ndpr_pltime = 0;
814 #if 0
815 	/*
816 	 * Though these flags are now meaningless, we'd rather keep the value
817 	 * not to confuse users when executing "ndp -p".
818 	 */
819 	pr->ndpr_raf_onlink = 0;
820 	pr->ndpr_raf_auto = 0;
821 #endif
822 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) &&
823 	    (e = nd6_prefix_offlink(pr)) != 0) {
824 		nd6log((LOG_ERR, "prelist_remove: failed to make %s/%d offlink "
825 		    "on %s, errno=%d\n",
826 		    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
827 		    pr->ndpr_plen, if_name(pr->ndpr_ifp), e));
828 		/* what should we do? */
829 	}
830 
831 	if (pr->ndpr_refcnt > 0)
832 		return;		/* notice here? */
833 
834 	mtx_lock(&nd6_mtx);
835 
836 	/* unlink ndpr_entry from nd_prefix list */
837 	LIST_REMOVE(pr, ndpr_entry);
838 
839 	/* free list of routers that adversed the prefix */
840 	for (pfr = pr->ndpr_advrtrs.lh_first; pfr; pfr = next) {
841 		next = pfr->pfr_next;
842 
843 		kfree(pfr, M_IP6NDP);
844 	}
845 	mtx_unlock(&nd6_mtx);
846 
847 	kfree(pr, M_IP6NDP);
848 
849 	pfxlist_onlink_check();
850 }
851 
852 /*
853  * Parameters:
854  *	dr:	may be NULL
855  */
856 int
857 prelist_update(struct nd_prefix *new, struct nd_defrouter *dr, struct mbuf *m)
858 {
859 	struct in6_ifaddr *ia6 = NULL, *ia6_match = NULL;
860 	struct ifaddr_container *ifac;
861 	struct ifnet *ifp = new->ndpr_ifp;
862 	struct nd_prefix *pr;
863 	int error = 0;
864 	int auth;
865 	struct in6_addrlifetime lt6_tmp;
866 
867 	auth = 0;
868 	mtx_lock(&nd6_mtx);
869 	if (m) {
870 		/*
871 		 * Authenticity for NA consists authentication for
872 		 * both IP header and IP datagrams, doesn't it ?
873 		 */
874 #if defined(M_AUTHIPHDR) && defined(M_AUTHIPDGM)
875 		auth = ((m->m_flags & M_AUTHIPHDR) &&
876 		    (m->m_flags & M_AUTHIPDGM));
877 #endif
878 	}
879 
880 	if ((pr = nd6_prefix_lookup(new)) != NULL) {
881 		/*
882 		 * nd6_prefix_lookup() ensures that pr and new have the same
883 		 * prefix on a same interface.
884 		 */
885 
886 		/*
887 		 * Update prefix information.  Note that the on-link (L) bit
888 		 * and the autonomous (A) bit should NOT be changed from 1
889 		 * to 0.
890 		 */
891 		if (new->ndpr_raf_onlink == 1)
892 			pr->ndpr_raf_onlink = 1;
893 		if (new->ndpr_raf_auto == 1)
894 			pr->ndpr_raf_auto = 1;
895 		if (new->ndpr_raf_onlink) {
896 			pr->ndpr_vltime = new->ndpr_vltime;
897 			pr->ndpr_pltime = new->ndpr_pltime;
898 			pr->ndpr_preferred = new->ndpr_preferred;
899 			pr->ndpr_expire = new->ndpr_expire;
900 		}
901 
902 		if (new->ndpr_raf_onlink &&
903 		    !(pr->ndpr_stateflags & NDPRF_ONLINK)) {
904 			int e;
905 
906 			if ((e = nd6_prefix_onlink(pr)) != 0) {
907 				nd6log((LOG_ERR,
908 				    "prelist_update: failed to make "
909 				    "the prefix %s/%d on-link on %s "
910 				    "(errno=%d)\n",
911 				    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
912 				    pr->ndpr_plen, if_name(pr->ndpr_ifp), e));
913 				/* proceed anyway. XXX: is it correct? */
914 			}
915 		}
916 
917 		if (dr && pfxrtr_lookup(pr, dr) == NULL)
918 			pfxrtr_add(pr, dr);
919 	} else {
920 		struct nd_prefix *newpr = NULL;
921 
922 		if (new->ndpr_vltime == 0)
923 			goto end;
924 		if (new->ndpr_raf_onlink == 0 && new->ndpr_raf_auto == 0)
925 			goto end;
926 
927 		bzero(&new->ndpr_addr, sizeof(struct in6_addr));
928 
929 		error = nd6_prelist_add(new, dr, &newpr);
930 		if (error != 0 || newpr == NULL) {
931 			nd6log((LOG_NOTICE, "prelist_update: "
932 			    "nd6_prelist_add failed for %s/%d on %s "
933 			    "errno=%d, returnpr=%p\n",
934 			    ip6_sprintf(&new->ndpr_prefix.sin6_addr),
935 			    new->ndpr_plen, if_name(new->ndpr_ifp),
936 			    error, newpr));
937 			goto end; /* we should just give up in this case. */
938 		}
939 
940 		/*
941 		 * XXX: from the ND point of view, we can ignore a prefix
942 		 * with the on-link bit being zero.  However, we need a
943 		 * prefix structure for references from autoconfigured
944 		 * addresses.  Thus, we explicitly make sure that the prefix
945 		 * itself expires now.
946 		 */
947 		if (newpr->ndpr_raf_onlink == 0) {
948 			newpr->ndpr_vltime = 0;
949 			newpr->ndpr_pltime = 0;
950 			in6_init_prefix_ltimes(newpr);
951 		}
952 
953 		pr = newpr;
954 	}
955 
956 	/*
957 	 * Address autoconfiguration based on Section 5.5.3 of RFC 2462.
958 	 * Note that pr must be non NULL at this point.
959 	 */
960 
961 	/* 5.5.3 (a). Ignore the prefix without the A bit set. */
962 	if (!new->ndpr_raf_auto)
963 		goto afteraddrconf;
964 
965 	/*
966 	 * 5.5.3 (b). the link-local prefix should have been ignored in
967 	 * nd6_ra_input.
968 	 */
969 
970 	/*
971 	 * 5.5.3 (c). Consistency check on lifetimes: pltime <= vltime.
972 	 * This should have been done in nd6_ra_input.
973 	 */
974 
975  	/*
976 	 * 5.5.3 (d). If the prefix advertised does not match the prefix of an
977 	 * address already in the list, and the Valid Lifetime is not 0,
978 	 * form an address.  Note that even a manually configured address
979 	 * should reject autoconfiguration of a new address.
980 	 */
981 	TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
982 		struct ifaddr *ifa = ifac->ifa;
983 		struct in6_ifaddr *ifa6;
984 		int ifa_plen;
985 		u_int32_t storedlifetime;
986 
987 		if (ifa->ifa_addr->sa_family != AF_INET6)
988 			continue;
989 
990 		ifa6 = (struct in6_ifaddr *)ifa;
991 
992 		/*
993 		 * Spec is not clear here, but I believe we should concentrate
994 		 * on unicast (i.e. not anycast) addresses.
995 		 * XXX: other ia6_flags? detached or duplicated?
996 		 */
997 		if (ifa6->ia6_flags & IN6_IFF_ANYCAST)
998 			continue;
999 
1000 		ifa_plen = in6_mask2len(&ifa6->ia_prefixmask.sin6_addr, NULL);
1001 		if (ifa_plen != new->ndpr_plen ||
1002 		    !in6_are_prefix_equal(&ifa6->ia_addr.sin6_addr,
1003 		    &new->ndpr_prefix.sin6_addr, ifa_plen))
1004 			continue;
1005 
1006 		if (ia6_match == NULL) /* remember the first one */
1007 			ia6_match = ifa6;
1008 
1009 		if (!(ifa6->ia6_flags & IN6_IFF_AUTOCONF))
1010 			continue;
1011 
1012 		/*
1013 		 * An already autoconfigured address matched.  Now that we
1014 		 * are sure there is at least one matched address, we can
1015 		 * proceed to 5.5.3. (e): update the lifetimes according to the
1016 		 * "two hours" rule and the privacy extension.
1017 		 */
1018 #define TWOHOUR		(120*60)
1019 		lt6_tmp = ifa6->ia6_lifetime;
1020 
1021 		if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME)
1022 			storedlifetime = ND6_INFINITE_LIFETIME;
1023 		else if (IFA6_IS_INVALID(ifa6))
1024 			storedlifetime = 0;
1025 		else
1026 			storedlifetime = lt6_tmp.ia6t_expire - time_uptime;
1027 
1028 		/* when not updating, keep the current stored lifetime. */
1029 		lt6_tmp.ia6t_vltime = storedlifetime;
1030 
1031 		if (TWOHOUR < new->ndpr_vltime ||
1032 		    storedlifetime < new->ndpr_vltime) {
1033 			lt6_tmp.ia6t_vltime = new->ndpr_vltime;
1034 		} else if (storedlifetime <= TWOHOUR
1035 #if 0
1036 			   /*
1037 			    * This condition is logically redundant, so we just
1038 			    * omit it.
1039 			    * See IPng 6712, 6717, and 6721.
1040 			    */
1041 			   && new->ndpr_vltime <= storedlifetime
1042 #endif
1043 			) {
1044 			if (auth) {
1045 				lt6_tmp.ia6t_vltime = new->ndpr_vltime;
1046 			}
1047 		} else {
1048 			/*
1049 			 * new->ndpr_vltime <= TWOHOUR &&
1050 			 * TWOHOUR < storedlifetime
1051 			 */
1052 			lt6_tmp.ia6t_vltime = TWOHOUR;
1053 		}
1054 
1055 		/* The 2 hour rule is not imposed for preferred lifetime. */
1056 		lt6_tmp.ia6t_pltime = new->ndpr_pltime;
1057 
1058 		in6_init_address_ltimes(pr, &lt6_tmp);
1059 
1060 		/*
1061 		 * When adjusting the lifetimes of an existing temporary
1062 		 * address, only lower the lifetimes.
1063 		 * RFC 3041 3.3. (1).
1064 		 * XXX: how should we modify ia6t_[pv]ltime?
1065 		 */
1066 		if (ifa6->ia6_flags & IN6_IFF_TEMPORARY) {
1067 			if (lt6_tmp.ia6t_expire == 0 || /* no expire */
1068 			    lt6_tmp.ia6t_expire >
1069 			    ifa6->ia6_lifetime.ia6t_expire) {
1070 				lt6_tmp.ia6t_expire =
1071 				    ifa6->ia6_lifetime.ia6t_expire;
1072 			}
1073 			if (lt6_tmp.ia6t_preferred == 0 || /* no expire */
1074 			    lt6_tmp.ia6t_preferred >
1075 			    ifa6->ia6_lifetime.ia6t_preferred) {
1076 				lt6_tmp.ia6t_preferred =
1077 				    ifa6->ia6_lifetime.ia6t_preferred;
1078 			}
1079 		}
1080 
1081 		ifa6->ia6_lifetime = lt6_tmp;
1082 	}
1083 	if (ia6_match == NULL && new->ndpr_vltime) {
1084 		/*
1085 		 * No address matched and the valid lifetime is non-zero.
1086 		 * Create a new address.
1087 		 */
1088 		if ((ia6 = in6_ifadd(new, NULL)) != NULL) {
1089 			/*
1090 			 * note that we should use pr (not new) for reference.
1091 			 */
1092 			pr->ndpr_refcnt++;
1093 			ia6->ia6_ndpr = pr;
1094 
1095 			/*
1096 			 * RFC 3041 3.3 (2).
1097 			 * When a new public address is created as described
1098 			 * in RFC2462, also create a new temporary address.
1099 			 *
1100 			 * RFC 3041 3.5.
1101 			 * When an interface connects to a new link, a new
1102 			 * randomized interface identifier should be generated
1103 			 * immediately together with a new set of temporary
1104 			 * addresses.  Thus, we specifiy 1 as the 2nd arg of
1105 			 * in6_tmpifadd().
1106 			 */
1107 			if (ip6_use_tempaddr) {
1108 				int e;
1109 				if ((e = in6_tmpifadd(ia6, 1)) != 0) {
1110 					nd6log((LOG_NOTICE, "prelist_update: "
1111 					    "failed to create a temporary "
1112 					    "address, errno=%d\n",
1113 					    e));
1114 				}
1115 			}
1116 
1117 			/*
1118 			 * A newly added address might affect the status
1119 			 * of other addresses, so we check and update it.
1120 			 * XXX: what if address duplication happens?
1121 			 */
1122 			pfxlist_onlink_check();
1123 		} else {
1124 			/* just set an error. do not bark here. */
1125 			error = EADDRNOTAVAIL; /* XXX: might be unused. */
1126 		}
1127 	}
1128 
1129 afteraddrconf:
1130 
1131 end:
1132 	mtx_unlock(&nd6_mtx);
1133 	return error;
1134 }
1135 
1136 /*
1137  * A supplement function used in the on-link detection below;
1138  * detect if a given prefix has a (probably) reachable advertising router.
1139  * XXX: lengthy function name...
1140  */
1141 static struct nd_pfxrouter *
1142 find_pfxlist_reachable_router(struct nd_prefix *pr)
1143 {
1144 	struct nd_pfxrouter *pfxrtr;
1145 	struct rtentry *rt;
1146 	struct llinfo_nd6 *ln;
1147 
1148 	for (pfxrtr = LIST_FIRST(&pr->ndpr_advrtrs); pfxrtr;
1149 	     pfxrtr = LIST_NEXT(pfxrtr, pfr_entry)) {
1150 		if ((rt = nd6_lookup(&pfxrtr->router->rtaddr, 0,
1151 		    pfxrtr->router->ifp)) &&
1152 		    (ln = (struct llinfo_nd6 *)rt->rt_llinfo) &&
1153 		    ND6_IS_LLINFO_PROBREACH(ln))
1154 			break;	/* found */
1155 	}
1156 
1157 	return (pfxrtr);
1158 }
1159 
1160 /*
1161  * Check if each prefix in the prefix list has at least one available router
1162  * that advertised the prefix (a router is "available" if its neighbor cache
1163  * entry is reachable or probably reachable).
1164  * If the check fails, the prefix may be off-link, because, for example,
1165  * we have moved from the network but the lifetime of the prefix has not
1166  * expired yet.  So we should not use the prefix if there is another prefix
1167  * that has an available router.
1168  * But, if there is no prefix that has an available router, we still regards
1169  * all the prefixes as on-link.  This is because we can't tell if all the
1170  * routers are simply dead or if we really moved from the network and there
1171  * is no router around us.
1172  */
1173 void
1174 pfxlist_onlink_check(void)
1175 {
1176 	struct nd_prefix *pr;
1177 	struct in6_ifaddr *ifa;
1178 
1179 	/*
1180 	 * Check if there is a prefix that has a reachable advertising
1181 	 * router.
1182 	 */
1183 	for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
1184 		if (pr->ndpr_raf_onlink && find_pfxlist_reachable_router(pr))
1185 			break;
1186 	}
1187 
1188 	if (pr) {
1189 		/*
1190 		 * There is at least one prefix that has a reachable router.
1191 		 * Detach prefixes which have no reachable advertising
1192 		 * router, and attach other prefixes.
1193 		 */
1194 		for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
1195 			/* XXX: a link-local prefix should never be detached */
1196 			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1197 				continue;
1198 
1199 			/*
1200 			 * we aren't interested in prefixes without the L bit
1201 			 * set.
1202 			 */
1203 			if (pr->ndpr_raf_onlink == 0)
1204 				continue;
1205 
1206 			if (!(pr->ndpr_stateflags & NDPRF_DETACHED) &&
1207 			    find_pfxlist_reachable_router(pr) == NULL)
1208 				pr->ndpr_stateflags |= NDPRF_DETACHED;
1209 			if ((pr->ndpr_stateflags & NDPRF_DETACHED) &&
1210 			    find_pfxlist_reachable_router(pr) != NULL)
1211 				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
1212 		}
1213 	} else {
1214 		/* there is no prefix that has a reachable router */
1215 		for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
1216 			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1217 				continue;
1218 
1219 			if (pr->ndpr_raf_onlink == 0)
1220 				continue;
1221 
1222 			if (pr->ndpr_stateflags & NDPRF_DETACHED)
1223 				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
1224 		}
1225 	}
1226 
1227 	/*
1228 	 * Remove each interface route associated with a (just) detached
1229 	 * prefix, and reinstall the interface route for a (just) attached
1230 	 * prefix.  Note that all attempt of reinstallation does not
1231 	 * necessarily success, when a same prefix is shared among multiple
1232 	 * interfaces.  Such cases will be handled in nd6_prefix_onlink,
1233 	 * so we don't have to care about them.
1234 	 */
1235 	for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
1236 		int e;
1237 
1238 		if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1239 			continue;
1240 
1241 		if (pr->ndpr_raf_onlink == 0)
1242 			continue;
1243 
1244 		if ((pr->ndpr_stateflags & NDPRF_DETACHED) &&
1245 		    (pr->ndpr_stateflags & NDPRF_ONLINK)) {
1246 			if ((e = nd6_prefix_offlink(pr)) != 0) {
1247 				nd6log((LOG_ERR,
1248 				    "pfxlist_onlink_check: failed to "
1249 				    "make %s/%d offlink, errno=%d\n",
1250 				    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
1251 				    pr->ndpr_plen, e));
1252 			}
1253 		}
1254 		if (!(pr->ndpr_stateflags & NDPRF_DETACHED) &&
1255 		    !(pr->ndpr_stateflags & NDPRF_ONLINK) &&
1256 		    pr->ndpr_raf_onlink) {
1257 			if ((e = nd6_prefix_onlink(pr)) != 0) {
1258 				nd6log((LOG_ERR,
1259 				    "pfxlist_onlink_check: failed to "
1260 				    "make %s/%d offlink, errno=%d\n",
1261 				    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
1262 				    pr->ndpr_plen, e));
1263 			}
1264 		}
1265 	}
1266 
1267 	/*
1268 	 * Changes on the prefix status might affect address status as well.
1269 	 * Make sure that all addresses derived from an attached prefix are
1270 	 * attached, and that all addresses derived from a detached prefix are
1271 	 * detached.  Note, however, that a manually configured address should
1272 	 * always be attached.
1273 	 * The precise detection logic is same as the one for prefixes.
1274 	 */
1275 	for (ifa = in6_ifaddr; ifa; ifa = ifa->ia_next) {
1276 		if (!(ifa->ia6_flags & IN6_IFF_AUTOCONF))
1277 			continue;
1278 
1279 		if (ifa->ia6_ndpr == NULL) {
1280 			/*
1281 			 * This can happen when we first configure the address
1282 			 * (i.e. the address exists, but the prefix does not).
1283 			 * XXX: complicated relationships...
1284 			 */
1285 			continue;
1286 		}
1287 
1288 		if (find_pfxlist_reachable_router(ifa->ia6_ndpr))
1289 			break;
1290 	}
1291 	if (ifa) {
1292 		for (ifa = in6_ifaddr; ifa; ifa = ifa->ia_next) {
1293 			if (!(ifa->ia6_flags & IN6_IFF_AUTOCONF))
1294 				continue;
1295 
1296 			if (ifa->ia6_ndpr == NULL) /* XXX: see above. */
1297 				continue;
1298 
1299 			if (find_pfxlist_reachable_router(ifa->ia6_ndpr)) {
1300 				if (ifa->ia6_flags & IN6_IFF_DETACHED) {
1301 					ifa->ia6_flags &= ~IN6_IFF_DETACHED;
1302 					ifa->ia6_flags |= IN6_IFF_TENTATIVE;
1303 					nd6_dad_start((struct ifaddr *)ifa, 0);
1304 				}
1305 			} else {
1306 				if ((ifa->ia6_flags & IN6_IFF_DETACHED) == 0) {
1307 					ifa->ia6_flags |= IN6_IFF_DETACHED;
1308 					in6_newaddrmsg((struct ifaddr *)ifa);
1309 				}
1310 			}
1311 		}
1312 	}
1313 	else {
1314 		for (ifa = in6_ifaddr; ifa; ifa = ifa->ia_next) {
1315 			if (!(ifa->ia6_flags & IN6_IFF_AUTOCONF))
1316 				continue;
1317 
1318 			ifa->ia6_flags &= ~IN6_IFF_DETACHED;
1319 			ifa->ia6_flags |= IN6_IFF_TENTATIVE;
1320 			nd6_dad_start((struct ifaddr *)ifa, 0);
1321 		}
1322 	}
1323 }
1324 
1325 int
1326 nd6_prefix_onlink(struct nd_prefix *pr)
1327 {
1328 	struct ifaddr *ifa;
1329 	struct ifnet *ifp = pr->ndpr_ifp;
1330 	struct sockaddr_in6 mask6;
1331 	struct nd_prefix *opr;
1332 	u_long rtflags;
1333 	int error = 0;
1334 
1335 	/* sanity check */
1336 	if (pr->ndpr_stateflags & NDPRF_ONLINK) {
1337 		nd6log((LOG_ERR,
1338 		    "nd6_prefix_onlink: %s/%d is already on-link\n",
1339 		    ip6_sprintf(&pr->ndpr_prefix.sin6_addr), pr->ndpr_plen);
1340 		return (EEXIST));
1341 	}
1342 
1343 	/*
1344 	 * Add the interface route associated with the prefix.  Before
1345 	 * installing the route, check if there's the same prefix on another
1346 	 * interface, and the prefix has already installed the interface route.
1347 	 * Although such a configuration is expected to be rare, we explicitly
1348 	 * allow it.
1349 	 */
1350 	for (opr = nd_prefix.lh_first; opr; opr = opr->ndpr_next) {
1351 		if (opr == pr)
1352 			continue;
1353 
1354 		if (!(opr->ndpr_stateflags & NDPRF_ONLINK))
1355 			continue;
1356 
1357 		if (opr->ndpr_plen == pr->ndpr_plen &&
1358 		    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
1359 		    &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen))
1360 			return (0);
1361 	}
1362 
1363 	/*
1364 	 * We prefer link-local addresses as the associated interface address.
1365 	 */
1366 	/* search for a link-local addr */
1367 	ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp,
1368 	    IN6_IFF_NOTREADY| IN6_IFF_ANYCAST);
1369 	if (ifa == NULL) {
1370 		struct ifaddr_container *ifac;
1371 
1372 		/* XXX: freebsd does not have ifa_ifwithaf */
1373 		TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1374 			if (ifac->ifa->ifa_addr->sa_family == AF_INET6) {
1375 				ifa = ifac->ifa;
1376 				break;
1377 			}
1378 		}
1379 		/* should we care about ia6_flags? */
1380 	}
1381 	if (ifa == NULL) {
1382 		/*
1383 		 * This can still happen, when, for example, we receive an RA
1384 		 * containing a prefix with the L bit set and the A bit clear,
1385 		 * after removing all IPv6 addresses on the receiving
1386 		 * interface.  This should, of course, be rare though.
1387 		 */
1388 		nd6log((LOG_NOTICE,
1389 		    "nd6_prefix_onlink: failed to find any ifaddr"
1390 		    " to add route for a prefix(%s/%d) on %s\n",
1391 		    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
1392 		    pr->ndpr_plen, if_name(ifp)));
1393 		return (0);
1394 	}
1395 
1396 	/*
1397 	 * in6_ifinit() sets nd6_rtrequest to ifa_rtrequest for all ifaddrs.
1398 	 * ifa->ifa_rtrequest = nd6_rtrequest;
1399 	 */
1400 	bzero(&mask6, sizeof(mask6));
1401 	mask6.sin6_len = sizeof(mask6);
1402 	mask6.sin6_addr = pr->ndpr_mask;
1403 	rtflags = ifa->ifa_flags | RTF_CLONING | RTF_UP;
1404 	if (nd6_need_cache(ifp)) {
1405 		/* explicitly set in case ifa_flags does not set the flag. */
1406 		rtflags |= RTF_CLONING;
1407 	} else {
1408 		/*
1409 		 * explicitly clear the cloning bit in case ifa_flags sets it.
1410 		 */
1411 		rtflags &= ~RTF_CLONING;
1412 	}
1413 	error = rtrequest_global(RTM_ADD, (struct sockaddr *)&pr->ndpr_prefix,
1414 	    ifa->ifa_addr, (struct sockaddr *)&mask6, rtflags);
1415 	if (error == 0) {
1416 		pr->ndpr_stateflags |= NDPRF_ONLINK;
1417 	} else {
1418 		nd6log((LOG_ERR, "nd6_prefix_onlink: failed to add route for a"
1419 		    " prefix (%s/%d) on %s, gw=%s, mask=%s, flags=%lx "
1420 		    "errno = %d\n",
1421 		    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
1422 		    pr->ndpr_plen, if_name(ifp),
1423 		    ip6_sprintf(&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr),
1424 		    ip6_sprintf(&mask6.sin6_addr), rtflags, error));
1425 	}
1426 	return (error);
1427 }
1428 
1429 int
1430 nd6_prefix_offlink(struct nd_prefix *pr)
1431 {
1432 	int error = 0;
1433 	struct ifnet *ifp = pr->ndpr_ifp;
1434 	struct nd_prefix *opr;
1435 	struct sockaddr_in6 sa6, mask6;
1436 
1437 	/* sanity check */
1438 	if (!(pr->ndpr_stateflags & NDPRF_ONLINK)) {
1439 		nd6log((LOG_ERR,
1440 		    "nd6_prefix_offlink: %s/%d is already off-link\n",
1441 		    ip6_sprintf(&pr->ndpr_prefix.sin6_addr), pr->ndpr_plen));
1442 		return (EEXIST);
1443 	}
1444 
1445 	bzero(&sa6, sizeof(sa6));
1446 	sa6.sin6_family = AF_INET6;
1447 	sa6.sin6_len = sizeof(sa6);
1448 	bcopy(&pr->ndpr_prefix.sin6_addr, &sa6.sin6_addr,
1449 	    sizeof(struct in6_addr));
1450 	bzero(&mask6, sizeof(mask6));
1451 	mask6.sin6_family = AF_INET6;
1452 	mask6.sin6_len = sizeof(sa6);
1453 	bcopy(&pr->ndpr_mask, &mask6.sin6_addr, sizeof(struct in6_addr));
1454 	error = rtrequest_global(RTM_DELETE, (struct sockaddr *)&sa6, NULL,
1455 	    (struct sockaddr *)&mask6, 0);
1456 	if (error == 0) {
1457 		pr->ndpr_stateflags &= ~NDPRF_ONLINK;
1458 
1459 		/*
1460 		 * There might be the same prefix on another interface,
1461 		 * the prefix which could not be on-link just because we have
1462 		 * the interface route (see comments in nd6_prefix_onlink).
1463 		 * If there's one, try to make the prefix on-link on the
1464 		 * interface.
1465 		 */
1466 		for (opr = nd_prefix.lh_first; opr; opr = opr->ndpr_next) {
1467 			if (opr == pr)
1468 				continue;
1469 
1470 			if (opr->ndpr_stateflags & NDPRF_ONLINK)
1471 				continue;
1472 
1473 			/*
1474 			 * KAME specific: detached prefixes should not be
1475 			 * on-link.
1476 			 */
1477 			if (opr->ndpr_stateflags & NDPRF_DETACHED)
1478 				continue;
1479 
1480 			if (opr->ndpr_plen == pr->ndpr_plen &&
1481 			    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
1482 			    &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen)) {
1483 				int e;
1484 
1485 				if ((e = nd6_prefix_onlink(opr)) != 0) {
1486 					nd6log((LOG_ERR,
1487 					    "nd6_prefix_offlink: failed to "
1488 					    "recover a prefix %s/%d from %s "
1489 					    "to %s (errno = %d)\n",
1490 					    ip6_sprintf(&opr->ndpr_prefix.sin6_addr),
1491 					    opr->ndpr_plen, if_name(ifp),
1492 					    if_name(opr->ndpr_ifp), e));
1493 				}
1494 			}
1495 		}
1496 	} else {
1497 		/* XXX: can we still set the NDPRF_ONLINK flag? */
1498 		nd6log((LOG_ERR,
1499 		    "nd6_prefix_offlink: failed to delete route: "
1500 		    "%s/%d on %s (errno = %d)\n",
1501 		    ip6_sprintf(&sa6.sin6_addr), pr->ndpr_plen, if_name(ifp),
1502 		    error));
1503 	}
1504 
1505 	return (error);
1506 }
1507 
1508 /*
1509  * Parameters:
1510  *	ifid:	Mobile IPv6 addition
1511  */
1512 static struct in6_ifaddr *
1513 in6_ifadd(struct nd_prefix *pr, struct in6_addr *ifid)
1514 {
1515 	struct ifnet *ifp = pr->ndpr_ifp;
1516 	struct ifaddr *ifa;
1517 	struct in6_aliasreq ifra;
1518 	struct in6_ifaddr *ia, *ib;
1519 	int error, plen0;
1520 	struct in6_addr mask;
1521 	int prefixlen = pr->ndpr_plen;
1522 
1523 	in6_prefixlen2mask(&mask, prefixlen);
1524 
1525 	/*
1526 	 * find a link-local address (will be interface ID).
1527 	 * Is it really mandatory? Theoretically, a global or a site-local
1528 	 * address can be configured without a link-local address, if we
1529 	 * have a unique interface identifier...
1530 	 *
1531 	 * it is not mandatory to have a link-local address, we can generate
1532 	 * interface identifier on the fly.  we do this because:
1533 	 * (1) it should be the easiest way to find interface identifier.
1534 	 * (2) RFC2462 5.4 suggesting the use of the same interface identifier
1535 	 * for multiple addresses on a single interface, and possible shortcut
1536 	 * of DAD.  we omitted DAD for this reason in the past.
1537 	 * (3) a user can prevent autoconfiguration of global address
1538 	 * by removing link-local address by hand (this is partly because we
1539 	 * don't have other way to control the use of IPv6 on a interface.
1540 	 * this has been our design choice - cf. NRL's "ifconfig auto").
1541 	 * (4) it is easier to manage when an interface has addresses
1542 	 * with the same interface identifier, than to have multiple addresses
1543 	 * with different interface identifiers.
1544 	 *
1545 	 * Mobile IPv6 addition: allow for caller to specify a wished interface
1546 	 * ID. This is to not break connections when moving addresses between
1547 	 * interfaces.
1548 	 */
1549 	ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp, 0); /* 0 is OK? */
1550 	if (ifa)
1551 		ib = (struct in6_ifaddr *)ifa;
1552 	else
1553 		return NULL;
1554 
1555 #if 0 /* don't care link local addr state, and always do DAD */
1556 	/* if link-local address is not eligible, do not autoconfigure. */
1557 	if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY) {
1558 		kprintf("in6_ifadd: link-local address not ready\n");
1559 		return NULL;
1560 	}
1561 #endif
1562 
1563 	/* prefixlen + ifidlen must be equal to 128 */
1564 	plen0 = in6_mask2len(&ib->ia_prefixmask.sin6_addr, NULL);
1565 	if (prefixlen != plen0) {
1566 		nd6log((LOG_INFO, "in6_ifadd: wrong prefixlen for %s "
1567 		    "(prefix=%d ifid=%d)\n",
1568 		    if_name(ifp), prefixlen, 128 - plen0));
1569 		return NULL;
1570 	}
1571 
1572 	/* make ifaddr */
1573 
1574 	bzero(&ifra, sizeof(ifra));
1575 	/*
1576 	 * in6_update_ifa() does not use ifra_name, but we accurately set it
1577 	 * for safety.
1578 	 */
1579 	strncpy(ifra.ifra_name, if_name(ifp), sizeof(ifra.ifra_name));
1580 	ifra.ifra_addr.sin6_family = AF_INET6;
1581 	ifra.ifra_addr.sin6_len = sizeof(struct sockaddr_in6);
1582 	/* prefix */
1583 	bcopy(&pr->ndpr_prefix.sin6_addr, &ifra.ifra_addr.sin6_addr,
1584 	    sizeof(ifra.ifra_addr.sin6_addr));
1585 	ifra.ifra_addr.sin6_addr.s6_addr32[0] &= mask.s6_addr32[0];
1586 	ifra.ifra_addr.sin6_addr.s6_addr32[1] &= mask.s6_addr32[1];
1587 	ifra.ifra_addr.sin6_addr.s6_addr32[2] &= mask.s6_addr32[2];
1588 	ifra.ifra_addr.sin6_addr.s6_addr32[3] &= mask.s6_addr32[3];
1589 
1590 	/* interface ID */
1591 	if (ifid == NULL || IN6_IS_ADDR_UNSPECIFIED(ifid))
1592 		ifid = &ib->ia_addr.sin6_addr;
1593 	ifra.ifra_addr.sin6_addr.s6_addr32[0] |=
1594 	    (ifid->s6_addr32[0] & ~mask.s6_addr32[0]);
1595 	ifra.ifra_addr.sin6_addr.s6_addr32[1] |=
1596 	    (ifid->s6_addr32[1] & ~mask.s6_addr32[1]);
1597 	ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
1598 	    (ifid->s6_addr32[2] & ~mask.s6_addr32[2]);
1599 	ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
1600 	    (ifid->s6_addr32[3] & ~mask.s6_addr32[3]);
1601 
1602 	/* new prefix mask. */
1603 	ifra.ifra_prefixmask.sin6_len = sizeof(struct sockaddr_in6);
1604 	ifra.ifra_prefixmask.sin6_family = AF_INET6;
1605 	bcopy(&mask, &ifra.ifra_prefixmask.sin6_addr,
1606 	    sizeof(ifra.ifra_prefixmask.sin6_addr));
1607 
1608 	/*
1609 	 * lifetime.
1610 	 * XXX: in6_init_address_ltimes would override these values later.
1611 	 * We should reconsider this logic.
1612 	 */
1613 	ifra.ifra_lifetime.ia6t_vltime = pr->ndpr_vltime;
1614 	ifra.ifra_lifetime.ia6t_pltime = pr->ndpr_pltime;
1615 
1616 	/* XXX: scope zone ID? */
1617 
1618 	ifra.ifra_flags |= IN6_IFF_AUTOCONF; /* obey autoconf */
1619 	/*
1620 	 * temporarily set the nopfx flag to avoid conflict.
1621 	 * XXX: we should reconsider the entire mechanism about prefix
1622 	 * manipulation.
1623 	 */
1624 	ifra.ifra_flags |= IN6_IFF_NOPFX;
1625 
1626 	/*
1627 	 * keep the new address, regardless of the result of in6_update_ifa.
1628 	 * XXX: this address is now meaningless.
1629 	 * We should reconsider its role.
1630 	 */
1631 	pr->ndpr_addr = ifra.ifra_addr.sin6_addr;
1632 
1633 	/* allocate ifaddr structure, link into chain, etc. */
1634 	if ((error = in6_update_ifa(ifp, &ifra, NULL)) != 0) {
1635 		nd6log((LOG_ERR,
1636 		    "in6_ifadd: failed to make ifaddr %s on %s (errno=%d)\n",
1637 		    ip6_sprintf(&ifra.ifra_addr.sin6_addr), if_name(ifp),
1638 		    error));
1639 		return (NULL);	/* ifaddr must not have been allocated. */
1640 	}
1641 
1642 	ia = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr);
1643 
1644 	return (ia);		/* this is always non-NULL */
1645 }
1646 
1647 /*
1648  * Parameters:
1649  *	ia0:	corresponding public address
1650  */
1651 int
1652 in6_tmpifadd(const struct in6_ifaddr *ia0, int forcegen)
1653 {
1654 	struct ifnet *ifp = ia0->ia_ifa.ifa_ifp;
1655 	struct in6_ifaddr *newia;
1656 	struct in6_aliasreq ifra;
1657 	int i, error;
1658 	int trylimit = 3;	/* XXX: adhoc value */
1659 	u_int32_t randid[2];
1660 	time_t vltime0, pltime0;
1661 
1662 	bzero(&ifra, sizeof(ifra));
1663 	strncpy(ifra.ifra_name, if_name(ifp), sizeof(ifra.ifra_name));
1664 	ifra.ifra_addr = ia0->ia_addr;
1665 	/* copy prefix mask */
1666 	ifra.ifra_prefixmask = ia0->ia_prefixmask;
1667 	/* clear the old IFID */
1668 	for (i = 0; i < 4; i++) {
1669 		ifra.ifra_addr.sin6_addr.s6_addr32[i] &=
1670 		    ifra.ifra_prefixmask.sin6_addr.s6_addr32[i];
1671 	}
1672 
1673 again:
1674 	in6_get_tmpifid(ifp, (u_int8_t *)randid,
1675 	    (const u_int8_t *)&ia0->ia_addr.sin6_addr.s6_addr[8], forcegen);
1676 	ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
1677 	    (randid[0] & ~(ifra.ifra_prefixmask.sin6_addr.s6_addr32[2]));
1678 	ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
1679 	    (randid[1] & ~(ifra.ifra_prefixmask.sin6_addr.s6_addr32[3]));
1680 
1681 	/*
1682 	 * If by chance the new temporary address is the same as an address
1683 	 * already assigned to the interface, generate a new randomized
1684 	 * interface identifier and repeat this step.
1685 	 * RFC 3041 3.3 (4).
1686 	 */
1687 	if (in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr) != NULL) {
1688 		if (trylimit-- == 0) {
1689 			nd6log((LOG_NOTICE, "in6_tmpifadd: failed to find "
1690 			    "a unique random IFID\n"));
1691 			return (EEXIST);
1692 		}
1693 		forcegen = 1;
1694 		goto again;
1695 	}
1696 
1697 	/*
1698 	 * The Valid Lifetime is the lower of the Valid Lifetime of the
1699          * public address or TEMP_VALID_LIFETIME.
1700 	 * The Preferred Lifetime is the lower of the Preferred Lifetime
1701          * of the public address or TEMP_PREFERRED_LIFETIME -
1702          * DESYNC_FACTOR.
1703 	 */
1704 	if (ia0->ia6_lifetime.ia6t_expire != 0) {
1705 		vltime0 = IFA6_IS_INVALID(ia0) ?
1706 		    0 : (ia0->ia6_lifetime.ia6t_expire - time_uptime);
1707 		if (vltime0 > ip6_temp_valid_lifetime)
1708 			vltime0 = ip6_temp_valid_lifetime;
1709 	} else
1710 		vltime0 = ip6_temp_valid_lifetime;
1711 	if (ia0->ia6_lifetime.ia6t_preferred != 0) {
1712 		pltime0 = IFA6_IS_DEPRECATED(ia0) ?
1713 		    0 : (ia0->ia6_lifetime.ia6t_preferred - time_uptime);
1714 		if (pltime0 > ip6_temp_preferred_lifetime - ip6_desync_factor) {
1715 			pltime0 = ip6_temp_preferred_lifetime -
1716 			    ip6_desync_factor;
1717 		}
1718 	} else
1719 		pltime0 = ip6_temp_preferred_lifetime - ip6_desync_factor;
1720 	ifra.ifra_lifetime.ia6t_vltime = vltime0;
1721 	ifra.ifra_lifetime.ia6t_pltime = pltime0;
1722 
1723 	/*
1724 	 * A temporary address is created only if this calculated Preferred
1725 	 * Lifetime is greater than REGEN_ADVANCE time units.
1726 	 */
1727 	if (ifra.ifra_lifetime.ia6t_pltime <= ip6_temp_regen_advance)
1728 		return (0);
1729 
1730 	/* XXX: scope zone ID? */
1731 
1732 	ifra.ifra_flags |= (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY);
1733 
1734 	/* allocate ifaddr structure, link into chain, etc. */
1735 	if ((error = in6_update_ifa(ifp, &ifra, NULL)) != 0)
1736 		return (error);
1737 
1738 	newia = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr);
1739 	if (newia == NULL) {	/* XXX: can it happen? */
1740 		nd6log((LOG_ERR,
1741 		    "in6_tmpifadd: ifa update succeeded, but we got "
1742 		    "no ifaddr\n"));
1743 		return (EINVAL); /* XXX */
1744 	}
1745 	newia->ia6_ndpr = ia0->ia6_ndpr;
1746 	newia->ia6_ndpr->ndpr_refcnt++;
1747 
1748 	return (0);
1749 }
1750 
1751 int
1752 in6_init_prefix_ltimes(struct nd_prefix *ndpr)
1753 {
1754 	/* check if preferred lifetime > valid lifetime.  RFC2462 5.5.3 (c) */
1755 	if (ndpr->ndpr_pltime > ndpr->ndpr_vltime) {
1756 		nd6log((LOG_INFO, "in6_init_prefix_ltimes: preferred lifetime"
1757 		    "(%d) is greater than valid lifetime(%d)\n",
1758 		    (u_int)ndpr->ndpr_pltime, (u_int)ndpr->ndpr_vltime));
1759 		return (EINVAL);
1760 	}
1761 	if (ndpr->ndpr_pltime == ND6_INFINITE_LIFETIME)
1762 		ndpr->ndpr_preferred = 0;
1763 	else
1764 		ndpr->ndpr_preferred = time_uptime + ndpr->ndpr_pltime;
1765 	if (ndpr->ndpr_vltime == ND6_INFINITE_LIFETIME)
1766 		ndpr->ndpr_expire = 0;
1767 	else
1768 		ndpr->ndpr_expire = time_uptime + ndpr->ndpr_vltime;
1769 
1770 	return 0;
1771 }
1772 
1773 static void
1774 in6_init_address_ltimes(struct nd_prefix *new, struct in6_addrlifetime *lt6)
1775 {
1776 	/* init ia6t_expire */
1777 	if (lt6->ia6t_vltime == ND6_INFINITE_LIFETIME)
1778 		lt6->ia6t_expire = 0;
1779 	else {
1780 		lt6->ia6t_expire = time_uptime;
1781 		lt6->ia6t_expire += lt6->ia6t_vltime;
1782 	}
1783 
1784 	/* init ia6t_preferred */
1785 	if (lt6->ia6t_pltime == ND6_INFINITE_LIFETIME)
1786 		lt6->ia6t_preferred = 0;
1787 	else {
1788 		lt6->ia6t_preferred = time_uptime;
1789 		lt6->ia6t_preferred += lt6->ia6t_pltime;
1790 	}
1791 }
1792 
1793 /*
1794  * Delete all the routing table entries that use the specified gateway.
1795  *
1796  * XXX: this function causes search through all entries of routing table, so
1797  * it shouldn't be called when acting as a router.
1798  */
1799 void
1800 rt6_flush(struct in6_addr *gateway, struct ifnet *ifp)
1801 {
1802 	struct radix_node_head *rnh = rt_tables[mycpuid][AF_INET6];
1803 
1804 	/* We'll care only link-local addresses */
1805 	if (!IN6_IS_ADDR_LINKLOCAL(gateway))
1806 		return;
1807 	/* XXX: hack for KAME's link-local address kludge */
1808 	gateway->s6_addr16[1] = htons(ifp->if_index);
1809 
1810 	rnh->rnh_walktree(rnh, rt6_deleteroute, (void *)gateway);
1811 }
1812 
1813 static int
1814 rt6_deleteroute(struct radix_node *rn, void *arg)
1815 {
1816 #define SIN6(s)	((struct sockaddr_in6 *)s)
1817 	struct rtentry *rt = (struct rtentry *)rn;
1818 	struct in6_addr *gate = (struct in6_addr *)arg;
1819 
1820 	if (rt->rt_gateway == NULL || rt->rt_gateway->sa_family != AF_INET6)
1821 		return (0);
1822 
1823 	if (!IN6_ARE_ADDR_EQUAL(gate, &SIN6(rt->rt_gateway)->sin6_addr))
1824 		return (0);
1825 
1826 	/*
1827 	 * Do not delete a static route.
1828 	 * XXX: this seems to be a bit ad-hoc. Should we consider the
1829 	 * 'cloned' bit instead?
1830 	 */
1831 	if (rt->rt_flags & RTF_STATIC)
1832 		return (0);
1833 
1834 	/*
1835 	 * We delete only host route. This means, in particular, we don't
1836 	 * delete default route.
1837 	 */
1838 	if (!(rt->rt_flags & RTF_HOST))
1839 		return (0);
1840 
1841 	return (rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway, rt_mask(rt),
1842 	    rt->rt_flags, 0));
1843 #undef SIN6
1844 }
1845 
1846 int
1847 nd6_setdefaultiface(int ifindex)
1848 {
1849 	int error = 0;
1850 
1851 	if (ifindex < 0 || if_index < ifindex)
1852 		return (EINVAL);
1853 
1854 	if (nd6_defifindex != ifindex) {
1855 		nd6_defifindex = ifindex;
1856 		if (nd6_defifindex > 0)
1857 			nd6_defifp = ifindex2ifnet[nd6_defifindex];
1858 		else
1859 			nd6_defifp = NULL;
1860 
1861 		/*
1862 		 * If the Default Router List is empty, install a route
1863 		 * to the specified interface as default or remove the default
1864 		 * route when the default interface becomes canceled.
1865 		 * The check for the queue is actually redundant, but
1866 		 * we do this here to avoid re-install the default route
1867 		 * if the list is NOT empty.
1868 		 */
1869 		if (TAILQ_FIRST(&nd_defrouter) == NULL)
1870 			defrouter_select();
1871 
1872 		/*
1873 		 * Our current implementation assumes one-to-one maping between
1874 		 * interfaces and links, so it would be natural to use the
1875 		 * default interface as the default link.
1876 		 */
1877 		scope6_setdefault(nd6_defifp);
1878 	}
1879 
1880 	return (error);
1881 }
1882