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