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