xref: /titanic_44/usr/src/uts/common/inet/ip/ip6_if.c (revision ee5416c9d7e449233197d5d20bc6b81e4ff091b2)
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 ipif.  (Always called as writer.)
1383  */
1384 int
1385 ipif_ndp_up(ipif_t *ipif)
1386 {
1387 	ill_t		*ill = ipif->ipif_ill;
1388 	int		err = 0;
1389 	nce_t		*nce = NULL;
1390 	nce_t		*mnce = NULL;
1391 
1392 	ip1dbg(("ipif_ndp_up(%s:%u)\n", ill->ill_name, ipif->ipif_id));
1393 
1394 	/*
1395 	 * ND not supported on XRESOLV interfaces. If ND support (multicast)
1396 	 * added later, take out this check.
1397 	 */
1398 	if ((ill->ill_flags & ILLF_XRESOLV) ||
1399 	    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr) ||
1400 	    (!(ill->ill_net_type & IRE_INTERFACE))) {
1401 		ipif->ipif_addr_ready = 1;
1402 		return (0);
1403 	}
1404 
1405 	/*
1406 	 * Need to setup multicast mapping only when the first
1407 	 * interface is coming UP.
1408 	 */
1409 	if (ill->ill_ipif_up_count == 0 &&
1410 	    (ill->ill_flags & ILLF_MULTICAST)) {
1411 		/*
1412 		 * We set the multicast before setting up the mapping for
1413 		 * local address because ipif_ndp_setup_multicast does
1414 		 * ndp_walk to delete nces which will delete the mapping
1415 		 * for local address also if we added the mapping for
1416 		 * local address first.
1417 		 */
1418 		err = ipif_ndp_setup_multicast(ipif, &mnce);
1419 		if (err != 0)
1420 			return (err);
1421 	}
1422 
1423 	if ((ipif->ipif_flags & (IPIF_UNNUMBERED|IPIF_NOLOCAL)) == 0) {
1424 		uint16_t	flags;
1425 		uchar_t	*hw_addr = NULL;
1426 
1427 		/* Permanent entries don't need NUD */
1428 		flags = NCE_F_PERMANENT | NCE_F_NONUD;
1429 		if (ill->ill_flags & ILLF_ROUTER)
1430 			flags |= NCE_F_ISROUTER;
1431 
1432 		if (ipif->ipif_flags & IPIF_ANYCAST)
1433 			flags |= NCE_F_ANYCAST;
1434 
1435 		if (ill->ill_net_type == IRE_IF_RESOLVER) {
1436 			hw_addr = ill->ill_nd_lla;
1437 
1438 			if (ill->ill_move_in_progress) {
1439 				/*
1440 				 * Addresses are failing over to this ill.
1441 				 * Don't wait for NUD to see this change.
1442 				 * Publish our new link-layer address.
1443 				 */
1444 				flags |= NCE_F_UNSOL_ADV;
1445 			}
1446 		}
1447 		err = ndp_lookup_then_add_v6(ill,
1448 		    hw_addr,
1449 		    &ipif->ipif_v6lcl_addr,
1450 		    &ipv6_all_ones,
1451 		    &ipv6_all_zeros,
1452 		    0,
1453 		    flags,
1454 		    ND_PROBE,	/* Causes Duplicate Address Detection to run */
1455 		    &nce);
1456 		switch (err) {
1457 		case 0:
1458 			ip1dbg(("ipif_ndp_up: NCE created for %s\n",
1459 			    ill->ill_name));
1460 			ipif->ipif_addr_ready = 1;
1461 			break;
1462 		case EINPROGRESS:
1463 			ip1dbg(("ipif_ndp_up: running DAD now for %s\n",
1464 			    ill->ill_name));
1465 			break;
1466 		case EEXIST:
1467 			NCE_REFRELE(nce);
1468 			ip1dbg(("ipif_ndp_up: NCE already exists for %s\n",
1469 			    ill->ill_name));
1470 			if (mnce != NULL) {
1471 				ndp_delete(mnce);
1472 				NCE_REFRELE(mnce);
1473 			}
1474 			return (err);
1475 		default:
1476 			ip1dbg(("ipif_ndp_up: NCE creation failed %s\n",
1477 			    ill->ill_name));
1478 			if (mnce != NULL) {
1479 				ndp_delete(mnce);
1480 				NCE_REFRELE(mnce);
1481 			}
1482 			return (err);
1483 		}
1484 	} else {
1485 		/* No local NCE for this entry */
1486 		ipif->ipif_addr_ready = 1;
1487 	}
1488 	if (nce != NULL)
1489 		NCE_REFRELE(nce);
1490 	if (mnce != NULL)
1491 		NCE_REFRELE(mnce);
1492 	return (0);
1493 }
1494 
1495 /* Remove all cache entries for this logical interface */
1496 void
1497 ipif_ndp_down(ipif_t *ipif)
1498 {
1499 	nce_t	*nce;
1500 
1501 	if (ipif->ipif_isv6) {
1502 		nce = ndp_lookup_v6(ipif->ipif_ill, &ipif->ipif_v6lcl_addr,
1503 		    B_FALSE);
1504 		if (nce != NULL) {
1505 			ndp_delete(nce);
1506 			NCE_REFRELE(nce);
1507 		}
1508 	}
1509 	/*
1510 	 * Remove mapping and all other nces dependent on this ill
1511 	 * when the last ipif is going away.
1512 	 */
1513 	if (ipif->ipif_ill->ill_ipif_up_count == 0) {
1514 		ndp_walk(ipif->ipif_ill, (pfi_t)ndp_delete_per_ill,
1515 		    (uchar_t *)ipif->ipif_ill, ipif->ipif_ill->ill_ipst);
1516 	}
1517 }
1518 
1519 /*
1520  * Used when an interface comes up to recreate any extra routes on this
1521  * interface.
1522  */
1523 static ire_t **
1524 ipif_recover_ire_v6(ipif_t *ipif)
1525 {
1526 	mblk_t	*mp;
1527 	ire_t   **ipif_saved_irep;
1528 	ire_t   **irep;
1529 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
1530 
1531 	ip1dbg(("ipif_recover_ire_v6(%s:%u)", ipif->ipif_ill->ill_name,
1532 	    ipif->ipif_id));
1533 
1534 	ASSERT(ipif->ipif_isv6);
1535 
1536 	mutex_enter(&ipif->ipif_saved_ire_lock);
1537 	ipif_saved_irep = (ire_t **)kmem_zalloc(sizeof (ire_t *) *
1538 	    ipif->ipif_saved_ire_cnt, KM_NOSLEEP);
1539 	if (ipif_saved_irep == NULL) {
1540 		mutex_exit(&ipif->ipif_saved_ire_lock);
1541 		return (NULL);
1542 	}
1543 
1544 	irep = ipif_saved_irep;
1545 
1546 	for (mp = ipif->ipif_saved_ire_mp; mp != NULL; mp = mp->b_cont) {
1547 		ire_t		*ire;
1548 		queue_t		*rfq;
1549 		queue_t		*stq;
1550 		ifrt_t		*ifrt;
1551 		in6_addr_t	*src_addr;
1552 		in6_addr_t	*gateway_addr;
1553 		char		buf[INET6_ADDRSTRLEN];
1554 		ushort_t	type;
1555 
1556 		/*
1557 		 * When the ire was initially created and then added in
1558 		 * ip_rt_add_v6(), it was created either using
1559 		 * ipif->ipif_net_type in the case of a traditional interface
1560 		 * route, or as one of the IRE_OFFSUBNET types (with the
1561 		 * exception of IRE_HOST type redirect ire which is created by
1562 		 * icmp_redirect_v6() and which we don't need to save or
1563 		 * recover).  In the case where ipif->ipif_net_type was
1564 		 * IRE_LOOPBACK, ip_rt_add_v6() will update the ire_type to
1565 		 * IRE_IF_NORESOLVER before calling ire_add_v6() to satisfy
1566 		 * software like GateD and Sun Cluster which creates routes
1567 		 * using the the loopback interface's address as a gateway.
1568 		 *
1569 		 * As ifrt->ifrt_type reflects the already updated ire_type,
1570 		 * ire_create_v6() will be called in the same way here as in
1571 		 * ip_rt_add_v6(), namely using ipif->ipif_net_type when the
1572 		 * route looks like a traditional interface route (where
1573 		 * ifrt->ifrt_type & IRE_INTERFACE is true) and otherwise
1574 		 * using the saved ifrt->ifrt_type.  This means that in
1575 		 * the case where ipif->ipif_net_type is IRE_LOOPBACK,
1576 		 * the ire created by ire_create_v6() will be an IRE_LOOPBACK,
1577 		 * it will then be turned into an IRE_IF_NORESOLVER and then
1578 		 * added by ire_add_v6().
1579 		 */
1580 		ifrt = (ifrt_t *)mp->b_rptr;
1581 		if (ifrt->ifrt_type & IRE_INTERFACE) {
1582 			rfq = NULL;
1583 			stq = (ipif->ipif_net_type == IRE_IF_RESOLVER)
1584 			    ? ipif->ipif_rq : ipif->ipif_wq;
1585 			src_addr = (ifrt->ifrt_flags & RTF_SETSRC)
1586 			    ? &ifrt->ifrt_v6src_addr
1587 			    : &ipif->ipif_v6src_addr;
1588 			gateway_addr = NULL;
1589 			type = ipif->ipif_net_type;
1590 		} else {
1591 			rfq = NULL;
1592 			stq = NULL;
1593 			src_addr = (ifrt->ifrt_flags & RTF_SETSRC)
1594 			    ? &ifrt->ifrt_v6src_addr : NULL;
1595 			gateway_addr = &ifrt->ifrt_v6gateway_addr;
1596 			type = ifrt->ifrt_type;
1597 		}
1598 
1599 		/*
1600 		 * Create a copy of the IRE with the saved address and netmask.
1601 		 */
1602 		ip1dbg(("ipif_recover_ire_v6: creating IRE %s (%d) for %s/%d\n",
1603 		    ip_nv_lookup(ire_nv_tbl, ifrt->ifrt_type), ifrt->ifrt_type,
1604 		    inet_ntop(AF_INET6, &ifrt->ifrt_v6addr, buf, sizeof (buf)),
1605 		    ip_mask_to_plen_v6(&ifrt->ifrt_v6mask)));
1606 		ire = ire_create_v6(
1607 		    &ifrt->ifrt_v6addr,
1608 		    &ifrt->ifrt_v6mask,
1609 		    src_addr,
1610 		    gateway_addr,
1611 		    &ifrt->ifrt_max_frag,
1612 		    NULL,
1613 		    rfq,
1614 		    stq,
1615 		    type,
1616 		    ipif,
1617 		    NULL,
1618 		    0,
1619 		    0,
1620 		    ifrt->ifrt_flags,
1621 		    &ifrt->ifrt_iulp_info,
1622 		    NULL,
1623 		    NULL,
1624 		    ipst);
1625 		if (ire == NULL) {
1626 			mutex_exit(&ipif->ipif_saved_ire_lock);
1627 			kmem_free(ipif_saved_irep,
1628 			    ipif->ipif_saved_ire_cnt * sizeof (ire_t *));
1629 			return (NULL);
1630 		}
1631 
1632 		/*
1633 		 * Some software (for example, GateD and Sun Cluster) attempts
1634 		 * to create (what amount to) IRE_PREFIX routes with the
1635 		 * loopback address as the gateway.  This is primarily done to
1636 		 * set up prefixes with the RTF_REJECT flag set (for example,
1637 		 * when generating aggregate routes.)
1638 		 *
1639 		 * If the IRE type (as defined by ipif->ipif_net_type) is
1640 		 * IRE_LOOPBACK, then we map the request into a
1641 		 * IRE_IF_NORESOLVER.
1642 		 */
1643 		if (ipif->ipif_net_type == IRE_LOOPBACK)
1644 			ire->ire_type = IRE_IF_NORESOLVER;
1645 		/*
1646 		 * ire held by ire_add, will be refreled' in ipif_up_done
1647 		 * towards the end
1648 		 */
1649 		(void) ire_add(&ire, NULL, NULL, NULL, B_FALSE);
1650 		*irep = ire;
1651 		irep++;
1652 		ip1dbg(("ipif_recover_ire_v6: added ire %p\n", (void *)ire));
1653 	}
1654 	mutex_exit(&ipif->ipif_saved_ire_lock);
1655 	return (ipif_saved_irep);
1656 }
1657 
1658 /*
1659  * Return the scope of the given IPv6 address.  If the address is an
1660  * IPv4 mapped IPv6 address, return the scope of the corresponding
1661  * IPv4 address.
1662  */
1663 in6addr_scope_t
1664 ip_addr_scope_v6(const in6_addr_t *addr)
1665 {
1666 	static in6_addr_t ipv6loopback = IN6ADDR_LOOPBACK_INIT;
1667 
1668 	if (IN6_IS_ADDR_V4MAPPED(addr)) {
1669 		in_addr_t v4addr_h = ntohl(V4_PART_OF_V6((*addr)));
1670 		if ((v4addr_h >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
1671 		    (v4addr_h & IN_AUTOCONF_MASK) == IN_AUTOCONF_NET)
1672 			return (IP6_SCOPE_LINKLOCAL);
1673 		if ((v4addr_h & IN_PRIVATE8_MASK) == IN_PRIVATE8_NET ||
1674 		    (v4addr_h & IN_PRIVATE12_MASK) == IN_PRIVATE12_NET ||
1675 		    (v4addr_h & IN_PRIVATE16_MASK) == IN_PRIVATE16_NET)
1676 			return (IP6_SCOPE_SITELOCAL);
1677 		return (IP6_SCOPE_GLOBAL);
1678 	}
1679 
1680 	if (IN6_IS_ADDR_MULTICAST(addr))
1681 		return (IN6_ADDR_MC_SCOPE(addr));
1682 
1683 	/* link-local and loopback addresses are of link-local scope */
1684 	if (IN6_IS_ADDR_LINKLOCAL(addr) ||
1685 	    IN6_ARE_ADDR_EQUAL(addr, &ipv6loopback))
1686 		return (IP6_SCOPE_LINKLOCAL);
1687 	if (IN6_IS_ADDR_SITELOCAL(addr))
1688 		return (IP6_SCOPE_SITELOCAL);
1689 	return (IP6_SCOPE_GLOBAL);
1690 }
1691 
1692 
1693 /*
1694  * Returns the length of the common prefix of a1 and a2, as per
1695  * CommonPrefixLen() defined in RFC 3484.
1696  */
1697 static int
1698 ip_common_prefix_v6(const in6_addr_t *a1, const in6_addr_t *a2)
1699 {
1700 	int i;
1701 	uint32_t a1val, a2val, mask;
1702 
1703 	for (i = 0; i < 4; i++) {
1704 		if ((a1val = a1->s6_addr32[i]) != (a2val = a2->s6_addr32[i])) {
1705 			a1val ^= a2val;
1706 			i *= 32;
1707 			mask = 0x80000000u;
1708 			while (!(a1val & mask)) {
1709 				mask >>= 1;
1710 				i++;
1711 			}
1712 			return (i);
1713 		}
1714 	}
1715 	return (IPV6_ABITS);
1716 }
1717 
1718 #define	IPIF_VALID_IPV6_SOURCE(ipif) \
1719 	(((ipif)->ipif_flags & IPIF_UP) && \
1720 	!((ipif)->ipif_flags & (IPIF_NOLOCAL|IPIF_ANYCAST)) && \
1721 	(ipif)->ipif_addr_ready)
1722 
1723 /* source address candidate */
1724 typedef struct candidate {
1725 	ipif_t		*cand_ipif;
1726 	/* The properties of this candidate */
1727 	boolean_t	cand_isdst;
1728 	boolean_t	cand_isdst_set;
1729 	in6addr_scope_t	cand_scope;
1730 	boolean_t	cand_scope_set;
1731 	boolean_t	cand_isdeprecated;
1732 	boolean_t	cand_isdeprecated_set;
1733 	boolean_t	cand_ispreferred;
1734 	boolean_t	cand_ispreferred_set;
1735 	boolean_t	cand_matchedinterface;
1736 	boolean_t	cand_matchedinterface_set;
1737 	boolean_t	cand_matchedlabel;
1738 	boolean_t	cand_matchedlabel_set;
1739 	boolean_t	cand_istmp;
1740 	boolean_t	cand_istmp_set;
1741 	int		cand_common_pref;
1742 	boolean_t	cand_common_pref_set;
1743 	boolean_t	cand_pref_eq;
1744 	boolean_t	cand_pref_eq_set;
1745 	int		cand_pref_len;
1746 	boolean_t	cand_pref_len_set;
1747 } cand_t;
1748 #define	cand_srcaddr	cand_ipif->ipif_v6lcl_addr
1749 #define	cand_mask	cand_ipif->ipif_v6net_mask
1750 #define	cand_flags	cand_ipif->ipif_flags
1751 #define	cand_ill	cand_ipif->ipif_ill
1752 #define	cand_zoneid	cand_ipif->ipif_zoneid
1753 
1754 /* information about the destination for source address selection */
1755 typedef struct dstinfo {
1756 	const in6_addr_t	*dst_addr;
1757 	ill_t			*dst_ill;
1758 	uint_t			dst_restrict_ill;
1759 	boolean_t		dst_prefer_src_tmp;
1760 	in6addr_scope_t		dst_scope;
1761 	char			*dst_label;
1762 } dstinfo_t;
1763 
1764 /*
1765  * The following functions are rules used to select a source address in
1766  * ipif_select_source_v6().  Each rule compares a current candidate (cc)
1767  * against the best candidate (bc).  Each rule has three possible outcomes;
1768  * the candidate is preferred over the best candidate (CAND_PREFER), the
1769  * candidate is not preferred over the best candidate (CAND_AVOID), or the
1770  * candidate is of equal value as the best candidate (CAND_TIE).
1771  *
1772  * These rules are part of a greater "Default Address Selection for IPv6"
1773  * sheme, which is standards based work coming out of the IETF ipv6 working
1774  * group.  The IETF document defines both IPv6 source address selection and
1775  * destination address ordering.  The rules defined here implement the IPv6
1776  * source address selection.  Destination address ordering is done by
1777  * libnsl, and uses a similar set of rules to implement the sorting.
1778  *
1779  * Most of the rules are defined by the RFC and are not typically altered.  The
1780  * last rule, number 8, has language that allows for local preferences.  In the
1781  * scheme below, this means that new Solaris rules should normally go between
1782  * rule_ifprefix and rule_prefix.
1783  */
1784 typedef enum {CAND_AVOID, CAND_TIE, CAND_PREFER} rule_res_t;
1785 typedef	rule_res_t (*rulef_t)(cand_t *, cand_t *, const dstinfo_t *,
1786     ip_stack_t *);
1787 
1788 /* Prefer an address if it is equal to the destination address. */
1789 /* ARGSUSED3 */
1790 static rule_res_t
1791 rule_isdst(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo, ip_stack_t *ipst)
1792 {
1793 	if (!bc->cand_isdst_set) {
1794 		bc->cand_isdst =
1795 		    IN6_ARE_ADDR_EQUAL(&bc->cand_srcaddr, dstinfo->dst_addr);
1796 		bc->cand_isdst_set = B_TRUE;
1797 	}
1798 
1799 	cc->cand_isdst =
1800 	    IN6_ARE_ADDR_EQUAL(&cc->cand_srcaddr, dstinfo->dst_addr);
1801 	cc->cand_isdst_set = B_TRUE;
1802 
1803 	if (cc->cand_isdst == bc->cand_isdst)
1804 		return (CAND_TIE);
1805 	else if (cc->cand_isdst)
1806 		return (CAND_PREFER);
1807 	else
1808 		return (CAND_AVOID);
1809 }
1810 
1811 /*
1812  * Prefer addresses that are of closest scope to the destination.  Always
1813  * prefer addresses that are of greater scope than the destination over
1814  * those that are of lesser scope than the destination.
1815  */
1816 /* ARGSUSED3 */
1817 static rule_res_t
1818 rule_scope(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo, ip_stack_t *ipst)
1819 {
1820 	if (!bc->cand_scope_set) {
1821 		bc->cand_scope = ip_addr_scope_v6(&bc->cand_srcaddr);
1822 		bc->cand_scope_set = B_TRUE;
1823 	}
1824 
1825 	cc->cand_scope = ip_addr_scope_v6(&cc->cand_srcaddr);
1826 	cc->cand_scope_set = B_TRUE;
1827 
1828 	if (cc->cand_scope < bc->cand_scope) {
1829 		if (cc->cand_scope < dstinfo->dst_scope)
1830 			return (CAND_AVOID);
1831 		else
1832 			return (CAND_PREFER);
1833 	} else if (bc->cand_scope < cc->cand_scope) {
1834 		if (bc->cand_scope < dstinfo->dst_scope)
1835 			return (CAND_PREFER);
1836 		else
1837 			return (CAND_AVOID);
1838 	} else {
1839 		return (CAND_TIE);
1840 	}
1841 }
1842 
1843 /*
1844  * Prefer non-deprecated source addresses.
1845  */
1846 /* ARGSUSED2 */
1847 static rule_res_t
1848 rule_deprecated(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo,
1849     ip_stack_t *ipst)
1850 {
1851 	if (!bc->cand_isdeprecated_set) {
1852 		bc->cand_isdeprecated =
1853 		    ((bc->cand_flags & IPIF_DEPRECATED) != 0);
1854 		bc->cand_isdeprecated_set = B_TRUE;
1855 	}
1856 
1857 	cc->cand_isdeprecated = ((cc->cand_flags & IPIF_DEPRECATED) != 0);
1858 	cc->cand_isdeprecated_set = B_TRUE;
1859 
1860 	if (bc->cand_isdeprecated == cc->cand_isdeprecated)
1861 		return (CAND_TIE);
1862 	else if (cc->cand_isdeprecated)
1863 		return (CAND_AVOID);
1864 	else
1865 		return (CAND_PREFER);
1866 }
1867 
1868 /*
1869  * Prefer source addresses that have the IPIF_PREFERRED flag set.  This
1870  * rule must be before rule_interface because the flag could be set on any
1871  * interface, not just the interface being used for outgoing packets (for
1872  * example, the IFF_PREFERRED could be set on an address assigned to the
1873  * loopback interface).
1874  */
1875 /* ARGSUSED2 */
1876 static rule_res_t
1877 rule_preferred(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo,
1878     ip_stack_t *ipst)
1879 {
1880 	if (!bc->cand_ispreferred_set) {
1881 		bc->cand_ispreferred = ((bc->cand_flags & IPIF_PREFERRED) != 0);
1882 		bc->cand_ispreferred_set = B_TRUE;
1883 	}
1884 
1885 	cc->cand_ispreferred = ((cc->cand_flags & IPIF_PREFERRED) != 0);
1886 	cc->cand_ispreferred_set = B_TRUE;
1887 
1888 	if (bc->cand_ispreferred == cc->cand_ispreferred)
1889 		return (CAND_TIE);
1890 	else if (cc->cand_ispreferred)
1891 		return (CAND_PREFER);
1892 	else
1893 		return (CAND_AVOID);
1894 }
1895 
1896 /*
1897  * Prefer source addresses that are assigned to the outgoing interface, or
1898  * to an interface that is in the same IPMP group as the outgoing
1899  * interface.
1900  */
1901 /* ARGSUSED3 */
1902 static rule_res_t
1903 rule_interface(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo,
1904     ip_stack_t *ipst)
1905 {
1906 	ill_t *dstill = dstinfo->dst_ill;
1907 
1908 	/*
1909 	 * If dstinfo->dst_restrict_ill is set, this rule is unnecessary
1910 	 * since we know all candidates will be on the same link.
1911 	 */
1912 	if (dstinfo->dst_restrict_ill)
1913 		return (CAND_TIE);
1914 
1915 	if (!bc->cand_matchedinterface_set) {
1916 		bc->cand_matchedinterface = (bc->cand_ill == dstill ||
1917 		    (dstill->ill_group != NULL &&
1918 		    dstill->ill_group == bc->cand_ill->ill_group));
1919 		bc->cand_matchedinterface_set = B_TRUE;
1920 	}
1921 
1922 	cc->cand_matchedinterface = (cc->cand_ill == dstill ||
1923 	    (dstill->ill_group != NULL &&
1924 	    dstill->ill_group == cc->cand_ill->ill_group));
1925 	cc->cand_matchedinterface_set = B_TRUE;
1926 
1927 	if (bc->cand_matchedinterface == cc->cand_matchedinterface)
1928 		return (CAND_TIE);
1929 	else if (cc->cand_matchedinterface)
1930 		return (CAND_PREFER);
1931 	else
1932 		return (CAND_AVOID);
1933 }
1934 
1935 /*
1936  * Prefer source addresses whose label matches the destination's label.
1937  */
1938 static rule_res_t
1939 rule_label(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo, ip_stack_t *ipst)
1940 {
1941 	char *label;
1942 
1943 	if (!bc->cand_matchedlabel_set) {
1944 		label = ip6_asp_lookup(&bc->cand_srcaddr, NULL, ipst);
1945 		bc->cand_matchedlabel =
1946 		    ip6_asp_labelcmp(label, dstinfo->dst_label);
1947 		bc->cand_matchedlabel_set = B_TRUE;
1948 	}
1949 
1950 	label = ip6_asp_lookup(&cc->cand_srcaddr, NULL, ipst);
1951 	cc->cand_matchedlabel = ip6_asp_labelcmp(label, dstinfo->dst_label);
1952 	cc->cand_matchedlabel_set = B_TRUE;
1953 
1954 	if (bc->cand_matchedlabel == cc->cand_matchedlabel)
1955 		return (CAND_TIE);
1956 	else if (cc->cand_matchedlabel)
1957 		return (CAND_PREFER);
1958 	else
1959 		return (CAND_AVOID);
1960 }
1961 
1962 /*
1963  * Prefer public addresses over temporary ones.  An application can reverse
1964  * the logic of this rule and prefer temporary addresses by using the
1965  * IPV6_SRC_PREFERENCES socket option.
1966  */
1967 /* ARGSUSED3 */
1968 static rule_res_t
1969 rule_temporary(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo,
1970     ip_stack_t *ipst)
1971 {
1972 	if (!bc->cand_istmp_set) {
1973 		bc->cand_istmp = ((bc->cand_flags & IPIF_TEMPORARY) != 0);
1974 		bc->cand_istmp_set = B_TRUE;
1975 	}
1976 
1977 	cc->cand_istmp = ((cc->cand_flags & IPIF_TEMPORARY) != 0);
1978 	cc->cand_istmp_set = B_TRUE;
1979 
1980 	if (bc->cand_istmp == cc->cand_istmp)
1981 		return (CAND_TIE);
1982 
1983 	if (dstinfo->dst_prefer_src_tmp && cc->cand_istmp)
1984 		return (CAND_PREFER);
1985 	else if (!dstinfo->dst_prefer_src_tmp && !cc->cand_istmp)
1986 		return (CAND_PREFER);
1987 	else
1988 		return (CAND_AVOID);
1989 }
1990 
1991 /*
1992  * Prefer source addresses with longer matching prefix with the destination
1993  * under the interface mask.  This gets us on the same subnet before applying
1994  * any Solaris-specific rules.
1995  */
1996 /* ARGSUSED3 */
1997 static rule_res_t
1998 rule_ifprefix(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo,
1999     ip_stack_t *ipst)
2000 {
2001 	if (!bc->cand_pref_eq_set) {
2002 		bc->cand_pref_eq = V6_MASK_EQ_2(bc->cand_srcaddr,
2003 		    bc->cand_mask, *dstinfo->dst_addr);
2004 		bc->cand_pref_eq_set = B_TRUE;
2005 	}
2006 
2007 	cc->cand_pref_eq = V6_MASK_EQ_2(cc->cand_srcaddr, cc->cand_mask,
2008 	    *dstinfo->dst_addr);
2009 	cc->cand_pref_eq_set = B_TRUE;
2010 
2011 	if (bc->cand_pref_eq) {
2012 		if (cc->cand_pref_eq) {
2013 			if (!bc->cand_pref_len_set) {
2014 				bc->cand_pref_len =
2015 				    ip_mask_to_plen_v6(&bc->cand_mask);
2016 				bc->cand_pref_len_set = B_TRUE;
2017 			}
2018 			cc->cand_pref_len = ip_mask_to_plen_v6(&cc->cand_mask);
2019 			cc->cand_pref_len_set = B_TRUE;
2020 			if (bc->cand_pref_len == cc->cand_pref_len)
2021 				return (CAND_TIE);
2022 			else if (bc->cand_pref_len > cc->cand_pref_len)
2023 				return (CAND_AVOID);
2024 			else
2025 				return (CAND_PREFER);
2026 		} else {
2027 			return (CAND_AVOID);
2028 		}
2029 	} else {
2030 		if (cc->cand_pref_eq)
2031 			return (CAND_PREFER);
2032 		else
2033 			return (CAND_TIE);
2034 	}
2035 }
2036 
2037 /*
2038  * Prefer to use zone-specific addresses when possible instead of all-zones
2039  * addresses.
2040  */
2041 /* ARGSUSED2 */
2042 static rule_res_t
2043 rule_zone_specific(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo,
2044     ip_stack_t *ipst)
2045 {
2046 	if ((bc->cand_zoneid == ALL_ZONES) ==
2047 	    (cc->cand_zoneid == ALL_ZONES))
2048 		return (CAND_TIE);
2049 	else if (cc->cand_zoneid == ALL_ZONES)
2050 		return (CAND_AVOID);
2051 	else
2052 		return (CAND_PREFER);
2053 }
2054 
2055 /*
2056  * Prefer to use DHCPv6 (first) and static addresses (second) when possible
2057  * instead of statelessly autoconfigured addresses.
2058  *
2059  * This is done after trying all other preferences (and before the final tie
2060  * breaker) so that, if all else is equal, we select addresses configured by
2061  * DHCPv6 over other addresses.  We presume that DHCPv6 addresses, unlike
2062  * stateless autoconfigured addresses, are deliberately configured by an
2063  * administrator, and thus are correctly set up in DNS and network packet
2064  * filters.
2065  */
2066 /* ARGSUSED2 */
2067 static rule_res_t
2068 rule_addr_type(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo,
2069     ip_stack_t *ipst)
2070 {
2071 #define	ATYPE(x)	\
2072 	((x) & IPIF_DHCPRUNNING) ? 1 : ((x) & IPIF_ADDRCONF) ? 3 : 2
2073 	int bcval = ATYPE(bc->cand_flags);
2074 	int ccval = ATYPE(cc->cand_flags);
2075 #undef ATYPE
2076 
2077 	if (bcval == ccval)
2078 		return (CAND_TIE);
2079 	else if (ccval < bcval)
2080 		return (CAND_PREFER);
2081 	else
2082 		return (CAND_AVOID);
2083 }
2084 
2085 /*
2086  * Prefer source addresses with longer matching prefix with the destination.
2087  * We do the longest matching prefix calculation by doing an xor of both
2088  * addresses with the destination, and pick the address with the longest string
2089  * of leading zeros, as per CommonPrefixLen() defined in RFC 3484.
2090  */
2091 /* ARGSUSED3 */
2092 static rule_res_t
2093 rule_prefix(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo, ip_stack_t *ipst)
2094 {
2095 	if (!bc->cand_common_pref_set) {
2096 		bc->cand_common_pref = ip_common_prefix_v6(&bc->cand_srcaddr,
2097 		    dstinfo->dst_addr);
2098 		bc->cand_common_pref_set = B_TRUE;
2099 	}
2100 
2101 	cc->cand_common_pref = ip_common_prefix_v6(&cc->cand_srcaddr,
2102 	    dstinfo->dst_addr);
2103 	cc->cand_common_pref_set = B_TRUE;
2104 
2105 	if (bc->cand_common_pref == cc->cand_common_pref)
2106 		return (CAND_TIE);
2107 	else if (bc->cand_common_pref > cc->cand_common_pref)
2108 		return (CAND_AVOID);
2109 	else
2110 		return (CAND_PREFER);
2111 }
2112 
2113 /*
2114  * Last rule: we must pick something, so just prefer the current best
2115  * candidate.
2116  */
2117 /* ARGSUSED */
2118 static rule_res_t
2119 rule_must_be_last(cand_t *bc, cand_t *cc, const dstinfo_t *dstinfo,
2120     ip_stack_t *ipst)
2121 {
2122 	return (CAND_AVOID);
2123 }
2124 
2125 /*
2126  * Determine the best source address given a destination address and a
2127  * destination ill.  If no suitable source address is found, it returns
2128  * NULL. If there is a usable address pointed to by the usesrc
2129  * (i.e ill_usesrc_ifindex != 0) then return that first since it is more
2130  * fine grained (i.e per interface)
2131  *
2132  * This implementation is based on the "Default Address Selection for IPv6"
2133  * specification produced by the IETF IPv6 working group.  It has been
2134  * implemented so that the list of addresses is only traversed once (the
2135  * specification's algorithm could traverse the list of addresses once for
2136  * every rule).
2137  *
2138  * The restrict_ill argument restricts the algorithm to chose a source
2139  * address that is assigned to the destination ill or an ill in the same
2140  * IPMP group as the destination ill.  This is used when the destination
2141  * address is a link-local or multicast address, and when
2142  * ipv6_strict_dst_multihoming is turned on.
2143  *
2144  * src_prefs is the caller's set of source address preferences.  If source
2145  * address selection is being called to determine the source address of a
2146  * connected socket (from ip_bind_connected_v6()), then the preferences are
2147  * taken from conn_src_preferences.  These preferences can be set on a
2148  * per-socket basis using the IPV6_SRC_PREFERENCES socket option.  The only
2149  * preference currently implemented is for rfc3041 temporary addresses.
2150  */
2151 ipif_t *
2152 ipif_select_source_v6(ill_t *dstill, const in6_addr_t *dst,
2153     uint_t restrict_ill, uint32_t src_prefs, zoneid_t zoneid)
2154 {
2155 	dstinfo_t	dstinfo;
2156 	char		dstr[INET6_ADDRSTRLEN];
2157 	char		sstr[INET6_ADDRSTRLEN];
2158 	ipif_t		*ipif;
2159 	ill_t		*ill, *usesrc_ill = NULL;
2160 	ill_walk_context_t	ctx;
2161 	cand_t		best_c;	/* The best candidate */
2162 	cand_t		curr_c;	/* The current candidate */
2163 	uint_t		index;
2164 	boolean_t	first_candidate = B_TRUE;
2165 	rule_res_t	rule_result;
2166 	tsol_tpc_t	*src_rhtp, *dst_rhtp;
2167 	ip_stack_t	*ipst = dstill->ill_ipst;
2168 
2169 	/*
2170 	 * The list of ordering rules.  They are applied in the order they
2171 	 * appear in the list.
2172 	 *
2173 	 * Solaris doesn't currently support Mobile IPv6, so there's no
2174 	 * rule_mipv6 corresponding to rule 4 in the specification.
2175 	 */
2176 	rulef_t	rules[] = {
2177 		rule_isdst,
2178 		rule_scope,
2179 		rule_deprecated,
2180 		rule_preferred,
2181 		rule_interface,
2182 		rule_label,
2183 		rule_temporary,
2184 		rule_ifprefix,			/* local rules after this */
2185 		rule_zone_specific,
2186 		rule_addr_type,
2187 		rule_prefix,			/* local rules before this */
2188 		rule_must_be_last,		/* must always be last */
2189 		NULL
2190 	};
2191 
2192 	ASSERT(dstill->ill_isv6);
2193 	ASSERT(!IN6_IS_ADDR_V4MAPPED(dst));
2194 
2195 	/*
2196 	 * Check if there is a usable src address pointed to by the
2197 	 * usesrc ifindex. This has higher precedence since it is
2198 	 * finer grained (i.e per interface) v/s being system wide.
2199 	 */
2200 	if (dstill->ill_usesrc_ifindex != 0) {
2201 		if ((usesrc_ill =
2202 		    ill_lookup_on_ifindex(dstill->ill_usesrc_ifindex, B_TRUE,
2203 		    NULL, NULL, NULL, NULL, ipst)) != NULL) {
2204 			dstinfo.dst_ill = usesrc_ill;
2205 		} else {
2206 			return (NULL);
2207 		}
2208 	} else {
2209 		dstinfo.dst_ill = dstill;
2210 	}
2211 
2212 	/*
2213 	 * If we're dealing with an unlabeled destination on a labeled system,
2214 	 * make sure that we ignore source addresses that are incompatible with
2215 	 * the destination's default label.  That destination's default label
2216 	 * must dominate the minimum label on the source address.
2217 	 *
2218 	 * (Note that this has to do with Trusted Solaris.  It's not related to
2219 	 * the labels described by ip6_asp_lookup.)
2220 	 */
2221 	dst_rhtp = NULL;
2222 	if (is_system_labeled()) {
2223 		dst_rhtp = find_tpc(dst, IPV6_VERSION, B_FALSE);
2224 		if (dst_rhtp == NULL)
2225 			return (NULL);
2226 		if (dst_rhtp->tpc_tp.host_type != UNLABELED) {
2227 			TPC_RELE(dst_rhtp);
2228 			dst_rhtp = NULL;
2229 		}
2230 	}
2231 
2232 	dstinfo.dst_addr = dst;
2233 	dstinfo.dst_scope = ip_addr_scope_v6(dst);
2234 	dstinfo.dst_label = ip6_asp_lookup(dst, NULL, ipst);
2235 	dstinfo.dst_prefer_src_tmp = ((src_prefs & IPV6_PREFER_SRC_TMP) != 0);
2236 
2237 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
2238 	/*
2239 	 * Section three of the I-D states that for multicast and
2240 	 * link-local destinations, the candidate set must be restricted to
2241 	 * an interface that is on the same link as the outgoing interface.
2242 	 * Also, when ipv6_strict_dst_multihoming is turned on, always
2243 	 * restrict the source address to the destination link as doing
2244 	 * otherwise will almost certainly cause problems.
2245 	 */
2246 	if (IN6_IS_ADDR_LINKLOCAL(dst) || IN6_IS_ADDR_MULTICAST(dst) ||
2247 	    ipst->ips_ipv6_strict_dst_multihoming || usesrc_ill != NULL) {
2248 		if (restrict_ill == RESTRICT_TO_NONE)
2249 			dstinfo.dst_restrict_ill = RESTRICT_TO_GROUP;
2250 		else
2251 			dstinfo.dst_restrict_ill = restrict_ill;
2252 	} else {
2253 		dstinfo.dst_restrict_ill = restrict_ill;
2254 	}
2255 
2256 	bzero(&best_c, sizeof (cand_t));
2257 
2258 	/*
2259 	 * Take a pass through the list of IPv6 interfaces to chose the
2260 	 * best possible source address.  If restrict_ill is true, we only
2261 	 * iterate through the ill's that are in the same IPMP group as the
2262 	 * destination's outgoing ill.  If restrict_ill is false, we walk
2263 	 * the entire list of IPv6 ill's.
2264 	 */
2265 	if (dstinfo.dst_restrict_ill != RESTRICT_TO_NONE) {
2266 		if (dstinfo.dst_ill->ill_group != NULL &&
2267 		    dstinfo.dst_restrict_ill == RESTRICT_TO_GROUP) {
2268 			ill = dstinfo.dst_ill->ill_group->illgrp_ill;
2269 		} else {
2270 			ill = dstinfo.dst_ill;
2271 		}
2272 	} else {
2273 		ill = ILL_START_WALK_V6(&ctx, ipst);
2274 	}
2275 
2276 	while (ill != NULL) {
2277 		ASSERT(ill->ill_isv6);
2278 
2279 		/*
2280 		 * Avoid FAILED/OFFLINE ills.
2281 		 * Global and site local addresses will failover and
2282 		 * will be available on the new ill.
2283 		 * But link local addresses don't move.
2284 		 */
2285 		if (dstinfo.dst_restrict_ill != RESTRICT_TO_ILL &&
2286 		    ill->ill_phyint->phyint_flags &
2287 		    (PHYI_OFFLINE | PHYI_FAILED))
2288 			goto next_ill;
2289 
2290 		for (ipif = ill->ill_ipif; ipif != NULL;
2291 		    ipif = ipif->ipif_next) {
2292 
2293 			if (!IPIF_VALID_IPV6_SOURCE(ipif))
2294 				continue;
2295 
2296 			if (zoneid != ALL_ZONES &&
2297 			    ipif->ipif_zoneid != zoneid &&
2298 			    ipif->ipif_zoneid != ALL_ZONES)
2299 				continue;
2300 
2301 			/*
2302 			 * Check compatibility of local address for
2303 			 * destination's default label if we're on a labeled
2304 			 * system.  Incompatible addresses can't be used at
2305 			 * all and must be skipped over.
2306 			 */
2307 			if (dst_rhtp != NULL) {
2308 				boolean_t incompat;
2309 
2310 				src_rhtp = find_tpc(&ipif->ipif_v6lcl_addr,
2311 				    IPV6_VERSION, B_FALSE);
2312 				if (src_rhtp == NULL)
2313 					continue;
2314 				incompat =
2315 				    src_rhtp->tpc_tp.host_type != SUN_CIPSO ||
2316 				    src_rhtp->tpc_tp.tp_doi !=
2317 				    dst_rhtp->tpc_tp.tp_doi ||
2318 				    (!_blinrange(&dst_rhtp->tpc_tp.tp_def_label,
2319 				    &src_rhtp->tpc_tp.tp_sl_range_cipso) &&
2320 				    !blinlset(&dst_rhtp->tpc_tp.tp_def_label,
2321 				    src_rhtp->tpc_tp.tp_sl_set_cipso));
2322 				TPC_RELE(src_rhtp);
2323 				if (incompat)
2324 					continue;
2325 			}
2326 
2327 			if (first_candidate) {
2328 				/*
2329 				 * This is first valid address in the list.
2330 				 * It is automatically the best candidate
2331 				 * so far.
2332 				 */
2333 				best_c.cand_ipif = ipif;
2334 				first_candidate = B_FALSE;
2335 				continue;
2336 			}
2337 
2338 			bzero(&curr_c, sizeof (cand_t));
2339 			curr_c.cand_ipif = ipif;
2340 
2341 			/*
2342 			 * Compare this current candidate (curr_c) with the
2343 			 * best candidate (best_c) by applying the
2344 			 * comparison rules in order until one breaks the
2345 			 * tie.
2346 			 */
2347 			for (index = 0; rules[index] != NULL; index++) {
2348 				/* Apply a comparison rule. */
2349 				rule_result =
2350 				    (rules[index])(&best_c, &curr_c, &dstinfo,
2351 				    ipst);
2352 				if (rule_result == CAND_AVOID) {
2353 					/*
2354 					 * The best candidate is still the
2355 					 * best candidate.  Forget about
2356 					 * this current candidate and go on
2357 					 * to the next one.
2358 					 */
2359 					break;
2360 				} else if (rule_result == CAND_PREFER) {
2361 					/*
2362 					 * This candidate is prefered.  It
2363 					 * becomes the best candidate so
2364 					 * far.  Go on to the next address.
2365 					 */
2366 					best_c = curr_c;
2367 					break;
2368 				}
2369 				/* We have a tie, apply the next rule. */
2370 			}
2371 
2372 			/*
2373 			 * The last rule must be a tie breaker rule and
2374 			 * must never produce a tie.  At this point, the
2375 			 * candidate should have either been rejected, or
2376 			 * have been prefered as the best candidate so far.
2377 			 */
2378 			ASSERT(rule_result != CAND_TIE);
2379 		}
2380 
2381 		/*
2382 		 * We may be walking the linked-list of ill's in an
2383 		 * IPMP group or traversing the IPv6 ill avl tree. If it is a
2384 		 * usesrc ILL then it can't be part of IPMP group and we
2385 		 * will exit the while loop.
2386 		 */
2387 next_ill:
2388 		if (dstinfo.dst_restrict_ill == RESTRICT_TO_ILL)
2389 			ill = NULL;
2390 		else if (dstinfo.dst_restrict_ill == RESTRICT_TO_GROUP)
2391 			ill = ill->ill_group_next;
2392 		else
2393 			ill = ill_next(&ctx, ill);
2394 	}
2395 
2396 	ipif = best_c.cand_ipif;
2397 	ip1dbg(("ipif_select_source_v6(%s, %s) -> %s\n",
2398 	    dstinfo.dst_ill->ill_name,
2399 	    inet_ntop(AF_INET6, dstinfo.dst_addr, dstr, sizeof (dstr)),
2400 	    (ipif == NULL ? "NULL" :
2401 	    inet_ntop(AF_INET6, &ipif->ipif_v6lcl_addr, sstr, sizeof (sstr)))));
2402 
2403 	if (usesrc_ill != NULL)
2404 		ill_refrele(usesrc_ill);
2405 
2406 	if (dst_rhtp != NULL)
2407 		TPC_RELE(dst_rhtp);
2408 
2409 	if (ipif == NULL) {
2410 		rw_exit(&ipst->ips_ill_g_lock);
2411 		return (NULL);
2412 	}
2413 
2414 	mutex_enter(&ipif->ipif_ill->ill_lock);
2415 	if (IPIF_CAN_LOOKUP(ipif)) {
2416 		ipif_refhold_locked(ipif);
2417 		mutex_exit(&ipif->ipif_ill->ill_lock);
2418 		rw_exit(&ipst->ips_ill_g_lock);
2419 		return (ipif);
2420 	}
2421 	mutex_exit(&ipif->ipif_ill->ill_lock);
2422 	rw_exit(&ipst->ips_ill_g_lock);
2423 	ip1dbg(("ipif_select_source_v6 cannot lookup ipif %p"
2424 	    " returning null \n", (void *)ipif));
2425 
2426 	return (NULL);
2427 }
2428 
2429 /*
2430  * If old_ipif is not NULL, see if ipif was derived from old
2431  * ipif and if so, recreate the interface route by re-doing
2432  * source address selection. This happens when ipif_down ->
2433  * ipif_update_other_ipifs calls us.
2434  *
2435  * If old_ipif is NULL, just redo the source address selection
2436  * if needed. This happens when illgrp_insert or ipif_up_done_v6
2437  * calls us.
2438  */
2439 void
2440 ipif_recreate_interface_routes_v6(ipif_t *old_ipif, ipif_t *ipif)
2441 {
2442 	ire_t *ire;
2443 	ire_t *ipif_ire;
2444 	queue_t *stq;
2445 	ill_t *ill;
2446 	ipif_t *nipif = NULL;
2447 	boolean_t nipif_refheld = B_FALSE;
2448 	boolean_t ip6_asp_table_held = B_FALSE;
2449 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
2450 
2451 	ill = ipif->ipif_ill;
2452 
2453 	if (!(ipif->ipif_flags &
2454 	    (IPIF_NOLOCAL|IPIF_ANYCAST|IPIF_DEPRECATED))) {
2455 		/*
2456 		 * Can't possibly have borrowed the source
2457 		 * from old_ipif.
2458 		 */
2459 		return;
2460 	}
2461 
2462 	/*
2463 	 * Is there any work to be done? No work if the address
2464 	 * is INADDR_ANY, loopback or NOLOCAL or ANYCAST (
2465 	 * ipif_select_source_v6() does not borrow addresses from
2466 	 * NOLOCAL and ANYCAST interfaces).
2467 	 */
2468 	if ((old_ipif != NULL) &&
2469 	    ((IN6_IS_ADDR_UNSPECIFIED(&old_ipif->ipif_v6lcl_addr)) ||
2470 	    (old_ipif->ipif_ill->ill_wq == NULL) ||
2471 	    (old_ipif->ipif_flags &
2472 	    (IPIF_NOLOCAL|IPIF_ANYCAST)))) {
2473 		return;
2474 	}
2475 
2476 	/*
2477 	 * Perform the same checks as when creating the
2478 	 * IRE_INTERFACE in ipif_up_done_v6.
2479 	 */
2480 	if (!(ipif->ipif_flags & IPIF_UP))
2481 		return;
2482 
2483 	if ((ipif->ipif_flags & IPIF_NOXMIT))
2484 		return;
2485 
2486 	if (IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6subnet) &&
2487 	    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6net_mask))
2488 		return;
2489 
2490 	/*
2491 	 * We know that ipif uses some other source for its
2492 	 * IRE_INTERFACE. Is it using the source of this
2493 	 * old_ipif?
2494 	 */
2495 	ipif_ire = ipif_to_ire_v6(ipif);
2496 	if (ipif_ire == NULL)
2497 		return;
2498 
2499 	if (old_ipif != NULL &&
2500 	    !IN6_ARE_ADDR_EQUAL(&old_ipif->ipif_v6lcl_addr,
2501 	    &ipif_ire->ire_src_addr_v6)) {
2502 		ire_refrele(ipif_ire);
2503 		return;
2504 	}
2505 
2506 	if (ip_debug > 2) {
2507 		/* ip1dbg */
2508 		pr_addr_dbg("ipif_recreate_interface_routes_v6: deleting IRE"
2509 		    " for src %s\n", AF_INET6, &ipif_ire->ire_src_addr_v6);
2510 	}
2511 
2512 	stq = ipif_ire->ire_stq;
2513 
2514 	/*
2515 	 * Can't use our source address. Select a different source address
2516 	 * for the IRE_INTERFACE.  We restrict interface route source
2517 	 * address selection to ipif's assigned to the same link as the
2518 	 * interface.
2519 	 */
2520 	if (ip6_asp_can_lookup(ipst)) {
2521 		ip6_asp_table_held = B_TRUE;
2522 		nipif = ipif_select_source_v6(ill, &ipif->ipif_v6subnet,
2523 		    RESTRICT_TO_GROUP, IPV6_PREFER_SRC_DEFAULT,
2524 		    ipif->ipif_zoneid);
2525 	}
2526 	if (nipif == NULL) {
2527 		/* Last resort - all ipif's have IPIF_NOLOCAL */
2528 		nipif = ipif;
2529 	} else {
2530 		nipif_refheld = B_TRUE;
2531 	}
2532 
2533 	ire = ire_create_v6(
2534 	    &ipif->ipif_v6subnet,	/* dest pref */
2535 	    &ipif->ipif_v6net_mask,	/* mask */
2536 	    &nipif->ipif_v6src_addr,	/* src addr */
2537 	    NULL,			/* no gateway */
2538 	    &ipif->ipif_mtu,		/* max frag */
2539 	    NULL,			/* no src nce */
2540 	    NULL,			/* no recv from queue */
2541 	    stq,			/* send-to queue */
2542 	    ill->ill_net_type,		/* IF_[NO]RESOLVER */
2543 	    ipif,
2544 	    NULL,
2545 	    0,
2546 	    0,
2547 	    0,
2548 	    &ire_uinfo_null,
2549 	    NULL,
2550 	    NULL,
2551 	    ipst);
2552 
2553 	if (ire != NULL) {
2554 		ire_t *ret_ire;
2555 		int   error;
2556 
2557 		/*
2558 		 * We don't need ipif_ire anymore. We need to delete
2559 		 * before we add so that ire_add does not detect
2560 		 * duplicates.
2561 		 */
2562 		ire_delete(ipif_ire);
2563 		ret_ire = ire;
2564 		error = ire_add(&ret_ire, NULL, NULL, NULL, B_FALSE);
2565 		ASSERT(error == 0);
2566 		ASSERT(ret_ire == ire);
2567 		if (ret_ire != NULL) {
2568 			/* Held in ire_add */
2569 			ire_refrele(ret_ire);
2570 		}
2571 	}
2572 	/*
2573 	 * Either we are falling through from above or could not
2574 	 * allocate a replacement.
2575 	 */
2576 	ire_refrele(ipif_ire);
2577 	if (ip6_asp_table_held)
2578 		ip6_asp_table_refrele(ipst);
2579 	if (nipif_refheld)
2580 		ipif_refrele(nipif);
2581 }
2582 
2583 /*
2584  * This old_ipif is going away.
2585  *
2586  * Determine if any other ipif's are using our address as
2587  * ipif_v6lcl_addr (due to those being IPIF_NOLOCAL, IPIF_ANYCAST, or
2588  * IPIF_DEPRECATED).
2589  * Find the IRE_INTERFACE for such ipif's and recreate them
2590  * to use an different source address following the rules in
2591  * ipif_up_done_v6.
2592  *
2593  * This function takes an illgrp as an argument so that illgrp_delete
2594  * can call this to update source address even after deleting the
2595  * old_ipif->ipif_ill from the ill group.
2596  */
2597 void
2598 ipif_update_other_ipifs_v6(ipif_t *old_ipif, ill_group_t *illgrp)
2599 {
2600 	ipif_t	*ipif;
2601 	ill_t	*ill;
2602 	char	buf[INET6_ADDRSTRLEN];
2603 
2604 	ASSERT(IAM_WRITER_IPIF(old_ipif));
2605 
2606 	ill = old_ipif->ipif_ill;
2607 
2608 	ip1dbg(("ipif_update_other_ipifs_v6(%s, %s)\n",
2609 	    ill->ill_name,
2610 	    inet_ntop(AF_INET6, &old_ipif->ipif_v6lcl_addr,
2611 	    buf, sizeof (buf))));
2612 
2613 	/*
2614 	 * If this part of a group, look at all ills as ipif_select_source
2615 	 * borrows a source address across all the ills in the group.
2616 	 */
2617 	if (illgrp != NULL)
2618 		ill = illgrp->illgrp_ill;
2619 
2620 	/* Don't need a lock since this is a writer */
2621 	for (; ill != NULL; ill = ill->ill_group_next) {
2622 		for (ipif = ill->ill_ipif; ipif != NULL;
2623 		    ipif = ipif->ipif_next) {
2624 
2625 			if (ipif == old_ipif)
2626 				continue;
2627 
2628 			ipif_recreate_interface_routes_v6(old_ipif, ipif);
2629 		}
2630 	}
2631 }
2632 
2633 /*
2634  * Perform an attach and bind to get phys addr plus info_req for
2635  * the physical device.
2636  * q and mp represents an ioctl which will be queued waiting for
2637  * completion of the DLPI message exchange.
2638  * MUST be called on an ill queue. Can not set conn_pending_ill for that
2639  * reason thus the DL_PHYS_ADDR_ACK code does not assume ill_pending_q.
2640  *
2641  * Returns EINPROGRESS when mp has been consumed by queueing it on
2642  * ill_pending_mp and the ioctl will complete in ip_rput.
2643  */
2644 int
2645 ill_dl_phys(ill_t *ill, ipif_t *ipif, mblk_t *mp, queue_t *q)
2646 {
2647 	mblk_t	*v6token_mp = NULL;
2648 	mblk_t	*v6lla_mp = NULL;
2649 	mblk_t	*phys_mp = NULL;
2650 	mblk_t	*info_mp = NULL;
2651 	mblk_t	*attach_mp = NULL;
2652 	mblk_t	*bind_mp = NULL;
2653 	mblk_t	*unbind_mp = NULL;
2654 	mblk_t	*notify_mp = NULL;
2655 
2656 	ip1dbg(("ill_dl_phys(%s:%u)\n", ill->ill_name, ipif->ipif_id));
2657 	ASSERT(ill->ill_dlpi_style_set);
2658 	ASSERT(WR(q)->q_next != NULL);
2659 
2660 	if (ill->ill_isv6) {
2661 		v6token_mp = ip_dlpi_alloc(sizeof (dl_phys_addr_req_t) +
2662 		    sizeof (t_scalar_t), DL_PHYS_ADDR_REQ);
2663 		if (v6token_mp == NULL)
2664 			goto bad;
2665 		((dl_phys_addr_req_t *)v6token_mp->b_rptr)->dl_addr_type =
2666 		    DL_IPV6_TOKEN;
2667 
2668 		v6lla_mp = ip_dlpi_alloc(sizeof (dl_phys_addr_req_t) +
2669 		    sizeof (t_scalar_t), DL_PHYS_ADDR_REQ);
2670 		if (v6lla_mp == NULL)
2671 			goto bad;
2672 		((dl_phys_addr_req_t *)v6lla_mp->b_rptr)->dl_addr_type =
2673 		    DL_IPV6_LINK_LAYER_ADDR;
2674 	}
2675 
2676 	/*
2677 	 * Allocate a DL_NOTIFY_REQ and set the notifications we want.
2678 	 */
2679 	notify_mp = ip_dlpi_alloc(sizeof (dl_notify_req_t) + sizeof (long),
2680 	    DL_NOTIFY_REQ);
2681 	if (notify_mp == NULL)
2682 		goto bad;
2683 	((dl_notify_req_t *)notify_mp->b_rptr)->dl_notifications =
2684 	    (DL_NOTE_PHYS_ADDR | DL_NOTE_SDU_SIZE | DL_NOTE_FASTPATH_FLUSH |
2685 	    DL_NOTE_LINK_UP | DL_NOTE_LINK_DOWN | DL_NOTE_CAPAB_RENEG);
2686 
2687 	phys_mp = ip_dlpi_alloc(sizeof (dl_phys_addr_req_t) +
2688 	    sizeof (t_scalar_t), DL_PHYS_ADDR_REQ);
2689 	if (phys_mp == NULL)
2690 		goto bad;
2691 	((dl_phys_addr_req_t *)phys_mp->b_rptr)->dl_addr_type =
2692 	    DL_CURR_PHYS_ADDR;
2693 
2694 	info_mp = ip_dlpi_alloc(
2695 	    sizeof (dl_info_req_t) + sizeof (dl_info_ack_t),
2696 	    DL_INFO_REQ);
2697 	if (info_mp == NULL)
2698 		goto bad;
2699 
2700 	bind_mp = ip_dlpi_alloc(sizeof (dl_bind_req_t) + sizeof (long),
2701 	    DL_BIND_REQ);
2702 	if (bind_mp == NULL)
2703 		goto bad;
2704 	((dl_bind_req_t *)bind_mp->b_rptr)->dl_sap = ill->ill_sap;
2705 	((dl_bind_req_t *)bind_mp->b_rptr)->dl_service_mode = DL_CLDLS;
2706 
2707 	unbind_mp = ip_dlpi_alloc(sizeof (dl_unbind_req_t), DL_UNBIND_REQ);
2708 	if (unbind_mp == NULL)
2709 		goto bad;
2710 
2711 	/* If we need to attach, pre-alloc and initialize the mblk */
2712 	if (ill->ill_needs_attach) {
2713 		attach_mp = ip_dlpi_alloc(sizeof (dl_attach_req_t),
2714 		    DL_ATTACH_REQ);
2715 		if (attach_mp == NULL)
2716 			goto bad;
2717 		((dl_attach_req_t *)attach_mp->b_rptr)->dl_ppa = ill->ill_ppa;
2718 	}
2719 
2720 	/*
2721 	 * Here we are going to delay the ioctl ack until after
2722 	 * ACKs from DL_PHYS_ADDR_REQ. So need to save the
2723 	 * original ioctl message before sending the requests
2724 	 */
2725 	mutex_enter(&ill->ill_lock);
2726 	/* ipsq_pending_mp_add won't fail since we pass in a NULL connp */
2727 	(void) ipsq_pending_mp_add(NULL, ipif, ill->ill_wq, mp, 0);
2728 	/*
2729 	 * Set ill_phys_addr_pend to zero. It will be set to the addr_type of
2730 	 * the DL_PHYS_ADDR_REQ in ill_dlpi_send() and ill_dlpi_done(). It will
2731 	 * be used to track which DL_PHYS_ADDR_REQ is being ACK'd/NAK'd.
2732 	 */
2733 	ill->ill_phys_addr_pend = 0;
2734 	mutex_exit(&ill->ill_lock);
2735 
2736 	if (attach_mp != NULL) {
2737 		ip1dbg(("ill_dl_phys: attach\n"));
2738 		ill_dlpi_send(ill, attach_mp);
2739 	}
2740 	ill_dlpi_send(ill, bind_mp);
2741 	ill_dlpi_send(ill, info_mp);
2742 	if (ill->ill_isv6) {
2743 		ill_dlpi_send(ill, v6token_mp);
2744 		ill_dlpi_send(ill, v6lla_mp);
2745 	}
2746 	ill_dlpi_send(ill, phys_mp);
2747 	ill_dlpi_send(ill, notify_mp);
2748 	ill_dlpi_send(ill, unbind_mp);
2749 
2750 	/*
2751 	 * This operation will complete in ip_rput_dlpi_writer with either
2752 	 * a DL_PHYS_ADDR_ACK or DL_ERROR_ACK.
2753 	 */
2754 	return (EINPROGRESS);
2755 bad:
2756 	freemsg(v6token_mp);
2757 	freemsg(v6lla_mp);
2758 	freemsg(phys_mp);
2759 	freemsg(info_mp);
2760 	freemsg(attach_mp);
2761 	freemsg(bind_mp);
2762 	freemsg(unbind_mp);
2763 	freemsg(notify_mp);
2764 	return (ENOMEM);
2765 }
2766 
2767 uint_t ip_loopback_mtu_v6plus = IP_LOOPBACK_MTU + IPV6_HDR_LEN + 20;
2768 
2769 /*
2770  * DLPI is up.
2771  * Create all the IREs associated with an interface bring up multicast.
2772  * Set the interface flag and finish other initialization
2773  * that potentially had to be differed to after DL_BIND_ACK.
2774  */
2775 int
2776 ipif_up_done_v6(ipif_t *ipif)
2777 {
2778 	ire_t	*ire_array[20];
2779 	ire_t	**irep = ire_array;
2780 	ire_t	**irep1;
2781 	ill_t	*ill = ipif->ipif_ill;
2782 	queue_t	*stq;
2783 	in6_addr_t	v6addr;
2784 	in6_addr_t	route_mask;
2785 	ipif_t	 *src_ipif = NULL;
2786 	ipif_t   *tmp_ipif;
2787 	boolean_t	flush_ire_cache = B_TRUE;
2788 	int	err;
2789 	char	buf[INET6_ADDRSTRLEN];
2790 	phyint_t *phyi;
2791 	ire_t	**ipif_saved_irep = NULL;
2792 	int ipif_saved_ire_cnt;
2793 	int cnt;
2794 	boolean_t src_ipif_held = B_FALSE;
2795 	boolean_t ire_added = B_FALSE;
2796 	boolean_t loopback = B_FALSE;
2797 	boolean_t ip6_asp_table_held = B_FALSE;
2798 	ip_stack_t	*ipst = ill->ill_ipst;
2799 
2800 	ip1dbg(("ipif_up_done_v6(%s:%u)\n",
2801 	    ipif->ipif_ill->ill_name, ipif->ipif_id));
2802 
2803 	/* Check if this is a loopback interface */
2804 	if (ipif->ipif_ill->ill_wq == NULL)
2805 		loopback = B_TRUE;
2806 
2807 	ASSERT(ipif->ipif_isv6);
2808 	ASSERT(!MUTEX_HELD(&ipif->ipif_ill->ill_lock));
2809 
2810 	/*
2811 	 * If all other interfaces for this ill are down or DEPRECATED,
2812 	 * or otherwise unsuitable for source address selection, remove
2813 	 * any IRE_CACHE entries for this ill to make sure source
2814 	 * address selection gets to take this new ipif into account.
2815 	 * No need to hold ill_lock while traversing the ipif list since
2816 	 * we are writer
2817 	 */
2818 	for (tmp_ipif = ill->ill_ipif; tmp_ipif;
2819 	    tmp_ipif = tmp_ipif->ipif_next) {
2820 		if (((tmp_ipif->ipif_flags &
2821 		    (IPIF_NOXMIT|IPIF_ANYCAST|IPIF_NOLOCAL|IPIF_DEPRECATED)) ||
2822 		    !(tmp_ipif->ipif_flags & IPIF_UP)) ||
2823 		    (tmp_ipif == ipif))
2824 			continue;
2825 		/* first useable pre-existing interface */
2826 		flush_ire_cache = B_FALSE;
2827 		break;
2828 	}
2829 	if (flush_ire_cache)
2830 		ire_walk_ill_v6(MATCH_IRE_ILL_GROUP | MATCH_IRE_TYPE,
2831 		    IRE_CACHE, ill_ipif_cache_delete, (char *)ill, ill);
2832 
2833 	/*
2834 	 * Figure out which way the send-to queue should go.  Only
2835 	 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER should show up here.
2836 	 */
2837 	switch (ill->ill_net_type) {
2838 	case IRE_IF_RESOLVER:
2839 		stq = ill->ill_rq;
2840 		break;
2841 	case IRE_IF_NORESOLVER:
2842 	case IRE_LOOPBACK:
2843 		stq = ill->ill_wq;
2844 		break;
2845 	default:
2846 		return (EINVAL);
2847 	}
2848 
2849 	if (IS_LOOPBACK(ill)) {
2850 		/*
2851 		 * lo0:1 and subsequent ipifs were marked IRE_LOCAL in
2852 		 * ipif_lookup_on_name(), but in the case of zones we can have
2853 		 * several loopback addresses on lo0. So all the interfaces with
2854 		 * loopback addresses need to be marked IRE_LOOPBACK.
2855 		 */
2856 		if (IN6_ARE_ADDR_EQUAL(&ipif->ipif_v6lcl_addr, &ipv6_loopback))
2857 			ipif->ipif_ire_type = IRE_LOOPBACK;
2858 		else
2859 			ipif->ipif_ire_type = IRE_LOCAL;
2860 	}
2861 
2862 	if (ipif->ipif_flags & (IPIF_NOLOCAL|IPIF_ANYCAST|IPIF_DEPRECATED)) {
2863 		/*
2864 		 * Can't use our source address. Select a different
2865 		 * source address for the IRE_INTERFACE and IRE_LOCAL
2866 		 */
2867 		if (ip6_asp_can_lookup(ipst)) {
2868 			ip6_asp_table_held = B_TRUE;
2869 			src_ipif = ipif_select_source_v6(ipif->ipif_ill,
2870 			    &ipif->ipif_v6subnet, RESTRICT_TO_NONE,
2871 			    IPV6_PREFER_SRC_DEFAULT, ipif->ipif_zoneid);
2872 		}
2873 		if (src_ipif == NULL)
2874 			src_ipif = ipif;	/* Last resort */
2875 		else
2876 			src_ipif_held = B_TRUE;
2877 	} else {
2878 		src_ipif = ipif;
2879 	}
2880 
2881 	if (!IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr) &&
2882 	    !(ipif->ipif_flags & IPIF_NOLOCAL)) {
2883 
2884 		/*
2885 		 * If we're on a labeled system then make sure that zone-
2886 		 * private addresses have proper remote host database entries.
2887 		 */
2888 		if (is_system_labeled() &&
2889 		    ipif->ipif_ire_type != IRE_LOOPBACK) {
2890 			if (ip6opt_ls == 0) {
2891 				cmn_err(CE_WARN, "IPv6 not enabled "
2892 				    "via /etc/system");
2893 				return (EINVAL);
2894 			}
2895 			if (!tsol_check_interface_address(ipif))
2896 				return (EINVAL);
2897 		}
2898 
2899 		/* Register the source address for __sin6_src_id */
2900 		err = ip_srcid_insert(&ipif->ipif_v6lcl_addr,
2901 		    ipif->ipif_zoneid, ipst);
2902 		if (err != 0) {
2903 			ip0dbg(("ipif_up_done_v6: srcid_insert %d\n", err));
2904 			if (src_ipif_held)
2905 				ipif_refrele(src_ipif);
2906 			if (ip6_asp_table_held)
2907 				ip6_asp_table_refrele(ipst);
2908 			return (err);
2909 		}
2910 		/*
2911 		 * If the interface address is set, create the LOCAL
2912 		 * or LOOPBACK IRE.
2913 		 */
2914 		ip1dbg(("ipif_up_done_v6: creating IRE %d for %s\n",
2915 		    ipif->ipif_ire_type,
2916 		    inet_ntop(AF_INET6, &ipif->ipif_v6lcl_addr,
2917 		    buf, sizeof (buf))));
2918 
2919 		*irep++ = ire_create_v6(
2920 		    &ipif->ipif_v6lcl_addr,		/* dest address */
2921 		    &ipv6_all_ones,			/* mask */
2922 		    &src_ipif->ipif_v6src_addr,		/* source address */
2923 		    NULL,				/* no gateway */
2924 		    &ip_loopback_mtu_v6plus,		/* max frag size */
2925 		    NULL,
2926 		    ipif->ipif_rq,			/* recv-from queue */
2927 		    NULL,				/* no send-to queue */
2928 		    ipif->ipif_ire_type,		/* LOCAL or LOOPBACK */
2929 		    ipif,				/* interface */
2930 		    NULL,
2931 		    0,
2932 		    0,
2933 		    (ipif->ipif_flags & IPIF_PRIVATE) ? RTF_PRIVATE : 0,
2934 		    &ire_uinfo_null,
2935 		    NULL,
2936 		    NULL,
2937 		    ipst);
2938 	}
2939 
2940 	/*
2941 	 * Set up the IRE_IF_RESOLVER or IRE_IF_NORESOLVER, as appropriate.
2942 	 * Note that atun interfaces have an all-zero ipif_v6subnet.
2943 	 * Thus we allow a zero subnet as long as the mask is non-zero.
2944 	 */
2945 	if (stq != NULL && !(ipif->ipif_flags & IPIF_NOXMIT) &&
2946 	    !(IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6subnet) &&
2947 	    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6net_mask))) {
2948 		/* ipif_v6subnet is ipif_v6pp_dst_addr for pt-pt */
2949 		v6addr = ipif->ipif_v6subnet;
2950 
2951 		if (ipif->ipif_flags & IPIF_POINTOPOINT) {
2952 			route_mask = ipv6_all_ones;
2953 		} else {
2954 			route_mask = ipif->ipif_v6net_mask;
2955 		}
2956 
2957 		ip1dbg(("ipif_up_done_v6: creating if IRE %d for %s\n",
2958 		    ill->ill_net_type,
2959 		    inet_ntop(AF_INET6, &v6addr, buf, sizeof (buf))));
2960 
2961 		*irep++ = ire_create_v6(
2962 		    &v6addr,			/* dest pref */
2963 		    &route_mask,		/* mask */
2964 		    &src_ipif->ipif_v6src_addr,	/* src addr */
2965 		    NULL,			/* no gateway */
2966 		    &ipif->ipif_mtu,		/* max frag */
2967 		    NULL,			/* no src nce */
2968 		    NULL,			/* no recv from queue */
2969 		    stq,			/* send-to queue */
2970 		    ill->ill_net_type,		/* IF_[NO]RESOLVER */
2971 		    ipif,
2972 		    NULL,
2973 		    0,
2974 		    0,
2975 		    (ipif->ipif_flags & IPIF_PRIVATE) ? RTF_PRIVATE : 0,
2976 		    &ire_uinfo_null,
2977 		    NULL,
2978 		    NULL,
2979 		    ipst);
2980 	}
2981 
2982 	/*
2983 	 * Setup 2002::/16 route, if this interface is a 6to4 tunnel
2984 	 */
2985 	if (IN6_IS_ADDR_6TO4(&ipif->ipif_v6lcl_addr) &&
2986 	    (ill->ill_is_6to4tun)) {
2987 		/*
2988 		 * Destination address is 2002::/16
2989 		 */
2990 #ifdef	_BIG_ENDIAN
2991 		const in6_addr_t prefix_addr = { 0x20020000U, 0, 0, 0 };
2992 		const in6_addr_t prefix_mask = { 0xffff0000U, 0, 0, 0 };
2993 #else
2994 		const in6_addr_t prefix_addr = { 0x00000220U, 0, 0, 0 };
2995 		const in6_addr_t prefix_mask = { 0x0000ffffU, 0, 0, 0 };
2996 #endif /* _BIG_ENDIAN */
2997 		char	buf2[INET6_ADDRSTRLEN];
2998 		ire_t *isdup;
2999 		in6_addr_t *first_addr = &ill->ill_ipif->ipif_v6lcl_addr;
3000 
3001 		/*
3002 		 * check to see if this route has already been added for
3003 		 * this tunnel interface.
3004 		 */
3005 		isdup = ire_ftable_lookup_v6(first_addr, &prefix_mask, 0,
3006 		    IRE_IF_NORESOLVER, ill->ill_ipif, NULL, ALL_ZONES, 0, NULL,
3007 		    (MATCH_IRE_SRC | MATCH_IRE_MASK), ipst);
3008 
3009 		if (isdup == NULL) {
3010 			ip1dbg(("ipif_up_done_v6: creating if IRE %d for %s",
3011 			    IRE_IF_NORESOLVER, inet_ntop(AF_INET6, &v6addr,
3012 			    buf2, sizeof (buf2))));
3013 
3014 			*irep++ = ire_create_v6(
3015 			    &prefix_addr,		/* 2002:: */
3016 			    &prefix_mask,		/* ffff:: */
3017 			    &ipif->ipif_v6lcl_addr, 	/* src addr */
3018 			    NULL, 			/* gateway */
3019 			    &ipif->ipif_mtu, 		/* max_frag */
3020 			    NULL, 			/* no src nce */
3021 			    NULL, 			/* no rfq */
3022 			    ill->ill_wq, 		/* stq */
3023 			    IRE_IF_NORESOLVER,		/* type */
3024 			    ipif,			/* interface */
3025 			    NULL,			/* v6cmask */
3026 			    0,
3027 			    0,
3028 			    RTF_UP,
3029 			    &ire_uinfo_null,
3030 			    NULL,
3031 			    NULL,
3032 			    ipst);
3033 		} else {
3034 			ire_refrele(isdup);
3035 		}
3036 	}
3037 
3038 	/* If an earlier ire_create failed, get out now */
3039 	for (irep1 = irep; irep1 > ire_array; ) {
3040 		irep1--;
3041 		if (*irep1 == NULL) {
3042 			ip1dbg(("ipif_up_done_v6: NULL ire found in"
3043 			    " ire_array\n"));
3044 			err = ENOMEM;
3045 			goto bad;
3046 		}
3047 	}
3048 
3049 	ASSERT(!MUTEX_HELD(&ipif->ipif_ill->ill_lock));
3050 
3051 	/*
3052 	 * Need to atomically check for ip_addr_availablity_check
3053 	 * now under ill_g_lock, and if it fails got bad, and remove
3054 	 * from group also
3055 	 */
3056 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
3057 	mutex_enter(&ipst->ips_ip_addr_avail_lock);
3058 	ill->ill_ipif_up_count++;
3059 	ipif->ipif_flags |= IPIF_UP;
3060 	err = ip_addr_availability_check(ipif);
3061 	mutex_exit(&ipst->ips_ip_addr_avail_lock);
3062 	rw_exit(&ipst->ips_ill_g_lock);
3063 
3064 	if (err != 0) {
3065 		/*
3066 		 * Our address may already be up on the same ill. In this case,
3067 		 * the external resolver entry for our ipif replaced the one for
3068 		 * the other ipif. So we don't want to delete it (otherwise the
3069 		 * other ipif would be unable to send packets).
3070 		 * ip_addr_availability_check() identifies this case for us and
3071 		 * returns EADDRINUSE; we need to turn it into EADDRNOTAVAIL
3072 		 * which is the expected error code.
3073 		 */
3074 		if (err == EADDRINUSE) {
3075 			if (ipif->ipif_ill->ill_flags & ILLF_XRESOLV) {
3076 				freemsg(ipif->ipif_arp_del_mp);
3077 				ipif->ipif_arp_del_mp = NULL;
3078 			}
3079 			err = EADDRNOTAVAIL;
3080 		}
3081 		ill->ill_ipif_up_count--;
3082 		ipif->ipif_flags &= ~IPIF_UP;
3083 		goto bad;
3084 	}
3085 
3086 	/*
3087 	 * Add in all newly created IREs. We want to add before
3088 	 * we call ifgrp_insert which wants to know whether
3089 	 * IRE_IF_RESOLVER exists or not.
3090 	 *
3091 	 * NOTE : We refrele the ire though we may branch to "bad"
3092 	 *	  later on where we do ire_delete. This is okay
3093 	 *	  because nobody can delete it as we are running
3094 	 *	  exclusively.
3095 	 */
3096 	for (irep1 = irep; irep1 > ire_array; ) {
3097 		irep1--;
3098 		/* Shouldn't be adding any bcast ire's */
3099 		ASSERT((*irep1)->ire_type != IRE_BROADCAST);
3100 		ASSERT(!MUTEX_HELD(&ipif->ipif_ill->ill_lock));
3101 		/*
3102 		 * refheld by ire_add. refele towards the end of the func
3103 		 */
3104 		(void) ire_add(irep1, NULL, NULL, NULL, B_FALSE);
3105 	}
3106 	if (ip6_asp_table_held) {
3107 		ip6_asp_table_refrele(ipst);
3108 		ip6_asp_table_held = B_FALSE;
3109 	}
3110 	ire_added = B_TRUE;
3111 
3112 	/*
3113 	 * Form groups if possible.
3114 	 *
3115 	 * If we are supposed to be in a ill_group with a name, insert it
3116 	 * now as we know that at least one ipif is UP. Otherwise form
3117 	 * nameless groups.
3118 	 *
3119 	 * If ip_enable_group_ifs is set and ipif address is not ::0, insert
3120 	 * this ipif into the appropriate interface group, or create a
3121 	 * new one. If this is already in a nameless group, we try to form
3122 	 * a bigger group looking at other ills potentially sharing this
3123 	 * ipif's prefix.
3124 	 */
3125 	phyi = ill->ill_phyint;
3126 	if (phyi->phyint_groupname_len != 0) {
3127 		ASSERT(phyi->phyint_groupname != NULL);
3128 		if (ill->ill_ipif_up_count == 1) {
3129 			ASSERT(ill->ill_group == NULL);
3130 			err = illgrp_insert(&ipst->ips_illgrp_head_v6, ill,
3131 			    phyi->phyint_groupname, NULL, B_TRUE);
3132 			if (err != 0) {
3133 				ip1dbg(("ipif_up_done_v6: illgrp allocation "
3134 				    "failed, error %d\n", err));
3135 				goto bad;
3136 			}
3137 		}
3138 		ASSERT(ill->ill_group != NULL);
3139 	}
3140 
3141 	/* Recover any additional IRE_IF_[NO]RESOLVER entries for this ipif */
3142 	ipif_saved_ire_cnt = ipif->ipif_saved_ire_cnt;
3143 	ipif_saved_irep = ipif_recover_ire_v6(ipif);
3144 
3145 	if (ipif->ipif_ipif_up_count == 1 && !loopback) {
3146 		/*
3147 		 * Need to recover all multicast memberships in the driver.
3148 		 * This had to be deferred until we had attached.
3149 		 */
3150 		ill_recover_multicast(ill);
3151 	}
3152 	/* Join the allhosts multicast address and the solicited node MC */
3153 	ipif_multicast_up(ipif);
3154 
3155 	if (!loopback) {
3156 		/*
3157 		 * See whether anybody else would benefit from the
3158 		 * new ipif that we added. We call this always rather
3159 		 * than while adding a non-IPIF_NOLOCAL/DEPRECATED/ANYCAST
3160 		 * ipif for the benefit of illgrp_insert (done above)
3161 		 * which does not do source address selection as it does
3162 		 * not want to re-create interface routes that we are
3163 		 * having reference to it here.
3164 		 */
3165 		ill_update_source_selection(ill);
3166 	}
3167 
3168 	for (irep1 = irep; irep1 > ire_array; ) {
3169 		irep1--;
3170 		if (*irep1 != NULL) {
3171 			/* was held in ire_add */
3172 			ire_refrele(*irep1);
3173 		}
3174 	}
3175 
3176 	cnt = ipif_saved_ire_cnt;
3177 	for (irep1 = ipif_saved_irep; cnt > 0; irep1++, cnt--) {
3178 		if (*irep1 != NULL) {
3179 			/* was held in ire_add */
3180 			ire_refrele(*irep1);
3181 		}
3182 	}
3183 
3184 	if (ipif->ipif_addr_ready) {
3185 		ip_rts_ifmsg(ipif);
3186 		ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
3187 		sctp_update_ipif(ipif, SCTP_IPIF_UP);
3188 	}
3189 
3190 	if (ipif_saved_irep != NULL) {
3191 		kmem_free(ipif_saved_irep,
3192 		    ipif_saved_ire_cnt * sizeof (ire_t *));
3193 	}
3194 
3195 	if (src_ipif_held)
3196 		ipif_refrele(src_ipif);
3197 	return (0);
3198 
3199 bad:
3200 	if (ip6_asp_table_held)
3201 		ip6_asp_table_refrele(ipst);
3202 	/*
3203 	 * We don't have to bother removing from ill groups because
3204 	 *
3205 	 * 1) For groups with names, we insert only when the first ipif
3206 	 *    comes up. In that case if it fails, it will not be in any
3207 	 *    group. So, we need not try to remove for that case.
3208 	 *
3209 	 * 2) For groups without names, either we tried to insert ipif_ill
3210 	 *    in a group as singleton or found some other group to become
3211 	 *    a bigger group. For the former, if it fails we don't have
3212 	 *    anything to do as ipif_ill is not in the group and for the
3213 	 *    latter, there are no failures in illgrp_insert/illgrp_delete
3214 	 *    (ENOMEM can't occur for this. Check ifgrp_insert).
3215 	 */
3216 
3217 	while (irep > ire_array) {
3218 		irep--;
3219 		if (*irep != NULL) {
3220 			ire_delete(*irep);
3221 			if (ire_added)
3222 				ire_refrele(*irep);
3223 		}
3224 
3225 	}
3226 	(void) ip_srcid_remove(&ipif->ipif_v6lcl_addr, ipif->ipif_zoneid, ipst);
3227 
3228 	if (ipif_saved_irep != NULL) {
3229 		kmem_free(ipif_saved_irep,
3230 		    ipif_saved_ire_cnt * sizeof (ire_t *));
3231 	}
3232 	if (src_ipif_held)
3233 		ipif_refrele(src_ipif);
3234 
3235 	ipif_ndp_down(ipif);
3236 	if (ipif->ipif_ill->ill_flags & ILLF_XRESOLV)
3237 		ipif_arp_down(ipif);
3238 
3239 	return (err);
3240 }
3241 
3242 /*
3243  * Delete an ND entry and the corresponding IRE_CACHE entry if it exists.
3244  */
3245 /* ARGSUSED */
3246 int
3247 ip_siocdelndp_v6(ipif_t *ipif, sin_t *dummy_sin, queue_t *q, mblk_t *mp,
3248     ip_ioctl_cmd_t *ipip, void *dummy_ifreq)
3249 {
3250 	in6_addr_t	addr;
3251 	sin6_t		*sin6;
3252 	nce_t		*nce;
3253 	struct lifreq	*lifr;
3254 	lif_nd_req_t	*lnr;
3255 	mblk_t	*mp1;
3256 
3257 	mp1 = mp->b_cont->b_cont;
3258 	lifr = (struct lifreq *)mp1->b_rptr;
3259 	lnr = &lifr->lifr_nd;
3260 	/* Only allow for logical unit zero i.e. not on "le0:17" */
3261 	if (ipif->ipif_id != 0)
3262 		return (EINVAL);
3263 
3264 	if (!ipif->ipif_isv6)
3265 		return (EINVAL);
3266 
3267 	if (lnr->lnr_addr.ss_family != AF_INET6)
3268 		return (EAFNOSUPPORT);
3269 
3270 	sin6 = (sin6_t *)&lnr->lnr_addr;
3271 	addr = sin6->sin6_addr;
3272 	nce = ndp_lookup_v6(ipif->ipif_ill, &addr, B_FALSE);
3273 	if (nce == NULL)
3274 		return (ESRCH);
3275 	ndp_delete(nce);
3276 	NCE_REFRELE(nce);
3277 	return (0);
3278 }
3279 
3280 /*
3281  * Return nbr cache info.
3282  */
3283 /* ARGSUSED */
3284 int
3285 ip_siocqueryndp_v6(ipif_t *ipif, sin_t *dummy_sin, queue_t *q, mblk_t *mp,
3286     ip_ioctl_cmd_t *ipip, void *dummy_ifreq)
3287 {
3288 	ill_t		*ill = ipif->ipif_ill;
3289 	struct lifreq	*lifr;
3290 	lif_nd_req_t	*lnr;
3291 
3292 	lifr = (struct lifreq *)mp->b_cont->b_cont->b_rptr;
3293 	lnr = &lifr->lifr_nd;
3294 	/* Only allow for logical unit zero i.e. not on "le0:17" */
3295 	if (ipif->ipif_id != 0)
3296 		return (EINVAL);
3297 
3298 	if (!ipif->ipif_isv6)
3299 		return (EINVAL);
3300 
3301 	if (lnr->lnr_addr.ss_family != AF_INET6)
3302 		return (EAFNOSUPPORT);
3303 
3304 	if (ill->ill_phys_addr_length > sizeof (lnr->lnr_hdw_addr))
3305 		return (EINVAL);
3306 
3307 	return (ndp_query(ill, lnr));
3308 }
3309 
3310 /*
3311  * Perform an update of the nd entry for the specified address.
3312  */
3313 /* ARGSUSED */
3314 int
3315 ip_siocsetndp_v6(ipif_t *ipif, sin_t *dummy_sin, queue_t *q, mblk_t *mp,
3316     ip_ioctl_cmd_t *ipip, void *dummy_ifreq)
3317 {
3318 	ill_t		*ill = ipif->ipif_ill;
3319 	struct	lifreq	*lifr;
3320 	lif_nd_req_t	*lnr;
3321 
3322 	ASSERT(!(q->q_flag & QREADR) && q->q_next == NULL);
3323 
3324 	lifr = (struct lifreq *)mp->b_cont->b_cont->b_rptr;
3325 	lnr = &lifr->lifr_nd;
3326 	/* Only allow for logical unit zero i.e. not on "le0:17" */
3327 	if (ipif->ipif_id != 0)
3328 		return (EINVAL);
3329 
3330 	if (!ipif->ipif_isv6)
3331 		return (EINVAL);
3332 
3333 	if (lnr->lnr_addr.ss_family != AF_INET6)
3334 		return (EAFNOSUPPORT);
3335 
3336 	return (ndp_sioc_update(ill, lnr));
3337 }
3338