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