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