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