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