xref: /freebsd/sys/netinet6/nd6_rtr.c (revision c0020399a650364d0134f79f3fa319f84064372d)
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 
439 	bzero((caddr_t)&info, sizeof(info));
440 	info.rti_info[RTAX_DST] = rt_key(rt);
441 	info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
442 	info.rti_info[RTAX_NETMASK] = rt_mask(rt);
443 	if (rt->rt_ifp) {
444 		info.rti_info[RTAX_IFP] =
445 		    TAILQ_FIRST(&rt->rt_ifp->if_addrlist)->ifa_addr;
446 		info.rti_info[RTAX_IFA] = rt->rt_ifa->ifa_addr;
447 	}
448 
449 	rt_missmsg(cmd, &info, rt->rt_flags, 0);
450 }
451 
452 void
453 defrouter_addreq(struct nd_defrouter *new)
454 {
455 	struct sockaddr_in6 def, mask, gate;
456 	struct rtentry *newrt = NULL;
457 	int s;
458 	int error;
459 
460 	bzero(&def, sizeof(def));
461 	bzero(&mask, sizeof(mask));
462 	bzero(&gate, sizeof(gate));
463 
464 	def.sin6_len = mask.sin6_len = gate.sin6_len =
465 	    sizeof(struct sockaddr_in6);
466 	def.sin6_family = gate.sin6_family = AF_INET6;
467 	gate.sin6_addr = new->rtaddr;
468 
469 	s = splnet();
470 	error = rtrequest(RTM_ADD, (struct sockaddr *)&def,
471 	    (struct sockaddr *)&gate, (struct sockaddr *)&mask,
472 	    RTF_GATEWAY, &newrt);
473 	if (newrt) {
474 		nd6_rtmsg(RTM_ADD, newrt); /* tell user process */
475 		RTFREE(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 llentry *ln = NULL;
617 
618 	/*
619 	 * This function should be called only when acting as an autoconfigured
620 	 * host.  Although the remaining part of this function is not effective
621 	 * if the node is not an autoconfigured host, we explicitly exclude
622 	 * such cases here for safety.
623 	 */
624 	if (V_ip6_forwarding || !V_ip6_accept_rtadv) {
625 		nd6log((LOG_WARNING,
626 		    "defrouter_select: called unexpectedly (forwarding=%d, "
627 		    "accept_rtadv=%d)\n", V_ip6_forwarding, V_ip6_accept_rtadv));
628 		splx(s);
629 		return;
630 	}
631 
632 	/*
633 	 * Let's handle easy case (3) first:
634 	 * If default router list is empty, there's nothing to be done.
635 	 */
636 	if (!TAILQ_FIRST(&V_nd_defrouter)) {
637 		splx(s);
638 		return;
639 	}
640 
641 	/*
642 	 * Search for a (probably) reachable router from the list.
643 	 * We just pick up the first reachable one (if any), assuming that
644 	 * the ordering rule of the list described in defrtrlist_update().
645 	 */
646 	for (dr = TAILQ_FIRST(&V_nd_defrouter); dr;
647 	     dr = TAILQ_NEXT(dr, dr_entry)) {
648 		IF_AFDATA_LOCK(dr->ifp);
649 		if (selected_dr == NULL &&
650 		    (ln = nd6_lookup(&dr->rtaddr, 0, dr->ifp)) &&
651 		    ND6_IS_LLINFO_PROBREACH(ln)) {
652 			selected_dr = dr;
653 		}
654 		IF_AFDATA_UNLOCK(dr->ifp);
655 		if (ln != NULL) {
656 			LLE_RUNLOCK(ln);
657 			ln = NULL;
658 		}
659 
660 		if (dr->installed && installed_dr == NULL)
661 			installed_dr = dr;
662 		else if (dr->installed && installed_dr) {
663 			/* this should not happen.  warn for diagnosis. */
664 			log(LOG_ERR, "defrouter_select: more than one router"
665 			    " is installed\n");
666 		}
667 	}
668 	/*
669 	 * If none of the default routers was found to be reachable,
670 	 * round-robin the list regardless of preference.
671 	 * Otherwise, if we have an installed router, check if the selected
672 	 * (reachable) router should really be preferred to the installed one.
673 	 * We only prefer the new router when the old one is not reachable
674 	 * or when the new one has a really higher preference value.
675 	 */
676 	if (selected_dr == NULL) {
677 		if (installed_dr == NULL || !TAILQ_NEXT(installed_dr, dr_entry))
678 			selected_dr = TAILQ_FIRST(&V_nd_defrouter);
679 		else
680 			selected_dr = TAILQ_NEXT(installed_dr, dr_entry);
681 	} else if (installed_dr) {
682 		IF_AFDATA_LOCK(installed_dr->ifp);
683 		if ((ln = nd6_lookup(&installed_dr->rtaddr, 0, installed_dr->ifp)) &&
684 		    ND6_IS_LLINFO_PROBREACH(ln) &&
685 		    rtpref(selected_dr) <= rtpref(installed_dr)) {
686 			selected_dr = installed_dr;
687 		}
688 		IF_AFDATA_UNLOCK(installed_dr->ifp);
689 		if (ln != NULL)
690 			LLE_RUNLOCK(ln);
691 	}
692 
693 	/*
694 	 * If the selected router is different than the installed one,
695 	 * remove the installed router and install the selected one.
696 	 * Note that the selected router is never NULL here.
697 	 */
698 	if (installed_dr != selected_dr) {
699 		if (installed_dr)
700 			defrouter_delreq(installed_dr);
701 		defrouter_addreq(selected_dr);
702 	}
703 
704 	splx(s);
705 	return;
706 }
707 
708 /*
709  * for default router selection
710  * regards router-preference field as a 2-bit signed integer
711  */
712 static int
713 rtpref(struct nd_defrouter *dr)
714 {
715 	switch (dr->flags & ND_RA_FLAG_RTPREF_MASK) {
716 	case ND_RA_FLAG_RTPREF_HIGH:
717 		return (RTPREF_HIGH);
718 	case ND_RA_FLAG_RTPREF_MEDIUM:
719 	case ND_RA_FLAG_RTPREF_RSV:
720 		return (RTPREF_MEDIUM);
721 	case ND_RA_FLAG_RTPREF_LOW:
722 		return (RTPREF_LOW);
723 	default:
724 		/*
725 		 * This case should never happen.  If it did, it would mean a
726 		 * serious bug of kernel internal.  We thus always bark here.
727 		 * Or, can we even panic?
728 		 */
729 		log(LOG_ERR, "rtpref: impossible RA flag %x\n", dr->flags);
730 		return (RTPREF_INVALID);
731 	}
732 	/* NOTREACHED */
733 }
734 
735 static struct nd_defrouter *
736 defrtrlist_update(struct nd_defrouter *new)
737 {
738 	INIT_VNET_INET6(curvnet);
739 	struct nd_defrouter *dr, *n;
740 	int s = splnet();
741 
742 	if ((dr = defrouter_lookup(&new->rtaddr, new->ifp)) != NULL) {
743 		/* entry exists */
744 		if (new->rtlifetime == 0) {
745 			defrtrlist_del(dr);
746 			dr = NULL;
747 		} else {
748 			int oldpref = rtpref(dr);
749 
750 			/* override */
751 			dr->flags = new->flags; /* xxx flag check */
752 			dr->rtlifetime = new->rtlifetime;
753 			dr->expire = new->expire;
754 
755 			/*
756 			 * If the preference does not change, there's no need
757 			 * to sort the entries.
758 			 */
759 			if (rtpref(new) == oldpref) {
760 				splx(s);
761 				return (dr);
762 			}
763 
764 			/*
765 			 * preferred router may be changed, so relocate
766 			 * this router.
767 			 * XXX: calling TAILQ_REMOVE directly is a bad manner.
768 			 * However, since defrtrlist_del() has many side
769 			 * effects, we intentionally do so here.
770 			 * defrouter_select() below will handle routing
771 			 * changes later.
772 			 */
773 			TAILQ_REMOVE(&V_nd_defrouter, dr, dr_entry);
774 			n = dr;
775 			goto insert;
776 		}
777 		splx(s);
778 		return (dr);
779 	}
780 
781 	/* entry does not exist */
782 	if (new->rtlifetime == 0) {
783 		splx(s);
784 		return (NULL);
785 	}
786 
787 	n = (struct nd_defrouter *)malloc(sizeof(*n), M_IP6NDP, M_NOWAIT);
788 	if (n == NULL) {
789 		splx(s);
790 		return (NULL);
791 	}
792 	bzero(n, sizeof(*n));
793 	*n = *new;
794 
795 insert:
796 	/*
797 	 * Insert the new router in the Default Router List;
798 	 * The Default Router List should be in the descending order
799 	 * of router-preferece.  Routers with the same preference are
800 	 * sorted in the arriving time order.
801 	 */
802 
803 	/* insert at the end of the group */
804 	for (dr = TAILQ_FIRST(&V_nd_defrouter); dr;
805 	     dr = TAILQ_NEXT(dr, dr_entry)) {
806 		if (rtpref(n) > rtpref(dr))
807 			break;
808 	}
809 	if (dr)
810 		TAILQ_INSERT_BEFORE(dr, n, dr_entry);
811 	else
812 		TAILQ_INSERT_TAIL(&V_nd_defrouter, n, dr_entry);
813 
814 	defrouter_select();
815 
816 	splx(s);
817 
818 	return (n);
819 }
820 
821 static struct nd_pfxrouter *
822 pfxrtr_lookup(struct nd_prefix *pr, struct nd_defrouter *dr)
823 {
824 	struct nd_pfxrouter *search;
825 
826 	for (search = pr->ndpr_advrtrs.lh_first; search; search = search->pfr_next) {
827 		if (search->router == dr)
828 			break;
829 	}
830 
831 	return (search);
832 }
833 
834 static void
835 pfxrtr_add(struct nd_prefix *pr, struct nd_defrouter *dr)
836 {
837 	struct nd_pfxrouter *new;
838 
839 	new = (struct nd_pfxrouter *)malloc(sizeof(*new), M_IP6NDP, M_NOWAIT);
840 	if (new == NULL)
841 		return;
842 	bzero(new, sizeof(*new));
843 	new->router = dr;
844 
845 	LIST_INSERT_HEAD(&pr->ndpr_advrtrs, new, pfr_entry);
846 
847 	pfxlist_onlink_check();
848 }
849 
850 static void
851 pfxrtr_del(struct nd_pfxrouter *pfr)
852 {
853 	LIST_REMOVE(pfr, pfr_entry);
854 	free(pfr, M_IP6NDP);
855 }
856 
857 struct nd_prefix *
858 nd6_prefix_lookup(struct nd_prefixctl *key)
859 {
860 	INIT_VNET_INET6(curvnet);
861 	struct nd_prefix *search;
862 
863 	for (search = V_nd_prefix.lh_first;
864 	    search; search = search->ndpr_next) {
865 		if (key->ndpr_ifp == search->ndpr_ifp &&
866 		    key->ndpr_plen == search->ndpr_plen &&
867 		    in6_are_prefix_equal(&key->ndpr_prefix.sin6_addr,
868 		    &search->ndpr_prefix.sin6_addr, key->ndpr_plen)) {
869 			break;
870 		}
871 	}
872 
873 	return (search);
874 }
875 
876 int
877 nd6_prelist_add(struct nd_prefixctl *pr, struct nd_defrouter *dr,
878     struct nd_prefix **newp)
879 {
880 	INIT_VNET_INET6(curvnet);
881 	struct nd_prefix *new = NULL;
882 	int error = 0;
883 	int i, s;
884 	char ip6buf[INET6_ADDRSTRLEN];
885 
886 	new = (struct nd_prefix *)malloc(sizeof(*new), M_IP6NDP, M_NOWAIT);
887 	if (new == NULL)
888 		return(ENOMEM);
889 	bzero(new, sizeof(*new));
890 	new->ndpr_ifp = pr->ndpr_ifp;
891 	new->ndpr_prefix = pr->ndpr_prefix;
892 	new->ndpr_plen = pr->ndpr_plen;
893 	new->ndpr_vltime = pr->ndpr_vltime;
894 	new->ndpr_pltime = pr->ndpr_pltime;
895 	new->ndpr_flags = pr->ndpr_flags;
896 	if ((error = in6_init_prefix_ltimes(new)) != 0) {
897 		free(new, M_IP6NDP);
898 		return(error);
899 	}
900 	new->ndpr_lastupdate = time_second;
901 	if (newp != NULL)
902 		*newp = new;
903 
904 	/* initialization */
905 	LIST_INIT(&new->ndpr_advrtrs);
906 	in6_prefixlen2mask(&new->ndpr_mask, new->ndpr_plen);
907 	/* make prefix in the canonical form */
908 	for (i = 0; i < 4; i++)
909 		new->ndpr_prefix.sin6_addr.s6_addr32[i] &=
910 		    new->ndpr_mask.s6_addr32[i];
911 
912 	s = splnet();
913 	/* link ndpr_entry to nd_prefix list */
914 	LIST_INSERT_HEAD(&V_nd_prefix, new, ndpr_entry);
915 	splx(s);
916 
917 	/* ND_OPT_PI_FLAG_ONLINK processing */
918 	if (new->ndpr_raf_onlink) {
919 		int e;
920 
921 		if ((e = nd6_prefix_onlink(new)) != 0) {
922 			nd6log((LOG_ERR, "nd6_prelist_add: failed to make "
923 			    "the prefix %s/%d on-link on %s (errno=%d)\n",
924 			    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
925 			    pr->ndpr_plen, if_name(pr->ndpr_ifp), e));
926 			/* proceed anyway. XXX: is it correct? */
927 		}
928 	}
929 
930 	if (dr)
931 		pfxrtr_add(new, dr);
932 
933 	return 0;
934 }
935 
936 void
937 prelist_remove(struct nd_prefix *pr)
938 {
939 	INIT_VNET_INET6(curvnet);
940 	struct nd_pfxrouter *pfr, *next;
941 	int e, s;
942 	char ip6buf[INET6_ADDRSTRLEN];
943 
944 	/* make sure to invalidate the prefix until it is really freed. */
945 	pr->ndpr_vltime = 0;
946 	pr->ndpr_pltime = 0;
947 
948 	/*
949 	 * Though these flags are now meaningless, we'd rather keep the value
950 	 * of pr->ndpr_raf_onlink and pr->ndpr_raf_auto not to confuse users
951 	 * when executing "ndp -p".
952 	 */
953 
954 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0 &&
955 	    (e = nd6_prefix_offlink(pr)) != 0) {
956 		nd6log((LOG_ERR, "prelist_remove: failed to make %s/%d offlink "
957 		    "on %s, errno=%d\n",
958 		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
959 		    pr->ndpr_plen, if_name(pr->ndpr_ifp), e));
960 		/* what should we do? */
961 	}
962 
963 	if (pr->ndpr_refcnt > 0)
964 		return;		/* notice here? */
965 
966 	s = splnet();
967 
968 	/* unlink ndpr_entry from nd_prefix list */
969 	LIST_REMOVE(pr, ndpr_entry);
970 
971 	/* free list of routers that adversed the prefix */
972 	for (pfr = pr->ndpr_advrtrs.lh_first; pfr; pfr = next) {
973 		next = pfr->pfr_next;
974 
975 		free(pfr, M_IP6NDP);
976 	}
977 	splx(s);
978 
979 	free(pr, M_IP6NDP);
980 
981 	pfxlist_onlink_check();
982 }
983 
984 /*
985  * dr - may be NULL
986  */
987 
988 static int
989 prelist_update(struct nd_prefixctl *new, struct nd_defrouter *dr,
990     struct mbuf *m, int mcast)
991 {
992 	INIT_VNET_INET6(curvnet);
993 	struct in6_ifaddr *ia6 = NULL, *ia6_match = NULL;
994 	struct ifaddr *ifa;
995 	struct ifnet *ifp = new->ndpr_ifp;
996 	struct nd_prefix *pr;
997 	int s = splnet();
998 	int error = 0;
999 	int newprefix = 0;
1000 	int auth;
1001 	struct in6_addrlifetime lt6_tmp;
1002 	char ip6buf[INET6_ADDRSTRLEN];
1003 
1004 	auth = 0;
1005 	if (m) {
1006 		/*
1007 		 * Authenticity for NA consists authentication for
1008 		 * both IP header and IP datagrams, doesn't it ?
1009 		 */
1010 #if defined(M_AUTHIPHDR) && defined(M_AUTHIPDGM)
1011 		auth = ((m->m_flags & M_AUTHIPHDR) &&
1012 		    (m->m_flags & M_AUTHIPDGM));
1013 #endif
1014 	}
1015 
1016 	if ((pr = nd6_prefix_lookup(new)) != NULL) {
1017 		/*
1018 		 * nd6_prefix_lookup() ensures that pr and new have the same
1019 		 * prefix on a same interface.
1020 		 */
1021 
1022 		/*
1023 		 * Update prefix information.  Note that the on-link (L) bit
1024 		 * and the autonomous (A) bit should NOT be changed from 1
1025 		 * to 0.
1026 		 */
1027 		if (new->ndpr_raf_onlink == 1)
1028 			pr->ndpr_raf_onlink = 1;
1029 		if (new->ndpr_raf_auto == 1)
1030 			pr->ndpr_raf_auto = 1;
1031 		if (new->ndpr_raf_onlink) {
1032 			pr->ndpr_vltime = new->ndpr_vltime;
1033 			pr->ndpr_pltime = new->ndpr_pltime;
1034 			(void)in6_init_prefix_ltimes(pr); /* XXX error case? */
1035 			pr->ndpr_lastupdate = time_second;
1036 		}
1037 
1038 		if (new->ndpr_raf_onlink &&
1039 		    (pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
1040 			int e;
1041 
1042 			if ((e = nd6_prefix_onlink(pr)) != 0) {
1043 				nd6log((LOG_ERR,
1044 				    "prelist_update: failed to make "
1045 				    "the prefix %s/%d on-link on %s "
1046 				    "(errno=%d)\n",
1047 				    ip6_sprintf(ip6buf,
1048 					    &pr->ndpr_prefix.sin6_addr),
1049 				    pr->ndpr_plen, if_name(pr->ndpr_ifp), e));
1050 				/* proceed anyway. XXX: is it correct? */
1051 			}
1052 		}
1053 
1054 		if (dr && pfxrtr_lookup(pr, dr) == NULL)
1055 			pfxrtr_add(pr, dr);
1056 	} else {
1057 		struct nd_prefix *newpr = NULL;
1058 
1059 		newprefix = 1;
1060 
1061 		if (new->ndpr_vltime == 0)
1062 			goto end;
1063 		if (new->ndpr_raf_onlink == 0 && new->ndpr_raf_auto == 0)
1064 			goto end;
1065 
1066 		error = nd6_prelist_add(new, dr, &newpr);
1067 		if (error != 0 || newpr == NULL) {
1068 			nd6log((LOG_NOTICE, "prelist_update: "
1069 			    "nd6_prelist_add failed for %s/%d on %s "
1070 			    "errno=%d, returnpr=%p\n",
1071 			    ip6_sprintf(ip6buf, &new->ndpr_prefix.sin6_addr),
1072 			    new->ndpr_plen, if_name(new->ndpr_ifp),
1073 			    error, newpr));
1074 			goto end; /* we should just give up in this case. */
1075 		}
1076 
1077 		/*
1078 		 * XXX: from the ND point of view, we can ignore a prefix
1079 		 * with the on-link bit being zero.  However, we need a
1080 		 * prefix structure for references from autoconfigured
1081 		 * addresses.  Thus, we explicitly make sure that the prefix
1082 		 * itself expires now.
1083 		 */
1084 		if (newpr->ndpr_raf_onlink == 0) {
1085 			newpr->ndpr_vltime = 0;
1086 			newpr->ndpr_pltime = 0;
1087 			in6_init_prefix_ltimes(newpr);
1088 		}
1089 
1090 		pr = newpr;
1091 	}
1092 
1093 	/*
1094 	 * Address autoconfiguration based on Section 5.5.3 of RFC 2462.
1095 	 * Note that pr must be non NULL at this point.
1096 	 */
1097 
1098 	/* 5.5.3 (a). Ignore the prefix without the A bit set. */
1099 	if (!new->ndpr_raf_auto)
1100 		goto end;
1101 
1102 	/*
1103 	 * 5.5.3 (b). the link-local prefix should have been ignored in
1104 	 * nd6_ra_input.
1105 	 */
1106 
1107 	/* 5.5.3 (c). Consistency check on lifetimes: pltime <= vltime. */
1108 	if (new->ndpr_pltime > new->ndpr_vltime) {
1109 		error = EINVAL;	/* XXX: won't be used */
1110 		goto end;
1111 	}
1112 
1113 	/*
1114 	 * 5.5.3 (d).  If the prefix advertised is not equal to the prefix of
1115 	 * an address configured by stateless autoconfiguration already in the
1116 	 * list of addresses associated with the interface, and the Valid
1117 	 * Lifetime is not 0, form an address.  We first check if we have
1118 	 * a matching prefix.
1119 	 * Note: we apply a clarification in rfc2462bis-02 here.  We only
1120 	 * consider autoconfigured addresses while RFC2462 simply said
1121 	 * "address".
1122 	 */
1123 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
1124 		struct in6_ifaddr *ifa6;
1125 		u_int32_t remaininglifetime;
1126 
1127 		if (ifa->ifa_addr->sa_family != AF_INET6)
1128 			continue;
1129 
1130 		ifa6 = (struct in6_ifaddr *)ifa;
1131 
1132 		/*
1133 		 * We only consider autoconfigured addresses as per rfc2462bis.
1134 		 */
1135 		if (!(ifa6->ia6_flags & IN6_IFF_AUTOCONF))
1136 			continue;
1137 
1138 		/*
1139 		 * Spec is not clear here, but I believe we should concentrate
1140 		 * on unicast (i.e. not anycast) addresses.
1141 		 * XXX: other ia6_flags? detached or duplicated?
1142 		 */
1143 		if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0)
1144 			continue;
1145 
1146 		/*
1147 		 * Ignore the address if it is not associated with a prefix
1148 		 * or is associated with a prefix that is different from this
1149 		 * one.  (pr is never NULL here)
1150 		 */
1151 		if (ifa6->ia6_ndpr != pr)
1152 			continue;
1153 
1154 		if (ia6_match == NULL) /* remember the first one */
1155 			ia6_match = ifa6;
1156 
1157 		/*
1158 		 * An already autoconfigured address matched.  Now that we
1159 		 * are sure there is at least one matched address, we can
1160 		 * proceed to 5.5.3. (e): update the lifetimes according to the
1161 		 * "two hours" rule and the privacy extension.
1162 		 * We apply some clarifications in rfc2462bis:
1163 		 * - use remaininglifetime instead of storedlifetime as a
1164 		 *   variable name
1165 		 * - remove the dead code in the "two-hour" rule
1166 		 */
1167 #define TWOHOUR		(120*60)
1168 		lt6_tmp = ifa6->ia6_lifetime;
1169 
1170 		if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME)
1171 			remaininglifetime = ND6_INFINITE_LIFETIME;
1172 		else if (time_second - ifa6->ia6_updatetime >
1173 			 lt6_tmp.ia6t_vltime) {
1174 			/*
1175 			 * The case of "invalid" address.  We should usually
1176 			 * not see this case.
1177 			 */
1178 			remaininglifetime = 0;
1179 		} else
1180 			remaininglifetime = lt6_tmp.ia6t_vltime -
1181 			    (time_second - ifa6->ia6_updatetime);
1182 
1183 		/* when not updating, keep the current stored lifetime. */
1184 		lt6_tmp.ia6t_vltime = remaininglifetime;
1185 
1186 		if (TWOHOUR < new->ndpr_vltime ||
1187 		    remaininglifetime < new->ndpr_vltime) {
1188 			lt6_tmp.ia6t_vltime = new->ndpr_vltime;
1189 		} else if (remaininglifetime <= TWOHOUR) {
1190 			if (auth) {
1191 				lt6_tmp.ia6t_vltime = new->ndpr_vltime;
1192 			}
1193 		} else {
1194 			/*
1195 			 * new->ndpr_vltime <= TWOHOUR &&
1196 			 * TWOHOUR < remaininglifetime
1197 			 */
1198 			lt6_tmp.ia6t_vltime = TWOHOUR;
1199 		}
1200 
1201 		/* The 2 hour rule is not imposed for preferred lifetime. */
1202 		lt6_tmp.ia6t_pltime = new->ndpr_pltime;
1203 
1204 		in6_init_address_ltimes(pr, &lt6_tmp);
1205 
1206 		/*
1207 		 * We need to treat lifetimes for temporary addresses
1208 		 * differently, according to
1209 		 * draft-ietf-ipv6-privacy-addrs-v2-01.txt 3.3 (1);
1210 		 * we only update the lifetimes when they are in the maximum
1211 		 * intervals.
1212 		 */
1213 		if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
1214 			u_int32_t maxvltime, maxpltime;
1215 
1216 			if (V_ip6_temp_valid_lifetime >
1217 			    (u_int32_t)((time_second - ifa6->ia6_createtime) +
1218 			    V_ip6_desync_factor)) {
1219 				maxvltime = V_ip6_temp_valid_lifetime -
1220 				    (time_second - ifa6->ia6_createtime) -
1221 				    V_ip6_desync_factor;
1222 			} else
1223 				maxvltime = 0;
1224 			if (V_ip6_temp_preferred_lifetime >
1225 			    (u_int32_t)((time_second - ifa6->ia6_createtime) +
1226 			    V_ip6_desync_factor)) {
1227 				maxpltime = V_ip6_temp_preferred_lifetime -
1228 				    (time_second - ifa6->ia6_createtime) -
1229 				    V_ip6_desync_factor;
1230 			} else
1231 				maxpltime = 0;
1232 
1233 			if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME ||
1234 			    lt6_tmp.ia6t_vltime > maxvltime) {
1235 				lt6_tmp.ia6t_vltime = maxvltime;
1236 			}
1237 			if (lt6_tmp.ia6t_pltime == ND6_INFINITE_LIFETIME ||
1238 			    lt6_tmp.ia6t_pltime > maxpltime) {
1239 				lt6_tmp.ia6t_pltime = maxpltime;
1240 			}
1241 		}
1242 		ifa6->ia6_lifetime = lt6_tmp;
1243 		ifa6->ia6_updatetime = time_second;
1244 	}
1245 	if (ia6_match == NULL && new->ndpr_vltime) {
1246 		int ifidlen;
1247 
1248 		/*
1249 		 * 5.5.3 (d) (continued)
1250 		 * No address matched and the valid lifetime is non-zero.
1251 		 * Create a new address.
1252 		 */
1253 
1254 		/*
1255 		 * Prefix Length check:
1256 		 * If the sum of the prefix length and interface identifier
1257 		 * length does not equal 128 bits, the Prefix Information
1258 		 * option MUST be ignored.  The length of the interface
1259 		 * identifier is defined in a separate link-type specific
1260 		 * document.
1261 		 */
1262 		ifidlen = in6_if2idlen(ifp);
1263 		if (ifidlen < 0) {
1264 			/* this should not happen, so we always log it. */
1265 			log(LOG_ERR, "prelist_update: IFID undefined (%s)\n",
1266 			    if_name(ifp));
1267 			goto end;
1268 		}
1269 		if (ifidlen + pr->ndpr_plen != 128) {
1270 			nd6log((LOG_INFO,
1271 			    "prelist_update: invalid prefixlen "
1272 			    "%d for %s, ignored\n",
1273 			    pr->ndpr_plen, if_name(ifp)));
1274 			goto end;
1275 		}
1276 
1277 		if ((ia6 = in6_ifadd(new, mcast)) != NULL) {
1278 			/*
1279 			 * note that we should use pr (not new) for reference.
1280 			 */
1281 			pr->ndpr_refcnt++;
1282 			ia6->ia6_ndpr = pr;
1283 
1284 			/*
1285 			 * RFC 3041 3.3 (2).
1286 			 * When a new public address is created as described
1287 			 * in RFC2462, also create a new temporary address.
1288 			 *
1289 			 * RFC 3041 3.5.
1290 			 * When an interface connects to a new link, a new
1291 			 * randomized interface identifier should be generated
1292 			 * immediately together with a new set of temporary
1293 			 * addresses.  Thus, we specifiy 1 as the 2nd arg of
1294 			 * in6_tmpifadd().
1295 			 */
1296 			if (V_ip6_use_tempaddr) {
1297 				int e;
1298 				if ((e = in6_tmpifadd(ia6, 1, 1)) != 0) {
1299 					nd6log((LOG_NOTICE, "prelist_update: "
1300 					    "failed to create a temporary "
1301 					    "address, errno=%d\n",
1302 					    e));
1303 				}
1304 			}
1305 
1306 			/*
1307 			 * A newly added address might affect the status
1308 			 * of other addresses, so we check and update it.
1309 			 * XXX: what if address duplication happens?
1310 			 */
1311 			pfxlist_onlink_check();
1312 		} else {
1313 			/* just set an error. do not bark here. */
1314 			error = EADDRNOTAVAIL; /* XXX: might be unused. */
1315 		}
1316 	}
1317 
1318  end:
1319 	splx(s);
1320 	return error;
1321 }
1322 
1323 /*
1324  * A supplement function used in the on-link detection below;
1325  * detect if a given prefix has a (probably) reachable advertising router.
1326  * XXX: lengthy function name...
1327  */
1328 static struct nd_pfxrouter *
1329 find_pfxlist_reachable_router(struct nd_prefix *pr)
1330 {
1331 	struct nd_pfxrouter *pfxrtr;
1332 	struct llentry *ln;
1333 	int canreach;
1334 
1335 	for (pfxrtr = LIST_FIRST(&pr->ndpr_advrtrs); pfxrtr != NULL;
1336 	     pfxrtr = LIST_NEXT(pfxrtr, pfr_entry)) {
1337 		IF_AFDATA_LOCK(pfxrtr->router->ifp);
1338 		ln = nd6_lookup(&pfxrtr->router->rtaddr, 0, pfxrtr->router->ifp);
1339 		IF_AFDATA_UNLOCK(pfxrtr->router->ifp);
1340 		if (ln == NULL)
1341 			continue;
1342 		canreach = ND6_IS_LLINFO_PROBREACH(ln);
1343 		LLE_RUNLOCK(ln);
1344 		if (canreach)
1345 			break;
1346 	}
1347 	return (pfxrtr);
1348 }
1349 
1350 /*
1351  * Check if each prefix in the prefix list has at least one available router
1352  * that advertised the prefix (a router is "available" if its neighbor cache
1353  * entry is reachable or probably reachable).
1354  * If the check fails, the prefix may be off-link, because, for example,
1355  * we have moved from the network but the lifetime of the prefix has not
1356  * expired yet.  So we should not use the prefix if there is another prefix
1357  * that has an available router.
1358  * But, if there is no prefix that has an available router, we still regards
1359  * all the prefixes as on-link.  This is because we can't tell if all the
1360  * routers are simply dead or if we really moved from the network and there
1361  * is no router around us.
1362  */
1363 void
1364 pfxlist_onlink_check()
1365 {
1366 	INIT_VNET_INET6(curvnet);
1367 	struct nd_prefix *pr;
1368 	struct in6_ifaddr *ifa;
1369 	struct nd_defrouter *dr;
1370 	struct nd_pfxrouter *pfxrtr = NULL;
1371 
1372 	/*
1373 	 * Check if there is a prefix that has a reachable advertising
1374 	 * router.
1375 	 */
1376 	for (pr = V_nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
1377 		if (pr->ndpr_raf_onlink && find_pfxlist_reachable_router(pr))
1378 			break;
1379 	}
1380 
1381 	/*
1382 	 * If we have no such prefix, check whether we still have a router
1383 	 * that does not advertise any prefixes.
1384 	 */
1385 	if (pr == NULL) {
1386 		for (dr = TAILQ_FIRST(&V_nd_defrouter); dr;
1387 		    dr = TAILQ_NEXT(dr, dr_entry)) {
1388 			struct nd_prefix *pr0;
1389 
1390 			for (pr0 = V_nd_prefix.lh_first; pr0;
1391 			    pr0 = pr0->ndpr_next) {
1392 				if ((pfxrtr = pfxrtr_lookup(pr0, dr)) != NULL)
1393 					break;
1394 			}
1395 			if (pfxrtr != NULL)
1396 				break;
1397 		}
1398 	}
1399 	if (pr != NULL || (TAILQ_FIRST(&V_nd_defrouter) && pfxrtr == NULL)) {
1400 		/*
1401 		 * There is at least one prefix that has a reachable router,
1402 		 * or at least a router which probably does not advertise
1403 		 * any prefixes.  The latter would be the case when we move
1404 		 * to a new link where we have a router that does not provide
1405 		 * prefixes and we configure an address by hand.
1406 		 * Detach prefixes which have no reachable advertising
1407 		 * router, and attach other prefixes.
1408 		 */
1409 		for (pr = V_nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
1410 			/* XXX: a link-local prefix should never be detached */
1411 			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1412 				continue;
1413 
1414 			/*
1415 			 * we aren't interested in prefixes without the L bit
1416 			 * set.
1417 			 */
1418 			if (pr->ndpr_raf_onlink == 0)
1419 				continue;
1420 
1421 			if ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
1422 			    find_pfxlist_reachable_router(pr) == NULL)
1423 				pr->ndpr_stateflags |= NDPRF_DETACHED;
1424 			if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0 &&
1425 			    find_pfxlist_reachable_router(pr) != 0)
1426 				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
1427 		}
1428 	} else {
1429 		/* there is no prefix that has a reachable router */
1430 		for (pr = V_nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
1431 			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1432 				continue;
1433 
1434 			if (pr->ndpr_raf_onlink == 0)
1435 				continue;
1436 
1437 			if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0)
1438 				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
1439 		}
1440 	}
1441 
1442 	/*
1443 	 * Remove each interface route associated with a (just) detached
1444 	 * prefix, and reinstall the interface route for a (just) attached
1445 	 * prefix.  Note that all attempt of reinstallation does not
1446 	 * necessarily success, when a same prefix is shared among multiple
1447 	 * interfaces.  Such cases will be handled in nd6_prefix_onlink,
1448 	 * so we don't have to care about them.
1449 	 */
1450 	for (pr = V_nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
1451 		int e;
1452 		char ip6buf[INET6_ADDRSTRLEN];
1453 
1454 		if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1455 			continue;
1456 
1457 		if (pr->ndpr_raf_onlink == 0)
1458 			continue;
1459 
1460 		if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0 &&
1461 		    (pr->ndpr_stateflags & NDPRF_ONLINK) != 0) {
1462 			if ((e = nd6_prefix_offlink(pr)) != 0) {
1463 				nd6log((LOG_ERR,
1464 				    "pfxlist_onlink_check: failed to "
1465 				    "make %s/%d offlink, errno=%d\n",
1466 				    ip6_sprintf(ip6buf,
1467 					    &pr->ndpr_prefix.sin6_addr),
1468 					    pr->ndpr_plen, e));
1469 			}
1470 		}
1471 		if ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
1472 		    (pr->ndpr_stateflags & NDPRF_ONLINK) == 0 &&
1473 		    pr->ndpr_raf_onlink) {
1474 			if ((e = nd6_prefix_onlink(pr)) != 0) {
1475 				nd6log((LOG_ERR,
1476 				    "pfxlist_onlink_check: failed to "
1477 				    "make %s/%d onlink, errno=%d\n",
1478 				    ip6_sprintf(ip6buf,
1479 					    &pr->ndpr_prefix.sin6_addr),
1480 					    pr->ndpr_plen, e));
1481 			}
1482 		}
1483 	}
1484 
1485 	/*
1486 	 * Changes on the prefix status might affect address status as well.
1487 	 * Make sure that all addresses derived from an attached prefix are
1488 	 * attached, and that all addresses derived from a detached prefix are
1489 	 * detached.  Note, however, that a manually configured address should
1490 	 * always be attached.
1491 	 * The precise detection logic is same as the one for prefixes.
1492 	 */
1493 	for (ifa = V_in6_ifaddr; ifa; ifa = ifa->ia_next) {
1494 		if (!(ifa->ia6_flags & IN6_IFF_AUTOCONF))
1495 			continue;
1496 
1497 		if (ifa->ia6_ndpr == NULL) {
1498 			/*
1499 			 * This can happen when we first configure the address
1500 			 * (i.e. the address exists, but the prefix does not).
1501 			 * XXX: complicated relationships...
1502 			 */
1503 			continue;
1504 		}
1505 
1506 		if (find_pfxlist_reachable_router(ifa->ia6_ndpr))
1507 			break;
1508 	}
1509 	if (ifa) {
1510 		for (ifa = V_in6_ifaddr; ifa; ifa = ifa->ia_next) {
1511 			if ((ifa->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1512 				continue;
1513 
1514 			if (ifa->ia6_ndpr == NULL) /* XXX: see above. */
1515 				continue;
1516 
1517 			if (find_pfxlist_reachable_router(ifa->ia6_ndpr)) {
1518 				if (ifa->ia6_flags & IN6_IFF_DETACHED) {
1519 					ifa->ia6_flags &= ~IN6_IFF_DETACHED;
1520 					ifa->ia6_flags |= IN6_IFF_TENTATIVE;
1521 					nd6_dad_start((struct ifaddr *)ifa, 0);
1522 				}
1523 			} else {
1524 				ifa->ia6_flags |= IN6_IFF_DETACHED;
1525 			}
1526 		}
1527 	}
1528 	else {
1529 		for (ifa = V_in6_ifaddr; ifa; ifa = ifa->ia_next) {
1530 			if ((ifa->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1531 				continue;
1532 
1533 			if (ifa->ia6_flags & IN6_IFF_DETACHED) {
1534 				ifa->ia6_flags &= ~IN6_IFF_DETACHED;
1535 				ifa->ia6_flags |= IN6_IFF_TENTATIVE;
1536 				/* Do we need a delay in this case? */
1537 				nd6_dad_start((struct ifaddr *)ifa, 0);
1538 			}
1539 		}
1540 	}
1541 }
1542 
1543 int
1544 nd6_prefix_onlink(struct nd_prefix *pr)
1545 {
1546 	INIT_VNET_INET6(curvnet);
1547 	struct ifaddr *ifa;
1548 	struct ifnet *ifp = pr->ndpr_ifp;
1549 	struct sockaddr_in6 mask6;
1550 	struct nd_prefix *opr;
1551 	u_long rtflags;
1552 	int error = 0;
1553 	struct radix_node_head *rnh;
1554 	struct rtentry *rt = NULL;
1555 	char ip6buf[INET6_ADDRSTRLEN];
1556 	struct sockaddr_dl null_sdl = {sizeof(null_sdl), AF_LINK};
1557 
1558 	/* sanity check */
1559 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0) {
1560 		nd6log((LOG_ERR,
1561 		    "nd6_prefix_onlink: %s/%d is already on-link\n",
1562 		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
1563 		    pr->ndpr_plen));
1564 		return (EEXIST);
1565 	}
1566 
1567 	/*
1568 	 * Add the interface route associated with the prefix.  Before
1569 	 * installing the route, check if there's the same prefix on another
1570 	 * interface, and the prefix has already installed the interface route.
1571 	 * Although such a configuration is expected to be rare, we explicitly
1572 	 * allow it.
1573 	 */
1574 	for (opr = V_nd_prefix.lh_first; opr; opr = opr->ndpr_next) {
1575 		if (opr == pr)
1576 			continue;
1577 
1578 		if ((opr->ndpr_stateflags & NDPRF_ONLINK) == 0)
1579 			continue;
1580 
1581 		if (opr->ndpr_plen == pr->ndpr_plen &&
1582 		    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
1583 		    &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen))
1584 			return (0);
1585 	}
1586 
1587 	/*
1588 	 * We prefer link-local addresses as the associated interface address.
1589 	 */
1590 	/* search for a link-local addr */
1591 	ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp,
1592 	    IN6_IFF_NOTREADY | IN6_IFF_ANYCAST);
1593 	if (ifa == NULL) {
1594 		/* XXX: freebsd does not have ifa_ifwithaf */
1595 		TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
1596 			if (ifa->ifa_addr->sa_family == AF_INET6)
1597 				break;
1598 		}
1599 		/* should we care about ia6_flags? */
1600 	}
1601 	if (ifa == NULL) {
1602 		/*
1603 		 * This can still happen, when, for example, we receive an RA
1604 		 * containing a prefix with the L bit set and the A bit clear,
1605 		 * after removing all IPv6 addresses on the receiving
1606 		 * interface.  This should, of course, be rare though.
1607 		 */
1608 		nd6log((LOG_NOTICE,
1609 		    "nd6_prefix_onlink: failed to find any ifaddr"
1610 		    " to add route for a prefix(%s/%d) on %s\n",
1611 		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
1612 		    pr->ndpr_plen, if_name(ifp)));
1613 		return (0);
1614 	}
1615 
1616 	/*
1617 	 * in6_ifinit() sets nd6_rtrequest to ifa_rtrequest for all ifaddrs.
1618 	 * ifa->ifa_rtrequest = nd6_rtrequest;
1619 	 */
1620 	bzero(&mask6, sizeof(mask6));
1621 	mask6.sin6_len = sizeof(mask6);
1622 	mask6.sin6_addr = pr->ndpr_mask;
1623 	rtflags = ifa->ifa_flags | RTF_UP;
1624 	error = rtrequest(RTM_ADD, (struct sockaddr *)&pr->ndpr_prefix,
1625 	    ifa->ifa_addr, (struct sockaddr *)&mask6, rtflags, &rt);
1626 	if (error == 0) {
1627 		if (rt != NULL) /* this should be non NULL, though */ {
1628 			rnh = V_rt_tables[rt->rt_fibnum][AF_INET6];
1629 			RADIX_NODE_HEAD_LOCK(rnh);
1630 			RT_LOCK(rt);
1631 			if (!rt_setgate(rt, rt_key(rt), (struct sockaddr *)&null_sdl)) {
1632 				((struct sockaddr_dl *)rt->rt_gateway)->sdl_type =
1633 					rt->rt_ifp->if_type;
1634 				((struct sockaddr_dl *)rt->rt_gateway)->sdl_index =
1635 					rt->rt_ifp->if_index;
1636 			}
1637 			RADIX_NODE_HEAD_UNLOCK(rnh);
1638 			nd6_rtmsg(RTM_ADD, rt);
1639 			RT_UNLOCK(rt);
1640 		}
1641 		pr->ndpr_stateflags |= NDPRF_ONLINK;
1642 	} else {
1643 		char ip6bufg[INET6_ADDRSTRLEN], ip6bufm[INET6_ADDRSTRLEN];
1644 		nd6log((LOG_ERR, "nd6_prefix_onlink: failed to add route for a"
1645 		    " prefix (%s/%d) on %s, gw=%s, mask=%s, flags=%lx "
1646 		    "errno = %d\n",
1647 		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
1648 		    pr->ndpr_plen, if_name(ifp),
1649 		    ip6_sprintf(ip6bufg, &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr),
1650 		    ip6_sprintf(ip6bufm, &mask6.sin6_addr), rtflags, error));
1651 	}
1652 
1653 	if (rt != NULL) {
1654 		RT_LOCK(rt);
1655 		RT_REMREF(rt);
1656 		RT_UNLOCK(rt);
1657 	}
1658 
1659 	return (error);
1660 }
1661 
1662 int
1663 nd6_prefix_offlink(struct nd_prefix *pr)
1664 {
1665 	INIT_VNET_INET6(curvnet);
1666 	int error = 0;
1667 	struct ifnet *ifp = pr->ndpr_ifp;
1668 	struct nd_prefix *opr;
1669 	struct sockaddr_in6 sa6, mask6;
1670 	struct rtentry *rt = NULL;
1671 	char ip6buf[INET6_ADDRSTRLEN];
1672 
1673 	/* sanity check */
1674 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
1675 		nd6log((LOG_ERR,
1676 		    "nd6_prefix_offlink: %s/%d is already off-link\n",
1677 		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
1678 		    pr->ndpr_plen));
1679 		return (EEXIST);
1680 	}
1681 
1682 	bzero(&sa6, sizeof(sa6));
1683 	sa6.sin6_family = AF_INET6;
1684 	sa6.sin6_len = sizeof(sa6);
1685 	bcopy(&pr->ndpr_prefix.sin6_addr, &sa6.sin6_addr,
1686 	    sizeof(struct in6_addr));
1687 	bzero(&mask6, sizeof(mask6));
1688 	mask6.sin6_family = AF_INET6;
1689 	mask6.sin6_len = sizeof(sa6);
1690 	bcopy(&pr->ndpr_mask, &mask6.sin6_addr, sizeof(struct in6_addr));
1691 	error = rtrequest(RTM_DELETE, (struct sockaddr *)&sa6, NULL,
1692 	    (struct sockaddr *)&mask6, 0, &rt);
1693 	if (error == 0) {
1694 		pr->ndpr_stateflags &= ~NDPRF_ONLINK;
1695 
1696 		/* report the route deletion to the routing socket. */
1697 		if (rt != NULL)
1698 			nd6_rtmsg(RTM_DELETE, rt);
1699 
1700 		/*
1701 		 * There might be the same prefix on another interface,
1702 		 * the prefix which could not be on-link just because we have
1703 		 * the interface route (see comments in nd6_prefix_onlink).
1704 		 * If there's one, try to make the prefix on-link on the
1705 		 * interface.
1706 		 */
1707 		for (opr = V_nd_prefix.lh_first; opr; opr = opr->ndpr_next) {
1708 			if (opr == pr)
1709 				continue;
1710 
1711 			if ((opr->ndpr_stateflags & NDPRF_ONLINK) != 0)
1712 				continue;
1713 
1714 			/*
1715 			 * KAME specific: detached prefixes should not be
1716 			 * on-link.
1717 			 */
1718 			if ((opr->ndpr_stateflags & NDPRF_DETACHED) != 0)
1719 				continue;
1720 
1721 			if (opr->ndpr_plen == pr->ndpr_plen &&
1722 			    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
1723 			    &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen)) {
1724 				int e;
1725 
1726 				if ((e = nd6_prefix_onlink(opr)) != 0) {
1727 					nd6log((LOG_ERR,
1728 					    "nd6_prefix_offlink: failed to "
1729 					    "recover a prefix %s/%d from %s "
1730 					    "to %s (errno = %d)\n",
1731 					    ip6_sprintf(ip6buf,
1732 						&opr->ndpr_prefix.sin6_addr),
1733 					    opr->ndpr_plen, if_name(ifp),
1734 					    if_name(opr->ndpr_ifp), e));
1735 				}
1736 			}
1737 		}
1738 	} else {
1739 		/* XXX: can we still set the NDPRF_ONLINK flag? */
1740 		nd6log((LOG_ERR,
1741 		    "nd6_prefix_offlink: failed to delete route: "
1742 		    "%s/%d on %s (errno = %d)\n",
1743 		    ip6_sprintf(ip6buf, &sa6.sin6_addr), pr->ndpr_plen,
1744 		    if_name(ifp), error));
1745 	}
1746 
1747 	if (rt != NULL) {
1748 		RTFREE(rt);
1749 	}
1750 
1751 	return (error);
1752 }
1753 
1754 static struct in6_ifaddr *
1755 in6_ifadd(struct nd_prefixctl *pr, int mcast)
1756 {
1757 	INIT_VNET_INET6(curvnet);
1758 	struct ifnet *ifp = pr->ndpr_ifp;
1759 	struct ifaddr *ifa;
1760 	struct in6_aliasreq ifra;
1761 	struct in6_ifaddr *ia, *ib;
1762 	int error, plen0;
1763 	struct in6_addr mask;
1764 	int prefixlen = pr->ndpr_plen;
1765 	int updateflags;
1766 	char ip6buf[INET6_ADDRSTRLEN];
1767 
1768 	in6_prefixlen2mask(&mask, prefixlen);
1769 
1770 	/*
1771 	 * find a link-local address (will be interface ID).
1772 	 * Is it really mandatory? Theoretically, a global or a site-local
1773 	 * address can be configured without a link-local address, if we
1774 	 * have a unique interface identifier...
1775 	 *
1776 	 * it is not mandatory to have a link-local address, we can generate
1777 	 * interface identifier on the fly.  we do this because:
1778 	 * (1) it should be the easiest way to find interface identifier.
1779 	 * (2) RFC2462 5.4 suggesting the use of the same interface identifier
1780 	 * for multiple addresses on a single interface, and possible shortcut
1781 	 * of DAD.  we omitted DAD for this reason in the past.
1782 	 * (3) a user can prevent autoconfiguration of global address
1783 	 * by removing link-local address by hand (this is partly because we
1784 	 * don't have other way to control the use of IPv6 on an interface.
1785 	 * this has been our design choice - cf. NRL's "ifconfig auto").
1786 	 * (4) it is easier to manage when an interface has addresses
1787 	 * with the same interface identifier, than to have multiple addresses
1788 	 * with different interface identifiers.
1789 	 */
1790 	ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp, 0); /* 0 is OK? */
1791 	if (ifa)
1792 		ib = (struct in6_ifaddr *)ifa;
1793 	else
1794 		return NULL;
1795 
1796 	/* prefixlen + ifidlen must be equal to 128 */
1797 	plen0 = in6_mask2len(&ib->ia_prefixmask.sin6_addr, NULL);
1798 	if (prefixlen != plen0) {
1799 		nd6log((LOG_INFO, "in6_ifadd: wrong prefixlen for %s "
1800 		    "(prefix=%d ifid=%d)\n",
1801 		    if_name(ifp), prefixlen, 128 - plen0));
1802 		return NULL;
1803 	}
1804 
1805 	/* make ifaddr */
1806 
1807 	bzero(&ifra, sizeof(ifra));
1808 	/*
1809 	 * in6_update_ifa() does not use ifra_name, but we accurately set it
1810 	 * for safety.
1811 	 */
1812 	strncpy(ifra.ifra_name, if_name(ifp), sizeof(ifra.ifra_name));
1813 	ifra.ifra_addr.sin6_family = AF_INET6;
1814 	ifra.ifra_addr.sin6_len = sizeof(struct sockaddr_in6);
1815 	/* prefix */
1816 	ifra.ifra_addr.sin6_addr = pr->ndpr_prefix.sin6_addr;
1817 	ifra.ifra_addr.sin6_addr.s6_addr32[0] &= mask.s6_addr32[0];
1818 	ifra.ifra_addr.sin6_addr.s6_addr32[1] &= mask.s6_addr32[1];
1819 	ifra.ifra_addr.sin6_addr.s6_addr32[2] &= mask.s6_addr32[2];
1820 	ifra.ifra_addr.sin6_addr.s6_addr32[3] &= mask.s6_addr32[3];
1821 
1822 	/* interface ID */
1823 	ifra.ifra_addr.sin6_addr.s6_addr32[0] |=
1824 	    (ib->ia_addr.sin6_addr.s6_addr32[0] & ~mask.s6_addr32[0]);
1825 	ifra.ifra_addr.sin6_addr.s6_addr32[1] |=
1826 	    (ib->ia_addr.sin6_addr.s6_addr32[1] & ~mask.s6_addr32[1]);
1827 	ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
1828 	    (ib->ia_addr.sin6_addr.s6_addr32[2] & ~mask.s6_addr32[2]);
1829 	ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
1830 	    (ib->ia_addr.sin6_addr.s6_addr32[3] & ~mask.s6_addr32[3]);
1831 
1832 	/* new prefix mask. */
1833 	ifra.ifra_prefixmask.sin6_len = sizeof(struct sockaddr_in6);
1834 	ifra.ifra_prefixmask.sin6_family = AF_INET6;
1835 	bcopy(&mask, &ifra.ifra_prefixmask.sin6_addr,
1836 	    sizeof(ifra.ifra_prefixmask.sin6_addr));
1837 
1838 	/* lifetimes. */
1839 	ifra.ifra_lifetime.ia6t_vltime = pr->ndpr_vltime;
1840 	ifra.ifra_lifetime.ia6t_pltime = pr->ndpr_pltime;
1841 
1842 	/* XXX: scope zone ID? */
1843 
1844 	ifra.ifra_flags |= IN6_IFF_AUTOCONF; /* obey autoconf */
1845 
1846 	/*
1847 	 * Make sure that we do not have this address already.  This should
1848 	 * usually not happen, but we can still see this case, e.g., if we
1849 	 * have manually configured the exact address to be configured.
1850 	 */
1851 	if (in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr) != NULL) {
1852 		/* this should be rare enough to make an explicit log */
1853 		log(LOG_INFO, "in6_ifadd: %s is already configured\n",
1854 		    ip6_sprintf(ip6buf, &ifra.ifra_addr.sin6_addr));
1855 		return (NULL);
1856 	}
1857 
1858 	/*
1859 	 * Allocate ifaddr structure, link into chain, etc.
1860 	 * If we are going to create a new address upon receiving a multicasted
1861 	 * RA, we need to impose a random delay before starting DAD.
1862 	 * [draft-ietf-ipv6-rfc2462bis-02.txt, Section 5.4.2]
1863 	 */
1864 	updateflags = 0;
1865 	if (mcast)
1866 		updateflags |= IN6_IFAUPDATE_DADDELAY;
1867 	if ((error = in6_update_ifa(ifp, &ifra, NULL, updateflags)) != 0) {
1868 		nd6log((LOG_ERR,
1869 		    "in6_ifadd: failed to make ifaddr %s on %s (errno=%d)\n",
1870 		    ip6_sprintf(ip6buf, &ifra.ifra_addr.sin6_addr),
1871 		    if_name(ifp), error));
1872 		return (NULL);	/* ifaddr must not have been allocated. */
1873 	}
1874 
1875 	ia = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr);
1876 
1877 	return (ia);		/* this is always non-NULL */
1878 }
1879 
1880 /*
1881  * ia0 - corresponding public address
1882  */
1883 int
1884 in6_tmpifadd(const struct in6_ifaddr *ia0, int forcegen, int delay)
1885 {
1886 	INIT_VNET_INET6(curvnet);
1887 	struct ifnet *ifp = ia0->ia_ifa.ifa_ifp;
1888 	struct in6_ifaddr *newia, *ia;
1889 	struct in6_aliasreq ifra;
1890 	int i, error;
1891 	int trylimit = 3;	/* XXX: adhoc value */
1892 	int updateflags;
1893 	u_int32_t randid[2];
1894 	time_t vltime0, pltime0;
1895 
1896 	bzero(&ifra, sizeof(ifra));
1897 	strncpy(ifra.ifra_name, if_name(ifp), sizeof(ifra.ifra_name));
1898 	ifra.ifra_addr = ia0->ia_addr;
1899 	/* copy prefix mask */
1900 	ifra.ifra_prefixmask = ia0->ia_prefixmask;
1901 	/* clear the old IFID */
1902 	for (i = 0; i < 4; i++) {
1903 		ifra.ifra_addr.sin6_addr.s6_addr32[i] &=
1904 		    ifra.ifra_prefixmask.sin6_addr.s6_addr32[i];
1905 	}
1906 
1907   again:
1908 	if (in6_get_tmpifid(ifp, (u_int8_t *)randid,
1909 	    (const u_int8_t *)&ia0->ia_addr.sin6_addr.s6_addr[8], forcegen)) {
1910 		nd6log((LOG_NOTICE, "in6_tmpifadd: failed to find a good "
1911 		    "random IFID\n"));
1912 		return (EINVAL);
1913 	}
1914 	ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
1915 	    (randid[0] & ~(ifra.ifra_prefixmask.sin6_addr.s6_addr32[2]));
1916 	ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
1917 	    (randid[1] & ~(ifra.ifra_prefixmask.sin6_addr.s6_addr32[3]));
1918 
1919 	/*
1920 	 * in6_get_tmpifid() quite likely provided a unique interface ID.
1921 	 * However, we may still have a chance to see collision, because
1922 	 * there may be a time lag between generation of the ID and generation
1923 	 * of the address.  So, we'll do one more sanity check.
1924 	 */
1925 	for (ia = V_in6_ifaddr; ia; ia = ia->ia_next) {
1926 		if (IN6_ARE_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
1927 		    &ifra.ifra_addr.sin6_addr)) {
1928 			if (trylimit-- == 0) {
1929 				/*
1930 				 * Give up.  Something strange should have
1931 				 * happened.
1932 				 */
1933 				nd6log((LOG_NOTICE, "in6_tmpifadd: failed to "
1934 				    "find a unique random IFID\n"));
1935 				return (EEXIST);
1936 			}
1937 			forcegen = 1;
1938 			goto again;
1939 		}
1940 	}
1941 
1942 	/*
1943 	 * The Valid Lifetime is the lower of the Valid Lifetime of the
1944          * public address or TEMP_VALID_LIFETIME.
1945 	 * The Preferred Lifetime is the lower of the Preferred Lifetime
1946          * of the public address or TEMP_PREFERRED_LIFETIME -
1947          * DESYNC_FACTOR.
1948 	 */
1949 	if (ia0->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
1950 		vltime0 = IFA6_IS_INVALID(ia0) ? 0 :
1951 		    (ia0->ia6_lifetime.ia6t_vltime -
1952 		    (time_second - ia0->ia6_updatetime));
1953 		if (vltime0 > V_ip6_temp_valid_lifetime)
1954 			vltime0 = V_ip6_temp_valid_lifetime;
1955 	} else
1956 		vltime0 = V_ip6_temp_valid_lifetime;
1957 	if (ia0->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
1958 		pltime0 = IFA6_IS_DEPRECATED(ia0) ? 0 :
1959 		    (ia0->ia6_lifetime.ia6t_pltime -
1960 		    (time_second - ia0->ia6_updatetime));
1961 		if (pltime0 > V_ip6_temp_preferred_lifetime - V_ip6_desync_factor){
1962 			pltime0 = V_ip6_temp_preferred_lifetime -
1963 			    V_ip6_desync_factor;
1964 		}
1965 	} else
1966 		pltime0 = V_ip6_temp_preferred_lifetime - V_ip6_desync_factor;
1967 	ifra.ifra_lifetime.ia6t_vltime = vltime0;
1968 	ifra.ifra_lifetime.ia6t_pltime = pltime0;
1969 
1970 	/*
1971 	 * A temporary address is created only if this calculated Preferred
1972 	 * Lifetime is greater than REGEN_ADVANCE time units.
1973 	 */
1974 	if (ifra.ifra_lifetime.ia6t_pltime <= V_ip6_temp_regen_advance)
1975 		return (0);
1976 
1977 	/* XXX: scope zone ID? */
1978 
1979 	ifra.ifra_flags |= (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY);
1980 
1981 	/* allocate ifaddr structure, link into chain, etc. */
1982 	updateflags = 0;
1983 	if (delay)
1984 		updateflags |= IN6_IFAUPDATE_DADDELAY;
1985 	if ((error = in6_update_ifa(ifp, &ifra, NULL, updateflags)) != 0)
1986 		return (error);
1987 
1988 	newia = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr);
1989 	if (newia == NULL) {	/* XXX: can it happen? */
1990 		nd6log((LOG_ERR,
1991 		    "in6_tmpifadd: ifa update succeeded, but we got "
1992 		    "no ifaddr\n"));
1993 		return (EINVAL); /* XXX */
1994 	}
1995 	newia->ia6_ndpr = ia0->ia6_ndpr;
1996 	newia->ia6_ndpr->ndpr_refcnt++;
1997 
1998 	/*
1999 	 * A newly added address might affect the status of other addresses.
2000 	 * XXX: when the temporary address is generated with a new public
2001 	 * address, the onlink check is redundant.  However, it would be safe
2002 	 * to do the check explicitly everywhere a new address is generated,
2003 	 * and, in fact, we surely need the check when we create a new
2004 	 * temporary address due to deprecation of an old temporary address.
2005 	 */
2006 	pfxlist_onlink_check();
2007 
2008 	return (0);
2009 }
2010 
2011 static int
2012 in6_init_prefix_ltimes(struct nd_prefix *ndpr)
2013 {
2014 	if (ndpr->ndpr_pltime == ND6_INFINITE_LIFETIME)
2015 		ndpr->ndpr_preferred = 0;
2016 	else
2017 		ndpr->ndpr_preferred = time_second + ndpr->ndpr_pltime;
2018 	if (ndpr->ndpr_vltime == ND6_INFINITE_LIFETIME)
2019 		ndpr->ndpr_expire = 0;
2020 	else
2021 		ndpr->ndpr_expire = time_second + ndpr->ndpr_vltime;
2022 
2023 	return 0;
2024 }
2025 
2026 static void
2027 in6_init_address_ltimes(struct nd_prefix *new, struct in6_addrlifetime *lt6)
2028 {
2029 	/* init ia6t_expire */
2030 	if (lt6->ia6t_vltime == ND6_INFINITE_LIFETIME)
2031 		lt6->ia6t_expire = 0;
2032 	else {
2033 		lt6->ia6t_expire = time_second;
2034 		lt6->ia6t_expire += lt6->ia6t_vltime;
2035 	}
2036 
2037 	/* init ia6t_preferred */
2038 	if (lt6->ia6t_pltime == ND6_INFINITE_LIFETIME)
2039 		lt6->ia6t_preferred = 0;
2040 	else {
2041 		lt6->ia6t_preferred = time_second;
2042 		lt6->ia6t_preferred += lt6->ia6t_pltime;
2043 	}
2044 }
2045 
2046 /*
2047  * Delete all the routing table entries that use the specified gateway.
2048  * XXX: this function causes search through all entries of routing table, so
2049  * it shouldn't be called when acting as a router.
2050  */
2051 void
2052 rt6_flush(struct in6_addr *gateway, struct ifnet *ifp)
2053 {
2054 	INIT_VNET_NET(curvnet);
2055 	struct radix_node_head *rnh = V_rt_tables[0][AF_INET6];
2056 	int s = splnet();
2057 
2058 	/* We'll care only link-local addresses */
2059 	if (!IN6_IS_ADDR_LINKLOCAL(gateway)) {
2060 		splx(s);
2061 		return;
2062 	}
2063 
2064 	RADIX_NODE_HEAD_LOCK(rnh);
2065 	rnh->rnh_walktree(rnh, rt6_deleteroute, (void *)gateway);
2066 	RADIX_NODE_HEAD_UNLOCK(rnh);
2067 	splx(s);
2068 }
2069 
2070 static int
2071 rt6_deleteroute(struct radix_node *rn, void *arg)
2072 {
2073 #define SIN6(s)	((struct sockaddr_in6 *)s)
2074 	struct rtentry *rt = (struct rtentry *)rn;
2075 	struct in6_addr *gate = (struct in6_addr *)arg;
2076 
2077 	if (rt->rt_gateway == NULL || rt->rt_gateway->sa_family != AF_INET6)
2078 		return (0);
2079 
2080 	if (!IN6_ARE_ADDR_EQUAL(gate, &SIN6(rt->rt_gateway)->sin6_addr)) {
2081 		return (0);
2082 	}
2083 
2084 	/*
2085 	 * Do not delete a static route.
2086 	 * XXX: this seems to be a bit ad-hoc. Should we consider the
2087 	 * 'cloned' bit instead?
2088 	 */
2089 	if ((rt->rt_flags & RTF_STATIC) != 0)
2090 		return (0);
2091 
2092 	/*
2093 	 * We delete only host route. This means, in particular, we don't
2094 	 * delete default route.
2095 	 */
2096 	if ((rt->rt_flags & RTF_HOST) == 0)
2097 		return (0);
2098 
2099 	return (rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
2100 	    rt_mask(rt), rt->rt_flags, 0));
2101 #undef SIN6
2102 }
2103 
2104 int
2105 nd6_setdefaultiface(int ifindex)
2106 {
2107 	INIT_VNET_NET(curvnet);
2108 	INIT_VNET_INET6(curvnet);
2109 	int error = 0;
2110 
2111 	if (ifindex < 0 || V_if_index < ifindex)
2112 		return (EINVAL);
2113 	if (ifindex != 0 && !ifnet_byindex(ifindex))
2114 		return (EINVAL);
2115 
2116 	if (V_nd6_defifindex != ifindex) {
2117 		V_nd6_defifindex = ifindex;
2118 		if (V_nd6_defifindex > 0)
2119 			V_nd6_defifp = ifnet_byindex(V_nd6_defifindex);
2120 		else
2121 			V_nd6_defifp = NULL;
2122 
2123 		/*
2124 		 * Our current implementation assumes one-to-one maping between
2125 		 * interfaces and links, so it would be natural to use the
2126 		 * default interface as the default link.
2127 		 */
2128 		scope6_setdefault(V_nd6_defifp);
2129 	}
2130 
2131 	return (error);
2132 }
2133