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