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