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