xref: /titanic_51/usr/src/uts/common/inet/ip/ip6_if.c (revision 1c2187e7a735b31a46941879f0bd124e0aa325a3)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 /*
26  * Copyright (c) 1990 Mentat Inc.
27  */
28 
29 #pragma ident	"%Z%%M%	%I%	%E% SMI"
30 
31 /*
32  * This file contains the interface control functions for IPv6.
33  */
34 
35 #include <sys/types.h>
36 #include <sys/sysmacros.h>
37 #include <sys/stream.h>
38 #include <sys/dlpi.h>
39 #include <sys/stropts.h>
40 #include <sys/ddi.h>
41 #include <sys/cmn_err.h>
42 #include <sys/kstat.h>
43 #include <sys/debug.h>
44 #include <sys/zone.h>
45 #include <sys/policy.h>
46 
47 #include <sys/systm.h>
48 #include <sys/param.h>
49 #include <sys/socket.h>
50 #include <sys/isa_defs.h>
51 #include <net/if.h>
52 #include <net/if_dl.h>
53 #include <net/route.h>
54 #include <netinet/in.h>
55 #include <netinet/igmp_var.h>
56 #include <netinet/ip6.h>
57 #include <netinet/icmp6.h>
58 #include <netinet/in.h>
59 
60 #include <inet/common.h>
61 #include <inet/nd.h>
62 #include <inet/mib2.h>
63 #include <inet/ip.h>
64 #include <inet/ip6.h>
65 #include <inet/ip_multi.h>
66 #include <inet/ip_ire.h>
67 #include <inet/ip_rts.h>
68 #include <inet/ip_ndp.h>
69 #include <inet/ip_if.h>
70 #include <inet/ip6_asp.h>
71 #include <inet/tun.h>
72 #include <inet/ipclassifier.h>
73 #include <inet/sctp_ip.h>
74 
75 #include <sys/tsol/tndb.h>
76 #include <sys/tsol/tnet.h>
77 
78 static in6_addr_t	ipv6_ll_template =
79 			{(uint32_t)V6_LINKLOCAL, 0x0, 0x0, 0x0};
80 
81 static ipif_t *
82 ipif_lookup_interface_v6(const in6_addr_t *if_addr, const in6_addr_t *dst,
83     queue_t *q, mblk_t *mp, ipsq_func_t func, int *error, ip_stack_t *ipst);
84 
85 /*
86  * These two functions, ipif_lookup_group_v6() and ill_lookup_group_v6(),
87  * are called when an application does not specify an interface to be
88  * used for multicast traffic.  It calls ire_lookup_multi_v6() to look
89  * for an interface route for the specified multicast group.  Doing
90  * this allows the administrator to add prefix routes for multicast to
91  * indicate which interface to be used for multicast traffic in the above
92  * scenario.  The route could be for all multicast (ff00::/8), for a single
93  * multicast group (a /128 route) or anything in between.  If there is no
94  * such multicast route, we just find any multicast capable interface and
95  * return it.
96  */
97 ipif_t *
98 ipif_lookup_group_v6(const in6_addr_t *group, zoneid_t zoneid, ip_stack_t *ipst)
99 {
100 	ire_t	*ire;
101 	ipif_t	*ipif;
102 
103 	ire = ire_lookup_multi_v6(group, zoneid, ipst);
104 	if (ire != NULL) {
105 		ipif = ire->ire_ipif;
106 		ipif_refhold(ipif);
107 		ire_refrele(ire);
108 		return (ipif);
109 	}
110 
111 	return (ipif_lookup_multicast(ipst, zoneid, B_TRUE));
112 }
113 
114 ill_t *
115 ill_lookup_group_v6(const in6_addr_t *group, zoneid_t zoneid, ip_stack_t *ipst)
116 {
117 	ire_t	*ire;
118 	ill_t	*ill;
119 	ipif_t	*ipif;
120 
121 	ire = ire_lookup_multi_v6(group, zoneid, ipst);
122 	if (ire != NULL) {
123 		ill = ire->ire_ipif->ipif_ill;
124 		ill_refhold(ill);
125 		ire_refrele(ire);
126 		return (ill);
127 	}
128 
129 	ipif = ipif_lookup_multicast(ipst, zoneid, B_TRUE);
130 	if (ipif == NULL)
131 		return (NULL);
132 
133 	ill = ipif->ipif_ill;
134 	ill_refhold(ill);
135 	ipif_refrele(ipif);
136 	return (ill);
137 }
138 
139 /*
140  * Look for an ipif with the specified interface address and destination.
141  * The destination address is used only for matching point-to-point interfaces.
142  */
143 static ipif_t *
144 ipif_lookup_interface_v6(const in6_addr_t *if_addr, const in6_addr_t *dst,
145     queue_t *q, mblk_t *mp, ipsq_func_t func, int *error, ip_stack_t *ipst)
146 {
147 	ipif_t	*ipif;
148 	ill_t	*ill;
149 	ipsq_t	*ipsq;
150 	ill_walk_context_t ctx;
151 
152 	if (error != NULL)
153 		*error = 0;
154 
155 	/*
156 	 * First match all the point-to-point interfaces
157 	 * before looking at non-point-to-point interfaces.
158 	 * This is done to avoid returning non-point-to-point
159 	 * ipif instead of unnumbered point-to-point ipif.
160 	 */
161 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
162 	ill = ILL_START_WALK_V6(&ctx, ipst);
163 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
164 		GRAB_CONN_LOCK(q);
165 		mutex_enter(&ill->ill_lock);
166 		for (ipif = ill->ill_ipif; ipif != NULL;
167 		    ipif = ipif->ipif_next) {
168 			/* Allow the ipif to be down */
169 			if ((ipif->ipif_flags & IPIF_POINTOPOINT) &&
170 			    (IN6_ARE_ADDR_EQUAL(&ipif->ipif_v6lcl_addr,
171 			    if_addr)) &&
172 			    (IN6_ARE_ADDR_EQUAL(&ipif->ipif_v6pp_dst_addr,
173 			    dst))) {
174 				if (IPIF_CAN_LOOKUP(ipif)) {
175 					ipif_refhold_locked(ipif);
176 					mutex_exit(&ill->ill_lock);
177 					RELEASE_CONN_LOCK(q);
178 					rw_exit(&ipst->ips_ill_g_lock);
179 					return (ipif);
180 				} else if (IPIF_CAN_WAIT(ipif, q)) {
181 					ipsq = ill->ill_phyint->phyint_ipsq;
182 					mutex_enter(&ipsq->ipsq_lock);
183 					mutex_exit(&ill->ill_lock);
184 					rw_exit(&ipst->ips_ill_g_lock);
185 					ipsq_enq(ipsq, q, mp, func, NEW_OP,
186 					    ill);
187 					mutex_exit(&ipsq->ipsq_lock);
188 					RELEASE_CONN_LOCK(q);
189 					if (error != NULL)
190 						*error = EINPROGRESS;
191 					return (NULL);
192 				}
193 			}
194 		}
195 		mutex_exit(&ill->ill_lock);
196 		RELEASE_CONN_LOCK(q);
197 	}
198 	rw_exit(&ipst->ips_ill_g_lock);
199 	/* lookup the ipif based on interface address */
200 	ipif = ipif_lookup_addr_v6(if_addr, NULL, ALL_ZONES, q, mp, func,
201 	    error, ipst);
202 	ASSERT(ipif == NULL || ipif->ipif_isv6);
203 	return (ipif);
204 }
205 
206 /*
207  * Look for an ipif with the specified address. For point-point links
208  * we look for matches on either the destination address and the local
209  * address, but we ignore the check on the local address if IPIF_UNNUMBERED
210  * is set.
211  * Matches on a specific ill if match_ill is set.
212  */
213 /* ARGSUSED */
214 ipif_t *
215 ipif_lookup_addr_v6(const in6_addr_t *addr, ill_t *match_ill, zoneid_t zoneid,
216     queue_t *q, mblk_t *mp, ipsq_func_t func, int *error, ip_stack_t *ipst)
217 {
218 	ipif_t	*ipif;
219 	ill_t	*ill;
220 	boolean_t  ptp = B_FALSE;
221 	ipsq_t	*ipsq;
222 	ill_walk_context_t ctx;
223 
224 	if (error != NULL)
225 		*error = 0;
226 
227 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
228 	/*
229 	 * Repeat twice, first based on local addresses and
230 	 * next time for pointopoint.
231 	 */
232 repeat:
233 	ill = ILL_START_WALK_V6(&ctx, ipst);
234 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
235 		if (match_ill != NULL && ill != match_ill) {
236 			continue;
237 		}
238 		GRAB_CONN_LOCK(q);
239 		mutex_enter(&ill->ill_lock);
240 		for (ipif = ill->ill_ipif; ipif != NULL;
241 		    ipif = ipif->ipif_next) {
242 			if (zoneid != ALL_ZONES &&
243 			    ipif->ipif_zoneid != zoneid &&
244 			    ipif->ipif_zoneid != ALL_ZONES)
245 				continue;
246 			/* Allow the ipif to be down */
247 			if ((!ptp && (IN6_ARE_ADDR_EQUAL(
248 			    &ipif->ipif_v6lcl_addr, addr) &&
249 			    (ipif->ipif_flags & IPIF_UNNUMBERED) == 0)) ||
250 			    (ptp && (ipif->ipif_flags & IPIF_POINTOPOINT) &&
251 			    IN6_ARE_ADDR_EQUAL(&ipif->ipif_v6pp_dst_addr,
252 			    addr))) {
253 				if (IPIF_CAN_LOOKUP(ipif)) {
254 					ipif_refhold_locked(ipif);
255 					mutex_exit(&ill->ill_lock);
256 					RELEASE_CONN_LOCK(q);
257 					rw_exit(&ipst->ips_ill_g_lock);
258 					return (ipif);
259 				} else if (IPIF_CAN_WAIT(ipif, q)) {
260 					ipsq = ill->ill_phyint->phyint_ipsq;
261 					mutex_enter(&ipsq->ipsq_lock);
262 					mutex_exit(&ill->ill_lock);
263 					rw_exit(&ipst->ips_ill_g_lock);
264 					ipsq_enq(ipsq, q, mp, func, NEW_OP,
265 					    ill);
266 					mutex_exit(&ipsq->ipsq_lock);
267 					RELEASE_CONN_LOCK(q);
268 					if (error != NULL)
269 						*error = EINPROGRESS;
270 					return (NULL);
271 				}
272 			}
273 		}
274 		mutex_exit(&ill->ill_lock);
275 		RELEASE_CONN_LOCK(q);
276 	}
277 
278 	/* If we already did the ptp case, then we are done */
279 	if (ptp) {
280 		rw_exit(&ipst->ips_ill_g_lock);
281 		if (error != NULL)
282 			*error = ENXIO;
283 		return (NULL);
284 	}
285 	ptp = B_TRUE;
286 	goto repeat;
287 }
288 
289 /*
290  * Look for an ipif with the specified address. For point-point links
291  * we look for matches on either the destination address and the local
292  * address, but we ignore the check on the local address if IPIF_UNNUMBERED
293  * is set.
294  * Matches on a specific ill if match_ill is set.
295  * Return the zoneid for the ipif. ALL_ZONES if none found.
296  */
297 zoneid_t
298 ipif_lookup_addr_zoneid_v6(const in6_addr_t *addr, ill_t *match_ill,
299     ip_stack_t *ipst)
300 {
301 	ipif_t	*ipif;
302 	ill_t	*ill;
303 	boolean_t  ptp = B_FALSE;
304 	ill_walk_context_t ctx;
305 	zoneid_t	zoneid;
306 
307 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
308 	/*
309 	 * Repeat twice, first based on local addresses and
310 	 * next time for pointopoint.
311 	 */
312 repeat:
313 	ill = ILL_START_WALK_V6(&ctx, ipst);
314 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
315 		if (match_ill != NULL && ill != match_ill) {
316 			continue;
317 		}
318 		mutex_enter(&ill->ill_lock);
319 		for (ipif = ill->ill_ipif; ipif != NULL;
320 		    ipif = ipif->ipif_next) {
321 			/* Allow the ipif to be down */
322 			if ((!ptp && (IN6_ARE_ADDR_EQUAL(
323 			    &ipif->ipif_v6lcl_addr, addr) &&
324 			    (ipif->ipif_flags & IPIF_UNNUMBERED) == 0)) ||
325 			    (ptp && (ipif->ipif_flags & IPIF_POINTOPOINT) &&
326 			    IN6_ARE_ADDR_EQUAL(&ipif->ipif_v6pp_dst_addr,
327 			    addr)) &&
328 			    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
329 				zoneid = ipif->ipif_zoneid;
330 				mutex_exit(&ill->ill_lock);
331 				rw_exit(&ipst->ips_ill_g_lock);
332 				/*
333 				 * If ipif_zoneid was ALL_ZONES then we have
334 				 * a trusted extensions shared IP address.
335 				 * In that case GLOBAL_ZONEID works to send.
336 				 */
337 				if (zoneid == ALL_ZONES)
338 					zoneid = GLOBAL_ZONEID;
339 				return (zoneid);
340 			}
341 		}
342 		mutex_exit(&ill->ill_lock);
343 	}
344 
345 	/* If we already did the ptp case, then we are done */
346 	if (ptp) {
347 		rw_exit(&ipst->ips_ill_g_lock);
348 		return (ALL_ZONES);
349 	}
350 	ptp = B_TRUE;
351 	goto repeat;
352 }
353 
354 /*
355  * Perform various checks to verify that an address would make sense as a local
356  * interface address.  This is currently only called when an attempt is made
357  * to set a local address.
358  *
359  * Does not allow a v4-mapped address, an address that equals the subnet
360  * anycast address, ... a multicast address, ...
361  */
362 boolean_t
363 ip_local_addr_ok_v6(const in6_addr_t *addr, const in6_addr_t *subnet_mask)
364 {
365 	in6_addr_t subnet;
366 
367 	if (IN6_IS_ADDR_UNSPECIFIED(addr))
368 		return (B_TRUE);	/* Allow all zeros */
369 
370 	/*
371 	 * Don't allow all zeroes or host part, but allow
372 	 * all ones netmask.
373 	 */
374 	V6_MASK_COPY(*addr, *subnet_mask, subnet);
375 	if (IN6_IS_ADDR_V4MAPPED(addr) ||
376 	    (IN6_ARE_ADDR_EQUAL(addr, &subnet) &&
377 	    !IN6_ARE_ADDR_EQUAL(subnet_mask, &ipv6_all_ones)) ||
378 	    (IN6_IS_ADDR_V4COMPAT(addr) && CLASSD(V4_PART_OF_V6((*addr)))) ||
379 	    IN6_IS_ADDR_MULTICAST(addr))
380 		return (B_FALSE);
381 
382 	return (B_TRUE);
383 }
384 
385 /*
386  * Perform various checks to verify that an address would make sense as a
387  * remote/subnet interface address.
388  */
389 boolean_t
390 ip_remote_addr_ok_v6(const in6_addr_t *addr, const in6_addr_t *subnet_mask)
391 {
392 	in6_addr_t subnet;
393 
394 	if (IN6_IS_ADDR_UNSPECIFIED(addr))
395 		return (B_TRUE);	/* Allow all zeros */
396 
397 	V6_MASK_COPY(*addr, *subnet_mask, subnet);
398 	if (IN6_IS_ADDR_V4MAPPED(addr) ||
399 	    (IN6_ARE_ADDR_EQUAL(addr, &subnet) &&
400 	    !IN6_ARE_ADDR_EQUAL(subnet_mask, &ipv6_all_ones)) ||
401 	    IN6_IS_ADDR_MULTICAST(addr) ||
402 	    (IN6_IS_ADDR_V4COMPAT(addr) && CLASSD(V4_PART_OF_V6((*addr)))))
403 		return (B_FALSE);
404 
405 	return (B_TRUE);
406 }
407 
408 /*
409  * ip_rt_add_v6 is called to add an IPv6 route to the forwarding table.
410  * ipif_arg is passed in to associate it with the correct interface
411  * (for link-local destinations and gateways).
412  */
413 /* ARGSUSED1 */
414 int
415 ip_rt_add_v6(const in6_addr_t *dst_addr, const in6_addr_t *mask,
416     const in6_addr_t *gw_addr, const in6_addr_t *src_addr, int flags,
417     ipif_t *ipif_arg, ire_t **ire_arg, queue_t *q, mblk_t *mp, ipsq_func_t func,
418     struct rtsa_s *sp, ip_stack_t *ipst)
419 {
420 	ire_t	*ire;
421 	ire_t	*gw_ire = NULL;
422 	ipif_t	*ipif;
423 	boolean_t ipif_refheld = B_FALSE;
424 	uint_t	type;
425 	int	match_flags = MATCH_IRE_TYPE;
426 	int	error;
427 	tsol_gc_t *gc = NULL;
428 	tsol_gcgrp_t *gcgrp = NULL;
429 	boolean_t gcgrp_xtraref = B_FALSE;
430 
431 	if (ire_arg != NULL)
432 		*ire_arg = NULL;
433 
434 	/*
435 	 * Prevent routes with a zero gateway from being created (since
436 	 * interfaces can currently be plumbed and brought up with no assigned
437 	 * address).
438 	 */
439 	if (IN6_IS_ADDR_UNSPECIFIED(gw_addr))
440 		return (ENETUNREACH);
441 
442 	/*
443 	 * If this is the case of RTF_HOST being set, then we set the netmask
444 	 * to all ones (regardless if one was supplied).
445 	 */
446 	if (flags & RTF_HOST)
447 		mask = &ipv6_all_ones;
448 
449 	/*
450 	 * Get the ipif, if any, corresponding to the gw_addr
451 	 */
452 	ipif = ipif_lookup_interface_v6(gw_addr, dst_addr, q, mp, func,
453 	    &error, ipst);
454 	if (ipif != NULL)
455 		ipif_refheld = B_TRUE;
456 	else if (error == EINPROGRESS) {
457 		ip1dbg(("ip_rt_add_v6: null and EINPROGRESS"));
458 		return (error);
459 	}
460 
461 	/*
462 	 * GateD will attempt to create routes with a loopback interface
463 	 * address as the gateway and with RTF_GATEWAY set.  We allow
464 	 * these routes to be added, but create them as interface routes
465 	 * since the gateway is an interface address.
466 	 */
467 	if ((ipif != NULL) && (ipif->ipif_ire_type == IRE_LOOPBACK)) {
468 		flags &= ~RTF_GATEWAY;
469 		if (IN6_ARE_ADDR_EQUAL(gw_addr, &ipv6_loopback) &&
470 		    IN6_ARE_ADDR_EQUAL(dst_addr, &ipv6_loopback) &&
471 		    IN6_ARE_ADDR_EQUAL(mask, &ipv6_all_ones)) {
472 			ire = ire_ctable_lookup_v6(dst_addr, 0, IRE_LOOPBACK,
473 			    ipif, ALL_ZONES, NULL, match_flags, ipst);
474 			if (ire != NULL) {
475 				ire_refrele(ire);
476 				if (ipif_refheld)
477 					ipif_refrele(ipif);
478 				return (EEXIST);
479 			}
480 			ip1dbg(("ipif_up_done: 0x%p creating IRE 0x%x"
481 			    "for 0x%x\n", (void *)ipif,
482 			    ipif->ipif_ire_type,
483 			    ntohl(ipif->ipif_lcl_addr)));
484 			ire = ire_create_v6(
485 			    dst_addr,
486 			    mask,
487 			    &ipif->ipif_v6src_addr,
488 			    NULL,
489 			    &ipif->ipif_mtu,
490 			    NULL,
491 			    NULL,
492 			    NULL,
493 			    ipif->ipif_net_type,
494 			    ipif,
495 			    NULL,
496 			    0,
497 			    0,
498 			    flags,
499 			    &ire_uinfo_null,
500 			    NULL,
501 			    NULL,
502 			    ipst);
503 			if (ire == NULL) {
504 				if (ipif_refheld)
505 					ipif_refrele(ipif);
506 				return (ENOMEM);
507 			}
508 			error = ire_add(&ire, q, mp, func, B_FALSE);
509 			if (error == 0)
510 				goto save_ire;
511 			/*
512 			 * In the result of failure, ire_add() will have already
513 			 * deleted the ire in question, so there is no need to
514 			 * do that here.
515 			 */
516 			if (ipif_refheld)
517 				ipif_refrele(ipif);
518 			return (error);
519 		}
520 	}
521 
522 	/*
523 	 * Traditionally, interface routes are ones where RTF_GATEWAY isn't set
524 	 * and the gateway address provided is one of the system's interface
525 	 * addresses.  By using the routing socket interface and supplying an
526 	 * RTA_IFP sockaddr with an interface index, an alternate method of
527 	 * specifying an interface route to be created is available which uses
528 	 * the interface index that specifies the outgoing interface rather than
529 	 * the address of an outgoing interface (which may not be able to
530 	 * uniquely identify an interface).  When coupled with the RTF_GATEWAY
531 	 * flag, routes can be specified which not only specify the next-hop to
532 	 * be used when routing to a certain prefix, but also which outgoing
533 	 * interface should be used.
534 	 *
535 	 * Previously, interfaces would have unique addresses assigned to them
536 	 * and so the address assigned to a particular interface could be used
537 	 * to identify a particular interface.  One exception to this was the
538 	 * case of an unnumbered interface (where IPIF_UNNUMBERED was set).
539 	 *
540 	 * With the advent of IPv6 and its link-local addresses, this
541 	 * restriction was relaxed and interfaces could share addresses between
542 	 * themselves.  In fact, typically all of the link-local interfaces on
543 	 * an IPv6 node or router will have the same link-local address.  In
544 	 * order to differentiate between these interfaces, the use of an
545 	 * interface index is necessary and this index can be carried inside a
546 	 * RTA_IFP sockaddr (which is actually a sockaddr_dl).  One restriction
547 	 * of using the interface index, however, is that all of the ipif's that
548 	 * are part of an ill have the same index and so the RTA_IFP sockaddr
549 	 * cannot be used to differentiate between ipif's (or logical
550 	 * interfaces) that belong to the same ill (physical interface).
551 	 *
552 	 * For example, in the following case involving IPv4 interfaces and
553 	 * logical interfaces
554 	 *
555 	 *	192.0.2.32	255.255.255.224	192.0.2.33	U	if0
556 	 *	192.0.2.32	255.255.255.224	192.0.2.34	U	if0:1
557 	 *	192.0.2.32	255.255.255.224	192.0.2.35	U	if0:2
558 	 *
559 	 * the ipif's corresponding to each of these interface routes can be
560 	 * uniquely identified by the "gateway" (actually interface address).
561 	 *
562 	 * In this case involving multiple IPv6 default routes to a particular
563 	 * link-local gateway, the use of RTA_IFP is necessary to specify which
564 	 * default route is of interest:
565 	 *
566 	 *	default		fe80::123:4567:89ab:cdef	U	if0
567 	 *	default		fe80::123:4567:89ab:cdef	U	if1
568 	 */
569 
570 	/* RTF_GATEWAY not set */
571 	if (!(flags & RTF_GATEWAY)) {
572 		queue_t	*stq;
573 
574 		if (sp != NULL) {
575 			ip2dbg(("ip_rt_add_v6: gateway security attributes "
576 			    "cannot be set with interface route\n"));
577 			if (ipif_refheld)
578 				ipif_refrele(ipif);
579 			return (EINVAL);
580 		}
581 
582 		/*
583 		 * As the interface index specified with the RTA_IFP sockaddr is
584 		 * the same for all ipif's off of an ill, the matching logic
585 		 * below uses MATCH_IRE_ILL if such an index was specified.
586 		 * This means that routes sharing the same prefix when added
587 		 * using a RTA_IFP sockaddr must have distinct interface
588 		 * indices (namely, they must be on distinct ill's).
589 		 *
590 		 * On the other hand, since the gateway address will usually be
591 		 * different for each ipif on the system, the matching logic
592 		 * uses MATCH_IRE_IPIF in the case of a traditional interface
593 		 * route.  This means that interface routes for the same prefix
594 		 * can be created if they belong to distinct ipif's and if a
595 		 * RTA_IFP sockaddr is not present.
596 		 */
597 		if (ipif_arg != NULL) {
598 			if (ipif_refheld) {
599 				ipif_refrele(ipif);
600 				ipif_refheld = B_FALSE;
601 			}
602 			ipif = ipif_arg;
603 			match_flags |= MATCH_IRE_ILL;
604 		} else {
605 			/*
606 			 * Check the ipif corresponding to the gw_addr
607 			 */
608 			if (ipif == NULL)
609 				return (ENETUNREACH);
610 			match_flags |= MATCH_IRE_IPIF;
611 		}
612 
613 		ASSERT(ipif != NULL);
614 		/*
615 		 * We check for an existing entry at this point.
616 		 */
617 		match_flags |= MATCH_IRE_MASK;
618 		ire = ire_ftable_lookup_v6(dst_addr, mask, 0, IRE_INTERFACE,
619 		    ipif, NULL, ALL_ZONES, 0, NULL, match_flags, ipst);
620 		if (ire != NULL) {
621 			ire_refrele(ire);
622 			if (ipif_refheld)
623 				ipif_refrele(ipif);
624 			return (EEXIST);
625 		}
626 
627 		stq = (ipif->ipif_net_type == IRE_IF_RESOLVER)
628 		    ? ipif->ipif_rq : ipif->ipif_wq;
629 
630 		/*
631 		 * Create a copy of the IRE_LOOPBACK, IRE_IF_NORESOLVER or
632 		 * IRE_IF_RESOLVER with the modified address and netmask.
633 		 */
634 		ire = ire_create_v6(
635 		    dst_addr,
636 		    mask,
637 		    &ipif->ipif_v6src_addr,
638 		    NULL,
639 		    &ipif->ipif_mtu,
640 		    NULL,
641 		    NULL,
642 		    stq,
643 		    ipif->ipif_net_type,
644 		    ipif,
645 		    NULL,
646 		    0,
647 		    0,
648 		    flags,
649 		    &ire_uinfo_null,
650 		    NULL,
651 		    NULL,
652 		    ipst);
653 		if (ire == NULL) {
654 			if (ipif_refheld)
655 				ipif_refrele(ipif);
656 			return (ENOMEM);
657 		}
658 
659 		/*
660 		 * Some software (for example, GateD and Sun Cluster) attempts
661 		 * to create (what amount to) IRE_PREFIX routes with the
662 		 * loopback address as the gateway.  This is primarily done to
663 		 * set up prefixes with the RTF_REJECT flag set (for example,
664 		 * when generating aggregate routes.)
665 		 *
666 		 * If the IRE type (as defined by ipif->ipif_net_type) is
667 		 * IRE_LOOPBACK, then we map the request into a
668 		 * IRE_IF_NORESOLVER.
669 		 *
670 		 * Needless to say, the real IRE_LOOPBACK is NOT created by this
671 		 * routine, but rather using ire_create_v6() directly.
672 		 */
673 		if (ipif->ipif_net_type == IRE_LOOPBACK)
674 			ire->ire_type = IRE_IF_NORESOLVER;
675 		error = ire_add(&ire, q, mp, func, B_FALSE);
676 		if (error == 0)
677 			goto save_ire;
678 		/*
679 		 * In the result of failure, ire_add() will have already
680 		 * deleted the ire in question, so there is no need to
681 		 * do that here.
682 		 */
683 		if (ipif_refheld)
684 			ipif_refrele(ipif);
685 		return (error);
686 	}
687 	if (ipif_refheld) {
688 		ipif_refrele(ipif);
689 		ipif_refheld = B_FALSE;
690 	}
691 
692 	/*
693 	 * Get an interface IRE for the specified gateway.
694 	 * If we don't have an IRE_IF_NORESOLVER or IRE_IF_RESOLVER for the
695 	 * gateway, it is currently unreachable and we fail the request
696 	 * accordingly.
697 	 */
698 	ipif = ipif_arg;
699 	if (ipif_arg != NULL)
700 		match_flags |= MATCH_IRE_ILL;
701 	gw_ire = ire_ftable_lookup_v6(gw_addr, 0, 0, IRE_INTERFACE, ipif_arg,
702 	    NULL, ALL_ZONES, 0, NULL, match_flags, ipst);
703 	if (gw_ire == NULL)
704 		return (ENETUNREACH);
705 
706 	/*
707 	 * We create one of three types of IREs as a result of this request
708 	 * based on the netmask.  A netmask of all ones (which is automatically
709 	 * assumed when RTF_HOST is set) results in an IRE_HOST being created.
710 	 * An all zeroes netmask implies a default route so an IRE_DEFAULT is
711 	 * created.  Otherwise, an IRE_PREFIX route is created for the
712 	 * destination prefix.
713 	 */
714 	if (IN6_ARE_ADDR_EQUAL(mask, &ipv6_all_ones))
715 		type = IRE_HOST;
716 	else if (IN6_IS_ADDR_UNSPECIFIED(mask))
717 		type = IRE_DEFAULT;
718 	else
719 		type = IRE_PREFIX;
720 
721 	/* check for a duplicate entry */
722 	ire = ire_ftable_lookup_v6(dst_addr, mask, gw_addr, type, ipif_arg,
723 	    NULL, ALL_ZONES, 0, NULL,
724 	    match_flags | MATCH_IRE_MASK | MATCH_IRE_GW, ipst);
725 	if (ire != NULL) {
726 		ire_refrele(gw_ire);
727 		ire_refrele(ire);
728 		return (EEXIST);
729 	}
730 
731 	/* Security attribute exists */
732 	if (sp != NULL) {
733 		tsol_gcgrp_addr_t ga;
734 
735 		/* find or create the gateway credentials group */
736 		ga.ga_af = AF_INET6;
737 		ga.ga_addr = *gw_addr;
738 
739 		/* we hold reference to it upon success */
740 		gcgrp = gcgrp_lookup(&ga, B_TRUE);
741 		if (gcgrp == NULL) {
742 			ire_refrele(gw_ire);
743 			return (ENOMEM);
744 		}
745 
746 		/*
747 		 * Create and add the security attribute to the group; a
748 		 * reference to the group is made upon allocating a new
749 		 * entry successfully.  If it finds an already-existing
750 		 * entry for the security attribute in the group, it simply
751 		 * returns it and no new reference is made to the group.
752 		 */
753 		gc = gc_create(sp, gcgrp, &gcgrp_xtraref);
754 		if (gc == NULL) {
755 			/* release reference held by gcgrp_lookup */
756 			GCGRP_REFRELE(gcgrp);
757 			ire_refrele(gw_ire);
758 			return (ENOMEM);
759 		}
760 	}
761 
762 	/* Create the IRE. */
763 	ire = ire_create_v6(
764 	    dst_addr,				/* dest address */
765 	    mask,				/* mask */
766 	    /* src address assigned by the caller? */
767 	    (((flags & RTF_SETSRC) && !IN6_IS_ADDR_UNSPECIFIED(src_addr)) ?
768 	    src_addr : NULL),
769 	    gw_addr,				/* gateway address */
770 	    &gw_ire->ire_max_frag,
771 	    NULL,				/* no src nce */
772 	    NULL,				/* no recv-from queue */
773 	    NULL,				/* no send-to queue */
774 	    (ushort_t)type,			/* IRE type */
775 	    ipif_arg,
776 	    NULL,
777 	    0,
778 	    0,
779 	    flags,
780 	    &gw_ire->ire_uinfo,			/* Inherit ULP info from gw */
781 	    gc,					/* security attribute */
782 	    NULL,
783 	    ipst);
784 
785 	/*
786 	 * The ire holds a reference to the 'gc' and the 'gc' holds a
787 	 * reference to the 'gcgrp'. We can now release the extra reference
788 	 * the 'gcgrp' acquired in the gcgrp_lookup, if it was not used.
789 	 */
790 	if (gcgrp_xtraref)
791 		GCGRP_REFRELE(gcgrp);
792 	if (ire == NULL) {
793 		if (gc != NULL)
794 			GC_REFRELE(gc);
795 		ire_refrele(gw_ire);
796 		return (ENOMEM);
797 	}
798 
799 	/*
800 	 * POLICY: should we allow an RTF_HOST with address INADDR_ANY?
801 	 * SUN/OS socket stuff does but do we really want to allow ::0 ?
802 	 */
803 
804 	/* Add the new IRE. */
805 	error = ire_add(&ire, q, mp, func, B_FALSE);
806 	/*
807 	 * In the result of failure, ire_add() will have already
808 	 * deleted the ire in question, so there is no need to
809 	 * do that here.
810 	 */
811 	if (error != 0) {
812 		ire_refrele(gw_ire);
813 		return (error);
814 	}
815 
816 	if (flags & RTF_MULTIRT) {
817 		/*
818 		 * Invoke the CGTP (multirouting) filtering module
819 		 * to add the dst address in the filtering database.
820 		 * Replicated inbound packets coming from that address
821 		 * will be filtered to discard the duplicates.
822 		 * It is not necessary to call the CGTP filter hook
823 		 * when the dst address is a multicast, because an
824 		 * IP source address cannot be a multicast.
825 		 */
826 		if (ipst->ips_ip_cgtp_filter_ops != NULL &&
827 		    !IN6_IS_ADDR_MULTICAST(&(ire->ire_addr_v6))) {
828 			int res;
829 
830 			res = ipst->ips_ip_cgtp_filter_ops->cfo_add_dest_v6(
831 			    ipst->ips_netstack->netstack_stackid,
832 			    &ire->ire_addr_v6,
833 			    &ire->ire_gateway_addr_v6,
834 			    &ire->ire_src_addr_v6,
835 			    &gw_ire->ire_src_addr_v6);
836 			if (res != 0) {
837 				ire_refrele(gw_ire);
838 				ire_delete(ire);
839 				return (res);
840 			}
841 		}
842 	}
843 
844 	/*
845 	 * Now that the prefix IRE entry has been created, delete any
846 	 * existing gateway IRE cache entries as well as any IRE caches
847 	 * using the gateway, and force them to be created through
848 	 * ip_newroute_v6.
849 	 */
850 	if (gc != NULL) {
851 		ASSERT(gcgrp != NULL);
852 		ire_clookup_delete_cache_gw_v6(gw_addr, ALL_ZONES, ipst);
853 	}
854 
855 save_ire:
856 	if (gw_ire != NULL) {
857 		ire_refrele(gw_ire);
858 	}
859 	if (ipif != NULL) {
860 		mblk_t	*save_mp;
861 
862 		/*
863 		 * Save enough information so that we can recreate the IRE if
864 		 * the interface goes down and then up.  The metrics associated
865 		 * with the route will be saved as well when rts_setmetrics() is
866 		 * called after the IRE has been created.  In the case where
867 		 * memory cannot be allocated, none of this information will be
868 		 * saved.
869 		 */
870 		save_mp = allocb(sizeof (ifrt_t), BPRI_MED);
871 		if (save_mp != NULL) {
872 			ifrt_t	*ifrt;
873 
874 			save_mp->b_wptr += sizeof (ifrt_t);
875 			ifrt = (ifrt_t *)save_mp->b_rptr;
876 			bzero(ifrt, sizeof (ifrt_t));
877 			ifrt->ifrt_type = ire->ire_type;
878 			ifrt->ifrt_v6addr = ire->ire_addr_v6;
879 			mutex_enter(&ire->ire_lock);
880 			ifrt->ifrt_v6gateway_addr = ire->ire_gateway_addr_v6;
881 			ifrt->ifrt_v6src_addr = ire->ire_src_addr_v6;
882 			mutex_exit(&ire->ire_lock);
883 			ifrt->ifrt_v6mask = ire->ire_mask_v6;
884 			ifrt->ifrt_flags = ire->ire_flags;
885 			ifrt->ifrt_max_frag = ire->ire_max_frag;
886 			mutex_enter(&ipif->ipif_saved_ire_lock);
887 			save_mp->b_cont = ipif->ipif_saved_ire_mp;
888 			ipif->ipif_saved_ire_mp = save_mp;
889 			ipif->ipif_saved_ire_cnt++;
890 			mutex_exit(&ipif->ipif_saved_ire_lock);
891 		}
892 	}
893 	if (ire_arg != NULL) {
894 		/*
895 		 * Store the ire that was successfully added into where ire_arg
896 		 * points to so that callers don't have to look it up
897 		 * themselves (but they are responsible for ire_refrele()ing
898 		 * the ire when they are finished with it).
899 		 */
900 		*ire_arg = ire;
901 	} else {
902 		ire_refrele(ire);		/* Held in ire_add */
903 	}
904 	if (ipif_refheld)
905 		ipif_refrele(ipif);
906 	return (0);
907 }
908 
909 /*
910  * ip_rt_delete_v6 is called to delete an IPv6 route.
911  * ipif_arg is passed in to associate it with the correct interface
912  * (for link-local destinations and gateways).
913  */
914 /* ARGSUSED4 */
915 int
916 ip_rt_delete_v6(const in6_addr_t *dst_addr, const in6_addr_t *mask,
917     const in6_addr_t *gw_addr, uint_t rtm_addrs, int flags, ipif_t *ipif_arg,
918     queue_t *q, mblk_t *mp, ipsq_func_t func, ip_stack_t *ipst)
919 {
920 	ire_t	*ire = NULL;
921 	ipif_t	*ipif;
922 	uint_t	type;
923 	uint_t	match_flags = MATCH_IRE_TYPE;
924 	int	err = 0;
925 	boolean_t	ipif_refheld = B_FALSE;
926 
927 	/*
928 	 * If this is the case of RTF_HOST being set, then we set the netmask
929 	 * to all ones.  Otherwise, we use the netmask if one was supplied.
930 	 */
931 	if (flags & RTF_HOST) {
932 		mask = &ipv6_all_ones;
933 		match_flags |= MATCH_IRE_MASK;
934 	} else if (rtm_addrs & RTA_NETMASK) {
935 		match_flags |= MATCH_IRE_MASK;
936 	}
937 
938 	/*
939 	 * Note that RTF_GATEWAY is never set on a delete, therefore
940 	 * we check if the gateway address is one of our interfaces first,
941 	 * and fall back on RTF_GATEWAY routes.
942 	 *
943 	 * This makes it possible to delete an original
944 	 * IRE_IF_NORESOLVER/IRE_IF_RESOLVER - consistent with SunOS 4.1.
945 	 *
946 	 * As the interface index specified with the RTA_IFP sockaddr is the
947 	 * same for all ipif's off of an ill, the matching logic below uses
948 	 * MATCH_IRE_ILL if such an index was specified.  This means a route
949 	 * sharing the same prefix and interface index as the the route
950 	 * intended to be deleted might be deleted instead if a RTA_IFP sockaddr
951 	 * is specified in the request.
952 	 *
953 	 * On the other hand, since the gateway address will usually be
954 	 * different for each ipif on the system, the matching logic
955 	 * uses MATCH_IRE_IPIF in the case of a traditional interface
956 	 * route.  This means that interface routes for the same prefix can be
957 	 * uniquely identified if they belong to distinct ipif's and if a
958 	 * RTA_IFP sockaddr is not present.
959 	 *
960 	 * For more detail on specifying routes by gateway address and by
961 	 * interface index, see the comments in ip_rt_add_v6().
962 	 */
963 	ipif = ipif_lookup_interface_v6(gw_addr, dst_addr, q, mp, func, &err,
964 	    ipst);
965 	if (ipif != NULL) {
966 		ipif_refheld = B_TRUE;
967 		if (ipif_arg != NULL) {
968 			ipif_refrele(ipif);
969 			ipif_refheld = B_FALSE;
970 			ipif = ipif_arg;
971 			match_flags |= MATCH_IRE_ILL;
972 		} else {
973 			match_flags |= MATCH_IRE_IPIF;
974 		}
975 
976 		if (ipif->ipif_ire_type == IRE_LOOPBACK)
977 			ire = ire_ctable_lookup_v6(dst_addr, 0, IRE_LOOPBACK,
978 			    ipif, ALL_ZONES, NULL, match_flags, ipst);
979 		if (ire == NULL)
980 			ire = ire_ftable_lookup_v6(dst_addr, mask, 0,
981 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0, NULL,
982 			    match_flags, ipst);
983 	} else if (err == EINPROGRESS) {
984 		return (err);
985 	} else {
986 		err = 0;
987 	}
988 	if (ire == NULL) {
989 		/*
990 		 * At this point, the gateway address is not one of our own
991 		 * addresses or a matching interface route was not found.  We
992 		 * set the IRE type to lookup based on whether
993 		 * this is a host route, a default route or just a prefix.
994 		 *
995 		 * If an ipif_arg was passed in, then the lookup is based on an
996 		 * interface index so MATCH_IRE_ILL is added to match_flags.
997 		 * In any case, MATCH_IRE_IPIF is cleared and MATCH_IRE_GW is
998 		 * set as the route being looked up is not a traditional
999 		 * interface route.
1000 		 */
1001 		match_flags &= ~MATCH_IRE_IPIF;
1002 		match_flags |= MATCH_IRE_GW;
1003 		if (ipif_arg != NULL)
1004 			match_flags |= MATCH_IRE_ILL;
1005 		if (IN6_ARE_ADDR_EQUAL(mask, &ipv6_all_ones))
1006 			type = IRE_HOST;
1007 		else if (IN6_IS_ADDR_UNSPECIFIED(mask))
1008 			type = IRE_DEFAULT;
1009 		else
1010 			type = IRE_PREFIX;
1011 		ire = ire_ftable_lookup_v6(dst_addr, mask, gw_addr, type,
1012 		    ipif_arg, NULL, ALL_ZONES, 0, NULL, match_flags, ipst);
1013 	}
1014 
1015 	if (ipif_refheld) {
1016 		ipif_refrele(ipif);
1017 		ipif_refheld = B_FALSE;
1018 	}
1019 	if (ire == NULL)
1020 		return (ESRCH);
1021 
1022 	if (ire->ire_flags & RTF_MULTIRT) {
1023 		/*
1024 		 * Invoke the CGTP (multirouting) filtering module
1025 		 * to remove the dst address from the filtering database.
1026 		 * Packets coming from that address will no longer be
1027 		 * filtered to remove duplicates.
1028 		 */
1029 		if (ipst->ips_ip_cgtp_filter_ops != NULL) {
1030 			err = ipst->ips_ip_cgtp_filter_ops->cfo_del_dest_v6(
1031 			    ipst->ips_netstack->netstack_stackid,
1032 			    &ire->ire_addr_v6, &ire->ire_gateway_addr_v6);
1033 		}
1034 	}
1035 
1036 	ipif = ire->ire_ipif;
1037 	if (ipif != NULL) {
1038 		mblk_t		**mpp;
1039 		mblk_t		*mp;
1040 		ifrt_t		*ifrt;
1041 		in6_addr_t	gw_addr_v6;
1042 
1043 		/* Remove from ipif_saved_ire_mp list if it is there */
1044 		mutex_enter(&ire->ire_lock);
1045 		gw_addr_v6 = ire->ire_gateway_addr_v6;
1046 		mutex_exit(&ire->ire_lock);
1047 		mutex_enter(&ipif->ipif_saved_ire_lock);
1048 		for (mpp = &ipif->ipif_saved_ire_mp; *mpp != NULL;
1049 		    mpp = &(*mpp)->b_cont) {
1050 			/*
1051 			 * On a given ipif, the triple of address, gateway and
1052 			 * mask is unique for each saved IRE (in the case of
1053 			 * ordinary interface routes, the gateway address is
1054 			 * all-zeroes).
1055 			 */
1056 			mp = *mpp;
1057 			ifrt = (ifrt_t *)mp->b_rptr;
1058 			if (IN6_ARE_ADDR_EQUAL(&ifrt->ifrt_v6addr,
1059 			    &ire->ire_addr_v6) &&
1060 			    IN6_ARE_ADDR_EQUAL(&ifrt->ifrt_v6gateway_addr,
1061 			    &gw_addr_v6) &&
1062 			    IN6_ARE_ADDR_EQUAL(&ifrt->ifrt_v6mask,
1063 			    &ire->ire_mask_v6)) {
1064 				*mpp = mp->b_cont;
1065 				ipif->ipif_saved_ire_cnt--;
1066 				freeb(mp);
1067 				break;
1068 			}
1069 		}
1070 		mutex_exit(&ipif->ipif_saved_ire_lock);
1071 	}
1072 	ire_delete(ire);
1073 	ire_refrele(ire);
1074 	return (err);
1075 }
1076 
1077 /*
1078  * Derive a token from the link layer address.
1079  */
1080 boolean_t
1081 ill_setdefaulttoken(ill_t *ill)
1082 {
1083 	int 		i;
1084 	in6_addr_t	v6addr, v6mask;
1085 
1086 	if (!MEDIA_V6INTFID(ill->ill_media, ill->ill_phys_addr_length,
1087 	    ill->ill_phys_addr, &v6addr))
1088 		return (B_FALSE);
1089 
1090 	(void) ip_plen_to_mask_v6(IPV6_TOKEN_LEN, &v6mask);
1091 
1092 	for (i = 0; i < 4; i++)
1093 		v6mask.s6_addr32[i] = v6mask.s6_addr32[i] ^
1094 		    (uint32_t)0xffffffff;
1095 
1096 	V6_MASK_COPY(v6addr, v6mask, ill->ill_token);
1097 	ill->ill_token_length = IPV6_TOKEN_LEN;
1098 	return (B_TRUE);
1099 }
1100 
1101 /*
1102  * Create a link-local address from a token.
1103  */
1104 static void
1105 ipif_get_linklocal(in6_addr_t *dest, const in6_addr_t *token)
1106 {
1107 	int i;
1108 
1109 	for (i = 0; i < 4; i++) {
1110 		dest->s6_addr32[i] =
1111 		    token->s6_addr32[i] | ipv6_ll_template.s6_addr32[i];
1112 	}
1113 }
1114 
1115 /*
1116  * Set a nice default address for either automatic tunnels tsrc/96 or
1117  * 6to4 tunnels 2002:<tsrc>::1/64
1118  */
1119 static void
1120 ipif_set_tun_auto_addr(ipif_t *ipif, struct iftun_req *ta)
1121 {
1122 	sin6_t	sin6;
1123 	sin_t	*sin;
1124 	ill_t 	*ill = ipif->ipif_ill;
1125 	tun_t *tp = (tun_t *)ill->ill_wq->q_next->q_ptr;
1126 
1127 	if (ta->ifta_saddr.ss_family != AF_INET ||
1128 	    (ipif->ipif_flags & IPIF_UP) || !ipif->ipif_isv6 ||
1129 	    (ta->ifta_flags & IFTUN_SRC) == 0)
1130 		return;
1131 
1132 	/*
1133 	 * Check the tunnel type by examining q_next->q_ptr
1134 	 */
1135 	if (tp->tun_flags & TUN_AUTOMATIC) {
1136 		/* this is an automatic tunnel */
1137 		(void) ip_plen_to_mask_v6(IPV6_ABITS - IP_ABITS,
1138 		    &ipif->ipif_v6net_mask);
1139 		bzero(&sin6, sizeof (sin6_t));
1140 		sin = (sin_t *)&ta->ifta_saddr;
1141 		V4_PART_OF_V6(sin6.sin6_addr) = sin->sin_addr.s_addr;
1142 		sin6.sin6_family = AF_INET6;
1143 		(void) ip_sioctl_addr(ipif, (sin_t *)&sin6,
1144 		    NULL, NULL, NULL, NULL);
1145 	} else if (tp->tun_flags & TUN_6TO4) {
1146 		/* this is a 6to4 tunnel */
1147 		(void) ip_plen_to_mask_v6(IPV6_PREFIX_LEN,
1148 		    &ipif->ipif_v6net_mask);
1149 		sin = (sin_t *)&ta->ifta_saddr;
1150 		/* create a 6to4 address from the IPv4 tsrc */
1151 		IN6_V4ADDR_TO_6TO4(&sin->sin_addr, &sin6.sin6_addr);
1152 		sin6.sin6_family = AF_INET6;
1153 		(void) ip_sioctl_addr(ipif, (sin_t *)&sin6,
1154 		    NULL, NULL, NULL, NULL);
1155 	} else {
1156 		ip1dbg(("ipif_set_tun_auto_addr: Unknown tunnel type"));
1157 		return;
1158 	}
1159 }
1160 
1161 /*
1162  * Set link local for ipif_id 0 of a configured tunnel based on the
1163  * tsrc or tdst parameter
1164  * For tunnels over IPv4 use the IPv4 address prepended with 32 zeros as
1165  * the token.
1166  * For tunnels over IPv6 use the low-order 64 bits of the "inner" IPv6 address
1167  * as the token for the "outer" link.
1168  */
1169 void
1170 ipif_set_tun_llink(ill_t *ill, struct iftun_req *ta)
1171 {
1172 	ipif_t		*ipif;
1173 	sin_t		*sin;
1174 	in6_addr_t	*s6addr;
1175 
1176 	ASSERT(IAM_WRITER_ILL(ill));
1177 
1178 	/* The first ipif must be id zero. */
1179 	ipif = ill->ill_ipif;
1180 	ASSERT(ipif->ipif_id == 0);
1181 
1182 	/* no link local for automatic tunnels */
1183 	if (!(ipif->ipif_flags & IPIF_POINTOPOINT)) {
1184 		ipif_set_tun_auto_addr(ipif, ta);
1185 		return;
1186 	}
1187 
1188 	if ((ta->ifta_flags & IFTUN_DST) &&
1189 	    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6pp_dst_addr)) {
1190 		sin6_t	sin6;
1191 
1192 		ASSERT(!(ipif->ipif_flags & IPIF_UP));
1193 		bzero(&sin6, sizeof (sin6_t));
1194 		if ((ta->ifta_saddr.ss_family == AF_INET)) {
1195 			sin = (sin_t *)&ta->ifta_daddr;
1196 			V4_PART_OF_V6(sin6.sin6_addr) =
1197 			    sin->sin_addr.s_addr;
1198 		} else {
1199 			s6addr =
1200 			    &((sin6_t *)&ta->ifta_daddr)->sin6_addr;
1201 			sin6.sin6_addr.s6_addr32[3] = s6addr->s6_addr32[3];
1202 			sin6.sin6_addr.s6_addr32[2] = s6addr->s6_addr32[2];
1203 		}
1204 		ipif_get_linklocal(&ipif->ipif_v6pp_dst_addr,
1205 		    &sin6.sin6_addr);
1206 		ipif->ipif_v6subnet = ipif->ipif_v6pp_dst_addr;
1207 	}
1208 	if ((ta->ifta_flags & IFTUN_SRC)) {
1209 		ASSERT(!(ipif->ipif_flags & IPIF_UP));
1210 
1211 		/* Set the token if it isn't already set */
1212 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token)) {
1213 			if ((ta->ifta_saddr.ss_family == AF_INET)) {
1214 				sin = (sin_t *)&ta->ifta_saddr;
1215 				V4_PART_OF_V6(ill->ill_token) =
1216 				    sin->sin_addr.s_addr;
1217 			} else {
1218 				s6addr =
1219 				    &((sin6_t *)&ta->ifta_saddr)->sin6_addr;
1220 				ill->ill_token.s6_addr32[3] =
1221 				    s6addr->s6_addr32[3];
1222 				ill->ill_token.s6_addr32[2] =
1223 				    s6addr->s6_addr32[2];
1224 			}
1225 			ill->ill_token_length = IPV6_TOKEN_LEN;
1226 		}
1227 		/*
1228 		 * Attempt to set the link local address if it isn't set.
1229 		 */
1230 		if (IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
1231 			(void) ipif_setlinklocal(ipif);
1232 	}
1233 }
1234 
1235 /*
1236  * Is it not possible to set the link local address?
1237  * The address can be set if the token is set, and the token
1238  * isn't too long.
1239  * Return B_TRUE if the address can't be set, or B_FALSE if it can.
1240  */
1241 boolean_t
1242 ipif_cant_setlinklocal(ipif_t *ipif)
1243 {
1244 	ill_t *ill = ipif->ipif_ill;
1245 
1246 	if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token) ||
1247 	    ill->ill_token_length > IPV6_ABITS - IPV6_LL_PREFIXLEN)
1248 		return (B_TRUE);
1249 
1250 	return (B_FALSE);
1251 }
1252 
1253 /*
1254  * Generate a link-local address from the token.
1255  * Return zero if the address was set, or non-zero if it couldn't be set.
1256  */
1257 int
1258 ipif_setlinklocal(ipif_t *ipif)
1259 {
1260 	ill_t		*ill = ipif->ipif_ill;
1261 	in6_addr_t	ov6addr;
1262 
1263 	ASSERT(IAM_WRITER_ILL(ill));
1264 
1265 	if (ipif_cant_setlinklocal(ipif))
1266 		return (-1);
1267 
1268 	ov6addr = ipif->ipif_v6lcl_addr;
1269 	ipif_get_linklocal(&ipif->ipif_v6lcl_addr, &ill->ill_token);
1270 	sctp_update_ipif_addr(ipif, ov6addr);
1271 	(void) ip_plen_to_mask_v6(IPV6_LL_PREFIXLEN, &ipif->ipif_v6net_mask);
1272 	V6_MASK_COPY(ipif->ipif_v6lcl_addr, ipif->ipif_v6net_mask,
1273 	    ipif->ipif_v6subnet);
1274 
1275 	if (ipif->ipif_flags & IPIF_NOLOCAL) {
1276 		ipif->ipif_v6src_addr = ipv6_all_zeros;
1277 	} else {
1278 		ipif->ipif_v6src_addr = ipif->ipif_v6lcl_addr;
1279 	}
1280 	return (0);
1281 }
1282 
1283 /*
1284  * This function sets up the multicast mappings in NDP.
1285  * Unlike ARP, there are no mapping_mps here. We delete the
1286  * mapping nces and add a new one.
1287  *
1288  * Returns non-zero on error and 0 on success.
1289  */
1290 int
1291 ipif_ndp_setup_multicast(ipif_t *ipif, nce_t **ret_nce)
1292 {
1293 	ill_t		*ill = ipif->ipif_ill;
1294 	in6_addr_t	v6_mcast_addr = {(uint32_t)V6_MCAST, 0, 0, 0};
1295 	in6_addr_t	v6_mcast_mask = {(uint32_t)V6_MCAST, 0, 0, 0};
1296 	in6_addr_t	v6_extract_mask;
1297 	uchar_t		*phys_addr, *bphys_addr, *alloc_phys;
1298 	nce_t		*mnce = NULL;
1299 	int		err = 0;
1300 	phyint_t	*phyi = ill->ill_phyint;
1301 	uint32_t	hw_extract_start;
1302 	dl_unitdata_req_t *dlur;
1303 	ip_stack_t	*ipst = ill->ill_ipst;
1304 
1305 	if (ret_nce != NULL)
1306 		*ret_nce = NULL;
1307 	/*
1308 	 * Delete the mapping nce. Normally these should not exist
1309 	 * as a previous ipif_down -> ipif_ndp_down should have deleted
1310 	 * all the nces. But they can exist if ip_rput_dlpi_writer
1311 	 * calls this when PHYI_MULTI_BCAST is set.
1312 	 */
1313 	mnce = ndp_lookup_v6(ill, &v6_mcast_addr, B_FALSE);
1314 	if (mnce != NULL) {
1315 		ndp_delete(mnce);
1316 		NCE_REFRELE(mnce);
1317 		mnce = NULL;
1318 	}
1319 
1320 	/*
1321 	 * Get media specific v6 mapping information. Note that
1322 	 * nd_lla_len can be 0 for tunnels.
1323 	 */
1324 	alloc_phys = kmem_alloc(ill->ill_nd_lla_len, KM_NOSLEEP);
1325 	if ((alloc_phys == NULL) && (ill->ill_nd_lla_len != 0))
1326 		return (ENOMEM);
1327 	/*
1328 	 * Determine the broadcast address.
1329 	 */
1330 	dlur = (dl_unitdata_req_t *)ill->ill_bcast_mp->b_rptr;
1331 	if (ill->ill_sap_length < 0)
1332 		bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset;
1333 	else
1334 		bphys_addr = (uchar_t *)dlur +
1335 		    dlur->dl_dest_addr_offset + ill->ill_sap_length;
1336 
1337 	/*
1338 	 * Check PHYI_MULTI_BCAST and possible length of physical
1339 	 * address to determine if we use the mapping or the
1340 	 * broadcast address.
1341 	 */
1342 	if ((phyi->phyint_flags & PHYI_MULTI_BCAST) ||
1343 	    (!MEDIA_V6MINFO(ill->ill_media, ill->ill_nd_lla_len,
1344 	    bphys_addr, alloc_phys, &hw_extract_start,
1345 	    &v6_extract_mask))) {
1346 		if (ill->ill_phys_addr_length > IP_MAX_HW_LEN) {
1347 			kmem_free(alloc_phys, ill->ill_nd_lla_len);
1348 			return (E2BIG);
1349 		}
1350 		/* Use the link-layer broadcast address for MULTI_BCAST */
1351 		phys_addr = bphys_addr;
1352 		bzero(&v6_extract_mask, sizeof (v6_extract_mask));
1353 		hw_extract_start = ill->ill_nd_lla_len;
1354 	} else {
1355 		phys_addr = alloc_phys;
1356 	}
1357 	if ((ipif->ipif_flags & IPIF_BROADCAST) ||
1358 	    (ill->ill_flags & ILLF_MULTICAST) ||
1359 	    (phyi->phyint_flags & PHYI_MULTI_BCAST)) {
1360 		mutex_enter(&ipst->ips_ndp6->ndp_g_lock);
1361 		err = ndp_add_v6(ill,
1362 		    phys_addr,
1363 		    &v6_mcast_addr,	/* v6 address */
1364 		    &v6_mcast_mask,	/* v6 mask */
1365 		    &v6_extract_mask,
1366 		    hw_extract_start,
1367 		    NCE_F_MAPPING | NCE_F_PERMANENT | NCE_F_NONUD,
1368 		    ND_REACHABLE,
1369 		    &mnce);
1370 		mutex_exit(&ipst->ips_ndp6->ndp_g_lock);
1371 		if (err == 0) {
1372 			if (ret_nce != NULL) {
1373 				*ret_nce = mnce;
1374 			} else {
1375 				NCE_REFRELE(mnce);
1376 			}
1377 		}
1378 	}
1379 	kmem_free(alloc_phys, ill->ill_nd_lla_len);
1380 	return (err);
1381 }
1382 
1383 /*
1384  * Get the resolver set up for a new ipif.  (Always called as writer.)
1385  */
1386 int
1387 ipif_ndp_up(ipif_t *ipif)
1388 {
1389 	ill_t		*ill = ipif->ipif_ill;
1390 	int		err = 0;
1391 	nce_t		*nce = NULL;
1392 	nce_t		*mnce = NULL;
1393 
1394 	ip1dbg(("ipif_ndp_up(%s:%u)\n", ill->ill_name, ipif->ipif_id));
1395 
1396 	/*
1397 	 * ND not supported on XRESOLV interfaces. If ND support (multicast)
1398 	 * added later, take out this check.
1399 	 */
1400 	if ((ill->ill_flags & ILLF_XRESOLV) ||
1401 	    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr) ||
1402 	    (!(ill->ill_net_type & IRE_INTERFACE))) {
1403 		ipif->ipif_addr_ready = 1;
1404 		return (0);
1405 	}
1406 
1407 	/*
1408 	 * Need to setup multicast mapping only when the first
1409 	 * interface is coming UP.
1410 	 */
1411 	if (ill->ill_ipif_up_count == 0 &&
1412 	    (ill->ill_flags & ILLF_MULTICAST)) {
1413 		/*
1414 		 * We set the multicast before setting up the mapping for
1415 		 * local address because ipif_ndp_setup_multicast does
1416 		 * ndp_walk to delete nces which will delete the mapping
1417 		 * for local address also if we added the mapping for
1418 		 * local address first.
1419 		 */
1420 		err = ipif_ndp_setup_multicast(ipif, &mnce);
1421 		if (err != 0)
1422 			return (err);
1423 	}
1424 
1425 	if ((ipif->ipif_flags & (IPIF_UNNUMBERED|IPIF_NOLOCAL)) == 0) {
1426 		uint16_t	flags;
1427 		uchar_t	*hw_addr = NULL;
1428 
1429 		/* Permanent entries don't need NUD */
1430 		flags = NCE_F_PERMANENT | NCE_F_NONUD;
1431 		if (ill->ill_flags & ILLF_ROUTER)
1432 			flags |= NCE_F_ISROUTER;
1433 
1434 		if (ipif->ipif_flags & IPIF_ANYCAST)
1435 			flags |= NCE_F_ANYCAST;
1436 
1437 		if (ill->ill_net_type == IRE_IF_RESOLVER) {
1438 			hw_addr = ill->ill_nd_lla;
1439 
1440 			if (ill->ill_move_in_progress) {
1441 				/*
1442 				 * Addresses are failing over to this ill.
1443 				 * Don't wait for NUD to see this change.
1444 				 * Publish our new link-layer address.
1445 				 */
1446 				flags |= NCE_F_UNSOL_ADV;
1447 			}
1448 		}
1449 		err = ndp_lookup_then_add_v6(ill,
1450 		    hw_addr,
1451 		    &ipif->ipif_v6lcl_addr,
1452 		    &ipv6_all_ones,
1453 		    &ipv6_all_zeros,
1454 		    0,
1455 		    flags,
1456 		    ND_PROBE,	/* Causes Duplicate Address Detection to run */
1457 		    &nce);
1458 		switch (err) {
1459 		case 0:
1460 			ip1dbg(("ipif_ndp_up: NCE created for %s\n",
1461 			    ill->ill_name));
1462 			ipif->ipif_addr_ready = 1;
1463 			break;
1464 		case EINPROGRESS:
1465 			ip1dbg(("ipif_ndp_up: running DAD now for %s\n",
1466 			    ill->ill_name));
1467 			break;
1468 		case EEXIST:
1469 			NCE_REFRELE(nce);
1470 			ip1dbg(("ipif_ndp_up: NCE already exists for %s\n",
1471 			    ill->ill_name));
1472 			if (mnce != NULL) {
1473 				ndp_delete(mnce);
1474 				NCE_REFRELE(mnce);
1475 			}
1476 			return (err);
1477 		default:
1478 			ip1dbg(("ipif_ndp_up: NCE creation failed %s\n",
1479 			    ill->ill_name));
1480 			if (mnce != NULL) {
1481 				ndp_delete(mnce);
1482 				NCE_REFRELE(mnce);
1483 			}
1484 			return (err);
1485 		}
1486 	} else {
1487 		/* No local NCE for this entry */
1488 		ipif->ipif_addr_ready = 1;
1489 	}
1490 	if (nce != NULL)
1491 		NCE_REFRELE(nce);
1492 	if (mnce != NULL)
1493 		NCE_REFRELE(mnce);
1494 	return (0);
1495 }
1496 
1497 /* Remove all cache entries for this logical interface */
1498 void
1499 ipif_ndp_down(ipif_t *ipif)
1500 {
1501 	nce_t	*nce;
1502 
1503 	if (ipif->ipif_isv6) {
1504 		nce = ndp_lookup_v6(ipif->ipif_ill, &ipif->ipif_v6lcl_addr,
1505 		    B_FALSE);
1506 		if (nce != NULL) {
1507 			ndp_delete(nce);
1508 			NCE_REFRELE(nce);
1509 		}
1510 	}
1511 	/*
1512 	 * Remove mapping and all other nces dependent on this ill
1513 	 * when the last ipif is going away.
1514 	 */
1515 	if (ipif->ipif_ill->ill_ipif_up_count == 0) {
1516 		ndp_walk(ipif->ipif_ill, (pfi_t)ndp_delete_per_ill,
1517 		    (uchar_t *)ipif->ipif_ill, ipif->ipif_ill->ill_ipst);
1518 	}
1519 }
1520 
1521 /*
1522  * Used when an interface comes up to recreate any extra routes on this
1523  * interface.
1524  */
1525 static ire_t **
1526 ipif_recover_ire_v6(ipif_t *ipif)
1527 {
1528 	mblk_t	*mp;
1529 	ire_t   **ipif_saved_irep;
1530 	ire_t   **irep;
1531 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
1532 
1533 	ip1dbg(("ipif_recover_ire_v6(%s:%u)", ipif->ipif_ill->ill_name,
1534 	    ipif->ipif_id));
1535 
1536 	ASSERT(ipif->ipif_isv6);
1537 
1538 	mutex_enter(&ipif->ipif_saved_ire_lock);
1539 	ipif_saved_irep = (ire_t **)kmem_zalloc(sizeof (ire_t *) *
1540 	    ipif->ipif_saved_ire_cnt, KM_NOSLEEP);
1541 	if (ipif_saved_irep == NULL) {
1542 		mutex_exit(&ipif->ipif_saved_ire_lock);
1543 		return (NULL);
1544 	}
1545 
1546 	irep = ipif_saved_irep;
1547 
1548 	for (mp = ipif->ipif_saved_ire_mp; mp != NULL; mp = mp->b_cont) {
1549 		ire_t		*ire;
1550 		queue_t		*rfq;
1551 		queue_t		*stq;
1552 		ifrt_t		*ifrt;
1553 		in6_addr_t	*src_addr;
1554 		in6_addr_t	*gateway_addr;
1555 		char		buf[INET6_ADDRSTRLEN];
1556 		ushort_t	type;
1557 
1558 		/*
1559 		 * When the ire was initially created and then added in
1560 		 * ip_rt_add_v6(), it was created either using
1561 		 * ipif->ipif_net_type in the case of a traditional interface
1562 		 * route, or as one of the IRE_OFFSUBNET types (with the
1563 		 * exception of IRE_HOST type redirect ire which is created by
1564 		 * icmp_redirect_v6() and which we don't need to save or
1565 		 * recover).  In the case where ipif->ipif_net_type was
1566 		 * IRE_LOOPBACK, ip_rt_add_v6() will update the ire_type to
1567 		 * IRE_IF_NORESOLVER before calling ire_add_v6() to satisfy
1568 		 * software like GateD and Sun Cluster which creates routes
1569 		 * using the the loopback interface's address as a gateway.
1570 		 *
1571 		 * As ifrt->ifrt_type reflects the already updated ire_type,
1572 		 * ire_create_v6() will be called in the same way here as in
1573 		 * ip_rt_add_v6(), namely using ipif->ipif_net_type when the
1574 		 * route looks like a traditional interface route (where
1575 		 * ifrt->ifrt_type & IRE_INTERFACE is true) and otherwise
1576 		 * using the saved ifrt->ifrt_type.  This means that in
1577 		 * the case where ipif->ipif_net_type is IRE_LOOPBACK,
1578 		 * the ire created by ire_create_v6() will be an IRE_LOOPBACK,
1579 		 * it will then be turned into an IRE_IF_NORESOLVER and then
1580 		 * added by ire_add_v6().
1581 		 */
1582 		ifrt = (ifrt_t *)mp->b_rptr;
1583 		if (ifrt->ifrt_type & IRE_INTERFACE) {
1584 			rfq = NULL;
1585 			stq = (ipif->ipif_net_type == IRE_IF_RESOLVER)
1586 			    ? ipif->ipif_rq : ipif->ipif_wq;
1587 			src_addr = (ifrt->ifrt_flags & RTF_SETSRC)
1588 			    ? &ifrt->ifrt_v6src_addr
1589 			    : &ipif->ipif_v6src_addr;
1590 			gateway_addr = NULL;
1591 			type = ipif->ipif_net_type;
1592 		} else {
1593 			rfq = NULL;
1594 			stq = NULL;
1595 			src_addr = (ifrt->ifrt_flags & RTF_SETSRC)
1596 			    ? &ifrt->ifrt_v6src_addr : NULL;
1597 			gateway_addr = &ifrt->ifrt_v6gateway_addr;
1598 			type = ifrt->ifrt_type;
1599 		}
1600 
1601 		/*
1602 		 * Create a copy of the IRE with the saved address and netmask.
1603 		 */
1604 		ip1dbg(("ipif_recover_ire_v6: creating IRE %s (%d) for %s/%d\n",
1605 		    ip_nv_lookup(ire_nv_tbl, ifrt->ifrt_type), ifrt->ifrt_type,
1606 		    inet_ntop(AF_INET6, &ifrt->ifrt_v6addr, buf, sizeof (buf)),
1607 		    ip_mask_to_plen_v6(&ifrt->ifrt_v6mask)));
1608 		ire = ire_create_v6(
1609 		    &ifrt->ifrt_v6addr,
1610 		    &ifrt->ifrt_v6mask,
1611 		    src_addr,
1612 		    gateway_addr,
1613 		    &ifrt->ifrt_max_frag,
1614 		    NULL,
1615 		    rfq,
1616 		    stq,
1617 		    type,
1618 		    ipif,
1619 		    NULL,
1620 		    0,
1621 		    0,
1622 		    ifrt->ifrt_flags,
1623 		    &ifrt->ifrt_iulp_info,
1624 		    NULL,
1625 		    NULL,
1626 		    ipst);
1627 		if (ire == NULL) {
1628 			mutex_exit(&ipif->ipif_saved_ire_lock);
1629 			kmem_free(ipif_saved_irep,
1630 			    ipif->ipif_saved_ire_cnt * sizeof (ire_t *));
1631 			return (NULL);
1632 		}
1633 
1634 		/*
1635 		 * Some software (for example, GateD and Sun Cluster) attempts
1636 		 * to create (what amount to) IRE_PREFIX routes with the
1637 		 * loopback address as the gateway.  This is primarily done to
1638 		 * set up prefixes with the RTF_REJECT flag set (for example,
1639 		 * when generating aggregate routes.)
1640 		 *
1641 		 * If the IRE type (as defined by ipif->ipif_net_type) is
1642 		 * IRE_LOOPBACK, then we map the request into a
1643 		 * IRE_IF_NORESOLVER.
1644 		 */
1645 		if (ipif->ipif_net_type == IRE_LOOPBACK)
1646 			ire->ire_type = IRE_IF_NORESOLVER;
1647 		/*
1648 		 * ire held by ire_add, will be refreled' in ipif_up_done
1649 		 * towards the end
1650 		 */
1651 		(void) ire_add(&ire, NULL, NULL, NULL, B_FALSE);
1652 		*irep = ire;
1653 		irep++;
1654 		ip1dbg(("ipif_recover_ire_v6: added ire %p\n", (void *)ire));
1655 	}
1656 	mutex_exit(&ipif->ipif_saved_ire_lock);
1657 	return (ipif_saved_irep);
1658 }
1659 
1660 /*
1661  * Return the scope of the given IPv6 address.  If the address is an
1662  * IPv4 mapped IPv6 address, return the scope of the corresponding
1663  * IPv4 address.
1664  */
1665 in6addr_scope_t
1666 ip_addr_scope_v6(const in6_addr_t *addr)
1667 {
1668 	static in6_addr_t ipv6loopback = IN6ADDR_LOOPBACK_INIT;
1669 
1670 	if (IN6_IS_ADDR_V4MAPPED(addr)) {
1671 		in_addr_t v4addr_h = ntohl(V4_PART_OF_V6((*addr)));
1672 		if ((v4addr_h >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
1673 		    (v4addr_h & IN_AUTOCONF_MASK) == IN_AUTOCONF_NET)
1674 			return (IP6_SCOPE_LINKLOCAL);
1675 		if ((v4addr_h & IN_PRIVATE8_MASK) == IN_PRIVATE8_NET ||
1676 		    (v4addr_h & IN_PRIVATE12_MASK) == IN_PRIVATE12_NET ||
1677 		    (v4addr_h & IN_PRIVATE16_MASK) == IN_PRIVATE16_NET)
1678 			return (IP6_SCOPE_SITELOCAL);
1679 		return (IP6_SCOPE_GLOBAL);
1680 	}
1681 
1682 	if (IN6_IS_ADDR_MULTICAST(addr))
1683 		return (IN6_ADDR_MC_SCOPE(addr));
1684 
1685 	/* link-local and loopback addresses are of link-local scope */
1686 	if (IN6_IS_ADDR_LINKLOCAL(addr) ||
1687 	    IN6_ARE_ADDR_EQUAL(addr, &ipv6loopback))
1688 		return (IP6_SCOPE_LINKLOCAL);
1689 	if (IN6_IS_ADDR_SITELOCAL(addr))
1690 		return (IP6_SCOPE_SITELOCAL);
1691 	return (IP6_SCOPE_GLOBAL);
1692 }
1693 
1694 
1695 /*
1696  * Returns the length of the common prefix of a1 and a2, as per
1697  * CommonPrefixLen() defined in RFC 3484.
1698  */
1699 static int
1700 ip_common_prefix_v6(const in6_addr_t *a1, const in6_addr_t *a2)
1701 {
1702 	int i;
1703 	uint32_t a1val, a2val, mask;
1704 
1705 	for (i = 0; i < 4; i++) {
1706 		if ((a1val = a1->s6_addr32[i]) != (a2val = a2->s6_addr32[i])) {
1707 			a1val ^= a2val;
1708 			i *= 32;
1709 			mask = 0x80000000u;
1710 			while (!(a1val & mask)) {
1711 				mask >>= 1;
1712 				i++;
1713 			}
1714 			return (i);
1715 		}
1716 	}
1717 	return (IPV6_ABITS);
1718 }
1719 
1720 #define	IPIF_VALID_IPV6_SOURCE(ipif) \
1721 	(((ipif)->ipif_flags & IPIF_UP) && \
1722 	!((ipif)->ipif_flags & (IPIF_NOLOCAL|IPIF_ANYCAST)) && \
1723 	(ipif)->ipif_addr_ready)
1724 
1725 /* source address candidate */
1726 typedef struct candidate {
1727 	ipif_t		*cand_ipif;
1728 	/* The properties of this candidate */
1729 	boolean_t	cand_isdst;
1730 	boolean_t	cand_isdst_set;
1731 	in6addr_scope_t	cand_scope;
1732 	boolean_t	cand_scope_set;
1733 	boolean_t	cand_isdeprecated;
1734 	boolean_t	cand_isdeprecated_set;
1735 	boolean_t	cand_ispreferred;
1736 	boolean_t	cand_ispreferred_set;
1737 	boolean_t	cand_matchedinterface;
1738 	boolean_t	cand_matchedinterface_set;
1739 	boolean_t	cand_matchedlabel;
1740 	boolean_t	cand_matchedlabel_set;
1741 	boolean_t	cand_istmp;
1742 	boolean_t	cand_istmp_set;
1743 	int		cand_common_pref;
1744 	boolean_t	cand_common_pref_set;
1745 	boolean_t	cand_pref_eq;
1746 	boolean_t	cand_pref_eq_set;
1747 	int		cand_pref_len;
1748 	boolean_t	cand_pref_len_set;
1749 } cand_t;
1750 #define	cand_srcaddr	cand_ipif->ipif_v6lcl_addr
1751 #define	cand_mask	cand_ipif->ipif_v6net_mask
1752 #define	cand_flags	cand_ipif->ipif_flags
1753 #define	cand_ill	cand_ipif->ipif_ill
1754 #define	cand_zoneid	cand_ipif->ipif_zoneid
1755 
1756 /* information about the destination for source address selection */
1757 typedef struct dstinfo {
1758 	const in6_addr_t	*dst_addr;
1759 	ill_t			*dst_ill;
1760 	uint_t			dst_restrict_ill;
1761 	boolean_t		dst_prefer_src_tmp;
1762 	in6addr_scope_t		dst_scope;
1763 	char			*dst_label;
1764 } dstinfo_t;
1765 
1766 /*
1767  * The following functions are rules used to select a source address in
1768  * ipif_select_source_v6().  Each rule compares a current candidate (cc)
1769  * against the best candidate (bc).  Each rule has three possible outcomes;
1770  * the candidate is preferred over the best candidate (CAND_PREFER), the
1771  * candidate is not preferred over the best candidate (CAND_AVOID), or the
1772  * candidate is of equal value as the best candidate (CAND_TIE).
1773  *
1774  * These rules are part of a greater "Default Address Selection for IPv6"
1775  * sheme, which is standards based work coming out of the IETF ipv6 working
1776  * group.  The IETF document defines both IPv6 source address selection and
1777  * destination address ordering.  The rules defined here implement the IPv6
1778  * source address selection.  Destination address ordering is done by
1779  * libnsl, and uses a similar set of rules to implement the sorting.
1780  *
1781  * Most of the rules are defined by the RFC and are not typically altered.  The
1782  * last rule, number 8, has language that allows for local preferences.  In the
1783  * scheme below, this means that new Solaris rules should normally go between
1784  * rule_ifprefix and rule_prefix.
1785  */
1786 typedef enum {CAND_AVOID, CAND_TIE, CAND_PREFER} rule_res_t;
1787 typedef	rule_res_t (*rulef_t)(cand_t *, cand_t *, const dstinfo_t *,
1788     ip_stack_t *);
1789 
1790 /* Prefer an address if it is equal to the destination address. */
1791 /* ARGSUSED3 */
1792 static rule_res_t
1793 rule_isdst(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo, ip_stack_t *ipst)
1794 {
1795 	if (!bc->cand_isdst_set) {
1796 		bc->cand_isdst =
1797 		    IN6_ARE_ADDR_EQUAL(&bc->cand_srcaddr, dstinfo->dst_addr);
1798 		bc->cand_isdst_set = B_TRUE;
1799 	}
1800 
1801 	cc->cand_isdst =
1802 	    IN6_ARE_ADDR_EQUAL(&cc->cand_srcaddr, dstinfo->dst_addr);
1803 	cc->cand_isdst_set = B_TRUE;
1804 
1805 	if (cc->cand_isdst == bc->cand_isdst)
1806 		return (CAND_TIE);
1807 	else if (cc->cand_isdst)
1808 		return (CAND_PREFER);
1809 	else
1810 		return (CAND_AVOID);
1811 }
1812 
1813 /*
1814  * Prefer addresses that are of closest scope to the destination.  Always
1815  * prefer addresses that are of greater scope than the destination over
1816  * those that are of lesser scope than the destination.
1817  */
1818 /* ARGSUSED3 */
1819 static rule_res_t
1820 rule_scope(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo, ip_stack_t *ipst)
1821 {
1822 	if (!bc->cand_scope_set) {
1823 		bc->cand_scope = ip_addr_scope_v6(&bc->cand_srcaddr);
1824 		bc->cand_scope_set = B_TRUE;
1825 	}
1826 
1827 	cc->cand_scope = ip_addr_scope_v6(&cc->cand_srcaddr);
1828 	cc->cand_scope_set = B_TRUE;
1829 
1830 	if (cc->cand_scope < bc->cand_scope) {
1831 		if (cc->cand_scope < dstinfo->dst_scope)
1832 			return (CAND_AVOID);
1833 		else
1834 			return (CAND_PREFER);
1835 	} else if (bc->cand_scope < cc->cand_scope) {
1836 		if (bc->cand_scope < dstinfo->dst_scope)
1837 			return (CAND_PREFER);
1838 		else
1839 			return (CAND_AVOID);
1840 	} else {
1841 		return (CAND_TIE);
1842 	}
1843 }
1844 
1845 /*
1846  * Prefer non-deprecated source addresses.
1847  */
1848 /* ARGSUSED2 */
1849 static rule_res_t
1850 rule_deprecated(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo,
1851     ip_stack_t *ipst)
1852 {
1853 	if (!bc->cand_isdeprecated_set) {
1854 		bc->cand_isdeprecated =
1855 		    ((bc->cand_flags & IPIF_DEPRECATED) != 0);
1856 		bc->cand_isdeprecated_set = B_TRUE;
1857 	}
1858 
1859 	cc->cand_isdeprecated = ((cc->cand_flags & IPIF_DEPRECATED) != 0);
1860 	cc->cand_isdeprecated_set = B_TRUE;
1861 
1862 	if (bc->cand_isdeprecated == cc->cand_isdeprecated)
1863 		return (CAND_TIE);
1864 	else if (cc->cand_isdeprecated)
1865 		return (CAND_AVOID);
1866 	else
1867 		return (CAND_PREFER);
1868 }
1869 
1870 /*
1871  * Prefer source addresses that have the IPIF_PREFERRED flag set.  This
1872  * rule must be before rule_interface because the flag could be set on any
1873  * interface, not just the interface being used for outgoing packets (for
1874  * example, the IFF_PREFERRED could be set on an address assigned to the
1875  * loopback interface).
1876  */
1877 /* ARGSUSED2 */
1878 static rule_res_t
1879 rule_preferred(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo,
1880     ip_stack_t *ipst)
1881 {
1882 	if (!bc->cand_ispreferred_set) {
1883 		bc->cand_ispreferred = ((bc->cand_flags & IPIF_PREFERRED) != 0);
1884 		bc->cand_ispreferred_set = B_TRUE;
1885 	}
1886 
1887 	cc->cand_ispreferred = ((cc->cand_flags & IPIF_PREFERRED) != 0);
1888 	cc->cand_ispreferred_set = B_TRUE;
1889 
1890 	if (bc->cand_ispreferred == cc->cand_ispreferred)
1891 		return (CAND_TIE);
1892 	else if (cc->cand_ispreferred)
1893 		return (CAND_PREFER);
1894 	else
1895 		return (CAND_AVOID);
1896 }
1897 
1898 /*
1899  * Prefer source addresses that are assigned to the outgoing interface, or
1900  * to an interface that is in the same IPMP group as the outgoing
1901  * interface.
1902  */
1903 /* ARGSUSED3 */
1904 static rule_res_t
1905 rule_interface(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo,
1906     ip_stack_t *ipst)
1907 {
1908 	ill_t *dstill = dstinfo->dst_ill;
1909 
1910 	/*
1911 	 * If dstinfo->dst_restrict_ill is set, this rule is unnecessary
1912 	 * since we know all candidates will be on the same link.
1913 	 */
1914 	if (dstinfo->dst_restrict_ill)
1915 		return (CAND_TIE);
1916 
1917 	if (!bc->cand_matchedinterface_set) {
1918 		bc->cand_matchedinterface = (bc->cand_ill == dstill ||
1919 		    (dstill->ill_group != NULL &&
1920 		    dstill->ill_group == bc->cand_ill->ill_group));
1921 		bc->cand_matchedinterface_set = B_TRUE;
1922 	}
1923 
1924 	cc->cand_matchedinterface = (cc->cand_ill == dstill ||
1925 	    (dstill->ill_group != NULL &&
1926 	    dstill->ill_group == cc->cand_ill->ill_group));
1927 	cc->cand_matchedinterface_set = B_TRUE;
1928 
1929 	if (bc->cand_matchedinterface == cc->cand_matchedinterface)
1930 		return (CAND_TIE);
1931 	else if (cc->cand_matchedinterface)
1932 		return (CAND_PREFER);
1933 	else
1934 		return (CAND_AVOID);
1935 }
1936 
1937 /*
1938  * Prefer source addresses whose label matches the destination's label.
1939  */
1940 static rule_res_t
1941 rule_label(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo, ip_stack_t *ipst)
1942 {
1943 	char *label;
1944 
1945 	if (!bc->cand_matchedlabel_set) {
1946 		label = ip6_asp_lookup(&bc->cand_srcaddr, NULL, ipst);
1947 		bc->cand_matchedlabel =
1948 		    ip6_asp_labelcmp(label, dstinfo->dst_label);
1949 		bc->cand_matchedlabel_set = B_TRUE;
1950 	}
1951 
1952 	label = ip6_asp_lookup(&cc->cand_srcaddr, NULL, ipst);
1953 	cc->cand_matchedlabel = ip6_asp_labelcmp(label, dstinfo->dst_label);
1954 	cc->cand_matchedlabel_set = B_TRUE;
1955 
1956 	if (bc->cand_matchedlabel == cc->cand_matchedlabel)
1957 		return (CAND_TIE);
1958 	else if (cc->cand_matchedlabel)
1959 		return (CAND_PREFER);
1960 	else
1961 		return (CAND_AVOID);
1962 }
1963 
1964 /*
1965  * Prefer public addresses over temporary ones.  An application can reverse
1966  * the logic of this rule and prefer temporary addresses by using the
1967  * IPV6_SRC_PREFERENCES socket option.
1968  */
1969 /* ARGSUSED3 */
1970 static rule_res_t
1971 rule_temporary(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo,
1972     ip_stack_t *ipst)
1973 {
1974 	if (!bc->cand_istmp_set) {
1975 		bc->cand_istmp = ((bc->cand_flags & IPIF_TEMPORARY) != 0);
1976 		bc->cand_istmp_set = B_TRUE;
1977 	}
1978 
1979 	cc->cand_istmp = ((cc->cand_flags & IPIF_TEMPORARY) != 0);
1980 	cc->cand_istmp_set = B_TRUE;
1981 
1982 	if (bc->cand_istmp == cc->cand_istmp)
1983 		return (CAND_TIE);
1984 
1985 	if (dstinfo->dst_prefer_src_tmp && cc->cand_istmp)
1986 		return (CAND_PREFER);
1987 	else if (!dstinfo->dst_prefer_src_tmp && !cc->cand_istmp)
1988 		return (CAND_PREFER);
1989 	else
1990 		return (CAND_AVOID);
1991 }
1992 
1993 /*
1994  * Prefer source addresses with longer matching prefix with the destination
1995  * under the interface mask.  This gets us on the same subnet before applying
1996  * any Solaris-specific rules.
1997  */
1998 /* ARGSUSED3 */
1999 static rule_res_t
2000 rule_ifprefix(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo,
2001     ip_stack_t *ipst)
2002 {
2003 	if (!bc->cand_pref_eq_set) {
2004 		bc->cand_pref_eq = V6_MASK_EQ_2(bc->cand_srcaddr,
2005 		    bc->cand_mask, *dstinfo->dst_addr);
2006 		bc->cand_pref_eq_set = B_TRUE;
2007 	}
2008 
2009 	cc->cand_pref_eq = V6_MASK_EQ_2(cc->cand_srcaddr, cc->cand_mask,
2010 	    *dstinfo->dst_addr);
2011 	cc->cand_pref_eq_set = B_TRUE;
2012 
2013 	if (bc->cand_pref_eq) {
2014 		if (cc->cand_pref_eq) {
2015 			if (!bc->cand_pref_len_set) {
2016 				bc->cand_pref_len =
2017 				    ip_mask_to_plen_v6(&bc->cand_mask);
2018 				bc->cand_pref_len_set = B_TRUE;
2019 			}
2020 			cc->cand_pref_len = ip_mask_to_plen_v6(&cc->cand_mask);
2021 			cc->cand_pref_len_set = B_TRUE;
2022 			if (bc->cand_pref_len == cc->cand_pref_len)
2023 				return (CAND_TIE);
2024 			else if (bc->cand_pref_len > cc->cand_pref_len)
2025 				return (CAND_AVOID);
2026 			else
2027 				return (CAND_PREFER);
2028 		} else {
2029 			return (CAND_AVOID);
2030 		}
2031 	} else {
2032 		if (cc->cand_pref_eq)
2033 			return (CAND_PREFER);
2034 		else
2035 			return (CAND_TIE);
2036 	}
2037 }
2038 
2039 /*
2040  * Prefer to use zone-specific addresses when possible instead of all-zones
2041  * addresses.
2042  */
2043 /* ARGSUSED2 */
2044 static rule_res_t
2045 rule_zone_specific(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo,
2046     ip_stack_t *ipst)
2047 {
2048 	if ((bc->cand_zoneid == ALL_ZONES) ==
2049 	    (cc->cand_zoneid == ALL_ZONES))
2050 		return (CAND_TIE);
2051 	else if (cc->cand_zoneid == ALL_ZONES)
2052 		return (CAND_AVOID);
2053 	else
2054 		return (CAND_PREFER);
2055 }
2056 
2057 /*
2058  * Prefer to use DHCPv6 (first) and static addresses (second) when possible
2059  * instead of statelessly autoconfigured addresses.
2060  *
2061  * This is done after trying all other preferences (and before the final tie
2062  * breaker) so that, if all else is equal, we select addresses configured by
2063  * DHCPv6 over other addresses.  We presume that DHCPv6 addresses, unlike
2064  * stateless autoconfigured addresses, are deliberately configured by an
2065  * administrator, and thus are correctly set up in DNS and network packet
2066  * filters.
2067  */
2068 /* ARGSUSED2 */
2069 static rule_res_t
2070 rule_addr_type(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo,
2071     ip_stack_t *ipst)
2072 {
2073 #define	ATYPE(x)	\
2074 	((x) & IPIF_DHCPRUNNING) ? 1 : ((x) & IPIF_ADDRCONF) ? 3 : 2
2075 	int bcval = ATYPE(bc->cand_flags);
2076 	int ccval = ATYPE(cc->cand_flags);
2077 #undef ATYPE
2078 
2079 	if (bcval == ccval)
2080 		return (CAND_TIE);
2081 	else if (ccval < bcval)
2082 		return (CAND_PREFER);
2083 	else
2084 		return (CAND_AVOID);
2085 }
2086 
2087 /*
2088  * Prefer source addresses with longer matching prefix with the destination.
2089  * We do the longest matching prefix calculation by doing an xor of both
2090  * addresses with the destination, and pick the address with the longest string
2091  * of leading zeros, as per CommonPrefixLen() defined in RFC 3484.
2092  */
2093 /* ARGSUSED3 */
2094 static rule_res_t
2095 rule_prefix(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo, ip_stack_t *ipst)
2096 {
2097 	if (!bc->cand_common_pref_set) {
2098 		bc->cand_common_pref = ip_common_prefix_v6(&bc->cand_srcaddr,
2099 		    dstinfo->dst_addr);
2100 		bc->cand_common_pref_set = B_TRUE;
2101 	}
2102 
2103 	cc->cand_common_pref = ip_common_prefix_v6(&cc->cand_srcaddr,
2104 	    dstinfo->dst_addr);
2105 	cc->cand_common_pref_set = B_TRUE;
2106 
2107 	if (bc->cand_common_pref == cc->cand_common_pref)
2108 		return (CAND_TIE);
2109 	else if (bc->cand_common_pref > cc->cand_common_pref)
2110 		return (CAND_AVOID);
2111 	else
2112 		return (CAND_PREFER);
2113 }
2114 
2115 /*
2116  * Last rule: we must pick something, so just prefer the current best
2117  * candidate.
2118  */
2119 /* ARGSUSED */
2120 static rule_res_t
2121 rule_must_be_last(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo,
2122     ip_stack_t *ipst)
2123 {
2124 	return (CAND_AVOID);
2125 }
2126 
2127 /*
2128  * Determine the best source address given a destination address and a
2129  * destination ill.  If no suitable source address is found, it returns
2130  * NULL. If there is a usable address pointed to by the usesrc
2131  * (i.e ill_usesrc_ifindex != 0) then return that first since it is more
2132  * fine grained (i.e per interface)
2133  *
2134  * This implementation is based on the "Default Address Selection for IPv6"
2135  * specification produced by the IETF IPv6 working group.  It has been
2136  * implemented so that the list of addresses is only traversed once (the
2137  * specification's algorithm could traverse the list of addresses once for
2138  * every rule).
2139  *
2140  * The restrict_ill argument restricts the algorithm to chose a source
2141  * address that is assigned to the destination ill or an ill in the same
2142  * IPMP group as the destination ill.  This is used when the destination
2143  * address is a link-local or multicast address, and when
2144  * ipv6_strict_dst_multihoming is turned on.
2145  *
2146  * src_prefs is the caller's set of source address preferences.  If source
2147  * address selection is being called to determine the source address of a
2148  * connected socket (from ip_bind_connected_v6()), then the preferences are
2149  * taken from conn_src_preferences.  These preferences can be set on a
2150  * per-socket basis using the IPV6_SRC_PREFERENCES socket option.  The only
2151  * preference currently implemented is for rfc3041 temporary addresses.
2152  */
2153 ipif_t *
2154 ipif_select_source_v6(ill_t *dstill, const in6_addr_t *dst,
2155     uint_t restrict_ill, uint32_t src_prefs, zoneid_t zoneid)
2156 {
2157 	dstinfo_t	dstinfo;
2158 	char		dstr[INET6_ADDRSTRLEN];
2159 	char		sstr[INET6_ADDRSTRLEN];
2160 	ipif_t		*ipif;
2161 	ill_t		*ill, *usesrc_ill = NULL;
2162 	ill_walk_context_t	ctx;
2163 	cand_t		best_c;	/* The best candidate */
2164 	cand_t		curr_c;	/* The current candidate */
2165 	uint_t		index;
2166 	boolean_t	first_candidate = B_TRUE;
2167 	rule_res_t	rule_result;
2168 	tsol_tpc_t	*src_rhtp, *dst_rhtp;
2169 	ip_stack_t	*ipst = dstill->ill_ipst;
2170 
2171 	/*
2172 	 * The list of ordering rules.  They are applied in the order they
2173 	 * appear in the list.
2174 	 *
2175 	 * Solaris doesn't currently support Mobile IPv6, so there's no
2176 	 * rule_mipv6 corresponding to rule 4 in the specification.
2177 	 */
2178 	rulef_t	rules[] = {
2179 		rule_isdst,
2180 		rule_scope,
2181 		rule_deprecated,
2182 		rule_preferred,
2183 		rule_interface,
2184 		rule_label,
2185 		rule_temporary,
2186 		rule_ifprefix,			/* local rules after this */
2187 		rule_zone_specific,
2188 		rule_addr_type,
2189 		rule_prefix,			/* local rules before this */
2190 		rule_must_be_last,		/* must always be last */
2191 		NULL
2192 	};
2193 
2194 	ASSERT(dstill->ill_isv6);
2195 	ASSERT(!IN6_IS_ADDR_V4MAPPED(dst));
2196 
2197 	/*
2198 	 * Check if there is a usable src address pointed to by the
2199 	 * usesrc ifindex. This has higher precedence since it is
2200 	 * finer grained (i.e per interface) v/s being system wide.
2201 	 */
2202 	if (dstill->ill_usesrc_ifindex != 0) {
2203 		if ((usesrc_ill =
2204 		    ill_lookup_on_ifindex(dstill->ill_usesrc_ifindex, B_TRUE,
2205 		    NULL, NULL, NULL, NULL, ipst)) != NULL) {
2206 			dstinfo.dst_ill = usesrc_ill;
2207 		} else {
2208 			return (NULL);
2209 		}
2210 	} else {
2211 		dstinfo.dst_ill = dstill;
2212 	}
2213 
2214 	/*
2215 	 * If we're dealing with an unlabeled destination on a labeled system,
2216 	 * make sure that we ignore source addresses that are incompatible with
2217 	 * the destination's default label.  That destination's default label
2218 	 * must dominate the minimum label on the source address.
2219 	 *
2220 	 * (Note that this has to do with Trusted Solaris.  It's not related to
2221 	 * the labels described by ip6_asp_lookup.)
2222 	 */
2223 	dst_rhtp = NULL;
2224 	if (is_system_labeled()) {
2225 		dst_rhtp = find_tpc(dst, IPV6_VERSION, B_FALSE);
2226 		if (dst_rhtp == NULL)
2227 			return (NULL);
2228 		if (dst_rhtp->tpc_tp.host_type != UNLABELED) {
2229 			TPC_RELE(dst_rhtp);
2230 			dst_rhtp = NULL;
2231 		}
2232 	}
2233 
2234 	dstinfo.dst_addr = dst;
2235 	dstinfo.dst_scope = ip_addr_scope_v6(dst);
2236 	dstinfo.dst_label = ip6_asp_lookup(dst, NULL, ipst);
2237 	dstinfo.dst_prefer_src_tmp = ((src_prefs & IPV6_PREFER_SRC_TMP) != 0);
2238 
2239 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
2240 	/*
2241 	 * Section three of the I-D states that for multicast and
2242 	 * link-local destinations, the candidate set must be restricted to
2243 	 * an interface that is on the same link as the outgoing interface.
2244 	 * Also, when ipv6_strict_dst_multihoming is turned on, always
2245 	 * restrict the source address to the destination link as doing
2246 	 * otherwise will almost certainly cause problems.
2247 	 */
2248 	if (IN6_IS_ADDR_LINKLOCAL(dst) || IN6_IS_ADDR_MULTICAST(dst) ||
2249 	    ipst->ips_ipv6_strict_dst_multihoming || usesrc_ill != NULL) {
2250 		if (restrict_ill == RESTRICT_TO_NONE)
2251 			dstinfo.dst_restrict_ill = RESTRICT_TO_GROUP;
2252 		else
2253 			dstinfo.dst_restrict_ill = restrict_ill;
2254 	} else {
2255 		dstinfo.dst_restrict_ill = restrict_ill;
2256 	}
2257 
2258 	bzero(&best_c, sizeof (cand_t));
2259 
2260 	/*
2261 	 * Take a pass through the list of IPv6 interfaces to chose the
2262 	 * best possible source address.  If restrict_ill is true, we only
2263 	 * iterate through the ill's that are in the same IPMP group as the
2264 	 * destination's outgoing ill.  If restrict_ill is false, we walk
2265 	 * the entire list of IPv6 ill's.
2266 	 */
2267 	if (dstinfo.dst_restrict_ill != RESTRICT_TO_NONE) {
2268 		if (dstinfo.dst_ill->ill_group != NULL &&
2269 		    dstinfo.dst_restrict_ill == RESTRICT_TO_GROUP) {
2270 			ill = dstinfo.dst_ill->ill_group->illgrp_ill;
2271 		} else {
2272 			ill = dstinfo.dst_ill;
2273 		}
2274 	} else {
2275 		ill = ILL_START_WALK_V6(&ctx, ipst);
2276 	}
2277 
2278 	while (ill != NULL) {
2279 		ASSERT(ill->ill_isv6);
2280 
2281 		/*
2282 		 * Avoid FAILED/OFFLINE ills.
2283 		 * Global and site local addresses will failover and
2284 		 * will be available on the new ill.
2285 		 * But link local addresses don't move.
2286 		 */
2287 		if (dstinfo.dst_restrict_ill != RESTRICT_TO_ILL &&
2288 		    ill->ill_phyint->phyint_flags &
2289 		    (PHYI_OFFLINE | PHYI_FAILED))
2290 			goto next_ill;
2291 
2292 		for (ipif = ill->ill_ipif; ipif != NULL;
2293 		    ipif = ipif->ipif_next) {
2294 
2295 			if (!IPIF_VALID_IPV6_SOURCE(ipif))
2296 				continue;
2297 
2298 			if (zoneid != ALL_ZONES &&
2299 			    ipif->ipif_zoneid != zoneid &&
2300 			    ipif->ipif_zoneid != ALL_ZONES)
2301 				continue;
2302 
2303 			/*
2304 			 * Check compatibility of local address for
2305 			 * destination's default label if we're on a labeled
2306 			 * system.  Incompatible addresses can't be used at
2307 			 * all and must be skipped over.
2308 			 */
2309 			if (dst_rhtp != NULL) {
2310 				boolean_t incompat;
2311 
2312 				src_rhtp = find_tpc(&ipif->ipif_v6lcl_addr,
2313 				    IPV6_VERSION, B_FALSE);
2314 				if (src_rhtp == NULL)
2315 					continue;
2316 				incompat =
2317 				    src_rhtp->tpc_tp.host_type != SUN_CIPSO ||
2318 				    src_rhtp->tpc_tp.tp_doi !=
2319 				    dst_rhtp->tpc_tp.tp_doi ||
2320 				    (!_blinrange(&dst_rhtp->tpc_tp.tp_def_label,
2321 				    &src_rhtp->tpc_tp.tp_sl_range_cipso) &&
2322 				    !blinlset(&dst_rhtp->tpc_tp.tp_def_label,
2323 				    src_rhtp->tpc_tp.tp_sl_set_cipso));
2324 				TPC_RELE(src_rhtp);
2325 				if (incompat)
2326 					continue;
2327 			}
2328 
2329 			if (first_candidate) {
2330 				/*
2331 				 * This is first valid address in the list.
2332 				 * It is automatically the best candidate
2333 				 * so far.
2334 				 */
2335 				best_c.cand_ipif = ipif;
2336 				first_candidate = B_FALSE;
2337 				continue;
2338 			}
2339 
2340 			bzero(&curr_c, sizeof (cand_t));
2341 			curr_c.cand_ipif = ipif;
2342 
2343 			/*
2344 			 * Compare this current candidate (curr_c) with the
2345 			 * best candidate (best_c) by applying the
2346 			 * comparison rules in order until one breaks the
2347 			 * tie.
2348 			 */
2349 			for (index = 0; rules[index] != NULL; index++) {
2350 				/* Apply a comparison rule. */
2351 				rule_result =
2352 				    (rules[index])(&best_c, &curr_c, &dstinfo,
2353 				    ipst);
2354 				if (rule_result == CAND_AVOID) {
2355 					/*
2356 					 * The best candidate is still the
2357 					 * best candidate.  Forget about
2358 					 * this current candidate and go on
2359 					 * to the next one.
2360 					 */
2361 					break;
2362 				} else if (rule_result == CAND_PREFER) {
2363 					/*
2364 					 * This candidate is prefered.  It
2365 					 * becomes the best candidate so
2366 					 * far.  Go on to the next address.
2367 					 */
2368 					best_c = curr_c;
2369 					break;
2370 				}
2371 				/* We have a tie, apply the next rule. */
2372 			}
2373 
2374 			/*
2375 			 * The last rule must be a tie breaker rule and
2376 			 * must never produce a tie.  At this point, the
2377 			 * candidate should have either been rejected, or
2378 			 * have been prefered as the best candidate so far.
2379 			 */
2380 			ASSERT(rule_result != CAND_TIE);
2381 		}
2382 
2383 		/*
2384 		 * We may be walking the linked-list of ill's in an
2385 		 * IPMP group or traversing the IPv6 ill avl tree. If it is a
2386 		 * usesrc ILL then it can't be part of IPMP group and we
2387 		 * will exit the while loop.
2388 		 */
2389 next_ill:
2390 		if (dstinfo.dst_restrict_ill == RESTRICT_TO_ILL)
2391 			ill = NULL;
2392 		else if (dstinfo.dst_restrict_ill == RESTRICT_TO_GROUP)
2393 			ill = ill->ill_group_next;
2394 		else
2395 			ill = ill_next(&ctx, ill);
2396 	}
2397 
2398 	ipif = best_c.cand_ipif;
2399 	ip1dbg(("ipif_select_source_v6(%s, %s) -> %s\n",
2400 	    dstinfo.dst_ill->ill_name,
2401 	    inet_ntop(AF_INET6, dstinfo.dst_addr, dstr, sizeof (dstr)),
2402 	    (ipif == NULL ? "NULL" :
2403 	    inet_ntop(AF_INET6, &ipif->ipif_v6lcl_addr, sstr, sizeof (sstr)))));
2404 
2405 	if (usesrc_ill != NULL)
2406 		ill_refrele(usesrc_ill);
2407 
2408 	if (dst_rhtp != NULL)
2409 		TPC_RELE(dst_rhtp);
2410 
2411 	if (ipif == NULL) {
2412 		rw_exit(&ipst->ips_ill_g_lock);
2413 		return (NULL);
2414 	}
2415 
2416 	mutex_enter(&ipif->ipif_ill->ill_lock);
2417 	if (IPIF_CAN_LOOKUP(ipif)) {
2418 		ipif_refhold_locked(ipif);
2419 		mutex_exit(&ipif->ipif_ill->ill_lock);
2420 		rw_exit(&ipst->ips_ill_g_lock);
2421 		return (ipif);
2422 	}
2423 	mutex_exit(&ipif->ipif_ill->ill_lock);
2424 	rw_exit(&ipst->ips_ill_g_lock);
2425 	ip1dbg(("ipif_select_source_v6 cannot lookup ipif %p"
2426 	    " returning null \n", (void *)ipif));
2427 
2428 	return (NULL);
2429 }
2430 
2431 /*
2432  * If old_ipif is not NULL, see if ipif was derived from old
2433  * ipif and if so, recreate the interface route by re-doing
2434  * source address selection. This happens when ipif_down ->
2435  * ipif_update_other_ipifs calls us.
2436  *
2437  * If old_ipif is NULL, just redo the source address selection
2438  * if needed. This happens when illgrp_insert or ipif_up_done_v6
2439  * calls us.
2440  */
2441 void
2442 ipif_recreate_interface_routes_v6(ipif_t *old_ipif, ipif_t *ipif)
2443 {
2444 	ire_t *ire;
2445 	ire_t *ipif_ire;
2446 	queue_t *stq;
2447 	ill_t *ill;
2448 	ipif_t *nipif = NULL;
2449 	boolean_t nipif_refheld = B_FALSE;
2450 	boolean_t ip6_asp_table_held = B_FALSE;
2451 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
2452 
2453 	ill = ipif->ipif_ill;
2454 
2455 	if (!(ipif->ipif_flags &
2456 	    (IPIF_NOLOCAL|IPIF_ANYCAST|IPIF_DEPRECATED))) {
2457 		/*
2458 		 * Can't possibly have borrowed the source
2459 		 * from old_ipif.
2460 		 */
2461 		return;
2462 	}
2463 
2464 	/*
2465 	 * Is there any work to be done? No work if the address
2466 	 * is INADDR_ANY, loopback or NOLOCAL or ANYCAST (
2467 	 * ipif_select_source_v6() does not borrow addresses from
2468 	 * NOLOCAL and ANYCAST interfaces).
2469 	 */
2470 	if ((old_ipif != NULL) &&
2471 	    ((IN6_IS_ADDR_UNSPECIFIED(&old_ipif->ipif_v6lcl_addr)) ||
2472 	    (old_ipif->ipif_ill->ill_wq == NULL) ||
2473 	    (old_ipif->ipif_flags &
2474 	    (IPIF_NOLOCAL|IPIF_ANYCAST)))) {
2475 		return;
2476 	}
2477 
2478 	/*
2479 	 * Perform the same checks as when creating the
2480 	 * IRE_INTERFACE in ipif_up_done_v6.
2481 	 */
2482 	if (!(ipif->ipif_flags & IPIF_UP))
2483 		return;
2484 
2485 	if ((ipif->ipif_flags & IPIF_NOXMIT))
2486 		return;
2487 
2488 	if (IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6subnet) &&
2489 	    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6net_mask))
2490 		return;
2491 
2492 	/*
2493 	 * We know that ipif uses some other source for its
2494 	 * IRE_INTERFACE. Is it using the source of this
2495 	 * old_ipif?
2496 	 */
2497 	ipif_ire = ipif_to_ire_v6(ipif);
2498 	if (ipif_ire == NULL)
2499 		return;
2500 
2501 	if (old_ipif != NULL &&
2502 	    !IN6_ARE_ADDR_EQUAL(&old_ipif->ipif_v6lcl_addr,
2503 	    &ipif_ire->ire_src_addr_v6)) {
2504 		ire_refrele(ipif_ire);
2505 		return;
2506 	}
2507 
2508 	if (ip_debug > 2) {
2509 		/* ip1dbg */
2510 		pr_addr_dbg("ipif_recreate_interface_routes_v6: deleting IRE"
2511 		    " for src %s\n", AF_INET6, &ipif_ire->ire_src_addr_v6);
2512 	}
2513 
2514 	stq = ipif_ire->ire_stq;
2515 
2516 	/*
2517 	 * Can't use our source address. Select a different source address
2518 	 * for the IRE_INTERFACE.  We restrict interface route source
2519 	 * address selection to ipif's assigned to the same link as the
2520 	 * interface.
2521 	 */
2522 	if (ip6_asp_can_lookup(ipst)) {
2523 		ip6_asp_table_held = B_TRUE;
2524 		nipif = ipif_select_source_v6(ill, &ipif->ipif_v6subnet,
2525 		    RESTRICT_TO_GROUP, IPV6_PREFER_SRC_DEFAULT,
2526 		    ipif->ipif_zoneid);
2527 	}
2528 	if (nipif == NULL) {
2529 		/* Last resort - all ipif's have IPIF_NOLOCAL */
2530 		nipif = ipif;
2531 	} else {
2532 		nipif_refheld = B_TRUE;
2533 	}
2534 
2535 	ire = ire_create_v6(
2536 	    &ipif->ipif_v6subnet,	/* dest pref */
2537 	    &ipif->ipif_v6net_mask,	/* mask */
2538 	    &nipif->ipif_v6src_addr,	/* src addr */
2539 	    NULL,			/* no gateway */
2540 	    &ipif->ipif_mtu,		/* max frag */
2541 	    NULL,			/* no src nce */
2542 	    NULL,			/* no recv from queue */
2543 	    stq,			/* send-to queue */
2544 	    ill->ill_net_type,		/* IF_[NO]RESOLVER */
2545 	    ipif,
2546 	    NULL,
2547 	    0,
2548 	    0,
2549 	    0,
2550 	    &ire_uinfo_null,
2551 	    NULL,
2552 	    NULL,
2553 	    ipst);
2554 
2555 	if (ire != NULL) {
2556 		ire_t *ret_ire;
2557 		int   error;
2558 
2559 		/*
2560 		 * We don't need ipif_ire anymore. We need to delete
2561 		 * before we add so that ire_add does not detect
2562 		 * duplicates.
2563 		 */
2564 		ire_delete(ipif_ire);
2565 		ret_ire = ire;
2566 		error = ire_add(&ret_ire, NULL, NULL, NULL, B_FALSE);
2567 		ASSERT(error == 0);
2568 		ASSERT(ret_ire == ire);
2569 		if (ret_ire != NULL) {
2570 			/* Held in ire_add */
2571 			ire_refrele(ret_ire);
2572 		}
2573 	}
2574 	/*
2575 	 * Either we are falling through from above or could not
2576 	 * allocate a replacement.
2577 	 */
2578 	ire_refrele(ipif_ire);
2579 	if (ip6_asp_table_held)
2580 		ip6_asp_table_refrele(ipst);
2581 	if (nipif_refheld)
2582 		ipif_refrele(nipif);
2583 }
2584 
2585 /*
2586  * This old_ipif is going away.
2587  *
2588  * Determine if any other ipif's are using our address as
2589  * ipif_v6lcl_addr (due to those being IPIF_NOLOCAL, IPIF_ANYCAST, or
2590  * IPIF_DEPRECATED).
2591  * Find the IRE_INTERFACE for such ipif's and recreate them
2592  * to use an different source address following the rules in
2593  * ipif_up_done_v6.
2594  *
2595  * This function takes an illgrp as an argument so that illgrp_delete
2596  * can call this to update source address even after deleting the
2597  * old_ipif->ipif_ill from the ill group.
2598  */
2599 void
2600 ipif_update_other_ipifs_v6(ipif_t *old_ipif, ill_group_t *illgrp)
2601 {
2602 	ipif_t	*ipif;
2603 	ill_t	*ill;
2604 	char	buf[INET6_ADDRSTRLEN];
2605 
2606 	ASSERT(IAM_WRITER_IPIF(old_ipif));
2607 
2608 	ill = old_ipif->ipif_ill;
2609 
2610 	ip1dbg(("ipif_update_other_ipifs_v6(%s, %s)\n",
2611 	    ill->ill_name,
2612 	    inet_ntop(AF_INET6, &old_ipif->ipif_v6lcl_addr,
2613 	    buf, sizeof (buf))));
2614 
2615 	/*
2616 	 * If this part of a group, look at all ills as ipif_select_source
2617 	 * borrows a source address across all the ills in the group.
2618 	 */
2619 	if (illgrp != NULL)
2620 		ill = illgrp->illgrp_ill;
2621 
2622 	/* Don't need a lock since this is a writer */
2623 	for (; ill != NULL; ill = ill->ill_group_next) {
2624 		for (ipif = ill->ill_ipif; ipif != NULL;
2625 		    ipif = ipif->ipif_next) {
2626 
2627 			if (ipif == old_ipif)
2628 				continue;
2629 
2630 			ipif_recreate_interface_routes_v6(old_ipif, ipif);
2631 		}
2632 	}
2633 }
2634 
2635 /*
2636  * Perform an attach and bind to get phys addr plus info_req for
2637  * the physical device.
2638  * q and mp represents an ioctl which will be queued waiting for
2639  * completion of the DLPI message exchange.
2640  * MUST be called on an ill queue. Can not set conn_pending_ill for that
2641  * reason thus the DL_PHYS_ADDR_ACK code does not assume ill_pending_q.
2642  *
2643  * Returns EINPROGRESS when mp has been consumed by queueing it on
2644  * ill_pending_mp and the ioctl will complete in ip_rput.
2645  */
2646 int
2647 ill_dl_phys(ill_t *ill, ipif_t *ipif, mblk_t *mp, queue_t *q)
2648 {
2649 	mblk_t	*v6token_mp = NULL;
2650 	mblk_t	*v6lla_mp = NULL;
2651 	mblk_t	*phys_mp = NULL;
2652 	mblk_t	*info_mp = NULL;
2653 	mblk_t	*attach_mp = NULL;
2654 	mblk_t	*bind_mp = NULL;
2655 	mblk_t	*unbind_mp = NULL;
2656 	mblk_t	*notify_mp = NULL;
2657 
2658 	ip1dbg(("ill_dl_phys(%s:%u)\n", ill->ill_name, ipif->ipif_id));
2659 	ASSERT(ill->ill_dlpi_style_set);
2660 	ASSERT(WR(q)->q_next != NULL);
2661 
2662 	if (ill->ill_isv6) {
2663 		v6token_mp = ip_dlpi_alloc(sizeof (dl_phys_addr_req_t) +
2664 		    sizeof (t_scalar_t), DL_PHYS_ADDR_REQ);
2665 		if (v6token_mp == NULL)
2666 			goto bad;
2667 		((dl_phys_addr_req_t *)v6token_mp->b_rptr)->dl_addr_type =
2668 		    DL_IPV6_TOKEN;
2669 
2670 		v6lla_mp = ip_dlpi_alloc(sizeof (dl_phys_addr_req_t) +
2671 		    sizeof (t_scalar_t), DL_PHYS_ADDR_REQ);
2672 		if (v6lla_mp == NULL)
2673 			goto bad;
2674 		((dl_phys_addr_req_t *)v6lla_mp->b_rptr)->dl_addr_type =
2675 		    DL_IPV6_LINK_LAYER_ADDR;
2676 	}
2677 
2678 	/*
2679 	 * Allocate a DL_NOTIFY_REQ and set the notifications we want.
2680 	 */
2681 	notify_mp = ip_dlpi_alloc(sizeof (dl_notify_req_t) + sizeof (long),
2682 	    DL_NOTIFY_REQ);
2683 	if (notify_mp == NULL)
2684 		goto bad;
2685 	((dl_notify_req_t *)notify_mp->b_rptr)->dl_notifications =
2686 	    (DL_NOTE_PHYS_ADDR | DL_NOTE_SDU_SIZE | DL_NOTE_FASTPATH_FLUSH |
2687 	    DL_NOTE_LINK_UP | DL_NOTE_LINK_DOWN | DL_NOTE_CAPAB_RENEG);
2688 
2689 	phys_mp = ip_dlpi_alloc(sizeof (dl_phys_addr_req_t) +
2690 	    sizeof (t_scalar_t), DL_PHYS_ADDR_REQ);
2691 	if (phys_mp == NULL)
2692 		goto bad;
2693 	((dl_phys_addr_req_t *)phys_mp->b_rptr)->dl_addr_type =
2694 	    DL_CURR_PHYS_ADDR;
2695 
2696 	info_mp = ip_dlpi_alloc(
2697 	    sizeof (dl_info_req_t) + sizeof (dl_info_ack_t),
2698 	    DL_INFO_REQ);
2699 	if (info_mp == NULL)
2700 		goto bad;
2701 
2702 	bind_mp = ip_dlpi_alloc(sizeof (dl_bind_req_t) + sizeof (long),
2703 	    DL_BIND_REQ);
2704 	if (bind_mp == NULL)
2705 		goto bad;
2706 	((dl_bind_req_t *)bind_mp->b_rptr)->dl_sap = ill->ill_sap;
2707 	((dl_bind_req_t *)bind_mp->b_rptr)->dl_service_mode = DL_CLDLS;
2708 
2709 	unbind_mp = ip_dlpi_alloc(sizeof (dl_unbind_req_t), DL_UNBIND_REQ);
2710 	if (unbind_mp == NULL)
2711 		goto bad;
2712 
2713 	/* If we need to attach, pre-alloc and initialize the mblk */
2714 	if (ill->ill_needs_attach) {
2715 		attach_mp = ip_dlpi_alloc(sizeof (dl_attach_req_t),
2716 		    DL_ATTACH_REQ);
2717 		if (attach_mp == NULL)
2718 			goto bad;
2719 		((dl_attach_req_t *)attach_mp->b_rptr)->dl_ppa = ill->ill_ppa;
2720 	}
2721 
2722 	/*
2723 	 * Here we are going to delay the ioctl ack until after
2724 	 * ACKs from DL_PHYS_ADDR_REQ. So need to save the
2725 	 * original ioctl message before sending the requests
2726 	 */
2727 	mutex_enter(&ill->ill_lock);
2728 	/* ipsq_pending_mp_add won't fail since we pass in a NULL connp */
2729 	(void) ipsq_pending_mp_add(NULL, ipif, ill->ill_wq, mp, 0);
2730 	/*
2731 	 * Set ill_phys_addr_pend to zero. It will be set to the addr_type of
2732 	 * the DL_PHYS_ADDR_REQ in ill_dlpi_send() and ill_dlpi_done(). It will
2733 	 * be used to track which DL_PHYS_ADDR_REQ is being ACK'd/NAK'd.
2734 	 */
2735 	ill->ill_phys_addr_pend = 0;
2736 	mutex_exit(&ill->ill_lock);
2737 
2738 	if (attach_mp != NULL) {
2739 		ip1dbg(("ill_dl_phys: attach\n"));
2740 		ill_dlpi_send(ill, attach_mp);
2741 	}
2742 	ill_dlpi_send(ill, bind_mp);
2743 	ill_dlpi_send(ill, info_mp);
2744 	if (ill->ill_isv6) {
2745 		ill_dlpi_send(ill, v6token_mp);
2746 		ill_dlpi_send(ill, v6lla_mp);
2747 	}
2748 	ill_dlpi_send(ill, phys_mp);
2749 	ill_dlpi_send(ill, notify_mp);
2750 	ill_dlpi_send(ill, unbind_mp);
2751 
2752 	/*
2753 	 * This operation will complete in ip_rput_dlpi_writer with either
2754 	 * a DL_PHYS_ADDR_ACK or DL_ERROR_ACK.
2755 	 */
2756 	return (EINPROGRESS);
2757 bad:
2758 	freemsg(v6token_mp);
2759 	freemsg(v6lla_mp);
2760 	freemsg(phys_mp);
2761 	freemsg(info_mp);
2762 	freemsg(attach_mp);
2763 	freemsg(bind_mp);
2764 	freemsg(unbind_mp);
2765 	freemsg(notify_mp);
2766 	return (ENOMEM);
2767 }
2768 
2769 uint_t ip_loopback_mtu_v6plus = IP_LOOPBACK_MTU + IPV6_HDR_LEN + 20;
2770 
2771 /*
2772  * DLPI is up.
2773  * Create all the IREs associated with an interface bring up multicast.
2774  * Set the interface flag and finish other initialization
2775  * that potentially had to be differed to after DL_BIND_ACK.
2776  */
2777 int
2778 ipif_up_done_v6(ipif_t *ipif)
2779 {
2780 	ire_t	*ire_array[20];
2781 	ire_t	**irep = ire_array;
2782 	ire_t	**irep1;
2783 	ill_t	*ill = ipif->ipif_ill;
2784 	queue_t	*stq;
2785 	in6_addr_t	v6addr;
2786 	in6_addr_t	route_mask;
2787 	ipif_t	 *src_ipif = NULL;
2788 	ipif_t   *tmp_ipif;
2789 	boolean_t	flush_ire_cache = B_TRUE;
2790 	int	err;
2791 	char	buf[INET6_ADDRSTRLEN];
2792 	phyint_t *phyi;
2793 	ire_t	**ipif_saved_irep = NULL;
2794 	int ipif_saved_ire_cnt;
2795 	int cnt;
2796 	boolean_t src_ipif_held = B_FALSE;
2797 	boolean_t ire_added = B_FALSE;
2798 	boolean_t loopback = B_FALSE;
2799 	boolean_t ip6_asp_table_held = B_FALSE;
2800 	ip_stack_t	*ipst = ill->ill_ipst;
2801 
2802 	ip1dbg(("ipif_up_done_v6(%s:%u)\n",
2803 	    ipif->ipif_ill->ill_name, ipif->ipif_id));
2804 
2805 	/* Check if this is a loopback interface */
2806 	if (ipif->ipif_ill->ill_wq == NULL)
2807 		loopback = B_TRUE;
2808 
2809 	ASSERT(ipif->ipif_isv6);
2810 	ASSERT(!MUTEX_HELD(&ipif->ipif_ill->ill_lock));
2811 
2812 	/*
2813 	 * If all other interfaces for this ill are down or DEPRECATED,
2814 	 * or otherwise unsuitable for source address selection, remove
2815 	 * any IRE_CACHE entries for this ill to make sure source
2816 	 * address selection gets to take this new ipif into account.
2817 	 * No need to hold ill_lock while traversing the ipif list since
2818 	 * we are writer
2819 	 */
2820 	for (tmp_ipif = ill->ill_ipif; tmp_ipif;
2821 	    tmp_ipif = tmp_ipif->ipif_next) {
2822 		if (((tmp_ipif->ipif_flags &
2823 		    (IPIF_NOXMIT|IPIF_ANYCAST|IPIF_NOLOCAL|IPIF_DEPRECATED)) ||
2824 		    !(tmp_ipif->ipif_flags & IPIF_UP)) ||
2825 		    (tmp_ipif == ipif))
2826 			continue;
2827 		/* first useable pre-existing interface */
2828 		flush_ire_cache = B_FALSE;
2829 		break;
2830 	}
2831 	if (flush_ire_cache)
2832 		ire_walk_ill_v6(MATCH_IRE_ILL_GROUP | MATCH_IRE_TYPE,
2833 		    IRE_CACHE, ill_ipif_cache_delete, (char *)ill, ill);
2834 
2835 	/*
2836 	 * Figure out which way the send-to queue should go.  Only
2837 	 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER should show up here.
2838 	 */
2839 	switch (ill->ill_net_type) {
2840 	case IRE_IF_RESOLVER:
2841 		stq = ill->ill_rq;
2842 		break;
2843 	case IRE_IF_NORESOLVER:
2844 	case IRE_LOOPBACK:
2845 		stq = ill->ill_wq;
2846 		break;
2847 	default:
2848 		return (EINVAL);
2849 	}
2850 
2851 	if (IS_LOOPBACK(ill)) {
2852 		/*
2853 		 * lo0:1 and subsequent ipifs were marked IRE_LOCAL in
2854 		 * ipif_lookup_on_name(), but in the case of zones we can have
2855 		 * several loopback addresses on lo0. So all the interfaces with
2856 		 * loopback addresses need to be marked IRE_LOOPBACK.
2857 		 */
2858 		if (IN6_ARE_ADDR_EQUAL(&ipif->ipif_v6lcl_addr, &ipv6_loopback))
2859 			ipif->ipif_ire_type = IRE_LOOPBACK;
2860 		else
2861 			ipif->ipif_ire_type = IRE_LOCAL;
2862 	}
2863 
2864 	if (ipif->ipif_flags & (IPIF_NOLOCAL|IPIF_ANYCAST|IPIF_DEPRECATED)) {
2865 		/*
2866 		 * Can't use our source address. Select a different
2867 		 * source address for the IRE_INTERFACE and IRE_LOCAL
2868 		 */
2869 		if (ip6_asp_can_lookup(ipst)) {
2870 			ip6_asp_table_held = B_TRUE;
2871 			src_ipif = ipif_select_source_v6(ipif->ipif_ill,
2872 			    &ipif->ipif_v6subnet, RESTRICT_TO_NONE,
2873 			    IPV6_PREFER_SRC_DEFAULT, ipif->ipif_zoneid);
2874 		}
2875 		if (src_ipif == NULL)
2876 			src_ipif = ipif;	/* Last resort */
2877 		else
2878 			src_ipif_held = B_TRUE;
2879 	} else {
2880 		src_ipif = ipif;
2881 	}
2882 
2883 	if (!IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr) &&
2884 	    !(ipif->ipif_flags & IPIF_NOLOCAL)) {
2885 
2886 		/*
2887 		 * If we're on a labeled system then make sure that zone-
2888 		 * private addresses have proper remote host database entries.
2889 		 */
2890 		if (is_system_labeled() &&
2891 		    ipif->ipif_ire_type != IRE_LOOPBACK) {
2892 			if (ip6opt_ls == 0) {
2893 				cmn_err(CE_WARN, "IPv6 not enabled "
2894 				    "via /etc/system");
2895 				return (EINVAL);
2896 			}
2897 			if (!tsol_check_interface_address(ipif))
2898 				return (EINVAL);
2899 		}
2900 
2901 		/* Register the source address for __sin6_src_id */
2902 		err = ip_srcid_insert(&ipif->ipif_v6lcl_addr,
2903 		    ipif->ipif_zoneid, ipst);
2904 		if (err != 0) {
2905 			ip0dbg(("ipif_up_done_v6: srcid_insert %d\n", err));
2906 			if (src_ipif_held)
2907 				ipif_refrele(src_ipif);
2908 			if (ip6_asp_table_held)
2909 				ip6_asp_table_refrele(ipst);
2910 			return (err);
2911 		}
2912 		/*
2913 		 * If the interface address is set, create the LOCAL
2914 		 * or LOOPBACK IRE.
2915 		 */
2916 		ip1dbg(("ipif_up_done_v6: creating IRE %d for %s\n",
2917 		    ipif->ipif_ire_type,
2918 		    inet_ntop(AF_INET6, &ipif->ipif_v6lcl_addr,
2919 		    buf, sizeof (buf))));
2920 
2921 		*irep++ = ire_create_v6(
2922 		    &ipif->ipif_v6lcl_addr,		/* dest address */
2923 		    &ipv6_all_ones,			/* mask */
2924 		    &src_ipif->ipif_v6src_addr,		/* source address */
2925 		    NULL,				/* no gateway */
2926 		    &ip_loopback_mtu_v6plus,		/* max frag size */
2927 		    NULL,
2928 		    ipif->ipif_rq,			/* recv-from queue */
2929 		    NULL,				/* no send-to queue */
2930 		    ipif->ipif_ire_type,		/* LOCAL or LOOPBACK */
2931 		    ipif,				/* interface */
2932 		    NULL,
2933 		    0,
2934 		    0,
2935 		    (ipif->ipif_flags & IPIF_PRIVATE) ? RTF_PRIVATE : 0,
2936 		    &ire_uinfo_null,
2937 		    NULL,
2938 		    NULL,
2939 		    ipst);
2940 	}
2941 
2942 	/*
2943 	 * Set up the IRE_IF_RESOLVER or IRE_IF_NORESOLVER, as appropriate.
2944 	 * Note that atun interfaces have an all-zero ipif_v6subnet.
2945 	 * Thus we allow a zero subnet as long as the mask is non-zero.
2946 	 */
2947 	if (stq != NULL && !(ipif->ipif_flags & IPIF_NOXMIT) &&
2948 	    !(IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6subnet) &&
2949 	    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6net_mask))) {
2950 		/* ipif_v6subnet is ipif_v6pp_dst_addr for pt-pt */
2951 		v6addr = ipif->ipif_v6subnet;
2952 
2953 		if (ipif->ipif_flags & IPIF_POINTOPOINT) {
2954 			route_mask = ipv6_all_ones;
2955 		} else {
2956 			route_mask = ipif->ipif_v6net_mask;
2957 		}
2958 
2959 		ip1dbg(("ipif_up_done_v6: creating if IRE %d for %s\n",
2960 		    ill->ill_net_type,
2961 		    inet_ntop(AF_INET6, &v6addr, buf, sizeof (buf))));
2962 
2963 		*irep++ = ire_create_v6(
2964 		    &v6addr,			/* dest pref */
2965 		    &route_mask,		/* mask */
2966 		    &src_ipif->ipif_v6src_addr,	/* src addr */
2967 		    NULL,			/* no gateway */
2968 		    &ipif->ipif_mtu,		/* max frag */
2969 		    NULL,			/* no src nce */
2970 		    NULL,			/* no recv from queue */
2971 		    stq,			/* send-to queue */
2972 		    ill->ill_net_type,		/* IF_[NO]RESOLVER */
2973 		    ipif,
2974 		    NULL,
2975 		    0,
2976 		    0,
2977 		    (ipif->ipif_flags & IPIF_PRIVATE) ? RTF_PRIVATE : 0,
2978 		    &ire_uinfo_null,
2979 		    NULL,
2980 		    NULL,
2981 		    ipst);
2982 	}
2983 
2984 	/*
2985 	 * Setup 2002::/16 route, if this interface is a 6to4 tunnel
2986 	 */
2987 	if (IN6_IS_ADDR_6TO4(&ipif->ipif_v6lcl_addr) &&
2988 	    (ill->ill_is_6to4tun)) {
2989 		/*
2990 		 * Destination address is 2002::/16
2991 		 */
2992 #ifdef	_BIG_ENDIAN
2993 		const in6_addr_t prefix_addr = { 0x20020000U, 0, 0, 0 };
2994 		const in6_addr_t prefix_mask = { 0xffff0000U, 0, 0, 0 };
2995 #else
2996 		const in6_addr_t prefix_addr = { 0x00000220U, 0, 0, 0 };
2997 		const in6_addr_t prefix_mask = { 0x0000ffffU, 0, 0, 0 };
2998 #endif /* _BIG_ENDIAN */
2999 		char	buf2[INET6_ADDRSTRLEN];
3000 		ire_t *isdup;
3001 		in6_addr_t *first_addr = &ill->ill_ipif->ipif_v6lcl_addr;
3002 
3003 		/*
3004 		 * check to see if this route has already been added for
3005 		 * this tunnel interface.
3006 		 */
3007 		isdup = ire_ftable_lookup_v6(first_addr, &prefix_mask, 0,
3008 		    IRE_IF_NORESOLVER, ill->ill_ipif, NULL, ALL_ZONES, 0, NULL,
3009 		    (MATCH_IRE_SRC | MATCH_IRE_MASK), ipst);
3010 
3011 		if (isdup == NULL) {
3012 			ip1dbg(("ipif_up_done_v6: creating if IRE %d for %s",
3013 			    IRE_IF_NORESOLVER, inet_ntop(AF_INET6, &v6addr,
3014 			    buf2, sizeof (buf2))));
3015 
3016 			*irep++ = ire_create_v6(
3017 			    &prefix_addr,		/* 2002:: */
3018 			    &prefix_mask,		/* ffff:: */
3019 			    &ipif->ipif_v6lcl_addr, 	/* src addr */
3020 			    NULL, 			/* gateway */
3021 			    &ipif->ipif_mtu, 		/* max_frag */
3022 			    NULL, 			/* no src nce */
3023 			    NULL, 			/* no rfq */
3024 			    ill->ill_wq, 		/* stq */
3025 			    IRE_IF_NORESOLVER,		/* type */
3026 			    ipif,			/* interface */
3027 			    NULL,			/* v6cmask */
3028 			    0,
3029 			    0,
3030 			    RTF_UP,
3031 			    &ire_uinfo_null,
3032 			    NULL,
3033 			    NULL,
3034 			    ipst);
3035 		} else {
3036 			ire_refrele(isdup);
3037 		}
3038 	}
3039 
3040 	/* If an earlier ire_create failed, get out now */
3041 	for (irep1 = irep; irep1 > ire_array; ) {
3042 		irep1--;
3043 		if (*irep1 == NULL) {
3044 			ip1dbg(("ipif_up_done_v6: NULL ire found in"
3045 			    " ire_array\n"));
3046 			err = ENOMEM;
3047 			goto bad;
3048 		}
3049 	}
3050 
3051 	ASSERT(!MUTEX_HELD(&ipif->ipif_ill->ill_lock));
3052 
3053 	/*
3054 	 * Need to atomically check for ip_addr_availablity_check
3055 	 * now under ill_g_lock, and if it fails got bad, and remove
3056 	 * from group also
3057 	 */
3058 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
3059 	mutex_enter(&ipst->ips_ip_addr_avail_lock);
3060 	ill->ill_ipif_up_count++;
3061 	ipif->ipif_flags |= IPIF_UP;
3062 	err = ip_addr_availability_check(ipif);
3063 	mutex_exit(&ipst->ips_ip_addr_avail_lock);
3064 	rw_exit(&ipst->ips_ill_g_lock);
3065 
3066 	if (err != 0) {
3067 		/*
3068 		 * Our address may already be up on the same ill. In this case,
3069 		 * the external resolver entry for our ipif replaced the one for
3070 		 * the other ipif. So we don't want to delete it (otherwise the
3071 		 * other ipif would be unable to send packets).
3072 		 * ip_addr_availability_check() identifies this case for us and
3073 		 * returns EADDRINUSE; we need to turn it into EADDRNOTAVAIL
3074 		 * which is the expected error code.
3075 		 */
3076 		if (err == EADDRINUSE) {
3077 			if (ipif->ipif_ill->ill_flags & ILLF_XRESOLV) {
3078 				freemsg(ipif->ipif_arp_del_mp);
3079 				ipif->ipif_arp_del_mp = NULL;
3080 			}
3081 			err = EADDRNOTAVAIL;
3082 		}
3083 		ill->ill_ipif_up_count--;
3084 		ipif->ipif_flags &= ~IPIF_UP;
3085 		goto bad;
3086 	}
3087 
3088 	/*
3089 	 * Add in all newly created IREs. We want to add before
3090 	 * we call ifgrp_insert which wants to know whether
3091 	 * IRE_IF_RESOLVER exists or not.
3092 	 *
3093 	 * NOTE : We refrele the ire though we may branch to "bad"
3094 	 *	  later on where we do ire_delete. This is okay
3095 	 *	  because nobody can delete it as we are running
3096 	 *	  exclusively.
3097 	 */
3098 	for (irep1 = irep; irep1 > ire_array; ) {
3099 		irep1--;
3100 		/* Shouldn't be adding any bcast ire's */
3101 		ASSERT((*irep1)->ire_type != IRE_BROADCAST);
3102 		ASSERT(!MUTEX_HELD(&ipif->ipif_ill->ill_lock));
3103 		/*
3104 		 * refheld by ire_add. refele towards the end of the func
3105 		 */
3106 		(void) ire_add(irep1, NULL, NULL, NULL, B_FALSE);
3107 	}
3108 	if (ip6_asp_table_held) {
3109 		ip6_asp_table_refrele(ipst);
3110 		ip6_asp_table_held = B_FALSE;
3111 	}
3112 	ire_added = B_TRUE;
3113 
3114 	/*
3115 	 * Form groups if possible.
3116 	 *
3117 	 * If we are supposed to be in a ill_group with a name, insert it
3118 	 * now as we know that at least one ipif is UP. Otherwise form
3119 	 * nameless groups.
3120 	 *
3121 	 * If ip_enable_group_ifs is set and ipif address is not ::0, insert
3122 	 * this ipif into the appropriate interface group, or create a
3123 	 * new one. If this is already in a nameless group, we try to form
3124 	 * a bigger group looking at other ills potentially sharing this
3125 	 * ipif's prefix.
3126 	 */
3127 	phyi = ill->ill_phyint;
3128 	if (phyi->phyint_groupname_len != 0) {
3129 		ASSERT(phyi->phyint_groupname != NULL);
3130 		if (ill->ill_ipif_up_count == 1) {
3131 			ASSERT(ill->ill_group == NULL);
3132 			err = illgrp_insert(&ipst->ips_illgrp_head_v6, ill,
3133 			    phyi->phyint_groupname, NULL, B_TRUE);
3134 			if (err != 0) {
3135 				ip1dbg(("ipif_up_done_v6: illgrp allocation "
3136 				    "failed, error %d\n", err));
3137 				goto bad;
3138 			}
3139 		}
3140 		ASSERT(ill->ill_group != NULL);
3141 	}
3142 
3143 	/* Recover any additional IRE_IF_[NO]RESOLVER entries for this ipif */
3144 	ipif_saved_ire_cnt = ipif->ipif_saved_ire_cnt;
3145 	ipif_saved_irep = ipif_recover_ire_v6(ipif);
3146 
3147 	if (ipif->ipif_ipif_up_count == 1 && !loopback) {
3148 		/*
3149 		 * Need to recover all multicast memberships in the driver.
3150 		 * This had to be deferred until we had attached.
3151 		 */
3152 		ill_recover_multicast(ill);
3153 	}
3154 	/* Join the allhosts multicast address and the solicited node MC */
3155 	ipif_multicast_up(ipif);
3156 
3157 	if (!loopback) {
3158 		/*
3159 		 * See whether anybody else would benefit from the
3160 		 * new ipif that we added. We call this always rather
3161 		 * than while adding a non-IPIF_NOLOCAL/DEPRECATED/ANYCAST
3162 		 * ipif for the benefit of illgrp_insert (done above)
3163 		 * which does not do source address selection as it does
3164 		 * not want to re-create interface routes that we are
3165 		 * having reference to it here.
3166 		 */
3167 		ill_update_source_selection(ill);
3168 	}
3169 
3170 	for (irep1 = irep; irep1 > ire_array; ) {
3171 		irep1--;
3172 		if (*irep1 != NULL) {
3173 			/* was held in ire_add */
3174 			ire_refrele(*irep1);
3175 		}
3176 	}
3177 
3178 	cnt = ipif_saved_ire_cnt;
3179 	for (irep1 = ipif_saved_irep; cnt > 0; irep1++, cnt--) {
3180 		if (*irep1 != NULL) {
3181 			/* was held in ire_add */
3182 			ire_refrele(*irep1);
3183 		}
3184 	}
3185 
3186 	if (ipif->ipif_addr_ready) {
3187 		ip_rts_ifmsg(ipif);
3188 		ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
3189 		sctp_update_ipif(ipif, SCTP_IPIF_UP);
3190 	}
3191 
3192 	if (ipif_saved_irep != NULL) {
3193 		kmem_free(ipif_saved_irep,
3194 		    ipif_saved_ire_cnt * sizeof (ire_t *));
3195 	}
3196 
3197 	if (src_ipif_held)
3198 		ipif_refrele(src_ipif);
3199 	return (0);
3200 
3201 bad:
3202 	if (ip6_asp_table_held)
3203 		ip6_asp_table_refrele(ipst);
3204 	/*
3205 	 * We don't have to bother removing from ill groups because
3206 	 *
3207 	 * 1) For groups with names, we insert only when the first ipif
3208 	 *    comes up. In that case if it fails, it will not be in any
3209 	 *    group. So, we need not try to remove for that case.
3210 	 *
3211 	 * 2) For groups without names, either we tried to insert ipif_ill
3212 	 *    in a group as singleton or found some other group to become
3213 	 *    a bigger group. For the former, if it fails we don't have
3214 	 *    anything to do as ipif_ill is not in the group and for the
3215 	 *    latter, there are no failures in illgrp_insert/illgrp_delete
3216 	 *    (ENOMEM can't occur for this. Check ifgrp_insert).
3217 	 */
3218 
3219 	while (irep > ire_array) {
3220 		irep--;
3221 		if (*irep != NULL) {
3222 			ire_delete(*irep);
3223 			if (ire_added)
3224 				ire_refrele(*irep);
3225 		}
3226 
3227 	}
3228 	(void) ip_srcid_remove(&ipif->ipif_v6lcl_addr, ipif->ipif_zoneid, ipst);
3229 
3230 	if (ipif_saved_irep != NULL) {
3231 		kmem_free(ipif_saved_irep,
3232 		    ipif_saved_ire_cnt * sizeof (ire_t *));
3233 	}
3234 	if (src_ipif_held)
3235 		ipif_refrele(src_ipif);
3236 
3237 	ipif_ndp_down(ipif);
3238 	if (ipif->ipif_ill->ill_flags & ILLF_XRESOLV)
3239 		ipif_arp_down(ipif);
3240 
3241 	return (err);
3242 }
3243 
3244 /*
3245  * Delete an ND entry and the corresponding IRE_CACHE entry if it exists.
3246  */
3247 /* ARGSUSED */
3248 int
3249 ip_siocdelndp_v6(ipif_t *ipif, sin_t *dummy_sin, queue_t *q, mblk_t *mp,
3250     ip_ioctl_cmd_t *ipip, void *dummy_ifreq)
3251 {
3252 	in6_addr_t	addr;
3253 	sin6_t		*sin6;
3254 	nce_t		*nce;
3255 	struct lifreq	*lifr;
3256 	lif_nd_req_t	*lnr;
3257 	mblk_t	*mp1;
3258 
3259 	mp1 = mp->b_cont->b_cont;
3260 	lifr = (struct lifreq *)mp1->b_rptr;
3261 	lnr = &lifr->lifr_nd;
3262 	/* Only allow for logical unit zero i.e. not on "le0:17" */
3263 	if (ipif->ipif_id != 0)
3264 		return (EINVAL);
3265 
3266 	if (!ipif->ipif_isv6)
3267 		return (EINVAL);
3268 
3269 	if (lnr->lnr_addr.ss_family != AF_INET6)
3270 		return (EAFNOSUPPORT);
3271 
3272 	sin6 = (sin6_t *)&lnr->lnr_addr;
3273 	addr = sin6->sin6_addr;
3274 	nce = ndp_lookup_v6(ipif->ipif_ill, &addr, B_FALSE);
3275 	if (nce == NULL)
3276 		return (ESRCH);
3277 	ndp_delete(nce);
3278 	NCE_REFRELE(nce);
3279 	return (0);
3280 }
3281 
3282 /*
3283  * Return nbr cache info.
3284  */
3285 /* ARGSUSED */
3286 int
3287 ip_siocqueryndp_v6(ipif_t *ipif, sin_t *dummy_sin, queue_t *q, mblk_t *mp,
3288     ip_ioctl_cmd_t *ipip, void *dummy_ifreq)
3289 {
3290 	ill_t		*ill = ipif->ipif_ill;
3291 	struct lifreq	*lifr;
3292 	lif_nd_req_t	*lnr;
3293 
3294 	lifr = (struct lifreq *)mp->b_cont->b_cont->b_rptr;
3295 	lnr = &lifr->lifr_nd;
3296 	/* Only allow for logical unit zero i.e. not on "le0:17" */
3297 	if (ipif->ipif_id != 0)
3298 		return (EINVAL);
3299 
3300 	if (!ipif->ipif_isv6)
3301 		return (EINVAL);
3302 
3303 	if (lnr->lnr_addr.ss_family != AF_INET6)
3304 		return (EAFNOSUPPORT);
3305 
3306 	if (ill->ill_phys_addr_length > sizeof (lnr->lnr_hdw_addr))
3307 		return (EINVAL);
3308 
3309 	return (ndp_query(ill, lnr));
3310 }
3311 
3312 /*
3313  * Perform an update of the nd entry for the specified address.
3314  */
3315 /* ARGSUSED */
3316 int
3317 ip_siocsetndp_v6(ipif_t *ipif, sin_t *dummy_sin, queue_t *q, mblk_t *mp,
3318     ip_ioctl_cmd_t *ipip, void *dummy_ifreq)
3319 {
3320 	ill_t		*ill = ipif->ipif_ill;
3321 	struct	lifreq	*lifr;
3322 	lif_nd_req_t	*lnr;
3323 
3324 	ASSERT(!(q->q_flag & QREADR) && q->q_next == NULL);
3325 
3326 	lifr = (struct lifreq *)mp->b_cont->b_cont->b_rptr;
3327 	lnr = &lifr->lifr_nd;
3328 	/* Only allow for logical unit zero i.e. not on "le0:17" */
3329 	if (ipif->ipif_id != 0)
3330 		return (EINVAL);
3331 
3332 	if (!ipif->ipif_isv6)
3333 		return (EINVAL);
3334 
3335 	if (lnr->lnr_addr.ss_family != AF_INET6)
3336 		return (EAFNOSUPPORT);
3337 
3338 	return (ndp_sioc_update(ill, lnr));
3339 }
3340