xref: /titanic_44/usr/src/uts/common/inet/ip/ip6_if.c (revision 0398691684c2596072212e4ca9d7033ad7ccfa54)
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 					*error = EINPROGRESS;
190 					return (NULL);
191 				}
192 			}
193 		}
194 		mutex_exit(&ill->ill_lock);
195 		RELEASE_CONN_LOCK(q);
196 	}
197 	rw_exit(&ipst->ips_ill_g_lock);
198 	/* lookup the ipif based on interface address */
199 	ipif = ipif_lookup_addr_v6(if_addr, NULL, ALL_ZONES, q, mp, func,
200 	    error, ipst);
201 	ASSERT(ipif == NULL || ipif->ipif_isv6);
202 	return (ipif);
203 }
204 
205 /*
206  * Look for an ipif with the specified address. For point-point links
207  * we look for matches on either the destination address and the local
208  * address, but we ignore the check on the local address if IPIF_UNNUMBERED
209  * is set.
210  * Matches on a specific ill if match_ill is set.
211  */
212 /* ARGSUSED */
213 ipif_t *
214 ipif_lookup_addr_v6(const in6_addr_t *addr, ill_t *match_ill, zoneid_t zoneid,
215     queue_t *q, mblk_t *mp, ipsq_func_t func, int *error, ip_stack_t *ipst)
216 {
217 	ipif_t	*ipif;
218 	ill_t	*ill;
219 	boolean_t  ptp = B_FALSE;
220 	ipsq_t	*ipsq;
221 	ill_walk_context_t ctx;
222 
223 	if (error != NULL)
224 		*error = 0;
225 
226 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
227 	/*
228 	 * Repeat twice, first based on local addresses and
229 	 * next time for pointopoint.
230 	 */
231 repeat:
232 	ill = ILL_START_WALK_V6(&ctx, ipst);
233 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
234 		if (match_ill != NULL && ill != match_ill) {
235 			continue;
236 		}
237 		GRAB_CONN_LOCK(q);
238 		mutex_enter(&ill->ill_lock);
239 		for (ipif = ill->ill_ipif; ipif != NULL;
240 		    ipif = ipif->ipif_next) {
241 			if (zoneid != ALL_ZONES &&
242 			    ipif->ipif_zoneid != zoneid &&
243 			    ipif->ipif_zoneid != ALL_ZONES)
244 				continue;
245 			/* Allow the ipif to be down */
246 			if ((!ptp && (IN6_ARE_ADDR_EQUAL(
247 			    &ipif->ipif_v6lcl_addr, addr) &&
248 			    (ipif->ipif_flags & IPIF_UNNUMBERED) == 0)) ||
249 			    (ptp && (ipif->ipif_flags & IPIF_POINTOPOINT) &&
250 			    IN6_ARE_ADDR_EQUAL(&ipif->ipif_v6pp_dst_addr,
251 			    addr))) {
252 				if (IPIF_CAN_LOOKUP(ipif)) {
253 					ipif_refhold_locked(ipif);
254 					mutex_exit(&ill->ill_lock);
255 					RELEASE_CONN_LOCK(q);
256 					rw_exit(&ipst->ips_ill_g_lock);
257 					return (ipif);
258 				} else if (IPIF_CAN_WAIT(ipif, q)) {
259 					ipsq = ill->ill_phyint->phyint_ipsq;
260 					mutex_enter(&ipsq->ipsq_lock);
261 					mutex_exit(&ill->ill_lock);
262 					rw_exit(&ipst->ips_ill_g_lock);
263 					ipsq_enq(ipsq, q, mp, func, NEW_OP,
264 					    ill);
265 					mutex_exit(&ipsq->ipsq_lock);
266 					RELEASE_CONN_LOCK(q);
267 					*error = EINPROGRESS;
268 					return (NULL);
269 				}
270 			}
271 		}
272 		mutex_exit(&ill->ill_lock);
273 		RELEASE_CONN_LOCK(q);
274 	}
275 
276 	/* If we already did the ptp case, then we are done */
277 	if (ptp) {
278 		rw_exit(&ipst->ips_ill_g_lock);
279 		if (error != NULL)
280 			*error = ENXIO;
281 		return (NULL);
282 	}
283 	ptp = B_TRUE;
284 	goto repeat;
285 }
286 
287 /*
288  * Look for an ipif with the specified address. For point-point links
289  * we look for matches on either the destination address and the local
290  * address, but we ignore the check on the local address if IPIF_UNNUMBERED
291  * is set.
292  * Matches on a specific ill if match_ill is set.
293  * Return the zoneid for the ipif. ALL_ZONES if none found.
294  */
295 zoneid_t
296 ipif_lookup_addr_zoneid_v6(const in6_addr_t *addr, ill_t *match_ill,
297     ip_stack_t *ipst)
298 {
299 	ipif_t	*ipif;
300 	ill_t	*ill;
301 	boolean_t  ptp = B_FALSE;
302 	ill_walk_context_t ctx;
303 	zoneid_t	zoneid;
304 
305 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
306 	/*
307 	 * Repeat twice, first based on local addresses and
308 	 * next time for pointopoint.
309 	 */
310 repeat:
311 	ill = ILL_START_WALK_V6(&ctx, ipst);
312 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
313 		if (match_ill != NULL && ill != match_ill) {
314 			continue;
315 		}
316 		mutex_enter(&ill->ill_lock);
317 		for (ipif = ill->ill_ipif; ipif != NULL;
318 		    ipif = ipif->ipif_next) {
319 			/* Allow the ipif to be down */
320 			if ((!ptp && (IN6_ARE_ADDR_EQUAL(
321 			    &ipif->ipif_v6lcl_addr, addr) &&
322 			    (ipif->ipif_flags & IPIF_UNNUMBERED) == 0)) ||
323 			    (ptp && (ipif->ipif_flags & IPIF_POINTOPOINT) &&
324 			    IN6_ARE_ADDR_EQUAL(&ipif->ipif_v6pp_dst_addr,
325 			    addr)) &&
326 			    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
327 				zoneid = ipif->ipif_zoneid;
328 				mutex_exit(&ill->ill_lock);
329 				rw_exit(&ipst->ips_ill_g_lock);
330 				/*
331 				 * If ipif_zoneid was ALL_ZONES then we have
332 				 * a trusted extensions shared IP address.
333 				 * In that case GLOBAL_ZONEID works to send.
334 				 */
335 				if (zoneid == ALL_ZONES)
336 					zoneid = GLOBAL_ZONEID;
337 				return (zoneid);
338 			}
339 		}
340 		mutex_exit(&ill->ill_lock);
341 	}
342 
343 	/* If we already did the ptp case, then we are done */
344 	if (ptp) {
345 		rw_exit(&ipst->ips_ill_g_lock);
346 		return (ALL_ZONES);
347 	}
348 	ptp = B_TRUE;
349 	goto repeat;
350 }
351 
352 /*
353  * Perform various checks to verify that an address would make sense as a local
354  * interface address.  This is currently only called when an attempt is made
355  * to set a local address.
356  *
357  * Does not allow a v4-mapped address, an address that equals the subnet
358  * anycast address, ... a multicast address, ...
359  */
360 boolean_t
361 ip_local_addr_ok_v6(const in6_addr_t *addr, const in6_addr_t *subnet_mask)
362 {
363 	in6_addr_t subnet;
364 
365 	if (IN6_IS_ADDR_UNSPECIFIED(addr))
366 		return (B_TRUE);	/* Allow all zeros */
367 
368 	/*
369 	 * Don't allow all zeroes or host part, but allow
370 	 * all ones netmask.
371 	 */
372 	V6_MASK_COPY(*addr, *subnet_mask, subnet);
373 	if (IN6_IS_ADDR_V4MAPPED(addr) ||
374 	    (IN6_ARE_ADDR_EQUAL(addr, &subnet) &&
375 	    !IN6_ARE_ADDR_EQUAL(subnet_mask, &ipv6_all_ones)) ||
376 	    (IN6_IS_ADDR_V4COMPAT(addr) && CLASSD(V4_PART_OF_V6((*addr)))) ||
377 	    IN6_IS_ADDR_MULTICAST(addr))
378 		return (B_FALSE);
379 
380 	return (B_TRUE);
381 }
382 
383 /*
384  * Perform various checks to verify that an address would make sense as a
385  * remote/subnet interface address.
386  */
387 boolean_t
388 ip_remote_addr_ok_v6(const in6_addr_t *addr, const in6_addr_t *subnet_mask)
389 {
390 	in6_addr_t subnet;
391 
392 	if (IN6_IS_ADDR_UNSPECIFIED(addr))
393 		return (B_TRUE);	/* Allow all zeros */
394 
395 	V6_MASK_COPY(*addr, *subnet_mask, subnet);
396 	if (IN6_IS_ADDR_V4MAPPED(addr) ||
397 	    (IN6_ARE_ADDR_EQUAL(addr, &subnet) &&
398 	    !IN6_ARE_ADDR_EQUAL(subnet_mask, &ipv6_all_ones)) ||
399 	    IN6_IS_ADDR_MULTICAST(addr) ||
400 	    (IN6_IS_ADDR_V4COMPAT(addr) && CLASSD(V4_PART_OF_V6((*addr)))))
401 		return (B_FALSE);
402 
403 	return (B_TRUE);
404 }
405 
406 /*
407  * ip_rt_add_v6 is called to add an IPv6 route to the forwarding table.
408  * ipif_arg is passed in to associate it with the correct interface
409  * (for link-local destinations and gateways).
410  */
411 /* ARGSUSED1 */
412 int
413 ip_rt_add_v6(const in6_addr_t *dst_addr, const in6_addr_t *mask,
414     const in6_addr_t *gw_addr, const in6_addr_t *src_addr, int flags,
415     ipif_t *ipif_arg, ire_t **ire_arg, queue_t *q, mblk_t *mp, ipsq_func_t func,
416     struct rtsa_s *sp, ip_stack_t *ipst)
417 {
418 	ire_t	*ire;
419 	ire_t	*gw_ire = NULL;
420 	ipif_t	*ipif;
421 	boolean_t ipif_refheld = B_FALSE;
422 	uint_t	type;
423 	int	match_flags = MATCH_IRE_TYPE;
424 	int	error;
425 	tsol_gc_t *gc = NULL;
426 	tsol_gcgrp_t *gcgrp = NULL;
427 	boolean_t gcgrp_xtraref = B_FALSE;
428 
429 	if (ire_arg != NULL)
430 		*ire_arg = NULL;
431 
432 	/*
433 	 * Prevent routes with a zero gateway from being created (since
434 	 * interfaces can currently be plumbed and brought up with no assigned
435 	 * address).
436 	 */
437 	if (IN6_IS_ADDR_UNSPECIFIED(gw_addr))
438 		return (ENETUNREACH);
439 
440 	/*
441 	 * If this is the case of RTF_HOST being set, then we set the netmask
442 	 * to all ones (regardless if one was supplied).
443 	 */
444 	if (flags & RTF_HOST)
445 		mask = &ipv6_all_ones;
446 
447 	/*
448 	 * Get the ipif, if any, corresponding to the gw_addr
449 	 */
450 	ipif = ipif_lookup_interface_v6(gw_addr, dst_addr, q, mp, func,
451 	    &error, ipst);
452 	if (ipif != NULL)
453 		ipif_refheld = B_TRUE;
454 	else if (error == EINPROGRESS) {
455 		ip1dbg(("ip_rt_add_v6: null and EINPROGRESS"));
456 		return (error);
457 	}
458 
459 	/*
460 	 * GateD will attempt to create routes with a loopback interface
461 	 * address as the gateway and with RTF_GATEWAY set.  We allow
462 	 * these routes to be added, but create them as interface routes
463 	 * since the gateway is an interface address.
464 	 */
465 	if ((ipif != NULL) && (ipif->ipif_ire_type == IRE_LOOPBACK)) {
466 		flags &= ~RTF_GATEWAY;
467 		if (IN6_ARE_ADDR_EQUAL(gw_addr, &ipv6_loopback) &&
468 		    IN6_ARE_ADDR_EQUAL(dst_addr, &ipv6_loopback) &&
469 		    IN6_ARE_ADDR_EQUAL(mask, &ipv6_all_ones)) {
470 			ire = ire_ctable_lookup_v6(dst_addr, 0, IRE_LOOPBACK,
471 			    ipif, ALL_ZONES, NULL, match_flags, ipst);
472 			if (ire != NULL) {
473 				ire_refrele(ire);
474 				if (ipif_refheld)
475 					ipif_refrele(ipif);
476 				return (EEXIST);
477 			}
478 			ip1dbg(("ipif_up_done: 0x%p creating IRE 0x%x"
479 			    "for 0x%x\n", (void *)ipif,
480 			    ipif->ipif_ire_type,
481 			    ntohl(ipif->ipif_lcl_addr)));
482 			ire = ire_create_v6(
483 			    dst_addr,
484 			    mask,
485 			    &ipif->ipif_v6src_addr,
486 			    NULL,
487 			    &ipif->ipif_mtu,
488 			    NULL,
489 			    NULL,
490 			    NULL,
491 			    ipif->ipif_net_type,
492 			    ipif,
493 			    NULL,
494 			    0,
495 			    0,
496 			    flags,
497 			    &ire_uinfo_null,
498 			    NULL,
499 			    NULL,
500 			    ipst);
501 			if (ire == NULL) {
502 				if (ipif_refheld)
503 					ipif_refrele(ipif);
504 				return (ENOMEM);
505 			}
506 			error = ire_add(&ire, q, mp, func, B_FALSE);
507 			if (error == 0)
508 				goto save_ire;
509 			/*
510 			 * In the result of failure, ire_add() will have already
511 			 * deleted the ire in question, so there is no need to
512 			 * do that here.
513 			 */
514 			if (ipif_refheld)
515 				ipif_refrele(ipif);
516 			return (error);
517 		}
518 	}
519 
520 	/*
521 	 * Traditionally, interface routes are ones where RTF_GATEWAY isn't set
522 	 * and the gateway address provided is one of the system's interface
523 	 * addresses.  By using the routing socket interface and supplying an
524 	 * RTA_IFP sockaddr with an interface index, an alternate method of
525 	 * specifying an interface route to be created is available which uses
526 	 * the interface index that specifies the outgoing interface rather than
527 	 * the address of an outgoing interface (which may not be able to
528 	 * uniquely identify an interface).  When coupled with the RTF_GATEWAY
529 	 * flag, routes can be specified which not only specify the next-hop to
530 	 * be used when routing to a certain prefix, but also which outgoing
531 	 * interface should be used.
532 	 *
533 	 * Previously, interfaces would have unique addresses assigned to them
534 	 * and so the address assigned to a particular interface could be used
535 	 * to identify a particular interface.  One exception to this was the
536 	 * case of an unnumbered interface (where IPIF_UNNUMBERED was set).
537 	 *
538 	 * With the advent of IPv6 and its link-local addresses, this
539 	 * restriction was relaxed and interfaces could share addresses between
540 	 * themselves.  In fact, typically all of the link-local interfaces on
541 	 * an IPv6 node or router will have the same link-local address.  In
542 	 * order to differentiate between these interfaces, the use of an
543 	 * interface index is necessary and this index can be carried inside a
544 	 * RTA_IFP sockaddr (which is actually a sockaddr_dl).  One restriction
545 	 * of using the interface index, however, is that all of the ipif's that
546 	 * are part of an ill have the same index and so the RTA_IFP sockaddr
547 	 * cannot be used to differentiate between ipif's (or logical
548 	 * interfaces) that belong to the same ill (physical interface).
549 	 *
550 	 * For example, in the following case involving IPv4 interfaces and
551 	 * logical interfaces
552 	 *
553 	 *	192.0.2.32	255.255.255.224	192.0.2.33	U	if0
554 	 *	192.0.2.32	255.255.255.224	192.0.2.34	U	if0:1
555 	 *	192.0.2.32	255.255.255.224	192.0.2.35	U	if0:2
556 	 *
557 	 * the ipif's corresponding to each of these interface routes can be
558 	 * uniquely identified by the "gateway" (actually interface address).
559 	 *
560 	 * In this case involving multiple IPv6 default routes to a particular
561 	 * link-local gateway, the use of RTA_IFP is necessary to specify which
562 	 * default route is of interest:
563 	 *
564 	 *	default		fe80::123:4567:89ab:cdef	U	if0
565 	 *	default		fe80::123:4567:89ab:cdef	U	if1
566 	 */
567 
568 	/* RTF_GATEWAY not set */
569 	if (!(flags & RTF_GATEWAY)) {
570 		queue_t	*stq;
571 
572 		if (sp != NULL) {
573 			ip2dbg(("ip_rt_add_v6: gateway security attributes "
574 			    "cannot be set with interface route\n"));
575 			if (ipif_refheld)
576 				ipif_refrele(ipif);
577 			return (EINVAL);
578 		}
579 
580 		/*
581 		 * As the interface index specified with the RTA_IFP sockaddr is
582 		 * the same for all ipif's off of an ill, the matching logic
583 		 * below uses MATCH_IRE_ILL if such an index was specified.
584 		 * This means that routes sharing the same prefix when added
585 		 * using a RTA_IFP sockaddr must have distinct interface
586 		 * indices (namely, they must be on distinct ill's).
587 		 *
588 		 * On the other hand, since the gateway address will usually be
589 		 * different for each ipif on the system, the matching logic
590 		 * uses MATCH_IRE_IPIF in the case of a traditional interface
591 		 * route.  This means that interface routes for the same prefix
592 		 * can be created if they belong to distinct ipif's and if a
593 		 * RTA_IFP sockaddr is not present.
594 		 */
595 		if (ipif_arg != NULL) {
596 			if (ipif_refheld) {
597 				ipif_refrele(ipif);
598 				ipif_refheld = B_FALSE;
599 			}
600 			ipif = ipif_arg;
601 			match_flags |= MATCH_IRE_ILL;
602 		} else {
603 			/*
604 			 * Check the ipif corresponding to the gw_addr
605 			 */
606 			if (ipif == NULL)
607 				return (ENETUNREACH);
608 			match_flags |= MATCH_IRE_IPIF;
609 		}
610 
611 		ASSERT(ipif != NULL);
612 		/*
613 		 * We check for an existing entry at this point.
614 		 */
615 		match_flags |= MATCH_IRE_MASK;
616 		ire = ire_ftable_lookup_v6(dst_addr, mask, 0, IRE_INTERFACE,
617 		    ipif, NULL, ALL_ZONES, 0, NULL, match_flags, ipst);
618 		if (ire != NULL) {
619 			ire_refrele(ire);
620 			if (ipif_refheld)
621 				ipif_refrele(ipif);
622 			return (EEXIST);
623 		}
624 
625 		stq = (ipif->ipif_net_type == IRE_IF_RESOLVER)
626 		    ? ipif->ipif_rq : ipif->ipif_wq;
627 
628 		/*
629 		 * Create a copy of the IRE_LOOPBACK, IRE_IF_NORESOLVER or
630 		 * IRE_IF_RESOLVER with the modified address and netmask.
631 		 */
632 		ire = ire_create_v6(
633 		    dst_addr,
634 		    mask,
635 		    &ipif->ipif_v6src_addr,
636 		    NULL,
637 		    &ipif->ipif_mtu,
638 		    NULL,
639 		    NULL,
640 		    stq,
641 		    ipif->ipif_net_type,
642 		    ipif,
643 		    NULL,
644 		    0,
645 		    0,
646 		    flags,
647 		    &ire_uinfo_null,
648 		    NULL,
649 		    NULL,
650 		    ipst);
651 		if (ire == NULL) {
652 			if (ipif_refheld)
653 				ipif_refrele(ipif);
654 			return (ENOMEM);
655 		}
656 
657 		/*
658 		 * Some software (for example, GateD and Sun Cluster) attempts
659 		 * to create (what amount to) IRE_PREFIX routes with the
660 		 * loopback address as the gateway.  This is primarily done to
661 		 * set up prefixes with the RTF_REJECT flag set (for example,
662 		 * when generating aggregate routes.)
663 		 *
664 		 * If the IRE type (as defined by ipif->ipif_net_type) is
665 		 * IRE_LOOPBACK, then we map the request into a
666 		 * IRE_IF_NORESOLVER.
667 		 *
668 		 * Needless to say, the real IRE_LOOPBACK is NOT created by this
669 		 * routine, but rather using ire_create_v6() directly.
670 		 */
671 		if (ipif->ipif_net_type == IRE_LOOPBACK)
672 			ire->ire_type = IRE_IF_NORESOLVER;
673 		error = ire_add(&ire, q, mp, func, B_FALSE);
674 		if (error == 0)
675 			goto save_ire;
676 		/*
677 		 * In the result of failure, ire_add() will have already
678 		 * deleted the ire in question, so there is no need to
679 		 * do that here.
680 		 */
681 		if (ipif_refheld)
682 			ipif_refrele(ipif);
683 		return (error);
684 	}
685 	if (ipif_refheld) {
686 		ipif_refrele(ipif);
687 		ipif_refheld = B_FALSE;
688 	}
689 
690 	/*
691 	 * Get an interface IRE for the specified gateway.
692 	 * If we don't have an IRE_IF_NORESOLVER or IRE_IF_RESOLVER for the
693 	 * gateway, it is currently unreachable and we fail the request
694 	 * accordingly.
695 	 */
696 	ipif = ipif_arg;
697 	if (ipif_arg != NULL)
698 		match_flags |= MATCH_IRE_ILL;
699 	gw_ire = ire_ftable_lookup_v6(gw_addr, 0, 0, IRE_INTERFACE, ipif_arg,
700 	    NULL, ALL_ZONES, 0, NULL, match_flags, ipst);
701 	if (gw_ire == NULL)
702 		return (ENETUNREACH);
703 
704 	/*
705 	 * We create one of three types of IREs as a result of this request
706 	 * based on the netmask.  A netmask of all ones (which is automatically
707 	 * assumed when RTF_HOST is set) results in an IRE_HOST being created.
708 	 * An all zeroes netmask implies a default route so an IRE_DEFAULT is
709 	 * created.  Otherwise, an IRE_PREFIX route is created for the
710 	 * destination prefix.
711 	 */
712 	if (IN6_ARE_ADDR_EQUAL(mask, &ipv6_all_ones))
713 		type = IRE_HOST;
714 	else if (IN6_IS_ADDR_UNSPECIFIED(mask))
715 		type = IRE_DEFAULT;
716 	else
717 		type = IRE_PREFIX;
718 
719 	/* check for a duplicate entry */
720 	ire = ire_ftable_lookup_v6(dst_addr, mask, gw_addr, type, ipif_arg,
721 	    NULL, ALL_ZONES, 0, NULL,
722 	    match_flags | MATCH_IRE_MASK | MATCH_IRE_GW, ipst);
723 	if (ire != NULL) {
724 		ire_refrele(gw_ire);
725 		ire_refrele(ire);
726 		return (EEXIST);
727 	}
728 
729 	/* Security attribute exists */
730 	if (sp != NULL) {
731 		tsol_gcgrp_addr_t ga;
732 
733 		/* find or create the gateway credentials group */
734 		ga.ga_af = AF_INET6;
735 		ga.ga_addr = *gw_addr;
736 
737 		/* we hold reference to it upon success */
738 		gcgrp = gcgrp_lookup(&ga, B_TRUE);
739 		if (gcgrp == NULL) {
740 			ire_refrele(gw_ire);
741 			return (ENOMEM);
742 		}
743 
744 		/*
745 		 * Create and add the security attribute to the group; a
746 		 * reference to the group is made upon allocating a new
747 		 * entry successfully.  If it finds an already-existing
748 		 * entry for the security attribute in the group, it simply
749 		 * returns it and no new reference is made to the group.
750 		 */
751 		gc = gc_create(sp, gcgrp, &gcgrp_xtraref);
752 		if (gc == NULL) {
753 			/* release reference held by gcgrp_lookup */
754 			GCGRP_REFRELE(gcgrp);
755 			ire_refrele(gw_ire);
756 			return (ENOMEM);
757 		}
758 	}
759 
760 	/* Create the IRE. */
761 	ire = ire_create_v6(
762 	    dst_addr,				/* dest address */
763 	    mask,				/* mask */
764 	    /* src address assigned by the caller? */
765 	    (((flags & RTF_SETSRC) && !IN6_IS_ADDR_UNSPECIFIED(src_addr)) ?
766 	    src_addr : NULL),
767 	    gw_addr,				/* gateway address */
768 	    &gw_ire->ire_max_frag,
769 	    NULL,				/* no src nce */
770 	    NULL,				/* no recv-from queue */
771 	    NULL,				/* no send-to queue */
772 	    (ushort_t)type,			/* IRE type */
773 	    ipif_arg,
774 	    NULL,
775 	    0,
776 	    0,
777 	    flags,
778 	    &gw_ire->ire_uinfo,			/* Inherit ULP info from gw */
779 	    gc,					/* security attribute */
780 	    NULL,
781 	    ipst);
782 
783 	/*
784 	 * The ire holds a reference to the 'gc' and the 'gc' holds a
785 	 * reference to the 'gcgrp'. We can now release the extra reference
786 	 * the 'gcgrp' acquired in the gcgrp_lookup, if it was not used.
787 	 */
788 	if (gcgrp_xtraref)
789 		GCGRP_REFRELE(gcgrp);
790 	if (ire == NULL) {
791 		if (gc != NULL)
792 			GC_REFRELE(gc);
793 		ire_refrele(gw_ire);
794 		return (ENOMEM);
795 	}
796 
797 	/*
798 	 * POLICY: should we allow an RTF_HOST with address INADDR_ANY?
799 	 * SUN/OS socket stuff does but do we really want to allow ::0 ?
800 	 */
801 
802 	/* Add the new IRE. */
803 	error = ire_add(&ire, q, mp, func, B_FALSE);
804 	/*
805 	 * In the result of failure, ire_add() will have already
806 	 * deleted the ire in question, so there is no need to
807 	 * do that here.
808 	 */
809 	if (error != 0) {
810 		ire_refrele(gw_ire);
811 		return (error);
812 	}
813 
814 	if (flags & RTF_MULTIRT) {
815 		/*
816 		 * Invoke the CGTP (multirouting) filtering module
817 		 * to add the dst address in the filtering database.
818 		 * Replicated inbound packets coming from that address
819 		 * will be filtered to discard the duplicates.
820 		 * It is not necessary to call the CGTP filter hook
821 		 * when the dst address is a multicast, because an
822 		 * IP source address cannot be a multicast.
823 		 */
824 		if (ipst->ips_ip_cgtp_filter_ops != NULL &&
825 		    !IN6_IS_ADDR_MULTICAST(&(ire->ire_addr_v6))) {
826 			int res;
827 
828 			res = ipst->ips_ip_cgtp_filter_ops->cfo_add_dest_v6(
829 			    ipst->ips_netstack->netstack_stackid,
830 			    &ire->ire_addr_v6,
831 			    &ire->ire_gateway_addr_v6,
832 			    &ire->ire_src_addr_v6,
833 			    &gw_ire->ire_src_addr_v6);
834 			if (res != 0) {
835 				ire_refrele(gw_ire);
836 				ire_delete(ire);
837 				return (res);
838 			}
839 		}
840 	}
841 
842 	/*
843 	 * Now that the prefix IRE entry has been created, delete any
844 	 * existing gateway IRE cache entries as well as any IRE caches
845 	 * using the gateway, and force them to be created through
846 	 * ip_newroute_v6.
847 	 */
848 	if (gc != NULL) {
849 		ASSERT(gcgrp != NULL);
850 		ire_clookup_delete_cache_gw_v6(gw_addr, ALL_ZONES, ipst);
851 	}
852 
853 save_ire:
854 	if (gw_ire != NULL) {
855 		ire_refrele(gw_ire);
856 	}
857 	if (ipif != NULL) {
858 		mblk_t	*save_mp;
859 
860 		/*
861 		 * Save enough information so that we can recreate the IRE if
862 		 * the interface goes down and then up.  The metrics associated
863 		 * with the route will be saved as well when rts_setmetrics() is
864 		 * called after the IRE has been created.  In the case where
865 		 * memory cannot be allocated, none of this information will be
866 		 * saved.
867 		 */
868 		save_mp = allocb(sizeof (ifrt_t), BPRI_MED);
869 		if (save_mp != NULL) {
870 			ifrt_t	*ifrt;
871 
872 			save_mp->b_wptr += sizeof (ifrt_t);
873 			ifrt = (ifrt_t *)save_mp->b_rptr;
874 			bzero(ifrt, sizeof (ifrt_t));
875 			ifrt->ifrt_type = ire->ire_type;
876 			ifrt->ifrt_v6addr = ire->ire_addr_v6;
877 			mutex_enter(&ire->ire_lock);
878 			ifrt->ifrt_v6gateway_addr = ire->ire_gateway_addr_v6;
879 			ifrt->ifrt_v6src_addr = ire->ire_src_addr_v6;
880 			mutex_exit(&ire->ire_lock);
881 			ifrt->ifrt_v6mask = ire->ire_mask_v6;
882 			ifrt->ifrt_flags = ire->ire_flags;
883 			ifrt->ifrt_max_frag = ire->ire_max_frag;
884 			mutex_enter(&ipif->ipif_saved_ire_lock);
885 			save_mp->b_cont = ipif->ipif_saved_ire_mp;
886 			ipif->ipif_saved_ire_mp = save_mp;
887 			ipif->ipif_saved_ire_cnt++;
888 			mutex_exit(&ipif->ipif_saved_ire_lock);
889 		}
890 	}
891 	if (ire_arg != NULL) {
892 		/*
893 		 * Store the ire that was successfully added into where ire_arg
894 		 * points to so that callers don't have to look it up
895 		 * themselves (but they are responsible for ire_refrele()ing
896 		 * the ire when they are finished with it).
897 		 */
898 		*ire_arg = ire;
899 	} else {
900 		ire_refrele(ire);		/* Held in ire_add */
901 	}
902 	if (ipif_refheld)
903 		ipif_refrele(ipif);
904 	return (0);
905 }
906 
907 /*
908  * ip_rt_delete_v6 is called to delete an IPv6 route.
909  * ipif_arg is passed in to associate it with the correct interface
910  * (for link-local destinations and gateways).
911  */
912 /* ARGSUSED4 */
913 int
914 ip_rt_delete_v6(const in6_addr_t *dst_addr, const in6_addr_t *mask,
915     const in6_addr_t *gw_addr, uint_t rtm_addrs, int flags, ipif_t *ipif_arg,
916     queue_t *q, mblk_t *mp, ipsq_func_t func, ip_stack_t *ipst)
917 {
918 	ire_t	*ire = NULL;
919 	ipif_t	*ipif;
920 	uint_t	type;
921 	uint_t	match_flags = MATCH_IRE_TYPE;
922 	int	err = 0;
923 	boolean_t	ipif_refheld = B_FALSE;
924 
925 	/*
926 	 * If this is the case of RTF_HOST being set, then we set the netmask
927 	 * to all ones.  Otherwise, we use the netmask if one was supplied.
928 	 */
929 	if (flags & RTF_HOST) {
930 		mask = &ipv6_all_ones;
931 		match_flags |= MATCH_IRE_MASK;
932 	} else if (rtm_addrs & RTA_NETMASK) {
933 		match_flags |= MATCH_IRE_MASK;
934 	}
935 
936 	/*
937 	 * Note that RTF_GATEWAY is never set on a delete, therefore
938 	 * we check if the gateway address is one of our interfaces first,
939 	 * and fall back on RTF_GATEWAY routes.
940 	 *
941 	 * This makes it possible to delete an original
942 	 * IRE_IF_NORESOLVER/IRE_IF_RESOLVER - consistent with SunOS 4.1.
943 	 *
944 	 * As the interface index specified with the RTA_IFP sockaddr is the
945 	 * same for all ipif's off of an ill, the matching logic below uses
946 	 * MATCH_IRE_ILL if such an index was specified.  This means a route
947 	 * sharing the same prefix and interface index as the the route
948 	 * intended to be deleted might be deleted instead if a RTA_IFP sockaddr
949 	 * is specified in the request.
950 	 *
951 	 * On the other hand, since the gateway address will usually be
952 	 * different for each ipif on the system, the matching logic
953 	 * uses MATCH_IRE_IPIF in the case of a traditional interface
954 	 * route.  This means that interface routes for the same prefix can be
955 	 * uniquely identified if they belong to distinct ipif's and if a
956 	 * RTA_IFP sockaddr is not present.
957 	 *
958 	 * For more detail on specifying routes by gateway address and by
959 	 * interface index, see the comments in ip_rt_add_v6().
960 	 */
961 	ipif = ipif_lookup_interface_v6(gw_addr, dst_addr, q, mp, func, &err,
962 	    ipst);
963 	if (ipif != NULL) {
964 		ipif_refheld = B_TRUE;
965 		if (ipif_arg != NULL) {
966 			ipif_refrele(ipif);
967 			ipif_refheld = B_FALSE;
968 			ipif = ipif_arg;
969 			match_flags |= MATCH_IRE_ILL;
970 		} else {
971 			match_flags |= MATCH_IRE_IPIF;
972 		}
973 
974 		if (ipif->ipif_ire_type == IRE_LOOPBACK)
975 			ire = ire_ctable_lookup_v6(dst_addr, 0, IRE_LOOPBACK,
976 			    ipif, ALL_ZONES, NULL, match_flags, ipst);
977 		if (ire == NULL)
978 			ire = ire_ftable_lookup_v6(dst_addr, mask, 0,
979 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0, NULL,
980 			    match_flags, ipst);
981 	} else if (err == EINPROGRESS) {
982 		return (err);
983 	} else {
984 		err = 0;
985 	}
986 	if (ire == NULL) {
987 		/*
988 		 * At this point, the gateway address is not one of our own
989 		 * addresses or a matching interface route was not found.  We
990 		 * set the IRE type to lookup based on whether
991 		 * this is a host route, a default route or just a prefix.
992 		 *
993 		 * If an ipif_arg was passed in, then the lookup is based on an
994 		 * interface index so MATCH_IRE_ILL is added to match_flags.
995 		 * In any case, MATCH_IRE_IPIF is cleared and MATCH_IRE_GW is
996 		 * set as the route being looked up is not a traditional
997 		 * interface route.
998 		 */
999 		match_flags &= ~MATCH_IRE_IPIF;
1000 		match_flags |= MATCH_IRE_GW;
1001 		if (ipif_arg != NULL)
1002 			match_flags |= MATCH_IRE_ILL;
1003 		if (IN6_ARE_ADDR_EQUAL(mask, &ipv6_all_ones))
1004 			type = IRE_HOST;
1005 		else if (IN6_IS_ADDR_UNSPECIFIED(mask))
1006 			type = IRE_DEFAULT;
1007 		else
1008 			type = IRE_PREFIX;
1009 		ire = ire_ftable_lookup_v6(dst_addr, mask, gw_addr, type,
1010 		    ipif_arg, NULL, ALL_ZONES, 0, NULL, match_flags, ipst);
1011 	}
1012 
1013 	if (ipif_refheld) {
1014 		ipif_refrele(ipif);
1015 		ipif_refheld = B_FALSE;
1016 	}
1017 	if (ire == NULL)
1018 		return (ESRCH);
1019 
1020 	if (ire->ire_flags & RTF_MULTIRT) {
1021 		/*
1022 		 * Invoke the CGTP (multirouting) filtering module
1023 		 * to remove the dst address from the filtering database.
1024 		 * Packets coming from that address will no longer be
1025 		 * filtered to remove duplicates.
1026 		 */
1027 		if (ipst->ips_ip_cgtp_filter_ops != NULL) {
1028 			err = ipst->ips_ip_cgtp_filter_ops->cfo_del_dest_v6(
1029 			    ipst->ips_netstack->netstack_stackid,
1030 			    &ire->ire_addr_v6, &ire->ire_gateway_addr_v6);
1031 		}
1032 	}
1033 
1034 	ipif = ire->ire_ipif;
1035 	if (ipif != NULL) {
1036 		mblk_t		**mpp;
1037 		mblk_t		*mp;
1038 		ifrt_t		*ifrt;
1039 		in6_addr_t	gw_addr_v6;
1040 
1041 		/* Remove from ipif_saved_ire_mp list if it is there */
1042 		mutex_enter(&ire->ire_lock);
1043 		gw_addr_v6 = ire->ire_gateway_addr_v6;
1044 		mutex_exit(&ire->ire_lock);
1045 		mutex_enter(&ipif->ipif_saved_ire_lock);
1046 		for (mpp = &ipif->ipif_saved_ire_mp; *mpp != NULL;
1047 		    mpp = &(*mpp)->b_cont) {
1048 			/*
1049 			 * On a given ipif, the triple of address, gateway and
1050 			 * mask is unique for each saved IRE (in the case of
1051 			 * ordinary interface routes, the gateway address is
1052 			 * all-zeroes).
1053 			 */
1054 			mp = *mpp;
1055 			ifrt = (ifrt_t *)mp->b_rptr;
1056 			if (IN6_ARE_ADDR_EQUAL(&ifrt->ifrt_v6addr,
1057 			    &ire->ire_addr_v6) &&
1058 			    IN6_ARE_ADDR_EQUAL(&ifrt->ifrt_v6gateway_addr,
1059 			    &gw_addr_v6) &&
1060 			    IN6_ARE_ADDR_EQUAL(&ifrt->ifrt_v6mask,
1061 			    &ire->ire_mask_v6)) {
1062 				*mpp = mp->b_cont;
1063 				ipif->ipif_saved_ire_cnt--;
1064 				freeb(mp);
1065 				break;
1066 			}
1067 		}
1068 		mutex_exit(&ipif->ipif_saved_ire_lock);
1069 	}
1070 	ire_delete(ire);
1071 	ire_refrele(ire);
1072 	return (err);
1073 }
1074 
1075 /*
1076  * Derive a token from the link layer address.
1077  */
1078 boolean_t
1079 ill_setdefaulttoken(ill_t *ill)
1080 {
1081 	int 		i;
1082 	in6_addr_t	v6addr, v6mask;
1083 
1084 	if (!MEDIA_V6INTFID(ill->ill_media, ill->ill_phys_addr_length,
1085 	    ill->ill_phys_addr, &v6addr))
1086 		return (B_FALSE);
1087 
1088 	(void) ip_plen_to_mask_v6(IPV6_TOKEN_LEN, &v6mask);
1089 
1090 	for (i = 0; i < 4; i++)
1091 		v6mask.s6_addr32[i] = v6mask.s6_addr32[i] ^
1092 		    (uint32_t)0xffffffff;
1093 
1094 	V6_MASK_COPY(v6addr, v6mask, ill->ill_token);
1095 	ill->ill_token_length = IPV6_TOKEN_LEN;
1096 	return (B_TRUE);
1097 }
1098 
1099 /*
1100  * Create a link-local address from a token.
1101  */
1102 static void
1103 ipif_get_linklocal(in6_addr_t *dest, const in6_addr_t *token)
1104 {
1105 	int i;
1106 
1107 	for (i = 0; i < 4; i++) {
1108 		dest->s6_addr32[i] =
1109 		    token->s6_addr32[i] | ipv6_ll_template.s6_addr32[i];
1110 	}
1111 }
1112 
1113 /*
1114  * Set a nice default address for either automatic tunnels tsrc/96 or
1115  * 6to4 tunnels 2002:<tsrc>::1/64
1116  */
1117 static void
1118 ipif_set_tun_auto_addr(ipif_t *ipif, struct iftun_req *ta)
1119 {
1120 	sin6_t	sin6;
1121 	sin_t	*sin;
1122 	ill_t 	*ill = ipif->ipif_ill;
1123 	tun_t *tp = (tun_t *)ill->ill_wq->q_next->q_ptr;
1124 
1125 	if (ta->ifta_saddr.ss_family != AF_INET ||
1126 	    (ipif->ipif_flags & IPIF_UP) || !ipif->ipif_isv6 ||
1127 	    (ta->ifta_flags & IFTUN_SRC) == 0)
1128 		return;
1129 
1130 	/*
1131 	 * Check the tunnel type by examining q_next->q_ptr
1132 	 */
1133 	if (tp->tun_flags & TUN_AUTOMATIC) {
1134 		/* this is an automatic tunnel */
1135 		(void) ip_plen_to_mask_v6(IPV6_ABITS - IP_ABITS,
1136 		    &ipif->ipif_v6net_mask);
1137 		bzero(&sin6, sizeof (sin6_t));
1138 		sin = (sin_t *)&ta->ifta_saddr;
1139 		V4_PART_OF_V6(sin6.sin6_addr) = sin->sin_addr.s_addr;
1140 		sin6.sin6_family = AF_INET6;
1141 		(void) ip_sioctl_addr(ipif, (sin_t *)&sin6,
1142 		    NULL, NULL, NULL, NULL);
1143 	} else if (tp->tun_flags & TUN_6TO4) {
1144 		/* this is a 6to4 tunnel */
1145 		(void) ip_plen_to_mask_v6(IPV6_PREFIX_LEN,
1146 		    &ipif->ipif_v6net_mask);
1147 		sin = (sin_t *)&ta->ifta_saddr;
1148 		/* create a 6to4 address from the IPv4 tsrc */
1149 		IN6_V4ADDR_TO_6TO4(&sin->sin_addr, &sin6.sin6_addr);
1150 		sin6.sin6_family = AF_INET6;
1151 		(void) ip_sioctl_addr(ipif, (sin_t *)&sin6,
1152 		    NULL, NULL, NULL, NULL);
1153 	} else {
1154 		ip1dbg(("ipif_set_tun_auto_addr: Unknown tunnel type"));
1155 		return;
1156 	}
1157 }
1158 
1159 /*
1160  * Set link local for ipif_id 0 of a configured tunnel based on the
1161  * tsrc or tdst parameter
1162  * For tunnels over IPv4 use the IPv4 address prepended with 32 zeros as
1163  * the token.
1164  * For tunnels over IPv6 use the low-order 64 bits of the "inner" IPv6 address
1165  * as the token for the "outer" link.
1166  */
1167 void
1168 ipif_set_tun_llink(ill_t *ill, struct iftun_req *ta)
1169 {
1170 	ipif_t		*ipif;
1171 	sin_t		*sin;
1172 	in6_addr_t	*s6addr;
1173 
1174 	ASSERT(IAM_WRITER_ILL(ill));
1175 
1176 	/* The first ipif must be id zero. */
1177 	ipif = ill->ill_ipif;
1178 	ASSERT(ipif->ipif_id == 0);
1179 
1180 	/* no link local for automatic tunnels */
1181 	if (!(ipif->ipif_flags & IPIF_POINTOPOINT)) {
1182 		ipif_set_tun_auto_addr(ipif, ta);
1183 		return;
1184 	}
1185 
1186 	if ((ta->ifta_flags & IFTUN_DST) &&
1187 	    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6pp_dst_addr)) {
1188 		sin6_t	sin6;
1189 
1190 		ASSERT(!(ipif->ipif_flags & IPIF_UP));
1191 		bzero(&sin6, sizeof (sin6_t));
1192 		if ((ta->ifta_saddr.ss_family == AF_INET)) {
1193 			sin = (sin_t *)&ta->ifta_daddr;
1194 			V4_PART_OF_V6(sin6.sin6_addr) =
1195 			    sin->sin_addr.s_addr;
1196 		} else {
1197 			s6addr =
1198 			    &((sin6_t *)&ta->ifta_daddr)->sin6_addr;
1199 			sin6.sin6_addr.s6_addr32[3] = s6addr->s6_addr32[3];
1200 			sin6.sin6_addr.s6_addr32[2] = s6addr->s6_addr32[2];
1201 		}
1202 		ipif_get_linklocal(&ipif->ipif_v6pp_dst_addr,
1203 		    &sin6.sin6_addr);
1204 		ipif->ipif_v6subnet = ipif->ipif_v6pp_dst_addr;
1205 	}
1206 	if ((ta->ifta_flags & IFTUN_SRC)) {
1207 		ASSERT(!(ipif->ipif_flags & IPIF_UP));
1208 
1209 		/* Set the token if it isn't already set */
1210 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token)) {
1211 			if ((ta->ifta_saddr.ss_family == AF_INET)) {
1212 				sin = (sin_t *)&ta->ifta_saddr;
1213 				V4_PART_OF_V6(ill->ill_token) =
1214 				    sin->sin_addr.s_addr;
1215 			} else {
1216 				s6addr =
1217 				    &((sin6_t *)&ta->ifta_saddr)->sin6_addr;
1218 				ill->ill_token.s6_addr32[3] =
1219 				    s6addr->s6_addr32[3];
1220 				ill->ill_token.s6_addr32[2] =
1221 				    s6addr->s6_addr32[2];
1222 			}
1223 			ill->ill_token_length = IPV6_TOKEN_LEN;
1224 		}
1225 		/*
1226 		 * Attempt to set the link local address if it isn't set.
1227 		 */
1228 		if (IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr))
1229 			(void) ipif_setlinklocal(ipif);
1230 	}
1231 }
1232 
1233 /*
1234  * Is it not possible to set the link local address?
1235  * The address can be set if the token is set, and the token
1236  * isn't too long.
1237  * Return B_TRUE if the address can't be set, or B_FALSE if it can.
1238  */
1239 boolean_t
1240 ipif_cant_setlinklocal(ipif_t *ipif)
1241 {
1242 	ill_t *ill = ipif->ipif_ill;
1243 
1244 	if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token) ||
1245 	    ill->ill_token_length > IPV6_ABITS - IPV6_LL_PREFIXLEN)
1246 		return (B_TRUE);
1247 
1248 	return (B_FALSE);
1249 }
1250 
1251 /*
1252  * Generate a link-local address from the token.
1253  * Return zero if the address was set, or non-zero if it couldn't be set.
1254  */
1255 int
1256 ipif_setlinklocal(ipif_t *ipif)
1257 {
1258 	ill_t		*ill = ipif->ipif_ill;
1259 	in6_addr_t	ov6addr;
1260 
1261 	ASSERT(IAM_WRITER_ILL(ill));
1262 
1263 	if (ipif_cant_setlinklocal(ipif))
1264 		return (-1);
1265 
1266 	ov6addr = ipif->ipif_v6lcl_addr;
1267 	ipif_get_linklocal(&ipif->ipif_v6lcl_addr, &ill->ill_token);
1268 	sctp_update_ipif_addr(ipif, ov6addr);
1269 	(void) ip_plen_to_mask_v6(IPV6_LL_PREFIXLEN, &ipif->ipif_v6net_mask);
1270 	V6_MASK_COPY(ipif->ipif_v6lcl_addr, ipif->ipif_v6net_mask,
1271 	    ipif->ipif_v6subnet);
1272 
1273 	if (ipif->ipif_flags & IPIF_NOLOCAL) {
1274 		ipif->ipif_v6src_addr = ipv6_all_zeros;
1275 	} else {
1276 		ipif->ipif_v6src_addr = ipif->ipif_v6lcl_addr;
1277 	}
1278 	return (0);
1279 }
1280 
1281 /*
1282  * This function sets up the multicast mappings in NDP.
1283  * Unlike ARP, there are no mapping_mps here. We delete the
1284  * mapping nces and add a new one.
1285  *
1286  * Returns non-zero on error and 0 on success.
1287  */
1288 int
1289 ipif_ndp_setup_multicast(ipif_t *ipif, nce_t **ret_nce)
1290 {
1291 	ill_t		*ill = ipif->ipif_ill;
1292 	in6_addr_t	v6_mcast_addr = {(uint32_t)V6_MCAST, 0, 0, 0};
1293 	in6_addr_t	v6_mcast_mask = {(uint32_t)V6_MCAST, 0, 0, 0};
1294 	in6_addr_t	v6_extract_mask;
1295 	uchar_t		*phys_addr, *bphys_addr, *alloc_phys;
1296 	nce_t		*mnce = NULL;
1297 	int		err = 0;
1298 	phyint_t	*phyi = ill->ill_phyint;
1299 	uint32_t	hw_extract_start;
1300 	dl_unitdata_req_t *dlur;
1301 	ip_stack_t	*ipst = ill->ill_ipst;
1302 
1303 	if (ret_nce != NULL)
1304 		*ret_nce = NULL;
1305 	/*
1306 	 * Delete the mapping nce. Normally these should not exist
1307 	 * as a previous ipif_down -> ipif_ndp_down should have deleted
1308 	 * all the nces. But they can exist if ip_rput_dlpi_writer
1309 	 * calls this when PHYI_MULTI_BCAST is set.
1310 	 */
1311 	mnce = ndp_lookup_v6(ill, &v6_mcast_addr, B_FALSE);
1312 	if (mnce != NULL) {
1313 		ndp_delete(mnce);
1314 		NCE_REFRELE(mnce);
1315 		mnce = NULL;
1316 	}
1317 
1318 	/*
1319 	 * Get media specific v6 mapping information. Note that
1320 	 * nd_lla_len can be 0 for tunnels.
1321 	 */
1322 	alloc_phys = kmem_alloc(ill->ill_nd_lla_len, KM_NOSLEEP);
1323 	if ((alloc_phys == NULL) && (ill->ill_nd_lla_len != 0))
1324 		return (ENOMEM);
1325 	/*
1326 	 * Determine the broadcast address.
1327 	 */
1328 	dlur = (dl_unitdata_req_t *)ill->ill_bcast_mp->b_rptr;
1329 	if (ill->ill_sap_length < 0)
1330 		bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset;
1331 	else
1332 		bphys_addr = (uchar_t *)dlur +
1333 		    dlur->dl_dest_addr_offset + ill->ill_sap_length;
1334 
1335 	/*
1336 	 * Check PHYI_MULTI_BCAST and possible length of physical
1337 	 * address to determine if we use the mapping or the
1338 	 * broadcast address.
1339 	 */
1340 	if ((phyi->phyint_flags & PHYI_MULTI_BCAST) ||
1341 	    (!MEDIA_V6MINFO(ill->ill_media, ill->ill_nd_lla_len,
1342 	    bphys_addr, alloc_phys, &hw_extract_start,
1343 	    &v6_extract_mask))) {
1344 		if (ill->ill_phys_addr_length > IP_MAX_HW_LEN) {
1345 			kmem_free(alloc_phys, ill->ill_nd_lla_len);
1346 			return (E2BIG);
1347 		}
1348 		/* Use the link-layer broadcast address for MULTI_BCAST */
1349 		phys_addr = bphys_addr;
1350 		bzero(&v6_extract_mask, sizeof (v6_extract_mask));
1351 		hw_extract_start = ill->ill_nd_lla_len;
1352 	} else {
1353 		phys_addr = alloc_phys;
1354 	}
1355 	if ((ipif->ipif_flags & IPIF_BROADCAST) ||
1356 	    (ill->ill_flags & ILLF_MULTICAST) ||
1357 	    (phyi->phyint_flags & PHYI_MULTI_BCAST)) {
1358 		mutex_enter(&ipst->ips_ndp6->ndp_g_lock);
1359 		err = ndp_add_v6(ill,
1360 		    phys_addr,
1361 		    &v6_mcast_addr,	/* v6 address */
1362 		    &v6_mcast_mask,	/* v6 mask */
1363 		    &v6_extract_mask,
1364 		    hw_extract_start,
1365 		    NCE_F_MAPPING | NCE_F_PERMANENT | NCE_F_NONUD,
1366 		    ND_REACHABLE,
1367 		    &mnce);
1368 		mutex_exit(&ipst->ips_ndp6->ndp_g_lock);
1369 		if (err == 0) {
1370 			if (ret_nce != NULL) {
1371 				*ret_nce = mnce;
1372 			} else {
1373 				NCE_REFRELE(mnce);
1374 			}
1375 		}
1376 	}
1377 	kmem_free(alloc_phys, ill->ill_nd_lla_len);
1378 	return (err);
1379 }
1380 
1381 /*
1382  * Get the resolver set up for a new interface address.  (Always called
1383  * as writer.)
1384  */
1385 int
1386 ipif_ndp_up(ipif_t *ipif, const in6_addr_t *addr)
1387 {
1388 	ill_t		*ill = ipif->ipif_ill;
1389 	int		err = 0;
1390 	nce_t		*nce = NULL;
1391 	nce_t		*mnce = NULL;
1392 
1393 	ip1dbg(("ipif_ndp_up(%s:%u)\n",
1394 	    ipif->ipif_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(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 		    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