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