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