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