xref: /titanic_51/usr/src/uts/common/inet/ip/ip_ire.c (revision 9e0b7c70f4e1d65d875a8606e4c31052555392f3)
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 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 /* Copyright (c) 1990 Mentat Inc. */
26 
27 /*
28  * This file contains routines that manipulate Internet Routing Entries (IREs).
29  */
30 
31 #include <sys/types.h>
32 #include <sys/stream.h>
33 #include <sys/stropts.h>
34 #include <sys/strsun.h>
35 #include <sys/strsubr.h>
36 #include <sys/ddi.h>
37 #include <sys/cmn_err.h>
38 #include <sys/policy.h>
39 
40 #include <sys/systm.h>
41 #include <sys/kmem.h>
42 #include <sys/param.h>
43 #include <sys/socket.h>
44 #include <net/if.h>
45 #include <net/route.h>
46 #include <netinet/in.h>
47 #include <net/if_dl.h>
48 #include <netinet/ip6.h>
49 #include <netinet/icmp6.h>
50 
51 #include <inet/common.h>
52 #include <inet/mi.h>
53 #include <inet/ip.h>
54 #include <inet/ip6.h>
55 #include <inet/ip_ndp.h>
56 #include <inet/arp.h>
57 #include <inet/ip_if.h>
58 #include <inet/ip_ire.h>
59 #include <inet/ip_ftable.h>
60 #include <inet/ip_rts.h>
61 #include <inet/nd.h>
62 
63 #include <inet/tcp.h>
64 #include <inet/ipclassifier.h>
65 #include <sys/zone.h>
66 #include <sys/cpuvar.h>
67 
68 #include <sys/tsol/label.h>
69 #include <sys/tsol/tnet.h>
70 
71 struct kmem_cache *rt_entry_cache;
72 
73 typedef struct nce_clookup_s {
74 	ipaddr_t ncecl_addr;
75 	boolean_t ncecl_found;
76 } nce_clookup_t;
77 
78 /*
79  * Synchronization notes:
80  *
81  * The fields of the ire_t struct are protected in the following way :
82  *
83  * ire_next/ire_ptpn
84  *
85  *	- bucket lock of the forwarding table in which is ire stored.
86  *
87  * ire_ill, ire_u *except* ire_gateway_addr[v6], ire_mask,
88  * ire_type, ire_create_time, ire_masklen, ire_ipversion, ire_flags,
89  * ire_bucket
90  *
91  *	- Set in ire_create_v4/v6 and never changes after that. Thus,
92  *	  we don't need a lock whenever these fields are accessed.
93  *
94  *	- ire_bucket and ire_masklen (also set in ire_create) is set in
95  *        ire_add before inserting in the bucket and never
96  *        changes after that. Thus we don't need a lock whenever these
97  *	  fields are accessed.
98  *
99  * ire_gateway_addr_v4[v6]
100  *
101  *	- ire_gateway_addr_v4[v6] is set during ire_create and later modified
102  *	  by rts_setgwr[v6]. As ire_gateway_addr is a uint32_t, updates to
103  *	  it assumed to be atomic and hence the other parts of the code
104  *	  does not use any locks. ire_gateway_addr_v6 updates are not atomic
105  *	  and hence any access to it uses ire_lock to get/set the right value.
106  *
107  * ire_refcnt, ire_identical_ref
108  *
109  *	- Updated atomically using atomic_add_32
110  *
111  * ire_ssthresh, ire_rtt_sd, ire_rtt, ire_ib_pkt_count, ire_ob_pkt_count
112  *
113  *	- Assumes that 32 bit writes are atomic. No locks. ire_lock is
114  *	  used to serialize updates to ire_ssthresh, ire_rtt_sd, ire_rtt.
115  *
116  * ire_generation
117  *	- Under ire_lock
118  *
119  * ire_nce_cache
120  *	- Under ire_lock
121  *
122  * ire_dep_parent (To next IRE in recursive lookup chain)
123  *	- Under ips_ire_dep_lock. Write held when modifying. Read held when
124  *	  walking. We also hold ire_lock when modifying to allow the data path
125  *	  to only acquire ire_lock.
126  *
127  * ire_dep_parent_generation (Generation number from ire_dep_parent)
128  *	- Under ips_ire_dep_lock and/or ire_lock. (A read claim on the dep_lock
129  *	  and ire_lock held when modifying)
130  *
131  * ire_dep_children (From parent to first child)
132  * ire_dep_sib_next (linked list of siblings)
133  * ire_dep_sib_ptpn (linked list of siblings)
134  *	- Under ips_ire_dep_lock. Write held when modifying. Read held when
135  *	  walking.
136  *
137  * As we always hold the bucket locks in all the places while accessing
138  * the above values, it is natural to use them for protecting them.
139  *
140  * We have a forwarding table for IPv4 and IPv6. The IPv6 forwarding table
141  * (ip_forwarding_table_v6) is an array of pointers to arrays of irb_t
142  * structures. ip_forwarding_table_v6 is allocated dynamically in
143  * ire_add_v6. ire_ft_init_lock is used to serialize multiple threads
144  * initializing the same bucket. Once a bucket is initialized, it is never
145  * de-alloacted. This assumption enables us to access
146  * ip_forwarding_table_v6[i] without any locks.
147  *
148  * The forwarding table for IPv4 is a radix tree whose leaves
149  * are rt_entry structures containing the irb_t for the rt_dst. The irb_t
150  * for IPv4 is dynamically allocated and freed.
151  *
152  * Each irb_t - ire bucket structure has a lock to protect
153  * a bucket and the ires residing in the bucket have a back pointer to
154  * the bucket structure. It also has a reference count for the number
155  * of threads walking the bucket - irb_refcnt which is bumped up
156  * using the irb_refhold function. The flags irb_marks can be
157  * set to IRB_MARK_CONDEMNED indicating that there are some ires
158  * in this bucket that are IRE_IS_CONDEMNED and the
159  * last thread to leave the bucket should delete the ires. Usually
160  * this is done by the irb_refrele function which is used to decrement
161  * the reference count on a bucket. See comments above irb_t structure
162  * definition in ip.h for further details.
163  *
164  * The ire_refhold/ire_refrele functions operate on the ire which increments/
165  * decrements the reference count, ire_refcnt, atomically on the ire.
166  * ire_refcnt is modified only using those functions. Operations on the IRE
167  * could be described as follows :
168  *
169  * CREATE an ire with reference count initialized to 1.
170  *
171  * ADDITION of an ire holds the bucket lock, checks for duplicates
172  * and then adds the ire. ire_add returns the ire after
173  * bumping up once more i.e the reference count is 2. This is to avoid
174  * an extra lookup in the functions calling ire_add which wants to
175  * work with the ire after adding.
176  *
177  * LOOKUP of an ire bumps up the reference count using ire_refhold
178  * function. It is valid to bump up the referece count of the IRE,
179  * after the lookup has returned an ire. Following are the lookup
180  * functions that return an HELD ire :
181  *
182  * ire_ftable_lookup[_v6], ire_lookup_multi_ill[_v6]
183  *
184  * DELETION of an ire holds the bucket lock, removes it from the list
185  * and then decrements the reference count for having removed from the list
186  * by using the ire_refrele function. If some other thread has looked up
187  * the ire, the reference count would have been bumped up and hence
188  * this ire will not be freed once deleted. It will be freed once the
189  * reference count drops to zero.
190  *
191  * Add and Delete acquires the bucket lock as RW_WRITER, while all the
192  * lookups acquire the bucket lock as RW_READER.
193  *
194  * The general rule is to do the ire_refrele in the function
195  * that is passing the ire as an argument.
196  *
197  * In trying to locate ires the following points are to be noted.
198  *
199  * IRE_IS_CONDEMNED signifies that the ire has been logically deleted and is
200  * to be ignored when walking the ires using ire_next.
201  *
202  * Zones note:
203  *	Walking IREs within a given zone also walks certain ires in other
204  *	zones.  This is done intentionally.  IRE walks with a specified
205  *	zoneid are used only when doing informational reports, and
206  *	zone users want to see things that they can access. See block
207  *	comment in ire_walk_ill_match().
208  */
209 
210 /*
211  * The size of the forwarding table.  We will make sure that it is a
212  * power of 2 in ip_ire_init().
213  * Setable in /etc/system
214  */
215 uint32_t ip6_ftable_hash_size = IP6_FTABLE_HASH_SIZE;
216 
217 struct	kmem_cache	*ire_cache;
218 struct	kmem_cache	*ncec_cache;
219 struct	kmem_cache	*nce_cache;
220 
221 static ire_t	ire_null;
222 
223 static ire_t	*ire_add_v4(ire_t *ire);
224 static void	ire_delete_v4(ire_t *ire);
225 static void	ire_dep_invalidate_children(ire_t *child);
226 static void	ire_walk_ipvers(pfv_t func, void *arg, uchar_t vers,
227     zoneid_t zoneid, ip_stack_t *);
228 static void	ire_walk_ill_ipvers(uint_t match_flags, uint_t ire_type,
229     pfv_t func, void *arg, uchar_t vers, ill_t *ill);
230 #ifdef DEBUG
231 static void	ire_trace_cleanup(const ire_t *);
232 #endif
233 
234 /*
235  * Following are the functions to increment/decrement the reference
236  * count of the IREs and IRBs (ire bucket).
237  *
238  * 1) We bump up the reference count of an IRE to make sure that
239  *    it does not get deleted and freed while we are using it.
240  *    Typically all the lookup functions hold the bucket lock,
241  *    and look for the IRE. If it finds an IRE, it bumps up the
242  *    reference count before dropping the lock. Sometimes we *may* want
243  *    to bump up the reference count after we *looked* up i.e without
244  *    holding the bucket lock. So, the ire_refhold function does not assert
245  *    on the bucket lock being held. Any thread trying to delete from
246  *    the hash bucket can still do so but cannot free the IRE if
247  *    ire_refcnt is not 0.
248  *
249  * 2) We bump up the reference count on the bucket where the IRE resides
250  *    (IRB), when we want to prevent the IREs getting deleted from a given
251  *    hash bucket. This makes life easier for ire_walk type functions which
252  *    wants to walk the IRE list, call a function, but needs to drop
253  *    the bucket lock to prevent recursive rw_enters. While the
254  *    lock is dropped, the list could be changed by other threads or
255  *    the same thread could end up deleting the ire or the ire pointed by
256  *    ire_next. ire_refholding the ire or ire_next is not sufficient as
257  *    a delete will still remove the ire from the bucket while we have
258  *    dropped the lock and hence the ire_next would be NULL. Thus, we
259  *    need a mechanism to prevent deletions from a given bucket.
260  *
261  *    To prevent deletions, we bump up the reference count on the
262  *    bucket. If the bucket is held, ire_delete just marks both
263  *    the ire and irb as CONDEMNED. When the
264  *    reference count on the bucket drops to zero, all the CONDEMNED ires
265  *    are deleted. We don't have to bump up the reference count on the
266  *    bucket if we are walking the bucket and never have to drop the bucket
267  *    lock. Note that irb_refhold does not prevent addition of new ires
268  *    in the list. It is okay because addition of new ires will not cause
269  *    ire_next to point to freed memory. We do irb_refhold only when
270  *    all of the 3 conditions are true :
271  *
272  *    1) The code needs to walk the IRE bucket from start to end.
273  *    2) It may have to drop the bucket lock sometimes while doing (1)
274  *    3) It does not want any ires to be deleted meanwhile.
275  */
276 
277 /*
278  * Bump up the reference count on the hash bucket - IRB to
279  * prevent ires from being deleted in this bucket.
280  */
281 void
282 irb_refhold(irb_t *irb)
283 {
284 	rw_enter(&irb->irb_lock, RW_WRITER);
285 	irb->irb_refcnt++;
286 	ASSERT(irb->irb_refcnt != 0);
287 	rw_exit(&irb->irb_lock);
288 }
289 
290 void
291 irb_refhold_locked(irb_t *irb)
292 {
293 	ASSERT(RW_WRITE_HELD(&irb->irb_lock));
294 	irb->irb_refcnt++;
295 	ASSERT(irb->irb_refcnt != 0);
296 }
297 
298 /*
299  * Note: when IRB_MARK_DYNAMIC is not set the irb_t
300  * is statically allocated, so that when the irb_refcnt goes to 0,
301  * we simply clean up the ire list and continue.
302  */
303 void
304 irb_refrele(irb_t *irb)
305 {
306 	if (irb->irb_marks & IRB_MARK_DYNAMIC) {
307 		irb_refrele_ftable(irb);
308 	} else {
309 		rw_enter(&irb->irb_lock, RW_WRITER);
310 		ASSERT(irb->irb_refcnt != 0);
311 		if (--irb->irb_refcnt	== 0 &&
312 		    (irb->irb_marks & IRB_MARK_CONDEMNED)) {
313 			ire_t *ire_list;
314 
315 			ire_list = ire_unlink(irb);
316 			rw_exit(&irb->irb_lock);
317 			ASSERT(ire_list != NULL);
318 			ire_cleanup(ire_list);
319 		} else {
320 			rw_exit(&irb->irb_lock);
321 		}
322 	}
323 }
324 
325 
326 /*
327  * Bump up the reference count on the IRE. We cannot assert that the
328  * bucket lock is being held as it is legal to bump up the reference
329  * count after the first lookup has returned the IRE without
330  * holding the lock.
331  */
332 void
333 ire_refhold(ire_t *ire)
334 {
335 	atomic_add_32(&(ire)->ire_refcnt, 1);
336 	ASSERT((ire)->ire_refcnt != 0);
337 #ifdef DEBUG
338 	ire_trace_ref(ire);
339 #endif
340 }
341 
342 void
343 ire_refhold_notr(ire_t *ire)
344 {
345 	atomic_add_32(&(ire)->ire_refcnt, 1);
346 	ASSERT((ire)->ire_refcnt != 0);
347 }
348 
349 void
350 ire_refhold_locked(ire_t *ire)
351 {
352 #ifdef DEBUG
353 	ire_trace_ref(ire);
354 #endif
355 	ire->ire_refcnt++;
356 }
357 
358 /*
359  * Release a ref on an IRE.
360  *
361  * Must not be called while holding any locks. Otherwise if this is
362  * the last reference to be released there is a chance of recursive mutex
363  * panic due to ire_refrele -> ipif_ill_refrele_tail -> qwriter_ip trying
364  * to restart an ioctl. The one exception is when the caller is sure that
365  * this is not the last reference to be released. Eg. if the caller is
366  * sure that the ire has not been deleted and won't be deleted.
367  *
368  * In architectures e.g sun4u, where atomic_add_32_nv is just
369  * a cas, we need to maintain the right memory barrier semantics
370  * as that of mutex_exit i.e all the loads and stores should complete
371  * before the cas is executed. membar_exit() does that here.
372  */
373 void
374 ire_refrele(ire_t *ire)
375 {
376 #ifdef DEBUG
377 	ire_untrace_ref(ire);
378 #endif
379 	ASSERT((ire)->ire_refcnt != 0);
380 	membar_exit();
381 	if (atomic_add_32_nv(&(ire)->ire_refcnt, -1) == 0)
382 		ire_inactive(ire);
383 }
384 
385 void
386 ire_refrele_notr(ire_t *ire)
387 {
388 	ASSERT((ire)->ire_refcnt != 0);
389 	membar_exit();
390 	if (atomic_add_32_nv(&(ire)->ire_refcnt, -1) == 0)
391 		ire_inactive(ire);
392 }
393 
394 /*
395  * This function is associated with the IP_IOC_IRE_DELETE[_NO_REPLY]
396  * IOCTL[s].  The NO_REPLY form is used by TCP to tell IP that it is
397  * having problems reaching a particular destination.
398  * This will make IP consider alternate routes (e.g., when there are
399  * muliple default routes), and it will also make IP discard any (potentially)
400  * stale redirect.
401  * Management processes may want to use the version that generates a reply.
402  *
403  * With the use of NUD like behavior for IPv4/ARP in addition to IPv6
404  * this function shouldn't be necessary for IP to recover from a bad redirect,
405  * a bad default router (when there are multiple default routers), or
406  * a stale ND/ARP entry. But we retain it in any case.
407  * For instance, this is helpful when TCP suspects a failure before NUD does.
408  */
409 int
410 ip_ire_delete(queue_t *q, mblk_t *mp, cred_t *ioc_cr)
411 {
412 	uchar_t		*addr_ucp;
413 	uint_t		ipversion;
414 	sin_t		*sin;
415 	sin6_t		*sin6;
416 	ipaddr_t	v4addr;
417 	in6_addr_t	v6addr;
418 	ire_t		*ire;
419 	ipid_t		*ipid;
420 	zoneid_t	zoneid;
421 	ip_stack_t	*ipst;
422 
423 	ASSERT(q->q_next == NULL);
424 	zoneid = IPCL_ZONEID(Q_TO_CONN(q));
425 	ipst = CONNQ_TO_IPST(q);
426 
427 	/*
428 	 * Check privilege using the ioctl credential; if it is NULL
429 	 * then this is a kernel message and therefor privileged.
430 	 */
431 	if (ioc_cr != NULL && secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
432 		return (EPERM);
433 
434 	ipid = (ipid_t *)mp->b_rptr;
435 
436 	addr_ucp = mi_offset_param(mp, ipid->ipid_addr_offset,
437 	    ipid->ipid_addr_length);
438 	if (addr_ucp == NULL || !OK_32PTR(addr_ucp))
439 		return (EINVAL);
440 	switch (ipid->ipid_addr_length) {
441 	case sizeof (sin_t):
442 		/*
443 		 * got complete (sockaddr) address - increment addr_ucp to point
444 		 * at the ip_addr field.
445 		 */
446 		sin = (sin_t *)addr_ucp;
447 		addr_ucp = (uchar_t *)&sin->sin_addr.s_addr;
448 		ipversion = IPV4_VERSION;
449 		break;
450 	case sizeof (sin6_t):
451 		/*
452 		 * got complete (sockaddr) address - increment addr_ucp to point
453 		 * at the ip_addr field.
454 		 */
455 		sin6 = (sin6_t *)addr_ucp;
456 		addr_ucp = (uchar_t *)&sin6->sin6_addr;
457 		ipversion = IPV6_VERSION;
458 		break;
459 	default:
460 		return (EINVAL);
461 	}
462 	if (ipversion == IPV4_VERSION) {
463 		/* Extract the destination address. */
464 		bcopy(addr_ucp, &v4addr, IP_ADDR_LEN);
465 
466 		ire = ire_ftable_lookup_v4(v4addr, 0, 0, 0, NULL,
467 		    zoneid, NULL, MATCH_IRE_DSTONLY, 0, ipst, NULL);
468 	} else {
469 		/* Extract the destination address. */
470 		bcopy(addr_ucp, &v6addr, IPV6_ADDR_LEN);
471 
472 		ire = ire_ftable_lookup_v6(&v6addr, NULL, NULL, 0, NULL,
473 		    zoneid, NULL, MATCH_IRE_DSTONLY, 0, ipst, NULL);
474 	}
475 	if (ire != NULL) {
476 		if (ipversion == IPV4_VERSION) {
477 			ip_rts_change(RTM_LOSING, ire->ire_addr,
478 			    ire->ire_gateway_addr, ire->ire_mask,
479 			    (Q_TO_CONN(q))->conn_laddr_v4,  0, 0, 0,
480 			    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_IFA),
481 			    ire->ire_ipst);
482 		}
483 		(void) ire_no_good(ire);
484 		ire_refrele(ire);
485 	}
486 	return (0);
487 }
488 
489 /*
490  * Initialize the ire that is specific to IPv4 part and call
491  * ire_init_common to finish it.
492  * Returns zero or errno.
493  */
494 int
495 ire_init_v4(ire_t *ire, uchar_t *addr, uchar_t *mask, uchar_t *gateway,
496     ushort_t type, ill_t *ill, zoneid_t zoneid, uint_t flags,
497     tsol_gc_t *gc, ip_stack_t *ipst)
498 {
499 	int error;
500 
501 	/*
502 	 * Reject IRE security attribute creation/initialization
503 	 * if system is not running in Trusted mode.
504 	 */
505 	if (gc != NULL && !is_system_labeled())
506 		return (EINVAL);
507 
508 	BUMP_IRE_STATS(ipst->ips_ire_stats_v4, ire_stats_alloced);
509 
510 	if (addr != NULL)
511 		bcopy(addr, &ire->ire_addr, IP_ADDR_LEN);
512 	if (gateway != NULL)
513 		bcopy(gateway, &ire->ire_gateway_addr, IP_ADDR_LEN);
514 
515 	/* Make sure we don't have stray values in some fields */
516 	switch (type) {
517 	case IRE_LOOPBACK:
518 		bcopy(&ire->ire_addr, &ire->ire_gateway_addr, IP_ADDR_LEN);
519 		/* FALLTHRU */
520 	case IRE_HOST:
521 	case IRE_BROADCAST:
522 	case IRE_LOCAL:
523 	case IRE_IF_CLONE:
524 		ire->ire_mask = IP_HOST_MASK;
525 		ire->ire_masklen = IPV4_ABITS;
526 		break;
527 	case IRE_PREFIX:
528 	case IRE_DEFAULT:
529 	case IRE_IF_RESOLVER:
530 	case IRE_IF_NORESOLVER:
531 		if (mask != NULL) {
532 			bcopy(mask, &ire->ire_mask, IP_ADDR_LEN);
533 			ire->ire_masklen = ip_mask_to_plen(ire->ire_mask);
534 		}
535 		break;
536 	case IRE_MULTICAST:
537 	case IRE_NOROUTE:
538 		ASSERT(mask == NULL);
539 		break;
540 	default:
541 		ASSERT(0);
542 		return (EINVAL);
543 	}
544 
545 	error = ire_init_common(ire, type, ill, zoneid, flags, IPV4_VERSION,
546 	    gc, ipst);
547 	if (error != NULL)
548 		return (error);
549 
550 	/* Determine which function pointers to use */
551 	ire->ire_postfragfn = ip_xmit;		/* Common case */
552 
553 	switch (ire->ire_type) {
554 	case IRE_LOCAL:
555 		ire->ire_sendfn = ire_send_local_v4;
556 		ire->ire_recvfn = ire_recv_local_v4;
557 		ASSERT(ire->ire_ill != NULL);
558 		if (ire->ire_ill->ill_flags & ILLF_NOACCEPT)
559 			ire->ire_recvfn = ire_recv_noaccept_v6;
560 		break;
561 	case IRE_LOOPBACK:
562 		ire->ire_sendfn = ire_send_local_v4;
563 		ire->ire_recvfn = ire_recv_loopback_v4;
564 		break;
565 	case IRE_BROADCAST:
566 		ire->ire_postfragfn = ip_postfrag_loopcheck;
567 		ire->ire_sendfn = ire_send_broadcast_v4;
568 		ire->ire_recvfn = ire_recv_broadcast_v4;
569 		break;
570 	case IRE_MULTICAST:
571 		ire->ire_postfragfn = ip_postfrag_loopcheck;
572 		ire->ire_sendfn = ire_send_multicast_v4;
573 		ire->ire_recvfn = ire_recv_multicast_v4;
574 		break;
575 	default:
576 		/*
577 		 * For IRE_IF_ALL and IRE_OFFLINK we forward received
578 		 * packets by default.
579 		 */
580 		ire->ire_sendfn = ire_send_wire_v4;
581 		ire->ire_recvfn = ire_recv_forward_v4;
582 		break;
583 	}
584 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
585 		ire->ire_sendfn = ire_send_noroute_v4;
586 		ire->ire_recvfn = ire_recv_noroute_v4;
587 	} else if (ire->ire_flags & RTF_MULTIRT) {
588 		ire->ire_postfragfn = ip_postfrag_multirt_v4;
589 		ire->ire_sendfn = ire_send_multirt_v4;
590 		/* Multirt receive of broadcast uses ire_recv_broadcast_v4 */
591 		if (ire->ire_type != IRE_BROADCAST)
592 			ire->ire_recvfn = ire_recv_multirt_v4;
593 	}
594 	ire->ire_nce_capable = ire_determine_nce_capable(ire);
595 	return (0);
596 }
597 
598 /*
599  * Determine ire_nce_capable
600  */
601 boolean_t
602 ire_determine_nce_capable(ire_t *ire)
603 {
604 	int max_masklen;
605 
606 	if ((ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
607 	    (ire->ire_type & IRE_MULTICAST))
608 		return (B_TRUE);
609 
610 	if (ire->ire_ipversion == IPV4_VERSION)
611 		max_masklen = IPV4_ABITS;
612 	else
613 		max_masklen = IPV6_ABITS;
614 
615 	if ((ire->ire_type & IRE_ONLINK) && ire->ire_masklen == max_masklen)
616 		return (B_TRUE);
617 	return (B_FALSE);
618 }
619 
620 /*
621  * ire_create is called to allocate and initialize a new IRE.
622  *
623  * NOTE : This is called as writer sometimes though not required
624  * by this function.
625  */
626 ire_t *
627 ire_create(uchar_t *addr, uchar_t *mask, uchar_t *gateway,
628     ushort_t type, ill_t *ill, zoneid_t zoneid, uint_t flags, tsol_gc_t *gc,
629     ip_stack_t *ipst)
630 {
631 	ire_t	*ire;
632 	int	error;
633 
634 	ire = kmem_cache_alloc(ire_cache, KM_NOSLEEP);
635 	if (ire == NULL) {
636 		DTRACE_PROBE(kmem__cache__alloc);
637 		return (NULL);
638 	}
639 	*ire = ire_null;
640 
641 	error = ire_init_v4(ire, addr, mask, gateway, type, ill, zoneid, flags,
642 	    gc, ipst);
643 	if (error != 0) {
644 		DTRACE_PROBE2(ire__init, ire_t *, ire, int, error);
645 		kmem_cache_free(ire_cache, ire);
646 		return (NULL);
647 	}
648 	return (ire);
649 }
650 
651 /*
652  * Common to IPv4 and IPv6
653  * Returns zero or errno.
654  */
655 int
656 ire_init_common(ire_t *ire, ushort_t type, ill_t *ill, zoneid_t zoneid,
657     uint_t flags, uchar_t ipversion, tsol_gc_t *gc, ip_stack_t *ipst)
658 {
659 	int error;
660 
661 #ifdef DEBUG
662 	if (ill != NULL) {
663 		if (ill->ill_isv6)
664 			ASSERT(ipversion == IPV6_VERSION);
665 		else
666 			ASSERT(ipversion == IPV4_VERSION);
667 	}
668 #endif /* DEBUG */
669 
670 	/*
671 	 * Create/initialize IRE security attribute only in Trusted mode;
672 	 * if the passed in gc is non-NULL, we expect that the caller
673 	 * has held a reference to it and will release it when this routine
674 	 * returns a failure, otherwise we own the reference.  We do this
675 	 * prior to initializing the rest IRE fields.
676 	 */
677 	if (is_system_labeled()) {
678 		if ((type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST |
679 		    IRE_IF_ALL | IRE_MULTICAST | IRE_NOROUTE)) != 0) {
680 			/* release references on behalf of caller */
681 			if (gc != NULL)
682 				GC_REFRELE(gc);
683 		} else {
684 			error = tsol_ire_init_gwattr(ire, ipversion, gc);
685 			if (error != 0)
686 				return (error);
687 		}
688 	}
689 
690 	ire->ire_type = type;
691 	ire->ire_flags = RTF_UP | flags;
692 	ire->ire_create_time = (uint32_t)gethrestime_sec();
693 	ire->ire_generation = IRE_GENERATION_INITIAL;
694 
695 	/*
696 	 * The ill_ire_cnt isn't increased until
697 	 * the IRE is added to ensure that a walker will find
698 	 * all IREs that hold a reference on an ill.
699 	 *
700 	 * Note that ill_ire_multicast doesn't hold a ref on the ill since
701 	 * ire_add() is not called for the IRE_MULTICAST.
702 	 */
703 	ire->ire_ill = ill;
704 	ire->ire_zoneid = zoneid;
705 	ire->ire_ipversion = ipversion;
706 
707 	mutex_init(&ire->ire_lock, NULL, MUTEX_DEFAULT, NULL);
708 	ire->ire_refcnt = 1;
709 	ire->ire_identical_ref = 1;	/* Number of ire_delete's needed */
710 	ire->ire_ipst = ipst;	/* No netstack_hold */
711 	ire->ire_trace_disable = B_FALSE;
712 
713 	return (0);
714 }
715 
716 /*
717  * This creates an IRE_BROADCAST based on the arguments.
718  * A mirror is ire_lookup_bcast().
719  *
720  * Any supression of unneeded ones is done in ire_add_v4.
721  * We add one IRE_BROADCAST per address. ire_send_broadcast_v4()
722  * takes care of generating a loopback copy of the packet.
723  */
724 ire_t **
725 ire_create_bcast(ill_t *ill, ipaddr_t addr, zoneid_t zoneid, ire_t **irep)
726 {
727 	ip_stack_t	*ipst = ill->ill_ipst;
728 
729 	ASSERT(IAM_WRITER_ILL(ill));
730 
731 	*irep++ = ire_create(
732 	    (uchar_t *)&addr,			/* dest addr */
733 	    (uchar_t *)&ip_g_all_ones,		/* mask */
734 	    NULL,				/* no gateway */
735 	    IRE_BROADCAST,
736 	    ill,
737 	    zoneid,
738 	    RTF_KERNEL,
739 	    NULL,
740 	    ipst);
741 
742 	return (irep);
743 }
744 
745 /*
746  * This looks up an IRE_BROADCAST based on the arguments.
747  * Mirrors ire_create_bcast().
748  */
749 ire_t *
750 ire_lookup_bcast(ill_t *ill, ipaddr_t addr, zoneid_t zoneid)
751 {
752 	ire_t		*ire;
753 	int		match_args;
754 
755 	match_args = MATCH_IRE_TYPE | MATCH_IRE_ILL | MATCH_IRE_GW |
756 	    MATCH_IRE_MASK | MATCH_IRE_ZONEONLY;
757 
758 	if (IS_UNDER_IPMP(ill))
759 		match_args |= MATCH_IRE_TESTHIDDEN;
760 
761 	ire = ire_ftable_lookup_v4(
762 	    addr,				/* dest addr */
763 	    ip_g_all_ones,			/* mask */
764 	    0,					/* no gateway */
765 	    IRE_BROADCAST,
766 	    ill,
767 	    zoneid,
768 	    NULL,
769 	    match_args,
770 	    0,
771 	    ill->ill_ipst,
772 	    NULL);
773 	return (ire);
774 }
775 
776 /* Arrange to call the specified function for every IRE in the world. */
777 void
778 ire_walk(pfv_t func, void *arg, ip_stack_t *ipst)
779 {
780 	ire_walk_ipvers(func, arg, 0, ALL_ZONES, ipst);
781 }
782 
783 void
784 ire_walk_v4(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
785 {
786 	ire_walk_ipvers(func, arg, IPV4_VERSION, zoneid, ipst);
787 }
788 
789 void
790 ire_walk_v6(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
791 {
792 	ire_walk_ipvers(func, arg, IPV6_VERSION, zoneid, ipst);
793 }
794 
795 /*
796  * Walk a particular version. version == 0 means both v4 and v6.
797  */
798 static void
799 ire_walk_ipvers(pfv_t func, void *arg, uchar_t vers, zoneid_t zoneid,
800     ip_stack_t *ipst)
801 {
802 	if (vers != IPV6_VERSION) {
803 		/*
804 		 * ip_forwarding_table variable doesn't matter for IPv4 since
805 		 * ire_walk_ill_tables uses ips_ip_ftable for IPv4.
806 		 */
807 		ire_walk_ill_tables(0, 0, func, arg, IP_MASK_TABLE_SIZE,
808 		    0, NULL,
809 		    NULL, zoneid, ipst);
810 	}
811 	if (vers != IPV4_VERSION) {
812 		ire_walk_ill_tables(0, 0, func, arg, IP6_MASK_TABLE_SIZE,
813 		    ipst->ips_ip6_ftable_hash_size,
814 		    ipst->ips_ip_forwarding_table_v6,
815 		    NULL, zoneid, ipst);
816 	}
817 }
818 
819 /*
820  * Arrange to call the specified function for every IRE that matches the ill.
821  */
822 void
823 ire_walk_ill(uint_t match_flags, uint_t ire_type, pfv_t func, void *arg,
824     ill_t *ill)
825 {
826 	uchar_t vers = (ill->ill_isv6 ? IPV6_VERSION : IPV4_VERSION);
827 
828 	ire_walk_ill_ipvers(match_flags, ire_type, func, arg, vers, ill);
829 }
830 
831 /*
832  * Walk a particular ill and version.
833  */
834 static void
835 ire_walk_ill_ipvers(uint_t match_flags, uint_t ire_type, pfv_t func,
836     void *arg, uchar_t vers, ill_t *ill)
837 {
838 	ip_stack_t	*ipst = ill->ill_ipst;
839 
840 	if (vers == IPV4_VERSION) {
841 		ire_walk_ill_tables(match_flags, ire_type, func, arg,
842 		    IP_MASK_TABLE_SIZE,
843 		    0, NULL,
844 		    ill, ALL_ZONES, ipst);
845 	}
846 	if (vers != IPV4_VERSION) {
847 		ire_walk_ill_tables(match_flags, ire_type, func, arg,
848 		    IP6_MASK_TABLE_SIZE, ipst->ips_ip6_ftable_hash_size,
849 		    ipst->ips_ip_forwarding_table_v6,
850 		    ill, ALL_ZONES, ipst);
851 	}
852 }
853 
854 /*
855  * Do the specific matching of IREs to shared-IP zones.
856  *
857  * We have the same logic as in ire_match_args but implemented slightly
858  * differently.
859  */
860 boolean_t
861 ire_walk_ill_match(uint_t match_flags, uint_t ire_type, ire_t *ire,
862     ill_t *ill, zoneid_t zoneid, ip_stack_t *ipst)
863 {
864 	ill_t *dst_ill = NULL;
865 
866 	ASSERT(match_flags != 0 || zoneid != ALL_ZONES);
867 	if (match_flags & MATCH_IRE_ILL) {
868 		dst_ill = ire->ire_ill;
869 	}
870 
871 	if (zoneid != ALL_ZONES && zoneid != ire->ire_zoneid &&
872 	    ire->ire_zoneid != ALL_ZONES) {
873 		/*
874 		 * We're walking the IREs for a specific zone. The only relevant
875 		 * IREs are:
876 		 * - all IREs with a matching ire_zoneid
877 		 * - IRE_IF_ALL IREs for interfaces with a usable source addr
878 		 *   with a matching zone
879 		 * - IRE_OFFLINK with a gateway reachable from the zone
880 		 * Note that ealier we only did the IRE_OFFLINK check for
881 		 * IRE_DEFAULT (and only when we had multiple IRE_DEFAULTs).
882 		 */
883 		dst_ill = ire->ire_ill;
884 
885 		if (ire->ire_type & IRE_ONLINK) {
886 			uint_t	ifindex;
887 
888 			/*
889 			 * Note there is no IRE_INTERFACE on vniN thus
890 			 * can't do an IRE lookup for a matching route.
891 			 */
892 			ifindex = dst_ill->ill_usesrc_ifindex;
893 			if (ifindex == 0)
894 				return (B_FALSE);
895 
896 			/*
897 			 * If there is a usable source address in the
898 			 * zone, then it's ok to return an
899 			 * IRE_INTERFACE
900 			 */
901 			if (!ipif_zone_avail(ifindex, dst_ill->ill_isv6,
902 			    zoneid, ipst)) {
903 				return (B_FALSE);
904 			}
905 		}
906 
907 		if (dst_ill != NULL && (ire->ire_type & IRE_OFFLINK)) {
908 			ipif_t	*tipif;
909 
910 			mutex_enter(&dst_ill->ill_lock);
911 			for (tipif = dst_ill->ill_ipif;
912 			    tipif != NULL; tipif = tipif->ipif_next) {
913 				if (!IPIF_IS_CONDEMNED(tipif) &&
914 				    (tipif->ipif_flags & IPIF_UP) &&
915 				    (tipif->ipif_zoneid == zoneid ||
916 				    tipif->ipif_zoneid == ALL_ZONES))
917 					break;
918 			}
919 			mutex_exit(&dst_ill->ill_lock);
920 			if (tipif == NULL) {
921 				return (B_FALSE);
922 			}
923 		}
924 
925 		/*
926 		 * Match all offlink routes from the global zone, irrespective
927 		 * of reachability. For a non-global zone only match those
928 		 * where ire_gateway_addr has an IRE_INTERFACE for the zoneid.
929 		 */
930 		if ((ire->ire_type & IRE_OFFLINK) && zoneid != GLOBAL_ZONEID &&
931 		    zoneid != ALL_ZONES) {
932 			in6_addr_t gw_addr_v6;
933 
934 			if (ire->ire_ipversion == IPV4_VERSION) {
935 				if (!ire_gateway_ok_zone_v4(
936 				    ire->ire_gateway_addr, zoneid,
937 				    dst_ill, NULL, ipst, B_FALSE))
938 					return (B_FALSE);
939 			} else {
940 				ASSERT(ire->ire_ipversion == IPV6_VERSION);
941 				mutex_enter(&ire->ire_lock);
942 				gw_addr_v6 = ire->ire_gateway_addr_v6;
943 				mutex_exit(&ire->ire_lock);
944 
945 				if (!ire_gateway_ok_zone_v6(&gw_addr_v6, zoneid,
946 				    dst_ill, NULL, ipst, B_FALSE))
947 					return (B_FALSE);
948 			}
949 		}
950 	}
951 
952 	if (((!(match_flags & MATCH_IRE_TYPE)) ||
953 	    (ire->ire_type & ire_type)) &&
954 	    ((!(match_flags & MATCH_IRE_ILL)) ||
955 	    (dst_ill == ill ||
956 	    dst_ill != NULL && IS_IN_SAME_ILLGRP(dst_ill, ill)))) {
957 		return (B_TRUE);
958 	}
959 	return (B_FALSE);
960 }
961 
962 int
963 rtfunc(struct radix_node *rn, void *arg)
964 {
965 	struct rtfuncarg *rtf = arg;
966 	struct rt_entry *rt;
967 	irb_t *irb;
968 	ire_t *ire;
969 	boolean_t ret;
970 
971 	rt = (struct rt_entry *)rn;
972 	ASSERT(rt != NULL);
973 	irb = &rt->rt_irb;
974 	for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
975 		if ((rtf->rt_match_flags != 0) ||
976 		    (rtf->rt_zoneid != ALL_ZONES)) {
977 			ret = ire_walk_ill_match(rtf->rt_match_flags,
978 			    rtf->rt_ire_type, ire,
979 			    rtf->rt_ill, rtf->rt_zoneid, rtf->rt_ipst);
980 		} else {
981 			ret = B_TRUE;
982 		}
983 		if (ret)
984 			(*rtf->rt_func)(ire, rtf->rt_arg);
985 	}
986 	return (0);
987 }
988 
989 /*
990  * Walk the ftable entries that match the ill.
991  */
992 void
993 ire_walk_ill_tables(uint_t match_flags, uint_t ire_type, pfv_t func,
994     void *arg, size_t ftbl_sz, size_t htbl_sz, irb_t **ipftbl,
995     ill_t *ill, zoneid_t zoneid,
996     ip_stack_t *ipst)
997 {
998 	irb_t	*irb_ptr;
999 	irb_t	*irb;
1000 	ire_t	*ire;
1001 	int i, j;
1002 	boolean_t ret;
1003 	struct rtfuncarg rtfarg;
1004 
1005 	ASSERT((!(match_flags & MATCH_IRE_ILL)) || (ill != NULL));
1006 	ASSERT(!(match_flags & MATCH_IRE_TYPE) || (ire_type != 0));
1007 
1008 	/* knobs such that routine is called only for v6 case */
1009 	if (ipftbl == ipst->ips_ip_forwarding_table_v6) {
1010 		for (i = (ftbl_sz - 1);  i >= 0; i--) {
1011 			if ((irb_ptr = ipftbl[i]) == NULL)
1012 				continue;
1013 			for (j = 0; j < htbl_sz; j++) {
1014 				irb = &irb_ptr[j];
1015 				if (irb->irb_ire == NULL)
1016 					continue;
1017 
1018 				irb_refhold(irb);
1019 				for (ire = irb->irb_ire; ire != NULL;
1020 				    ire = ire->ire_next) {
1021 					if (match_flags == 0 &&
1022 					    zoneid == ALL_ZONES) {
1023 						ret = B_TRUE;
1024 					} else {
1025 						ret =
1026 						    ire_walk_ill_match(
1027 						    match_flags,
1028 						    ire_type, ire, ill,
1029 						    zoneid, ipst);
1030 					}
1031 					if (ret)
1032 						(*func)(ire, arg);
1033 				}
1034 				irb_refrele(irb);
1035 			}
1036 		}
1037 	} else {
1038 		(void) memset(&rtfarg, 0, sizeof (rtfarg));
1039 		rtfarg.rt_func = func;
1040 		rtfarg.rt_arg = arg;
1041 		if (match_flags != 0) {
1042 			rtfarg.rt_match_flags = match_flags;
1043 		}
1044 		rtfarg.rt_ire_type = ire_type;
1045 		rtfarg.rt_ill = ill;
1046 		rtfarg.rt_zoneid = zoneid;
1047 		rtfarg.rt_ipst = ipst;	/* No netstack_hold */
1048 		(void) ipst->ips_ip_ftable->rnh_walktree_mt(
1049 		    ipst->ips_ip_ftable,
1050 		    rtfunc, &rtfarg, irb_refhold_rn, irb_refrele_rn);
1051 	}
1052 }
1053 
1054 /*
1055  * This function takes a mask and returns
1056  * number of bits set in the mask. If no
1057  * bit is set it returns 0.
1058  * Assumes a contiguous mask.
1059  */
1060 int
1061 ip_mask_to_plen(ipaddr_t mask)
1062 {
1063 	return (mask == 0 ? 0 : IP_ABITS - (ffs(ntohl(mask)) -1));
1064 }
1065 
1066 /*
1067  * Convert length for a mask to the mask.
1068  */
1069 ipaddr_t
1070 ip_plen_to_mask(uint_t masklen)
1071 {
1072 	if (masklen == 0)
1073 		return (0);
1074 
1075 	return (htonl(IP_HOST_MASK << (IP_ABITS - masklen)));
1076 }
1077 
1078 void
1079 ire_atomic_end(irb_t *irb_ptr, ire_t *ire)
1080 {
1081 	ill_t		*ill;
1082 
1083 	ill = ire->ire_ill;
1084 	if (ill != NULL)
1085 		mutex_exit(&ill->ill_lock);
1086 	rw_exit(&irb_ptr->irb_lock);
1087 }
1088 
1089 /*
1090  * ire_add_v[46] atomically make sure that the ill associated
1091  * with the new ire is not going away i.e., we check ILL_CONDEMNED.
1092  */
1093 int
1094 ire_atomic_start(irb_t *irb_ptr, ire_t *ire)
1095 {
1096 	ill_t		*ill;
1097 
1098 	ill = ire->ire_ill;
1099 
1100 	rw_enter(&irb_ptr->irb_lock, RW_WRITER);
1101 	if (ill != NULL) {
1102 		mutex_enter(&ill->ill_lock);
1103 
1104 		/*
1105 		 * Don't allow IRE's to be created on dying ills.
1106 		 */
1107 		if (ill->ill_state_flags & ILL_CONDEMNED) {
1108 			ire_atomic_end(irb_ptr, ire);
1109 			return (ENXIO);
1110 		}
1111 
1112 		if (IS_UNDER_IPMP(ill)) {
1113 			int	error = 0;
1114 			mutex_enter(&ill->ill_phyint->phyint_lock);
1115 			if (!ipmp_ill_is_active(ill) &&
1116 			    IRE_HIDDEN_TYPE(ire->ire_type) &&
1117 			    !ire->ire_testhidden) {
1118 				error = EINVAL;
1119 			}
1120 			mutex_exit(&ill->ill_phyint->phyint_lock);
1121 			if (error != 0) {
1122 				ire_atomic_end(irb_ptr, ire);
1123 				return (error);
1124 			}
1125 		}
1126 
1127 	}
1128 	return (0);
1129 }
1130 
1131 /*
1132  * Add a fully initialized IRE to the forwarding table.
1133  * This returns NULL on failure, or a held IRE on success.
1134  * Normally the returned IRE is the same as the argument. But a different
1135  * IRE will be returned if the added IRE is deemed identical to an existing
1136  * one. In that case ire_identical_ref will be increased.
1137  * The caller always needs to do an ire_refrele() on the returned IRE.
1138  */
1139 ire_t *
1140 ire_add(ire_t *ire)
1141 {
1142 	if (IRE_HIDDEN_TYPE(ire->ire_type) &&
1143 	    ire->ire_ill != NULL && IS_UNDER_IPMP(ire->ire_ill)) {
1144 		/*
1145 		 * IREs hosted on interfaces that are under IPMP
1146 		 * should be hidden so that applications don't
1147 		 * accidentally end up sending packets with test
1148 		 * addresses as their source addresses, or
1149 		 * sending out interfaces that are e.g. IFF_INACTIVE.
1150 		 * Hide them here.
1151 		 */
1152 		ire->ire_testhidden = B_TRUE;
1153 	}
1154 
1155 	if (ire->ire_ipversion == IPV6_VERSION)
1156 		return (ire_add_v6(ire));
1157 	else
1158 		return (ire_add_v4(ire));
1159 }
1160 
1161 /*
1162  * Add a fully initialized IPv4 IRE to the forwarding table.
1163  * This returns NULL on failure, or a held IRE on success.
1164  * Normally the returned IRE is the same as the argument. But a different
1165  * IRE will be returned if the added IRE is deemed identical to an existing
1166  * one. In that case ire_identical_ref will be increased.
1167  * The caller always needs to do an ire_refrele() on the returned IRE.
1168  */
1169 static ire_t *
1170 ire_add_v4(ire_t *ire)
1171 {
1172 	ire_t	*ire1;
1173 	irb_t	*irb_ptr;
1174 	ire_t	**irep;
1175 	int	match_flags;
1176 	int	error;
1177 	ip_stack_t	*ipst = ire->ire_ipst;
1178 
1179 	if (ire->ire_ill != NULL)
1180 		ASSERT(!MUTEX_HELD(&ire->ire_ill->ill_lock));
1181 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
1182 
1183 	/* Make sure the address is properly masked. */
1184 	ire->ire_addr &= ire->ire_mask;
1185 
1186 	match_flags = (MATCH_IRE_MASK | MATCH_IRE_TYPE | MATCH_IRE_GW);
1187 
1188 	if (ire->ire_ill != NULL) {
1189 		match_flags |= MATCH_IRE_ILL;
1190 	}
1191 	irb_ptr = ire_get_bucket(ire);
1192 	if (irb_ptr == NULL) {
1193 		printf("no bucket for %p\n", (void *)ire);
1194 		ire_delete(ire);
1195 		return (NULL);
1196 	}
1197 
1198 	/*
1199 	 * Start the atomic add of the ire. Grab the ill lock,
1200 	 * the bucket lock. Check for condemned.
1201 	 */
1202 	error = ire_atomic_start(irb_ptr, ire);
1203 	if (error != 0) {
1204 		printf("no ire_atomic_start for %p\n", (void *)ire);
1205 		ire_delete(ire);
1206 		irb_refrele(irb_ptr);
1207 		return (NULL);
1208 	}
1209 	/*
1210 	 * If we are creating a hidden IRE, make sure we search for
1211 	 * hidden IREs when searching for duplicates below.
1212 	 * Otherwise, we might find an IRE on some other interface
1213 	 * that's not marked hidden.
1214 	 */
1215 	if (ire->ire_testhidden)
1216 		match_flags |= MATCH_IRE_TESTHIDDEN;
1217 
1218 	/*
1219 	 * Atomically check for duplicate and insert in the table.
1220 	 */
1221 	for (ire1 = irb_ptr->irb_ire; ire1 != NULL; ire1 = ire1->ire_next) {
1222 		if (IRE_IS_CONDEMNED(ire1))
1223 			continue;
1224 		/*
1225 		 * Here we need an exact match on zoneid, i.e.,
1226 		 * ire_match_args doesn't fit.
1227 		 */
1228 		if (ire1->ire_zoneid != ire->ire_zoneid)
1229 			continue;
1230 
1231 		if (ire1->ire_type != ire->ire_type)
1232 			continue;
1233 
1234 		/*
1235 		 * Note: We do not allow multiple routes that differ only
1236 		 * in the gateway security attributes; such routes are
1237 		 * considered duplicates.
1238 		 * To change that we explicitly have to treat them as
1239 		 * different here.
1240 		 */
1241 		if (ire_match_args(ire1, ire->ire_addr, ire->ire_mask,
1242 		    ire->ire_gateway_addr, ire->ire_type, ire->ire_ill,
1243 		    ire->ire_zoneid, NULL, match_flags)) {
1244 			/*
1245 			 * Return the old ire after doing a REFHOLD.
1246 			 * As most of the callers continue to use the IRE
1247 			 * after adding, we return a held ire. This will
1248 			 * avoid a lookup in the caller again. If the callers
1249 			 * don't want to use it, they need to do a REFRELE.
1250 			 */
1251 			atomic_add_32(&ire1->ire_identical_ref, 1);
1252 			DTRACE_PROBE2(ire__add__exist, ire_t *, ire1,
1253 			    ire_t *, ire);
1254 			ire_refhold(ire1);
1255 			ire_atomic_end(irb_ptr, ire);
1256 			ire_delete(ire);
1257 			irb_refrele(irb_ptr);
1258 			return (ire1);
1259 		}
1260 	}
1261 
1262 	/*
1263 	 * Normally we do head insertion since most things do not care about
1264 	 * the order of the IREs in the bucket. Note that ip_cgtp_bcast_add
1265 	 * assumes we at least do head insertion so that its IRE_BROADCAST
1266 	 * arrive ahead of existing IRE_HOST for the same address.
1267 	 * However, due to shared-IP zones (and restrict_interzone_loopback)
1268 	 * we can have an IRE_LOCAL as well as IRE_IF_CLONE for the same
1269 	 * address. For that reason we do tail insertion for IRE_IF_CLONE.
1270 	 * Due to the IRE_BROADCAST on cgtp0, which must be last in the bucket,
1271 	 * we do tail insertion of IRE_BROADCASTs that do not have RTF_MULTIRT
1272 	 * set.
1273 	 */
1274 	irep = (ire_t **)irb_ptr;
1275 	if ((ire->ire_type & IRE_IF_CLONE) ||
1276 	    ((ire->ire_type & IRE_BROADCAST) &&
1277 	    !(ire->ire_flags & RTF_MULTIRT))) {
1278 		while ((ire1 = *irep) != NULL)
1279 			irep = &ire1->ire_next;
1280 	}
1281 	/* Insert at *irep */
1282 	ire1 = *irep;
1283 	if (ire1 != NULL)
1284 		ire1->ire_ptpn = &ire->ire_next;
1285 	ire->ire_next = ire1;
1286 	/* Link the new one in. */
1287 	ire->ire_ptpn = irep;
1288 
1289 	/*
1290 	 * ire_walk routines de-reference ire_next without holding
1291 	 * a lock. Before we point to the new ire, we want to make
1292 	 * sure the store that sets the ire_next of the new ire
1293 	 * reaches global visibility, so that ire_walk routines
1294 	 * don't see a truncated list of ires i.e if the ire_next
1295 	 * of the new ire gets set after we do "*irep = ire" due
1296 	 * to re-ordering, the ire_walk thread will see a NULL
1297 	 * once it accesses the ire_next of the new ire.
1298 	 * membar_producer() makes sure that the following store
1299 	 * happens *after* all of the above stores.
1300 	 */
1301 	membar_producer();
1302 	*irep = ire;
1303 	ire->ire_bucket = irb_ptr;
1304 	/*
1305 	 * We return a bumped up IRE above. Keep it symmetrical
1306 	 * so that the callers will always have to release. This
1307 	 * helps the callers of this function because they continue
1308 	 * to use the IRE after adding and hence they don't have to
1309 	 * lookup again after we return the IRE.
1310 	 *
1311 	 * NOTE : We don't have to use atomics as this is appearing
1312 	 * in the list for the first time and no one else can bump
1313 	 * up the reference count on this yet.
1314 	 */
1315 	ire_refhold_locked(ire);
1316 	BUMP_IRE_STATS(ipst->ips_ire_stats_v4, ire_stats_inserted);
1317 
1318 	irb_ptr->irb_ire_cnt++;
1319 	if (irb_ptr->irb_marks & IRB_MARK_DYNAMIC)
1320 		irb_ptr->irb_nire++;
1321 
1322 	if (ire->ire_ill != NULL) {
1323 		ire->ire_ill->ill_ire_cnt++;
1324 		ASSERT(ire->ire_ill->ill_ire_cnt != 0);	/* Wraparound */
1325 	}
1326 
1327 	ire_atomic_end(irb_ptr, ire);
1328 
1329 	/* Make any caching of the IREs be notified or updated */
1330 	ire_flush_cache_v4(ire, IRE_FLUSH_ADD);
1331 
1332 	if (ire->ire_ill != NULL)
1333 		ASSERT(!MUTEX_HELD(&ire->ire_ill->ill_lock));
1334 	irb_refrele(irb_ptr);
1335 	return (ire);
1336 }
1337 
1338 /*
1339  * irb_refrele is the only caller of the function. ire_unlink calls to
1340  * do the final cleanup for this ire.
1341  */
1342 void
1343 ire_cleanup(ire_t *ire)
1344 {
1345 	ire_t *ire_next;
1346 	ip_stack_t *ipst = ire->ire_ipst;
1347 
1348 	ASSERT(ire != NULL);
1349 
1350 	while (ire != NULL) {
1351 		ire_next = ire->ire_next;
1352 		if (ire->ire_ipversion == IPV4_VERSION) {
1353 			ire_delete_v4(ire);
1354 			BUMP_IRE_STATS(ipst->ips_ire_stats_v4,
1355 			    ire_stats_deleted);
1356 		} else {
1357 			ASSERT(ire->ire_ipversion == IPV6_VERSION);
1358 			ire_delete_v6(ire);
1359 			BUMP_IRE_STATS(ipst->ips_ire_stats_v6,
1360 			    ire_stats_deleted);
1361 		}
1362 		/*
1363 		 * Now it's really out of the list. Before doing the
1364 		 * REFRELE, set ire_next to NULL as ire_inactive asserts
1365 		 * so.
1366 		 */
1367 		ire->ire_next = NULL;
1368 		ire_refrele_notr(ire);
1369 		ire = ire_next;
1370 	}
1371 }
1372 
1373 /*
1374  * irb_refrele is the only caller of the function. It calls to unlink
1375  * all the CONDEMNED ires from this bucket.
1376  */
1377 ire_t *
1378 ire_unlink(irb_t *irb)
1379 {
1380 	ire_t *ire;
1381 	ire_t *ire1;
1382 	ire_t **ptpn;
1383 	ire_t *ire_list = NULL;
1384 
1385 	ASSERT(RW_WRITE_HELD(&irb->irb_lock));
1386 	ASSERT(((irb->irb_marks & IRB_MARK_DYNAMIC) && irb->irb_refcnt == 1) ||
1387 	    (irb->irb_refcnt == 0));
1388 	ASSERT(irb->irb_marks & IRB_MARK_CONDEMNED);
1389 	ASSERT(irb->irb_ire != NULL);
1390 
1391 	for (ire = irb->irb_ire; ire != NULL; ire = ire1) {
1392 		ire1 = ire->ire_next;
1393 		if (IRE_IS_CONDEMNED(ire)) {
1394 			ptpn = ire->ire_ptpn;
1395 			ire1 = ire->ire_next;
1396 			if (ire1)
1397 				ire1->ire_ptpn = ptpn;
1398 			*ptpn = ire1;
1399 			ire->ire_ptpn = NULL;
1400 			ire->ire_next = NULL;
1401 
1402 			/*
1403 			 * We need to call ire_delete_v4 or ire_delete_v6 to
1404 			 * clean up dependents and the redirects pointing at
1405 			 * the default gateway. We need to drop the lock
1406 			 * as ire_flush_cache/ire_delete_host_redircts require
1407 			 * so. But we can't drop the lock, as ire_unlink needs
1408 			 * to atomically remove the ires from the list.
1409 			 * So, create a temporary list of CONDEMNED ires
1410 			 * for doing ire_delete_v4/ire_delete_v6 operations
1411 			 * later on.
1412 			 */
1413 			ire->ire_next = ire_list;
1414 			ire_list = ire;
1415 		}
1416 	}
1417 	irb->irb_marks &= ~IRB_MARK_CONDEMNED;
1418 	return (ire_list);
1419 }
1420 
1421 /*
1422  * Clean up the radix node for this ire. Must be called by irb_refrele
1423  * when there are no ire's left in the bucket. Returns TRUE if the bucket
1424  * is deleted and freed.
1425  */
1426 boolean_t
1427 irb_inactive(irb_t *irb)
1428 {
1429 	struct rt_entry *rt;
1430 	struct radix_node *rn;
1431 	ip_stack_t *ipst = irb->irb_ipst;
1432 
1433 	ASSERT(irb->irb_ipst != NULL);
1434 
1435 	rt = IRB2RT(irb);
1436 	rn = (struct radix_node *)rt;
1437 
1438 	/* first remove it from the radix tree. */
1439 	RADIX_NODE_HEAD_WLOCK(ipst->ips_ip_ftable);
1440 	rw_enter(&irb->irb_lock, RW_WRITER);
1441 	if (irb->irb_refcnt == 1 && irb->irb_nire == 0) {
1442 		rn = ipst->ips_ip_ftable->rnh_deladdr(rn->rn_key, rn->rn_mask,
1443 		    ipst->ips_ip_ftable);
1444 		DTRACE_PROBE1(irb__free, rt_t *,  rt);
1445 		ASSERT((void *)rn == (void *)rt);
1446 		Free(rt, rt_entry_cache);
1447 		/* irb_lock is freed */
1448 		RADIX_NODE_HEAD_UNLOCK(ipst->ips_ip_ftable);
1449 		return (B_TRUE);
1450 	}
1451 	rw_exit(&irb->irb_lock);
1452 	RADIX_NODE_HEAD_UNLOCK(ipst->ips_ip_ftable);
1453 	return (B_FALSE);
1454 }
1455 
1456 /*
1457  * Delete the specified IRE.
1458  * We assume that if ire_bucket is not set then ire_ill->ill_ire_cnt was
1459  * not incremented i.e., that the insertion in the bucket and the increment
1460  * of that counter is done atomically.
1461  */
1462 void
1463 ire_delete(ire_t *ire)
1464 {
1465 	ire_t	*ire1;
1466 	ire_t	**ptpn;
1467 	irb_t	*irb;
1468 	nce_t	*nce;
1469 	ip_stack_t	*ipst = ire->ire_ipst;
1470 
1471 	/* We can clear ire_nce_cache under ire_lock even if the IRE is used */
1472 	mutex_enter(&ire->ire_lock);
1473 	nce = ire->ire_nce_cache;
1474 	ire->ire_nce_cache = NULL;
1475 	mutex_exit(&ire->ire_lock);
1476 	if (nce != NULL)
1477 		nce_refrele(nce);
1478 
1479 	if ((irb = ire->ire_bucket) == NULL) {
1480 		/*
1481 		 * It was never inserted in the list. Should call REFRELE
1482 		 * to free this IRE.
1483 		 */
1484 		ire_refrele_notr(ire);
1485 		return;
1486 	}
1487 
1488 	/*
1489 	 * Move the use counts from an IRE_IF_CLONE to its parent
1490 	 * IRE_INTERFACE.
1491 	 * We need to do this before acquiring irb_lock.
1492 	 */
1493 	if (ire->ire_type & IRE_IF_CLONE) {
1494 		ire_t *parent;
1495 
1496 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
1497 		if ((parent = ire->ire_dep_parent) != NULL) {
1498 			parent->ire_ob_pkt_count += ire->ire_ob_pkt_count;
1499 			parent->ire_ib_pkt_count += ire->ire_ib_pkt_count;
1500 			ire->ire_ob_pkt_count = 0;
1501 			ire->ire_ib_pkt_count = 0;
1502 		}
1503 		rw_exit(&ipst->ips_ire_dep_lock);
1504 	}
1505 
1506 	rw_enter(&irb->irb_lock, RW_WRITER);
1507 	if (ire->ire_ptpn == NULL) {
1508 		/*
1509 		 * Some other thread has removed us from the list.
1510 		 * It should have done the REFRELE for us.
1511 		 */
1512 		rw_exit(&irb->irb_lock);
1513 		return;
1514 	}
1515 
1516 	if (!IRE_IS_CONDEMNED(ire)) {
1517 		/* Is this an IRE representing multiple duplicate entries? */
1518 		ASSERT(ire->ire_identical_ref >= 1);
1519 		if (atomic_add_32_nv(&ire->ire_identical_ref, -1) != 0) {
1520 			/* Removed one of the identical parties */
1521 			rw_exit(&irb->irb_lock);
1522 			return;
1523 		}
1524 
1525 		irb->irb_ire_cnt--;
1526 		ire_make_condemned(ire);
1527 	}
1528 
1529 	if (irb->irb_refcnt != 0) {
1530 		/*
1531 		 * The last thread to leave this bucket will
1532 		 * delete this ire.
1533 		 */
1534 		irb->irb_marks |= IRB_MARK_CONDEMNED;
1535 		rw_exit(&irb->irb_lock);
1536 		return;
1537 	}
1538 
1539 	/*
1540 	 * Normally to delete an ire, we walk the bucket. While we
1541 	 * walk the bucket, we normally bump up irb_refcnt and hence
1542 	 * we return from above where we mark CONDEMNED and the ire
1543 	 * gets deleted from ire_unlink. This case is where somebody
1544 	 * knows the ire e.g by doing a lookup, and wants to delete the
1545 	 * IRE. irb_refcnt would be 0 in this case if nobody is walking
1546 	 * the bucket.
1547 	 */
1548 	ptpn = ire->ire_ptpn;
1549 	ire1 = ire->ire_next;
1550 	if (ire1 != NULL)
1551 		ire1->ire_ptpn = ptpn;
1552 	ASSERT(ptpn != NULL);
1553 	*ptpn = ire1;
1554 	ire->ire_ptpn = NULL;
1555 	ire->ire_next = NULL;
1556 	if (ire->ire_ipversion == IPV6_VERSION) {
1557 		BUMP_IRE_STATS(ipst->ips_ire_stats_v6, ire_stats_deleted);
1558 	} else {
1559 		BUMP_IRE_STATS(ipst->ips_ire_stats_v4, ire_stats_deleted);
1560 	}
1561 	rw_exit(&irb->irb_lock);
1562 
1563 	/* Cleanup dependents and related stuff */
1564 	if (ire->ire_ipversion == IPV6_VERSION) {
1565 		ire_delete_v6(ire);
1566 	} else {
1567 		ire_delete_v4(ire);
1568 	}
1569 	/*
1570 	 * We removed it from the list. Decrement the
1571 	 * reference count.
1572 	 */
1573 	ire_refrele_notr(ire);
1574 }
1575 
1576 /*
1577  * Delete the specified IRE.
1578  * All calls should use ire_delete().
1579  * Sometimes called as writer though not required by this function.
1580  *
1581  * NOTE : This function is called only if the ire was added
1582  * in the list.
1583  */
1584 static void
1585 ire_delete_v4(ire_t *ire)
1586 {
1587 	ip_stack_t	*ipst = ire->ire_ipst;
1588 
1589 	ASSERT(ire->ire_refcnt >= 1);
1590 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
1591 
1592 	ire_flush_cache_v4(ire, IRE_FLUSH_DELETE);
1593 	if (ire->ire_type == IRE_DEFAULT) {
1594 		/*
1595 		 * when a default gateway is going away
1596 		 * delete all the host redirects pointing at that
1597 		 * gateway.
1598 		 */
1599 		ire_delete_host_redirects(ire->ire_gateway_addr, ipst);
1600 	}
1601 
1602 	/*
1603 	 * If we are deleting an IRE_INTERFACE then we make sure we also
1604 	 * delete any IRE_IF_CLONE that has been created from it.
1605 	 * Those are always in ire_dep_children.
1606 	 */
1607 	if ((ire->ire_type & IRE_INTERFACE) && ire->ire_dep_children != NULL)
1608 		ire_dep_delete_if_clone(ire);
1609 
1610 	/* Remove from parent dependencies and child */
1611 	rw_enter(&ipst->ips_ire_dep_lock, RW_WRITER);
1612 	if (ire->ire_dep_parent != NULL)
1613 		ire_dep_remove(ire);
1614 
1615 	while (ire->ire_dep_children != NULL)
1616 		ire_dep_remove(ire->ire_dep_children);
1617 	rw_exit(&ipst->ips_ire_dep_lock);
1618 }
1619 
1620 /*
1621  * ire_refrele is the only caller of the function. It calls
1622  * to free the ire when the reference count goes to zero.
1623  */
1624 void
1625 ire_inactive(ire_t *ire)
1626 {
1627 	ill_t	*ill;
1628 	irb_t 	*irb;
1629 	ip_stack_t	*ipst = ire->ire_ipst;
1630 
1631 	ASSERT(ire->ire_refcnt == 0);
1632 	ASSERT(ire->ire_ptpn == NULL);
1633 	ASSERT(ire->ire_next == NULL);
1634 
1635 	/* Count how many condemned ires for kmem_cache callback */
1636 	if (IRE_IS_CONDEMNED(ire))
1637 		atomic_add_32(&ipst->ips_num_ire_condemned, -1);
1638 
1639 	if (ire->ire_gw_secattr != NULL) {
1640 		ire_gw_secattr_free(ire->ire_gw_secattr);
1641 		ire->ire_gw_secattr = NULL;
1642 	}
1643 
1644 	/*
1645 	 * ire_nce_cache is cleared in ire_delete, and we make sure we don't
1646 	 * set it once the ire is marked condemned.
1647 	 */
1648 	ASSERT(ire->ire_nce_cache == NULL);
1649 
1650 	/*
1651 	 * Since any parent would have a refhold on us they would already
1652 	 * have been removed.
1653 	 */
1654 	ASSERT(ire->ire_dep_parent == NULL);
1655 	ASSERT(ire->ire_dep_sib_next == NULL);
1656 	ASSERT(ire->ire_dep_sib_ptpn == NULL);
1657 
1658 	/*
1659 	 * Since any children would have a refhold on us they should have
1660 	 * already been removed.
1661 	 */
1662 	ASSERT(ire->ire_dep_children == NULL);
1663 
1664 	/*
1665 	 * ill_ire_ref is increased when the IRE is inserted in the
1666 	 * bucket - not when the IRE is created.
1667 	 */
1668 	irb = ire->ire_bucket;
1669 	ill = ire->ire_ill;
1670 	if (irb != NULL && ill != NULL) {
1671 		mutex_enter(&ill->ill_lock);
1672 		ASSERT(ill->ill_ire_cnt != 0);
1673 		DTRACE_PROBE3(ill__decr__cnt, (ill_t *), ill,
1674 		    (char *), "ire", (void *), ire);
1675 		ill->ill_ire_cnt--;
1676 		if (ILL_DOWN_OK(ill)) {
1677 			/* Drops the ill lock */
1678 			ipif_ill_refrele_tail(ill);
1679 		} else {
1680 			mutex_exit(&ill->ill_lock);
1681 		}
1682 	}
1683 	ire->ire_ill = NULL;
1684 
1685 	/* This should be true for both V4 and V6 */
1686 	if (irb != NULL && (irb->irb_marks & IRB_MARK_DYNAMIC)) {
1687 		rw_enter(&irb->irb_lock, RW_WRITER);
1688 		irb->irb_nire--;
1689 		/*
1690 		 * Instead of examining the conditions for freeing
1691 		 * the radix node here, we do it by calling
1692 		 * irb_refrele which is a single point in the code
1693 		 * that embeds that logic. Bump up the refcnt to
1694 		 * be able to call irb_refrele
1695 		 */
1696 		irb_refhold_locked(irb);
1697 		rw_exit(&irb->irb_lock);
1698 		irb_refrele(irb);
1699 	}
1700 
1701 #ifdef DEBUG
1702 	ire_trace_cleanup(ire);
1703 #endif
1704 	mutex_destroy(&ire->ire_lock);
1705 	if (ire->ire_ipversion == IPV6_VERSION) {
1706 		BUMP_IRE_STATS(ipst->ips_ire_stats_v6, ire_stats_freed);
1707 	} else {
1708 		BUMP_IRE_STATS(ipst->ips_ire_stats_v4, ire_stats_freed);
1709 	}
1710 	kmem_cache_free(ire_cache, ire);
1711 }
1712 
1713 /*
1714  * ire_update_generation is the callback function provided by
1715  * ire_get_bucket() to update the generation number of any
1716  * matching shorter route when a new route is added.
1717  *
1718  * This fucntion always returns a failure return (B_FALSE)
1719  * to force the caller (rn_matchaddr_args)
1720  * to back-track up the tree looking for shorter matches.
1721  */
1722 /* ARGSUSED */
1723 static boolean_t
1724 ire_update_generation(struct radix_node *rn, void *arg)
1725 {
1726 	struct rt_entry *rt = (struct rt_entry *)rn;
1727 
1728 	/* We need to handle all in the same bucket */
1729 	irb_increment_generation(&rt->rt_irb);
1730 	return (B_FALSE);
1731 }
1732 
1733 /*
1734  * Take care of all the generation numbers in the bucket.
1735  */
1736 void
1737 irb_increment_generation(irb_t *irb)
1738 {
1739 	ire_t *ire;
1740 
1741 	if (irb == NULL || irb->irb_ire_cnt == 0)
1742 		return;
1743 
1744 	irb_refhold(irb);
1745 	for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
1746 		if (!IRE_IS_CONDEMNED(ire))
1747 			ire_increment_generation(ire);	/* Ourselves */
1748 		ire_dep_incr_generation(ire);	/* Dependants */
1749 	}
1750 	irb_refrele(irb);
1751 }
1752 
1753 /*
1754  * When an IRE is added or deleted this routine is called to make sure
1755  * any caching of IRE information is notified or updated.
1756  *
1757  * The flag argument indicates if the flush request is due to addition
1758  * of new route (IRE_FLUSH_ADD), deletion of old route (IRE_FLUSH_DELETE),
1759  * or a change to ire_gateway_addr (IRE_FLUSH_GWCHANGE).
1760  */
1761 void
1762 ire_flush_cache_v4(ire_t *ire, int flag)
1763 {
1764 	irb_t *irb = ire->ire_bucket;
1765 	struct rt_entry *rt = IRB2RT(irb);
1766 	ip_stack_t *ipst = ire->ire_ipst;
1767 
1768 	/*
1769 	 * IRE_IF_CLONE ire's don't provide any new information
1770 	 * than the parent from which they are cloned, so don't
1771 	 * perturb the generation numbers.
1772 	 */
1773 	if (ire->ire_type & IRE_IF_CLONE)
1774 		return;
1775 
1776 	/*
1777 	 * Ensure that an ire_add during a lookup serializes the updates of the
1778 	 * generation numbers under the radix head lock so that the lookup gets
1779 	 * either the old ire and old generation number, or a new ire and new
1780 	 * generation number.
1781 	 */
1782 	RADIX_NODE_HEAD_WLOCK(ipst->ips_ip_ftable);
1783 
1784 	/*
1785 	 * If a route was just added, we need to notify everybody that
1786 	 * has cached an IRE_NOROUTE since there might now be a better
1787 	 * route for them.
1788 	 */
1789 	if (flag == IRE_FLUSH_ADD) {
1790 		ire_increment_generation(ipst->ips_ire_reject_v4);
1791 		ire_increment_generation(ipst->ips_ire_blackhole_v4);
1792 	}
1793 
1794 	/* Adding a default can't otherwise provide a better route */
1795 	if (ire->ire_type == IRE_DEFAULT && flag == IRE_FLUSH_ADD) {
1796 		RADIX_NODE_HEAD_UNLOCK(ipst->ips_ip_ftable);
1797 		return;
1798 	}
1799 
1800 	switch (flag) {
1801 	case IRE_FLUSH_DELETE:
1802 	case IRE_FLUSH_GWCHANGE:
1803 		/*
1804 		 * Update ire_generation for all ire_dep_children chains
1805 		 * starting with this IRE
1806 		 */
1807 		ire_dep_incr_generation(ire);
1808 		break;
1809 	case IRE_FLUSH_ADD:
1810 		/*
1811 		 * Update the generation numbers of all shorter matching routes.
1812 		 * ire_update_generation takes care of the dependants by
1813 		 * using ire_dep_incr_generation.
1814 		 */
1815 		(void) ipst->ips_ip_ftable->rnh_matchaddr_args(&rt->rt_dst,
1816 		    ipst->ips_ip_ftable, ire_update_generation, NULL);
1817 		break;
1818 	}
1819 	RADIX_NODE_HEAD_UNLOCK(ipst->ips_ip_ftable);
1820 }
1821 
1822 /*
1823  * Matches the arguments passed with the values in the ire.
1824  *
1825  * Note: for match types that match using "ill" passed in, ill
1826  * must be checked for non-NULL before calling this routine.
1827  */
1828 boolean_t
1829 ire_match_args(ire_t *ire, ipaddr_t addr, ipaddr_t mask, ipaddr_t gateway,
1830     int type, const ill_t *ill, zoneid_t zoneid,
1831     const ts_label_t *tsl, int match_flags)
1832 {
1833 	ill_t *ire_ill = NULL, *dst_ill;
1834 	ip_stack_t *ipst = ire->ire_ipst;
1835 
1836 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
1837 	ASSERT((ire->ire_addr & ~ire->ire_mask) == 0);
1838 	ASSERT((!(match_flags & MATCH_IRE_ILL)) ||
1839 	    (ill != NULL && !ill->ill_isv6));
1840 
1841 	/*
1842 	 * If MATCH_IRE_TESTHIDDEN is set, then only return the IRE if it is
1843 	 * in fact hidden, to ensure the caller gets the right one.
1844 	 */
1845 	if (ire->ire_testhidden) {
1846 		if (!(match_flags & MATCH_IRE_TESTHIDDEN))
1847 			return (B_FALSE);
1848 	}
1849 
1850 	if (zoneid != ALL_ZONES && zoneid != ire->ire_zoneid &&
1851 	    ire->ire_zoneid != ALL_ZONES) {
1852 		/*
1853 		 * If MATCH_IRE_ZONEONLY has been set and the supplied zoneid
1854 		 * does not match that of ire_zoneid, a failure to
1855 		 * match is reported at this point. Otherwise, since some IREs
1856 		 * that are available in the global zone can be used in local
1857 		 * zones, additional checks need to be performed:
1858 		 *
1859 		 * IRE_LOOPBACK
1860 		 *	entries should never be matched in this situation.
1861 		 *	Each zone has its own IRE_LOOPBACK.
1862 		 *
1863 		 * IRE_LOCAL
1864 		 *	We allow them for any zoneid. ire_route_recursive
1865 		 *	does additional checks when
1866 		 *	ip_restrict_interzone_loopback is set.
1867 		 *
1868 		 * If ill_usesrc_ifindex is set
1869 		 *	Then we check if the zone has a valid source address
1870 		 *	on the usesrc ill.
1871 		 *
1872 		 * If ire_ill is set, then check that the zone has an ipif
1873 		 *	on that ill.
1874 		 *
1875 		 * Outside of this function (in ire_round_robin) we check
1876 		 * that any IRE_OFFLINK has a gateway that reachable from the
1877 		 * zone when we have multiple choices (ECMP).
1878 		 */
1879 		if (match_flags & MATCH_IRE_ZONEONLY)
1880 			return (B_FALSE);
1881 		if (ire->ire_type & IRE_LOOPBACK)
1882 			return (B_FALSE);
1883 
1884 		if (ire->ire_type & IRE_LOCAL)
1885 			goto matchit;
1886 
1887 		/*
1888 		 * The normal case of IRE_ONLINK has a matching zoneid.
1889 		 * Here we handle the case when shared-IP zones have been
1890 		 * configured with IP addresses on vniN. In that case it
1891 		 * is ok for traffic from a zone to use IRE_ONLINK routes
1892 		 * if the ill has a usesrc pointing at vniN
1893 		 */
1894 		dst_ill = ire->ire_ill;
1895 		if (ire->ire_type & IRE_ONLINK) {
1896 			uint_t	ifindex;
1897 
1898 			/*
1899 			 * Note there is no IRE_INTERFACE on vniN thus
1900 			 * can't do an IRE lookup for a matching route.
1901 			 */
1902 			ifindex = dst_ill->ill_usesrc_ifindex;
1903 			if (ifindex == 0)
1904 				return (B_FALSE);
1905 
1906 			/*
1907 			 * If there is a usable source address in the
1908 			 * zone, then it's ok to return this IRE_INTERFACE
1909 			 */
1910 			if (!ipif_zone_avail(ifindex, dst_ill->ill_isv6,
1911 			    zoneid, ipst)) {
1912 				ip3dbg(("ire_match_args: no usrsrc for zone"
1913 				    " dst_ill %p\n", (void *)dst_ill));
1914 				return (B_FALSE);
1915 			}
1916 		}
1917 		/*
1918 		 * For exampe, with
1919 		 * route add 11.0.0.0 gw1 -ifp bge0
1920 		 * route add 11.0.0.0 gw2 -ifp bge1
1921 		 * this code would differentiate based on
1922 		 * where the sending zone has addresses.
1923 		 * Only if the zone has an address on bge0 can it use the first
1924 		 * route. It isn't clear if this behavior is documented
1925 		 * anywhere.
1926 		 */
1927 		if (dst_ill != NULL && (ire->ire_type & IRE_OFFLINK)) {
1928 			ipif_t	*tipif;
1929 
1930 			mutex_enter(&dst_ill->ill_lock);
1931 			for (tipif = dst_ill->ill_ipif;
1932 			    tipif != NULL; tipif = tipif->ipif_next) {
1933 				if (!IPIF_IS_CONDEMNED(tipif) &&
1934 				    (tipif->ipif_flags & IPIF_UP) &&
1935 				    (tipif->ipif_zoneid == zoneid ||
1936 				    tipif->ipif_zoneid == ALL_ZONES))
1937 					break;
1938 			}
1939 			mutex_exit(&dst_ill->ill_lock);
1940 			if (tipif == NULL) {
1941 				return (B_FALSE);
1942 			}
1943 		}
1944 	}
1945 
1946 matchit:
1947 	if (match_flags & MATCH_IRE_ILL) {
1948 		ire_ill = ire->ire_ill;
1949 
1950 		/*
1951 		 * If asked to match an ill, we *must* match
1952 		 * on the ire_ill for ipmp test addresses, or
1953 		 * any of the ill in the group for data addresses.
1954 		 * If we don't, we may as well fail.
1955 		 * However, we need an exception for IRE_LOCALs to ensure
1956 		 * we loopback packets even sent to test addresses on different
1957 		 * interfaces in the group.
1958 		 */
1959 		if ((match_flags & MATCH_IRE_TESTHIDDEN) &&
1960 		    !(ire->ire_type & IRE_LOCAL)) {
1961 			if (ire->ire_ill != ill)
1962 				return (B_FALSE);
1963 		} else  {
1964 			match_flags &= ~MATCH_IRE_TESTHIDDEN;
1965 			/*
1966 			 * We know that ill is not NULL, but ire_ill could be
1967 			 * NULL
1968 			 */
1969 			if (ire_ill == NULL || !IS_ON_SAME_LAN(ill, ire_ill))
1970 				return (B_FALSE);
1971 		}
1972 	}
1973 
1974 	if ((ire->ire_addr == (addr & mask)) &&
1975 	    ((!(match_flags & MATCH_IRE_GW)) ||
1976 	    (ire->ire_gateway_addr == gateway)) &&
1977 	    ((!(match_flags & MATCH_IRE_TYPE)) || (ire->ire_type & type)) &&
1978 	    ((!(match_flags & MATCH_IRE_TESTHIDDEN)) || ire->ire_testhidden) &&
1979 	    ((!(match_flags & MATCH_IRE_MASK)) || (ire->ire_mask == mask)) &&
1980 	    ((!(match_flags & MATCH_IRE_SECATTR)) ||
1981 	    (!is_system_labeled()) ||
1982 	    (tsol_ire_match_gwattr(ire, tsl) == 0))) {
1983 		/* We found the matched IRE */
1984 		return (B_TRUE);
1985 	}
1986 	return (B_FALSE);
1987 }
1988 
1989 /*
1990  * Check if the IRE_LOCAL uses the same ill as another route would use.
1991  * If there is no alternate route, or the alternate is a REJECT or BLACKHOLE,
1992  * then we don't allow this IRE_LOCAL to be used.
1993  * We always return an IRE; will be RTF_REJECT if no route available.
1994  */
1995 ire_t *
1996 ire_alt_local(ire_t *ire, zoneid_t zoneid, const ts_label_t *tsl,
1997     const ill_t *ill, uint_t *generationp)
1998 {
1999 	ip_stack_t	*ipst = ire->ire_ipst;
2000 	ire_t		*alt_ire;
2001 	uint_t		ire_type;
2002 	uint_t		generation;
2003 	uint_t		match_flags;
2004 
2005 	ASSERT(ire->ire_type & IRE_LOCAL);
2006 	ASSERT(ire->ire_ill != NULL);
2007 
2008 	/*
2009 	 * Need to match on everything but local.
2010 	 * This might result in the creation of a IRE_IF_CLONE for the
2011 	 * same address as the IRE_LOCAL when restrict_interzone_loopback is
2012 	 * set. ire_add_*() ensures that the IRE_IF_CLONE are tail inserted
2013 	 * to make sure the IRE_LOCAL is always found first.
2014 	 */
2015 	ire_type = (IRE_ONLINK | IRE_OFFLINK) & ~(IRE_LOCAL|IRE_LOOPBACK);
2016 	match_flags = MATCH_IRE_TYPE | MATCH_IRE_SECATTR;
2017 	if (ill != NULL)
2018 		match_flags |= MATCH_IRE_ILL;
2019 
2020 	if (ire->ire_ipversion == IPV4_VERSION) {
2021 		alt_ire = ire_route_recursive_v4(ire->ire_addr, ire_type,
2022 		    ill, zoneid, tsl, match_flags, B_TRUE, 0, ipst, NULL, NULL,
2023 		    &generation);
2024 	} else {
2025 		alt_ire = ire_route_recursive_v6(&ire->ire_addr_v6, ire_type,
2026 		    ill, zoneid, tsl, match_flags, B_TRUE, 0, ipst, NULL, NULL,
2027 		    &generation);
2028 	}
2029 	ASSERT(alt_ire != NULL);
2030 
2031 	if (alt_ire->ire_ill == ire->ire_ill) {
2032 		/* Going out the same ILL - ok to send to IRE_LOCAL */
2033 		ire_refrele(alt_ire);
2034 	} else {
2035 		/* Different ill - ignore IRE_LOCAL */
2036 		ire_refrele(ire);
2037 		ire = alt_ire;
2038 		if (generationp != NULL)
2039 			*generationp = generation;
2040 	}
2041 	return (ire);
2042 }
2043 
2044 boolean_t
2045 ire_find_zoneid(struct radix_node *rn, void *arg)
2046 {
2047 	struct rt_entry *rt = (struct rt_entry *)rn;
2048 	irb_t *irb;
2049 	ire_t *ire;
2050 	ire_ftable_args_t *margs = arg;
2051 
2052 	ASSERT(rt != NULL);
2053 
2054 	irb = &rt->rt_irb;
2055 
2056 	if (irb->irb_ire_cnt == 0)
2057 		return (B_FALSE);
2058 
2059 	rw_enter(&irb->irb_lock, RW_READER);
2060 	for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
2061 		if (IRE_IS_CONDEMNED(ire))
2062 			continue;
2063 
2064 		if (ire->ire_zoneid != ALL_ZONES &&
2065 		    ire->ire_zoneid != margs->ift_zoneid)
2066 			continue;
2067 
2068 		if (margs->ift_ill != NULL && margs->ift_ill != ire->ire_ill)
2069 			continue;
2070 
2071 		if (is_system_labeled() &&
2072 		    tsol_ire_match_gwattr(ire, margs->ift_tsl) != 0)
2073 			continue;
2074 
2075 		rw_exit(&irb->irb_lock);
2076 		return (B_TRUE);
2077 	}
2078 	rw_exit(&irb->irb_lock);
2079 	return (B_FALSE);
2080 }
2081 
2082 /*
2083  * Check if the zoneid (not ALL_ZONES) has an IRE_INTERFACE for the specified
2084  * gateway address. If ill is non-NULL we also match on it.
2085  * The caller must hold a read lock on RADIX_NODE_HEAD if lock_held is set.
2086  */
2087 boolean_t
2088 ire_gateway_ok_zone_v4(ipaddr_t gateway, zoneid_t zoneid, ill_t *ill,
2089     const ts_label_t *tsl, ip_stack_t *ipst, boolean_t lock_held)
2090 {
2091 	struct rt_sockaddr rdst;
2092 	struct rt_entry *rt;
2093 	ire_ftable_args_t margs;
2094 
2095 	ASSERT(ill == NULL || !ill->ill_isv6);
2096 	if (lock_held)
2097 		ASSERT(RW_READ_HELD(&ipst->ips_ip_ftable->rnh_lock));
2098 	else
2099 		RADIX_NODE_HEAD_RLOCK(ipst->ips_ip_ftable);
2100 
2101 	rdst.rt_sin_len = sizeof (rdst);
2102 	rdst.rt_sin_family = AF_INET;
2103 	rdst.rt_sin_addr.s_addr = gateway;
2104 
2105 	/*
2106 	 * We only use margs for ill, zoneid, and tsl matching in
2107 	 * ire_find_zoneid
2108 	 */
2109 	(void) memset(&margs, 0, sizeof (margs));
2110 	margs.ift_ill = ill;
2111 	margs.ift_zoneid = zoneid;
2112 	margs.ift_tsl = tsl;
2113 	rt = (struct rt_entry *)ipst->ips_ip_ftable->rnh_matchaddr_args(&rdst,
2114 	    ipst->ips_ip_ftable, ire_find_zoneid, (void *)&margs);
2115 
2116 	if (!lock_held)
2117 		RADIX_NODE_HEAD_UNLOCK(ipst->ips_ip_ftable);
2118 
2119 	return (rt != NULL);
2120 }
2121 
2122 /*
2123  * ire_walk routine to delete a fraction of redirect IREs and IRE_CLONE_IF IREs.
2124  * The fraction argument tells us what fraction of the IREs to delete.
2125  * Common for IPv4 and IPv6.
2126  * Used when memory backpressure.
2127  */
2128 static void
2129 ire_delete_reclaim(ire_t *ire, char *arg)
2130 {
2131 	ip_stack_t	*ipst = ire->ire_ipst;
2132 	uint_t		fraction = *(uint_t *)arg;
2133 	uint_t		rand;
2134 
2135 	if ((ire->ire_flags & RTF_DYNAMIC) ||
2136 	    (ire->ire_type & IRE_IF_CLONE)) {
2137 
2138 		/* Pick a random number */
2139 		rand = (uint_t)ddi_get_lbolt() +
2140 		    IRE_ADDR_HASH_V6(ire->ire_addr_v6, 256);
2141 
2142 		/* Use truncation */
2143 		if ((rand/fraction)*fraction == rand) {
2144 			IP_STAT(ipst, ip_ire_reclaim_deleted);
2145 			ire_delete(ire);
2146 		}
2147 	}
2148 
2149 }
2150 
2151 /*
2152  * kmem_cache callback to free up memory.
2153  *
2154  * Free a fraction (ips_ip_ire_reclaim_fraction) of things IP added dynamically
2155  * (RTF_DYNAMIC and IRE_IF_CLONE).
2156  */
2157 static void
2158 ip_ire_reclaim_stack(ip_stack_t *ipst)
2159 {
2160 	uint_t	fraction = ipst->ips_ip_ire_reclaim_fraction;
2161 
2162 	IP_STAT(ipst, ip_ire_reclaim_calls);
2163 
2164 	ire_walk(ire_delete_reclaim, &fraction, ipst);
2165 
2166 	/*
2167 	 * Walk all CONNs that can have a reference on an ire, nce or dce.
2168 	 * Get them to update any stale references to drop any refholds they
2169 	 * have.
2170 	 */
2171 	ipcl_walk(conn_ixa_cleanup, (void *)B_FALSE, ipst);
2172 }
2173 
2174 /*
2175  * Called by the memory allocator subsystem directly, when the system
2176  * is running low on memory.
2177  */
2178 /* ARGSUSED */
2179 void
2180 ip_ire_reclaim(void *args)
2181 {
2182 	netstack_handle_t nh;
2183 	netstack_t *ns;
2184 
2185 	netstack_next_init(&nh);
2186 	while ((ns = netstack_next(&nh)) != NULL) {
2187 		ip_ire_reclaim_stack(ns->netstack_ip);
2188 		netstack_rele(ns);
2189 	}
2190 	netstack_next_fini(&nh);
2191 }
2192 
2193 static void
2194 power2_roundup(uint32_t *value)
2195 {
2196 	int i;
2197 
2198 	for (i = 1; i < 31; i++) {
2199 		if (*value <= (1 << i))
2200 			break;
2201 	}
2202 	*value = (1 << i);
2203 }
2204 
2205 /* Global init for all zones */
2206 void
2207 ip_ire_g_init()
2208 {
2209 	/*
2210 	 * Create kmem_caches.  ip_ire_reclaim() and ip_nce_reclaim()
2211 	 * will give disposable IREs back to system when needed.
2212 	 * This needs to be done here before anything else, since
2213 	 * ire_add() expects the cache to be created.
2214 	 */
2215 	ire_cache = kmem_cache_create("ire_cache",
2216 	    sizeof (ire_t), 0, NULL, NULL,
2217 	    ip_ire_reclaim, NULL, NULL, 0);
2218 
2219 	ncec_cache = kmem_cache_create("ncec_cache",
2220 	    sizeof (ncec_t), 0, NULL, NULL,
2221 	    ip_nce_reclaim, NULL, NULL, 0);
2222 	nce_cache = kmem_cache_create("nce_cache",
2223 	    sizeof (nce_t), 0, NULL, NULL,
2224 	    NULL, NULL, NULL, 0);
2225 
2226 	rt_entry_cache = kmem_cache_create("rt_entry",
2227 	    sizeof (struct rt_entry), 0, NULL, NULL, NULL, NULL, NULL, 0);
2228 
2229 	/*
2230 	 * Have radix code setup kmem caches etc.
2231 	 */
2232 	rn_init();
2233 }
2234 
2235 void
2236 ip_ire_init(ip_stack_t *ipst)
2237 {
2238 	ire_t	*ire;
2239 	int	error;
2240 
2241 	mutex_init(&ipst->ips_ire_ft_init_lock, NULL, MUTEX_DEFAULT, 0);
2242 
2243 	(void) rn_inithead((void **)&ipst->ips_ip_ftable, 32);
2244 
2245 	/*
2246 	 * Make sure that the forwarding table size is a power of 2.
2247 	 * The IRE*_ADDR_HASH() macroes depend on that.
2248 	 */
2249 	ipst->ips_ip6_ftable_hash_size = ip6_ftable_hash_size;
2250 	power2_roundup(&ipst->ips_ip6_ftable_hash_size);
2251 
2252 	/*
2253 	 * Allocate/initialize a pair of IRE_NOROUTEs for each of IPv4 and IPv6.
2254 	 * The ire_reject_v* has RTF_REJECT set, and the ire_blackhole_v* has
2255 	 * RTF_BLACKHOLE set. We use the latter for transient errors such
2256 	 * as memory allocation failures and tripping on IRE_IS_CONDEMNED
2257 	 * entries.
2258 	 */
2259 	ire = kmem_cache_alloc(ire_cache, KM_SLEEP);
2260 	*ire = ire_null;
2261 	error = ire_init_v4(ire, 0, 0, 0, IRE_NOROUTE, NULL, ALL_ZONES,
2262 	    RTF_REJECT|RTF_UP, NULL, ipst);
2263 	ASSERT(error == 0);
2264 	ipst->ips_ire_reject_v4 = ire;
2265 
2266 	ire = kmem_cache_alloc(ire_cache, KM_SLEEP);
2267 	*ire = ire_null;
2268 	error = ire_init_v6(ire, 0, 0, 0, IRE_NOROUTE, NULL, ALL_ZONES,
2269 	    RTF_REJECT|RTF_UP, NULL, ipst);
2270 	ASSERT(error == 0);
2271 	ipst->ips_ire_reject_v6 = ire;
2272 
2273 	ire = kmem_cache_alloc(ire_cache, KM_SLEEP);
2274 	*ire = ire_null;
2275 	error = ire_init_v4(ire, 0, 0, 0, IRE_NOROUTE, NULL, ALL_ZONES,
2276 	    RTF_BLACKHOLE|RTF_UP, NULL, ipst);
2277 	ASSERT(error == 0);
2278 	ipst->ips_ire_blackhole_v4 = ire;
2279 
2280 	ire = kmem_cache_alloc(ire_cache, KM_SLEEP);
2281 	*ire = ire_null;
2282 	error = ire_init_v6(ire, 0, 0, 0, IRE_NOROUTE, NULL, ALL_ZONES,
2283 	    RTF_BLACKHOLE|RTF_UP, NULL, ipst);
2284 	ASSERT(error == 0);
2285 	ipst->ips_ire_blackhole_v6 = ire;
2286 
2287 	rw_init(&ipst->ips_ip6_ire_head_lock, NULL, RW_DEFAULT, NULL);
2288 	rw_init(&ipst->ips_ire_dep_lock, NULL, RW_DEFAULT, NULL);
2289 }
2290 
2291 void
2292 ip_ire_g_fini(void)
2293 {
2294 	kmem_cache_destroy(ire_cache);
2295 	kmem_cache_destroy(ncec_cache);
2296 	kmem_cache_destroy(nce_cache);
2297 	kmem_cache_destroy(rt_entry_cache);
2298 
2299 	rn_fini();
2300 }
2301 
2302 void
2303 ip_ire_fini(ip_stack_t *ipst)
2304 {
2305 	int i;
2306 
2307 	rw_destroy(&ipst->ips_ire_dep_lock);
2308 	rw_destroy(&ipst->ips_ip6_ire_head_lock);
2309 
2310 	ire_refrele_notr(ipst->ips_ire_reject_v6);
2311 	ipst->ips_ire_reject_v6 = NULL;
2312 	ire_refrele_notr(ipst->ips_ire_reject_v4);
2313 	ipst->ips_ire_reject_v4 = NULL;
2314 	ire_refrele_notr(ipst->ips_ire_blackhole_v6);
2315 	ipst->ips_ire_blackhole_v6 = NULL;
2316 	ire_refrele_notr(ipst->ips_ire_blackhole_v4);
2317 	ipst->ips_ire_blackhole_v4 = NULL;
2318 
2319 	/*
2320 	 * Delete all IREs - assumes that the ill/ipifs have
2321 	 * been removed so what remains are just the ftable to handle.
2322 	 */
2323 	ire_walk(ire_delete, NULL, ipst);
2324 
2325 	rn_freehead(ipst->ips_ip_ftable);
2326 	ipst->ips_ip_ftable = NULL;
2327 
2328 	mutex_destroy(&ipst->ips_ire_ft_init_lock);
2329 
2330 	for (i = 0; i < IP6_MASK_TABLE_SIZE; i++) {
2331 		irb_t *ptr;
2332 		int j;
2333 
2334 		if ((ptr = ipst->ips_ip_forwarding_table_v6[i]) == NULL)
2335 			continue;
2336 
2337 		for (j = 0; j < ipst->ips_ip6_ftable_hash_size; j++) {
2338 			ASSERT(ptr[j].irb_ire == NULL);
2339 			rw_destroy(&ptr[j].irb_lock);
2340 		}
2341 		mi_free(ptr);
2342 		ipst->ips_ip_forwarding_table_v6[i] = NULL;
2343 	}
2344 }
2345 
2346 #ifdef DEBUG
2347 void
2348 ire_trace_ref(ire_t *ire)
2349 {
2350 	mutex_enter(&ire->ire_lock);
2351 	if (ire->ire_trace_disable) {
2352 		mutex_exit(&ire->ire_lock);
2353 		return;
2354 	}
2355 
2356 	if (th_trace_ref(ire, ire->ire_ipst)) {
2357 		mutex_exit(&ire->ire_lock);
2358 	} else {
2359 		ire->ire_trace_disable = B_TRUE;
2360 		mutex_exit(&ire->ire_lock);
2361 		ire_trace_cleanup(ire);
2362 	}
2363 }
2364 
2365 void
2366 ire_untrace_ref(ire_t *ire)
2367 {
2368 	mutex_enter(&ire->ire_lock);
2369 	if (!ire->ire_trace_disable)
2370 		th_trace_unref(ire);
2371 	mutex_exit(&ire->ire_lock);
2372 }
2373 
2374 static void
2375 ire_trace_cleanup(const ire_t *ire)
2376 {
2377 	th_trace_cleanup(ire, ire->ire_trace_disable);
2378 }
2379 #endif /* DEBUG */
2380 
2381 /*
2382  * Find, or create if needed, the nce_t pointer to the neighbor cache
2383  * entry ncec_t for an IPv4 address. The nce_t will be created on the ill_t
2384  * in the non-IPMP case, or on the cast-ill in the IPMP bcast/mcast case, or
2385  * on the next available under-ill (selected by the IPMP rotor) in the
2386  * unicast IPMP case.
2387  *
2388  * If a neighbor-cache entry has to be created (i.e., one does not already
2389  * exist in the nce list) the ncec_lladdr and ncec_state of the neighbor cache
2390  * entry are initialized in nce_add_v4(). The broadcast, multicast, and
2391  * link-layer type determine the contents of {ncec_state, ncec_lladdr} of
2392  * the ncec_t created. The ncec_lladdr is non-null for all link types with
2393  * non-zero ill_phys_addr_length, though the contents may be zero in cases
2394  * where the link-layer type is not known at the time of creation
2395  * (e.g., IRE_IFRESOLVER links)
2396  *
2397  * All IRE_BROADCAST entries have ncec_state = ND_REACHABLE, and the nce_lladr
2398  * has the physical broadcast address of the outgoing interface.
2399  * For unicast ire entries,
2400  *   - if the outgoing interface is of type IRE_IF_RESOLVER, a newly created
2401  *     ncec_t with 0 nce_lladr contents, and will be in the ND_INITIAL state.
2402  *   - if the outgoing interface is a IRE_IF_NORESOLVER interface, no link
2403  *     layer resolution is necessary, so that the ncec_t will be in the
2404  *     ND_REACHABLE state
2405  *
2406  * The link layer information needed for broadcast addresses, and for
2407  * packets sent on IRE_IF_NORESOLVER interfaces is a constant mapping that
2408  * never needs re-verification for the lifetime of the ncec_t. These are
2409  * therefore marked NCE_F_NONUD.
2410  *
2411  * The nce returned will be created such that the nce_ill == ill that
2412  * is passed in. Note that the nce itself may not have ncec_ill == ill
2413  * where IPMP links are involved.
2414  */
2415 static nce_t *
2416 ire_nce_init(ill_t *ill, const void *addr, int ire_type)
2417 {
2418 	int		err;
2419 	nce_t		*nce = NULL;
2420 	uint16_t	ncec_flags;
2421 	uchar_t		*hwaddr;
2422 	boolean_t	need_refrele = B_FALSE;
2423 	ill_t		*in_ill = ill;
2424 	boolean_t	is_unicast;
2425 	uint_t		hwaddr_len;
2426 
2427 	is_unicast = ((ire_type & (IRE_MULTICAST|IRE_BROADCAST)) == 0);
2428 	if (IS_IPMP(ill) ||
2429 	    ((ire_type & IRE_BROADCAST) && IS_UNDER_IPMP(ill))) {
2430 		if ((ill = ipmp_ill_get_xmit_ill(ill, is_unicast)) == NULL)
2431 			return (NULL);
2432 		need_refrele = B_TRUE;
2433 	}
2434 	ncec_flags = (ill->ill_flags & ILLF_NONUD) ? NCE_F_NONUD : 0;
2435 
2436 	switch (ire_type) {
2437 	case IRE_BROADCAST:
2438 		ASSERT(!ill->ill_isv6);
2439 		ncec_flags |= (NCE_F_BCAST|NCE_F_NONUD);
2440 		break;
2441 	case IRE_MULTICAST:
2442 		ncec_flags |= (NCE_F_MCAST|NCE_F_NONUD);
2443 		break;
2444 	}
2445 
2446 	if (ill->ill_net_type == IRE_IF_NORESOLVER && is_unicast) {
2447 		hwaddr = ill->ill_dest_addr;
2448 	} else {
2449 		hwaddr = NULL;
2450 	}
2451 	hwaddr_len = ill->ill_phys_addr_length;
2452 
2453 retry:
2454 	/* nce_state will be computed by nce_add_common() */
2455 	if (!ill->ill_isv6) {
2456 		err = nce_lookup_then_add_v4(ill, hwaddr, hwaddr_len, addr,
2457 		    ncec_flags, ND_UNCHANGED, &nce);
2458 	} else {
2459 		err = nce_lookup_then_add_v6(ill, hwaddr, hwaddr_len, addr,
2460 		    ncec_flags, ND_UNCHANGED, &nce);
2461 	}
2462 
2463 	switch (err) {
2464 	case 0:
2465 		break;
2466 	case EEXIST:
2467 		/*
2468 		 * When subnets change or partially overlap what was once
2469 		 * a broadcast address could now be a unicast, or vice versa.
2470 		 */
2471 		if (((ncec_flags ^ nce->nce_common->ncec_flags) &
2472 		    NCE_F_BCAST) != 0) {
2473 			ASSERT(!ill->ill_isv6);
2474 			ncec_delete(nce->nce_common);
2475 			nce_refrele(nce);
2476 			goto retry;
2477 		}
2478 		break;
2479 	default:
2480 		DTRACE_PROBE2(nce__init__fail, ill_t *, ill, int, err);
2481 		if (need_refrele)
2482 			ill_refrele(ill);
2483 		return (NULL);
2484 	}
2485 	/*
2486 	 * If the ill was an under-ill of an IPMP group, we need to verify
2487 	 * that it is still active so that we select an active interface in
2488 	 * the group. However, since ipmp_ill_is_active ASSERTs for
2489 	 * IS_UNDER_IPMP(), we first need to verify that the ill is an
2490 	 * under-ill, and since this is being done in the data path, the
2491 	 * only way to ascertain this is by holding the ill_g_lock.
2492 	 */
2493 	rw_enter(&ill->ill_ipst->ips_ill_g_lock, RW_READER);
2494 	mutex_enter(&ill->ill_lock);
2495 	mutex_enter(&ill->ill_phyint->phyint_lock);
2496 	if (need_refrele && IS_UNDER_IPMP(ill) && !ipmp_ill_is_active(ill)) {
2497 		/*
2498 		 * need_refrele implies that the under ill was selected by
2499 		 * ipmp_ill_get_xmit_ill() because either the in_ill was an
2500 		 * ipmp_ill, or we are sending a non-unicast packet on
2501 		 * an under_ill. However, when we get here, the ill selected by
2502 		 * ipmp_ill_get_xmit_ill  was pulled out of the active set
2503 		 * (for unicast)  or cast_ill nomination (for
2504 		 * !unicast) after it was  picked as the outgoing ill.
2505 		 * We have to pick an active interface and/or cast_ill in the
2506 		 * group.
2507 		 */
2508 		mutex_exit(&ill->ill_phyint->phyint_lock);
2509 		nce_delete(nce);
2510 		mutex_exit(&ill->ill_lock);
2511 		rw_exit(&ill->ill_ipst->ips_ill_g_lock);
2512 		nce_refrele(nce);
2513 		ill_refrele(ill);
2514 		if ((ill = ipmp_ill_get_xmit_ill(in_ill, is_unicast)) == NULL)
2515 			return (NULL);
2516 		goto retry;
2517 	} else {
2518 		mutex_exit(&ill->ill_phyint->phyint_lock);
2519 		mutex_exit(&ill->ill_lock);
2520 		rw_exit(&ill->ill_ipst->ips_ill_g_lock);
2521 	}
2522 done:
2523 	ASSERT(nce->nce_ill == ill);
2524 	if (need_refrele)
2525 		ill_refrele(ill);
2526 	return (nce);
2527 }
2528 
2529 nce_t *
2530 arp_nce_init(ill_t *ill, in_addr_t addr4, int ire_type)
2531 {
2532 	return (ire_nce_init(ill, &addr4, ire_type));
2533 }
2534 
2535 nce_t *
2536 ndp_nce_init(ill_t *ill, const in6_addr_t *addr6, int ire_type)
2537 {
2538 	ASSERT((ire_type & IRE_BROADCAST) == 0);
2539 	return (ire_nce_init(ill, addr6, ire_type));
2540 }
2541 
2542 /*
2543  * The caller should hold irb_lock as a writer if the ire is in a bucket.
2544  */
2545 void
2546 ire_make_condemned(ire_t *ire)
2547 {
2548 	ip_stack_t	*ipst = ire->ire_ipst;
2549 
2550 	mutex_enter(&ire->ire_lock);
2551 	ASSERT(ire->ire_bucket == NULL ||
2552 	    RW_WRITE_HELD(&ire->ire_bucket->irb_lock));
2553 	ASSERT(!IRE_IS_CONDEMNED(ire));
2554 	ire->ire_generation = IRE_GENERATION_CONDEMNED;
2555 	/* Count how many condemned ires for kmem_cache callback */
2556 	atomic_add_32(&ipst->ips_num_ire_condemned, 1);
2557 	mutex_exit(&ire->ire_lock);
2558 }
2559 
2560 /*
2561  * Increment the generation avoiding the special condemned value
2562  */
2563 void
2564 ire_increment_generation(ire_t *ire)
2565 {
2566 	uint_t generation;
2567 
2568 	mutex_enter(&ire->ire_lock);
2569 	/*
2570 	 * Even though the caller has a hold it can't prevent a concurrent
2571 	 * ire_delete marking the IRE condemned
2572 	 */
2573 	if (!IRE_IS_CONDEMNED(ire)) {
2574 		generation = ire->ire_generation + 1;
2575 		if (generation == IRE_GENERATION_CONDEMNED)
2576 			generation = IRE_GENERATION_INITIAL;
2577 		ASSERT(generation != IRE_GENERATION_VERIFY);
2578 		ire->ire_generation = generation;
2579 	}
2580 	mutex_exit(&ire->ire_lock);
2581 }
2582 
2583 /*
2584  * Increment ire_generation on all the IRE_MULTICASTs
2585  * Used when the default multicast interface (as determined by
2586  * ill_lookup_multicast) might have changed.
2587  *
2588  * That includes the zoneid, IFF_ flags, the IPv6 scope of the address, and
2589  * ill unplumb.
2590  */
2591 void
2592 ire_increment_multicast_generation(ip_stack_t *ipst, boolean_t isv6)
2593 {
2594 	ill_t	*ill;
2595 	ill_walk_context_t ctx;
2596 
2597 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
2598 	if (isv6)
2599 		ill = ILL_START_WALK_V6(&ctx, ipst);
2600 	else
2601 		ill = ILL_START_WALK_V4(&ctx, ipst);
2602 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
2603 		if (ILL_IS_CONDEMNED(ill))
2604 			continue;
2605 		if (ill->ill_ire_multicast != NULL)
2606 			ire_increment_generation(ill->ill_ire_multicast);
2607 	}
2608 	rw_exit(&ipst->ips_ill_g_lock);
2609 }
2610 
2611 /*
2612  * Return a held IRE_NOROUTE with RTF_REJECT set
2613  */
2614 ire_t *
2615 ire_reject(ip_stack_t *ipst, boolean_t isv6)
2616 {
2617 	ire_t *ire;
2618 
2619 	if (isv6)
2620 		ire = ipst->ips_ire_reject_v6;
2621 	else
2622 		ire = ipst->ips_ire_reject_v4;
2623 
2624 	ASSERT(ire->ire_generation != IRE_GENERATION_CONDEMNED);
2625 	ire_refhold(ire);
2626 	return (ire);
2627 }
2628 
2629 /*
2630  * Return a held IRE_NOROUTE with RTF_BLACKHOLE set
2631  */
2632 ire_t *
2633 ire_blackhole(ip_stack_t *ipst, boolean_t isv6)
2634 {
2635 	ire_t *ire;
2636 
2637 	if (isv6)
2638 		ire = ipst->ips_ire_blackhole_v6;
2639 	else
2640 		ire = ipst->ips_ire_blackhole_v4;
2641 
2642 	ASSERT(ire->ire_generation != IRE_GENERATION_CONDEMNED);
2643 	ire_refhold(ire);
2644 	return (ire);
2645 }
2646 
2647 /*
2648  * Return a held IRE_MULTICAST.
2649  */
2650 ire_t *
2651 ire_multicast(ill_t *ill)
2652 {
2653 	ire_t *ire = ill->ill_ire_multicast;
2654 
2655 	ASSERT(ire == NULL || ire->ire_generation != IRE_GENERATION_CONDEMNED);
2656 	if (ire == NULL)
2657 		ire = ire_blackhole(ill->ill_ipst, ill->ill_isv6);
2658 	else
2659 		ire_refhold(ire);
2660 	return (ire);
2661 }
2662 
2663 /*
2664  * Given an IRE return its nexthop IRE. The nexthop IRE is an IRE_ONLINK
2665  * that is an exact match (i.e., a /32 for IPv4 and /128 for IPv6).
2666  * This can return an RTF_REJECT|RTF_BLACKHOLE.
2667  * The returned IRE is held.
2668  * The assumption is that ip_select_route() has been called and returned the
2669  * IRE (thus ip_select_route would have set up the ire_dep* information.)
2670  * If some IRE is deleteted then ire_dep_remove() will have been called and
2671  * we might not find a nexthop IRE, in which case we return NULL.
2672  */
2673 ire_t *
2674 ire_nexthop(ire_t *ire)
2675 {
2676 	ip_stack_t	*ipst = ire->ire_ipst;
2677 
2678 	/* Acquire lock to walk ire_dep_parent */
2679 	rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
2680 	while (ire != NULL) {
2681 		if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
2682 			goto done;
2683 		}
2684 		/*
2685 		 * If we find an IRE_ONLINK we are done. This includes
2686 		 * the case of IRE_MULTICAST.
2687 		 * Note that in order to send packets we need a host-specific
2688 		 * IRE_IF_ALL first in the ire_dep_parent chain. Normally this
2689 		 * is done by inserting an IRE_IF_CLONE if the IRE_INTERFACE
2690 		 * was not host specific.
2691 		 * However, ip_rts_request doesn't want to send packets
2692 		 * hence doesn't want to allocate an IRE_IF_CLONE. Yet
2693 		 * it needs an IRE_IF_ALL to get to the ill. Thus
2694 		 * we return IRE_IF_ALL that are not host specific here.
2695 		 */
2696 		if (ire->ire_type & IRE_ONLINK)
2697 			goto done;
2698 		ire = ire->ire_dep_parent;
2699 	}
2700 	rw_exit(&ipst->ips_ire_dep_lock);
2701 	return (NULL);
2702 
2703 done:
2704 	ire_refhold(ire);
2705 	rw_exit(&ipst->ips_ire_dep_lock);
2706 	return (ire);
2707 }
2708 
2709 /*
2710  * Find the ill used to send packets. This will be NULL in case
2711  * of a reject or blackhole.
2712  * The returned ill is held; caller needs to do ill_refrele when done.
2713  */
2714 ill_t *
2715 ire_nexthop_ill(ire_t *ire)
2716 {
2717 	ill_t		*ill;
2718 
2719 	ire = ire_nexthop(ire);
2720 	if (ire == NULL)
2721 		return (NULL);
2722 
2723 	/* ire_ill can not change for an existing ire */
2724 	ill = ire->ire_ill;
2725 	if (ill != NULL)
2726 		ill_refhold(ill);
2727 	ire_refrele(ire);
2728 	return (ill);
2729 }
2730 
2731 #ifdef DEBUG
2732 static boolean_t
2733 parent_has_child(ire_t *parent, ire_t *child)
2734 {
2735 	ire_t	*ire;
2736 	ire_t	*prev;
2737 
2738 	ire = parent->ire_dep_children;
2739 	prev = NULL;
2740 	while (ire != NULL) {
2741 		if (prev == NULL) {
2742 			ASSERT(ire->ire_dep_sib_ptpn ==
2743 			    &(parent->ire_dep_children));
2744 		} else {
2745 			ASSERT(ire->ire_dep_sib_ptpn ==
2746 			    &(prev->ire_dep_sib_next));
2747 		}
2748 		if (ire == child)
2749 			return (B_TRUE);
2750 		prev = ire;
2751 		ire = ire->ire_dep_sib_next;
2752 	}
2753 	return (B_FALSE);
2754 }
2755 
2756 static void
2757 ire_dep_verify(ire_t *ire)
2758 {
2759 	ire_t		*parent = ire->ire_dep_parent;
2760 	ire_t		*child = ire->ire_dep_children;
2761 
2762 	ASSERT(ire->ire_ipversion == IPV4_VERSION ||
2763 	    ire->ire_ipversion == IPV6_VERSION);
2764 	if (parent != NULL) {
2765 		ASSERT(parent->ire_ipversion == IPV4_VERSION ||
2766 		    parent->ire_ipversion == IPV6_VERSION);
2767 		ASSERT(parent->ire_refcnt >= 1);
2768 		ASSERT(parent_has_child(parent, ire));
2769 	}
2770 	if (child != NULL) {
2771 		ASSERT(child->ire_ipversion == IPV4_VERSION ||
2772 		    child->ire_ipversion == IPV6_VERSION);
2773 		ASSERT(child->ire_dep_parent == ire);
2774 		ASSERT(child->ire_dep_sib_ptpn != NULL);
2775 		ASSERT(parent_has_child(ire, child));
2776 	}
2777 }
2778 #endif /* DEBUG */
2779 
2780 /*
2781  * Assumes ire_dep_parent is set. Remove this child from its parent's linkage.
2782  */
2783 void
2784 ire_dep_remove(ire_t *ire)
2785 {
2786 	ip_stack_t	*ipst = ire->ire_ipst;
2787 	ire_t		*parent = ire->ire_dep_parent;
2788 	ire_t		*next;
2789 	nce_t		*nce;
2790 
2791 	ASSERT(RW_WRITE_HELD(&ipst->ips_ire_dep_lock));
2792 	ASSERT(ire->ire_dep_parent != NULL);
2793 	ASSERT(ire->ire_dep_sib_ptpn != NULL);
2794 
2795 #ifdef DEBUG
2796 	ire_dep_verify(ire);
2797 	ire_dep_verify(parent);
2798 #endif
2799 
2800 	next = ire->ire_dep_sib_next;
2801 	if (next != NULL)
2802 		next->ire_dep_sib_ptpn = ire->ire_dep_sib_ptpn;
2803 
2804 	ASSERT(*(ire->ire_dep_sib_ptpn) == ire);
2805 	*(ire->ire_dep_sib_ptpn) = ire->ire_dep_sib_next;
2806 
2807 	ire->ire_dep_sib_ptpn = NULL;
2808 	ire->ire_dep_sib_next = NULL;
2809 
2810 	mutex_enter(&ire->ire_lock);
2811 	parent = ire->ire_dep_parent;
2812 	ire->ire_dep_parent = NULL;
2813 	mutex_exit(&ire->ire_lock);
2814 
2815 	/*
2816 	 * Make sure all our children, grandchildren, etc set
2817 	 * ire_dep_parent_generation to IRE_GENERATION_VERIFY since
2818 	 * we can no longer guarantee than the children have a current
2819 	 * ire_nce_cache and ire_nexthop_ill().
2820 	 */
2821 	if (ire->ire_dep_children != NULL)
2822 		ire_dep_invalidate_children(ire->ire_dep_children);
2823 
2824 	/*
2825 	 * Since the parent is gone we make sure we clear ire_nce_cache.
2826 	 * We can clear it under ire_lock even if the IRE is used
2827 	 */
2828 	mutex_enter(&ire->ire_lock);
2829 	nce = ire->ire_nce_cache;
2830 	ire->ire_nce_cache = NULL;
2831 	mutex_exit(&ire->ire_lock);
2832 	if (nce != NULL)
2833 		nce_refrele(nce);
2834 
2835 #ifdef DEBUG
2836 	ire_dep_verify(ire);
2837 	ire_dep_verify(parent);
2838 #endif
2839 
2840 	ire_refrele_notr(parent);
2841 	ire_refrele_notr(ire);
2842 }
2843 
2844 /*
2845  * Insert the child in the linkage of the parent
2846  */
2847 static void
2848 ire_dep_parent_insert(ire_t *child, ire_t *parent)
2849 {
2850 	ip_stack_t	*ipst = child->ire_ipst;
2851 	ire_t		*next;
2852 
2853 	ASSERT(RW_WRITE_HELD(&ipst->ips_ire_dep_lock));
2854 	ASSERT(child->ire_dep_parent == NULL);
2855 
2856 #ifdef DEBUG
2857 	ire_dep_verify(child);
2858 	ire_dep_verify(parent);
2859 #endif
2860 	/* No parents => no siblings */
2861 	ASSERT(child->ire_dep_sib_ptpn == NULL);
2862 	ASSERT(child->ire_dep_sib_next == NULL);
2863 
2864 	ire_refhold_notr(parent);
2865 	ire_refhold_notr(child);
2866 
2867 	/* Head insertion */
2868 	next = parent->ire_dep_children;
2869 	if (next != NULL) {
2870 		ASSERT(next->ire_dep_sib_ptpn == &(parent->ire_dep_children));
2871 		child->ire_dep_sib_next = next;
2872 		next->ire_dep_sib_ptpn = &(child->ire_dep_sib_next);
2873 	}
2874 	parent->ire_dep_children = child;
2875 	child->ire_dep_sib_ptpn = &(parent->ire_dep_children);
2876 
2877 	mutex_enter(&child->ire_lock);
2878 	child->ire_dep_parent = parent;
2879 	mutex_exit(&child->ire_lock);
2880 
2881 #ifdef DEBUG
2882 	ire_dep_verify(child);
2883 	ire_dep_verify(parent);
2884 #endif
2885 }
2886 
2887 
2888 /*
2889  * Given count worth of ires and generations, build ire_dep_* relationships
2890  * from ires[0] to ires[count-1]. Record generations[i+1] in
2891  * ire_dep_parent_generation for ires[i].
2892  * We graft onto an existing parent chain by making sure that we don't
2893  * touch ire_dep_parent for ires[count-1].
2894  *
2895  * We check for any condemned ire_generation count and return B_FALSE in
2896  * that case so that the caller can tear it apart.
2897  *
2898  * Note that generations[0] is not used. Caller handles that.
2899  */
2900 boolean_t
2901 ire_dep_build(ire_t *ires[], uint_t generations[], uint_t count)
2902 {
2903 	ire_t		*ire = ires[0];
2904 	ip_stack_t	*ipst;
2905 	uint_t		i;
2906 
2907 	ASSERT(count > 0);
2908 	if (count == 1) {
2909 		/* No work to do */
2910 		return (B_TRUE);
2911 	}
2912 	ipst = ire->ire_ipst;
2913 	rw_enter(&ipst->ips_ire_dep_lock, RW_WRITER);
2914 	/*
2915 	 * Do not remove the linkage for any existing parent chain i.e.,
2916 	 * ires[count-1] is left alone.
2917 	 */
2918 	for (i = 0; i < count-1; i++) {
2919 		/* Remove existing parent if we need to change it */
2920 		if (ires[i]->ire_dep_parent != NULL &&
2921 		    ires[i]->ire_dep_parent != ires[i+1])
2922 			ire_dep_remove(ires[i]);
2923 	}
2924 
2925 	for (i = 0; i < count - 1; i++) {
2926 		ASSERT(ires[i]->ire_ipversion == IPV4_VERSION ||
2927 		    ires[i]->ire_ipversion == IPV6_VERSION);
2928 		/* Does it need to change? */
2929 		if (ires[i]->ire_dep_parent != ires[i+1])
2930 			ire_dep_parent_insert(ires[i], ires[i+1]);
2931 
2932 		mutex_enter(&ires[i+1]->ire_lock);
2933 		if (IRE_IS_CONDEMNED(ires[i+1])) {
2934 			mutex_exit(&ires[i+1]->ire_lock);
2935 			rw_exit(&ipst->ips_ire_dep_lock);
2936 			return (B_FALSE);
2937 		}
2938 		mutex_exit(&ires[i+1]->ire_lock);
2939 
2940 		mutex_enter(&ires[i]->ire_lock);
2941 		ires[i]->ire_dep_parent_generation = generations[i+1];
2942 		mutex_exit(&ires[i]->ire_lock);
2943 	}
2944 	rw_exit(&ipst->ips_ire_dep_lock);
2945 	return (B_TRUE);
2946 }
2947 
2948 /*
2949  * Given count worth of ires, unbuild ire_dep_* relationships
2950  * from ires[0] to ires[count-1].
2951  */
2952 void
2953 ire_dep_unbuild(ire_t *ires[], uint_t count)
2954 {
2955 	ip_stack_t	*ipst;
2956 	uint_t		i;
2957 
2958 	if (count == 0) {
2959 		/* No work to do */
2960 		return;
2961 	}
2962 	ipst = ires[0]->ire_ipst;
2963 	rw_enter(&ipst->ips_ire_dep_lock, RW_WRITER);
2964 	for (i = 0; i < count; i++) {
2965 		ASSERT(ires[i]->ire_ipversion == IPV4_VERSION ||
2966 		    ires[i]->ire_ipversion == IPV6_VERSION);
2967 		if (ires[i]->ire_dep_parent != NULL)
2968 			ire_dep_remove(ires[i]);
2969 		mutex_enter(&ires[i]->ire_lock);
2970 		ires[i]->ire_dep_parent_generation = IRE_GENERATION_VERIFY;
2971 		mutex_exit(&ires[i]->ire_lock);
2972 	}
2973 	rw_exit(&ipst->ips_ire_dep_lock);
2974 }
2975 
2976 /*
2977  * Both the forwarding and the outbound code paths can trip on
2978  * a condemned NCE, in which case we call this function.
2979  * We have two different behaviors: if the NCE was UNREACHABLE
2980  * it is an indication that something failed. In that case
2981  * we see if we should look for a different IRE (for example,
2982  * delete any matching redirect IRE, or try a different
2983  * IRE_DEFAULT (ECMP)). We mark the ire as bad so a hopefully
2984  * different IRE will be picked next time we send/forward.
2985  *
2986  * If we are called by the output path then fail_if_better is set
2987  * and we return NULL if there could be a better IRE. This is because the
2988  * output path retries the IRE lookup. (The input/forward path can not retry.)
2989  *
2990  * If the NCE was not unreachable then we pick/allocate a
2991  * new (most likely ND_INITIAL) NCE and proceed with it.
2992  *
2993  * ipha/ip6h are needed for multicast packets; ipha needs to be
2994  * set for IPv4 and ip6h needs to be set for IPv6 packets.
2995  */
2996 nce_t *
2997 ire_handle_condemned_nce(nce_t *nce, ire_t *ire, ipha_t *ipha, ip6_t *ip6h,
2998     boolean_t fail_if_better)
2999 {
3000 	if (nce->nce_common->ncec_state == ND_UNREACHABLE) {
3001 		if (ire_no_good(ire) && fail_if_better) {
3002 			/*
3003 			 * Did some changes, or ECMP likely to exist.
3004 			 * Make ip_output look for a different IRE
3005 			 */
3006 			return (NULL);
3007 		}
3008 	}
3009 	if (ire_revalidate_nce(ire) == ENETUNREACH) {
3010 		/* The ire_dep_parent chain went bad, or no memory? */
3011 		(void) ire_no_good(ire);
3012 		return (NULL);
3013 	}
3014 	if (ire->ire_ipversion == IPV4_VERSION) {
3015 		ASSERT(ipha != NULL);
3016 		nce = ire_to_nce(ire, ipha->ipha_dst, NULL);
3017 	} else {
3018 		ASSERT(ip6h != NULL);
3019 		nce = ire_to_nce(ire, INADDR_ANY, &ip6h->ip6_dst);
3020 	}
3021 
3022 	if (nce == NULL)
3023 		return (NULL);
3024 	if (nce->nce_is_condemned) {
3025 		nce_refrele(nce);
3026 		return (NULL);
3027 	}
3028 	return (nce);
3029 }
3030 
3031 /*
3032  * The caller has found that the ire is bad, either due to a reference to an NCE
3033  * in ND_UNREACHABLE state, or a MULTIRT route whose gateway can't be resolved.
3034  * We update things so a subsequent attempt to send to the destination
3035  * is likely to find different IRE, or that a new NCE would be created.
3036  *
3037  * Returns B_TRUE if it is likely that a subsequent ire_ftable_lookup would
3038  * find a different route (either due to having deleted a redirect, or there
3039  * being ECMP routes.)
3040  *
3041  * If we have a redirect (RTF_DYNAMIC) we delete it.
3042  * Otherwise we increment ire_badcnt and increment the generation number so
3043  * that a cached ixa_ire will redo the route selection. ire_badcnt is taken
3044  * into account in the route selection when we have multiple choices (multiple
3045  * default routes or ECMP in general).
3046  * Any time ip_select_route find an ire with a condemned ire_nce_cache
3047  * (e.g., if no equal cost route to the bad one) ip_select_route will make
3048  * sure the NCE is revalidated to avoid getting stuck on a
3049  * NCE_F_CONDMNED ncec that caused ire_no_good to be called.
3050  */
3051 boolean_t
3052 ire_no_good(ire_t *ire)
3053 {
3054 	ip_stack_t	*ipst = ire->ire_ipst;
3055 	ire_t		*ire2;
3056 	nce_t		*nce;
3057 
3058 	if (ire->ire_flags & RTF_DYNAMIC) {
3059 		ire_delete(ire);
3060 		return (B_TRUE);
3061 	}
3062 	if (ire->ire_flags & RTF_INDIRECT) {
3063 		/* Check if next IRE is a redirect */
3064 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
3065 		if (ire->ire_dep_parent != NULL &&
3066 		    (ire->ire_dep_parent->ire_flags & RTF_DYNAMIC)) {
3067 			ire2 = ire->ire_dep_parent;
3068 			ire_refhold(ire2);
3069 		} else {
3070 			ire2 = NULL;
3071 		}
3072 		rw_exit(&ipst->ips_ire_dep_lock);
3073 		if (ire2 != NULL) {
3074 			ire_delete(ire2);
3075 			ire_refrele(ire2);
3076 			return (B_TRUE);
3077 		}
3078 	}
3079 	/*
3080 	 * No redirect involved. Increment badcnt so that if we have ECMP
3081 	 * routes we are likely to pick a different one for the next packet.
3082 	 *
3083 	 * If the NCE is unreachable and condemned we should drop the reference
3084 	 * to it so that a new NCE can be created.
3085 	 *
3086 	 * Finally we increment the generation number so that any ixa_ire
3087 	 * cache will be revalidated.
3088 	 */
3089 	mutex_enter(&ire->ire_lock);
3090 	ire->ire_badcnt++;
3091 	ire->ire_last_badcnt = TICK_TO_SEC(ddi_get_lbolt64());
3092 	nce = ire->ire_nce_cache;
3093 	if (nce != NULL && nce->nce_is_condemned &&
3094 	    nce->nce_common->ncec_state == ND_UNREACHABLE)
3095 		ire->ire_nce_cache = NULL;
3096 	else
3097 		nce = NULL;
3098 	mutex_exit(&ire->ire_lock);
3099 	if (nce != NULL)
3100 		nce_refrele(nce);
3101 
3102 	ire_increment_generation(ire);
3103 	ire_dep_incr_generation(ire);
3104 
3105 	return (ire->ire_bucket->irb_ire_cnt > 1);
3106 }
3107 
3108 /*
3109  * Walk ire_dep_parent chain and validate that ire_dep_parent->ire_generation ==
3110  * ire_dep_parent_generation.
3111  * If they all match we just return ire_generation from the topmost IRE.
3112  * Otherwise we propagate the mismatch by setting all ire_dep_parent_generation
3113  * above the mismatch to IRE_GENERATION_VERIFY and also returning
3114  * IRE_GENERATION_VERIFY.
3115  */
3116 uint_t
3117 ire_dep_validate_generations(ire_t *ire)
3118 {
3119 	ip_stack_t	*ipst = ire->ire_ipst;
3120 	uint_t		generation;
3121 	ire_t		*ire1;
3122 
3123 	rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
3124 	generation = ire->ire_generation;	/* Assuming things match */
3125 	for (ire1 = ire; ire1 != NULL; ire1 = ire1->ire_dep_parent) {
3126 		ASSERT(ire1->ire_ipversion == IPV4_VERSION ||
3127 		    ire1->ire_ipversion == IPV6_VERSION);
3128 		if (ire1->ire_dep_parent == NULL)
3129 			break;
3130 		if (ire1->ire_dep_parent_generation !=
3131 		    ire1->ire_dep_parent->ire_generation)
3132 			goto mismatch;
3133 	}
3134 	rw_exit(&ipst->ips_ire_dep_lock);
3135 	return (generation);
3136 
3137 mismatch:
3138 	generation = IRE_GENERATION_VERIFY;
3139 	/* Fill from top down to the mismatch with _VERIFY */
3140 	while (ire != ire1) {
3141 		ASSERT(ire->ire_ipversion == IPV4_VERSION ||
3142 		    ire->ire_ipversion == IPV6_VERSION);
3143 		mutex_enter(&ire->ire_lock);
3144 		ire->ire_dep_parent_generation = IRE_GENERATION_VERIFY;
3145 		mutex_exit(&ire->ire_lock);
3146 		ire = ire->ire_dep_parent;
3147 	}
3148 	rw_exit(&ipst->ips_ire_dep_lock);
3149 	return (generation);
3150 }
3151 
3152 /*
3153  * Used when we need to return an ire with ire_dep_parent, but we
3154  * know the chain is invalid for instance we didn't create an IRE_IF_CLONE
3155  * Using IRE_GENERATION_VERIFY means that next time we'll redo the
3156  * recursive lookup.
3157  */
3158 void
3159 ire_dep_invalidate_generations(ire_t *ire)
3160 {
3161 	ip_stack_t	*ipst = ire->ire_ipst;
3162 
3163 	rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
3164 	while (ire != NULL) {
3165 		ASSERT(ire->ire_ipversion == IPV4_VERSION ||
3166 		    ire->ire_ipversion == IPV6_VERSION);
3167 		mutex_enter(&ire->ire_lock);
3168 		ire->ire_dep_parent_generation = IRE_GENERATION_VERIFY;
3169 		mutex_exit(&ire->ire_lock);
3170 		ire = ire->ire_dep_parent;
3171 	}
3172 	rw_exit(&ipst->ips_ire_dep_lock);
3173 }
3174 
3175 /* Set _VERIFY ire_dep_parent_generation for all children recursively */
3176 static void
3177 ire_dep_invalidate_children(ire_t *child)
3178 {
3179 	ip_stack_t	*ipst = child->ire_ipst;
3180 
3181 	ASSERT(RW_WRITE_HELD(&ipst->ips_ire_dep_lock));
3182 	/* Depth first */
3183 	if (child->ire_dep_children != NULL)
3184 		ire_dep_invalidate_children(child->ire_dep_children);
3185 
3186 	while (child != NULL) {
3187 		mutex_enter(&child->ire_lock);
3188 		child->ire_dep_parent_generation = IRE_GENERATION_VERIFY;
3189 		mutex_exit(&child->ire_lock);
3190 		child = child->ire_dep_sib_next;
3191 	}
3192 }
3193 
3194 static void
3195 ire_dep_increment_children(ire_t *child)
3196 {
3197 	ip_stack_t	*ipst = child->ire_ipst;
3198 
3199 	ASSERT(RW_READ_HELD(&ipst->ips_ire_dep_lock));
3200 	/* Depth first */
3201 	if (child->ire_dep_children != NULL)
3202 		ire_dep_increment_children(child->ire_dep_children);
3203 
3204 	while (child != NULL) {
3205 		if (!IRE_IS_CONDEMNED(child))
3206 			ire_increment_generation(child);
3207 		child = child->ire_dep_sib_next;
3208 	}
3209 }
3210 
3211 /*
3212  * Walk all the children of this ire recursively and increment their
3213  * generation number.
3214  */
3215 void
3216 ire_dep_incr_generation(ire_t *parent)
3217 {
3218 	ip_stack_t	*ipst = parent->ire_ipst;
3219 
3220 	rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
3221 	if (parent->ire_dep_children != NULL)
3222 		ire_dep_increment_children(parent->ire_dep_children);
3223 	rw_exit(&ipst->ips_ire_dep_lock);
3224 }
3225 
3226 /*
3227  * Get a new ire_nce_cache for this IRE as well as its nexthop.
3228  * Returns zero if it succeeds. Can fail due to lack of memory or when
3229  * the route has become unreachable. Returns ENOMEM and ENETUNREACH in those
3230  * cases.
3231  *
3232  * In the in.mpathd case, the ire will have ire_testhidden
3233  * set; so we should create the ncec for the underlying ill.
3234  *
3235  * Note that the error returned by ire_revalidate_nce() is ignored by most
3236  * callers except ire_handle_condemned_nce(), which handles the ENETUNREACH
3237  * error to mark potentially bad ire's. For all the other callers, an
3238  * error return could indicate a transient condition like ENOMEM, or could
3239  * be the result of an interface that is going down/unplumbing. In the former
3240  * case (transient error), we would leave the old stale ire/ire_nce_cache
3241  * in place, and possibly use incorrect link-layer information to send packets
3242  * but would eventually recover. In the latter case (ill down/replumb),
3243  * ire_revalidate_nce() might return a condemned nce back, but we would then
3244  * recover in the packet output path.
3245  */
3246 int
3247 ire_revalidate_nce(ire_t *ire)
3248 {
3249 	nce_t		*nce, *old_nce;
3250 	ire_t		*nexthop;
3251 
3252 	/*
3253 	 * For multicast we conceptually have an NCE but we don't store it
3254 	 * in ire_nce_cache; when ire_to_nce is called we allocate the nce.
3255 	 */
3256 	if (ire->ire_type & IRE_MULTICAST)
3257 		return (0);
3258 
3259 	/* ire_testhidden should only be set on under-interfaces */
3260 	ASSERT(!ire->ire_testhidden || !IS_IPMP(ire->ire_ill));
3261 
3262 	nexthop = ire_nexthop(ire);
3263 	if (nexthop == NULL) {
3264 		/* The route is potentially bad */
3265 		(void) ire_no_good(ire);
3266 		return (ENETUNREACH);
3267 	}
3268 	if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) {
3269 		ASSERT(ire->ire_ill != NULL);
3270 
3271 		if (ire->ire_ipversion == IPV4_VERSION)
3272 			nce = nce_lookup_v4(ire->ire_ill, &ire->ire_addr);
3273 		else
3274 			nce = nce_lookup_v6(ire->ire_ill, &ire->ire_addr_v6);
3275 	} else {
3276 		ASSERT(nexthop->ire_type & IRE_ONLINK);
3277 		if (ire->ire_ipversion == IPV4_VERSION) {
3278 			nce = arp_nce_init(nexthop->ire_ill, nexthop->ire_addr,
3279 			    nexthop->ire_type);
3280 		} else {
3281 			nce = ndp_nce_init(nexthop->ire_ill,
3282 			    &nexthop->ire_addr_v6, nexthop->ire_type);
3283 		}
3284 	}
3285 	if (nce == NULL) {
3286 		/*
3287 		 * Leave the old stale one in place to avoid a NULL
3288 		 * ire_nce_cache.
3289 		 */
3290 		ire_refrele(nexthop);
3291 		return (ENOMEM);
3292 	}
3293 
3294 	if (nexthop != ire) {
3295 		/* Update the nexthop ire */
3296 		mutex_enter(&nexthop->ire_lock);
3297 		old_nce = nexthop->ire_nce_cache;
3298 		if (!IRE_IS_CONDEMNED(nexthop)) {
3299 			nce_refhold(nce);
3300 			nexthop->ire_nce_cache = nce;
3301 		} else {
3302 			nexthop->ire_nce_cache = NULL;
3303 		}
3304 		mutex_exit(&nexthop->ire_lock);
3305 		if (old_nce != NULL)
3306 			nce_refrele(old_nce);
3307 	}
3308 	ire_refrele(nexthop);
3309 
3310 	mutex_enter(&ire->ire_lock);
3311 	old_nce = ire->ire_nce_cache;
3312 	if (!IRE_IS_CONDEMNED(ire)) {
3313 		nce_refhold(nce);
3314 		ire->ire_nce_cache = nce;
3315 	} else {
3316 		ire->ire_nce_cache = NULL;
3317 	}
3318 	mutex_exit(&ire->ire_lock);
3319 	if (old_nce != NULL)
3320 		nce_refrele(old_nce);
3321 
3322 	nce_refrele(nce);
3323 	return (0);
3324 }
3325 
3326 /*
3327  * Get a held nce for a given ire.
3328  * In the common case this is just from ire_nce_cache.
3329  * For IRE_MULTICAST this needs to do an explicit lookup since we do not
3330  * have an IRE_MULTICAST per address.
3331  * Note that this explicitly returns CONDEMNED NCEs. The caller needs those
3332  * so they can check whether the NCE went unreachable (as opposed to was
3333  * condemned for some other reason).
3334  */
3335 nce_t *
3336 ire_to_nce(ire_t *ire, ipaddr_t v4nexthop, const in6_addr_t *v6nexthop)
3337 {
3338 	nce_t	*nce;
3339 
3340 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
3341 		return (NULL);
3342 
3343 	/* ire_testhidden should only be set on under-interfaces */
3344 	ASSERT(!ire->ire_testhidden || !IS_IPMP(ire->ire_ill));
3345 
3346 	mutex_enter(&ire->ire_lock);
3347 	nce = ire->ire_nce_cache;
3348 	if (nce != NULL) {
3349 		nce_refhold(nce);
3350 		mutex_exit(&ire->ire_lock);
3351 		return (nce);
3352 	}
3353 	mutex_exit(&ire->ire_lock);
3354 
3355 	if (ire->ire_type & IRE_MULTICAST) {
3356 		ASSERT(ire->ire_ill != NULL);
3357 
3358 		if (ire->ire_ipversion == IPV4_VERSION) {
3359 			ASSERT(v6nexthop == NULL);
3360 
3361 			nce = arp_nce_init(ire->ire_ill, v4nexthop,
3362 			    ire->ire_type);
3363 		} else {
3364 			ASSERT(v6nexthop != NULL);
3365 			ASSERT(v4nexthop == 0);
3366 			nce = ndp_nce_init(ire->ire_ill, v6nexthop,
3367 			    ire->ire_type);
3368 		}
3369 		return (nce);
3370 	}
3371 	return (NULL);
3372 }
3373 
3374 nce_t *
3375 ire_to_nce_pkt(ire_t *ire, mblk_t *mp)
3376 {
3377 	ipha_t		*ipha;
3378 	ip6_t		*ip6h;
3379 
3380 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
3381 		ipha = (ipha_t *)mp->b_rptr;
3382 		return (ire_to_nce(ire, ipha->ipha_dst, NULL));
3383 	} else {
3384 		ip6h = (ip6_t *)mp->b_rptr;
3385 		return (ire_to_nce(ire, INADDR_ANY, &ip6h->ip6_dst));
3386 	}
3387 }
3388 
3389 /*
3390  * Given an IRE_INTERFACE (that matches more than one address) create
3391  * and return an IRE_IF_CLONE for the specific address.
3392  * Return the generation number.
3393  * Returns NULL is no memory for the IRE.
3394  * Handles both IPv4 and IPv6.
3395  */
3396 ire_t *
3397 ire_create_if_clone(ire_t *ire_if, const in6_addr_t *addr, uint_t *generationp)
3398 {
3399 	ire_t		*ire;
3400 	ire_t		*nire;
3401 
3402 	if (ire_if->ire_ipversion == IPV4_VERSION) {
3403 		ipaddr_t	v4addr;
3404 		ipaddr_t	mask = IP_HOST_MASK;
3405 
3406 		ASSERT(IN6_IS_ADDR_V4MAPPED(addr));
3407 		IN6_V4MAPPED_TO_IPADDR(addr, v4addr);
3408 
3409 		ire = ire_create(
3410 		    (uchar_t *)&v4addr,			/* dest address */
3411 		    (uchar_t *)&mask,			/* mask */
3412 		    (uchar_t *)&ire_if->ire_gateway_addr,
3413 		    IRE_IF_CLONE,			/* IRE type */
3414 		    ire_if->ire_ill,
3415 		    ire_if->ire_zoneid,
3416 		    ire_if->ire_flags | RTF_HOST,
3417 		    NULL,		/* No security attr for IRE_IF_ALL */
3418 		    ire_if->ire_ipst);
3419 	} else {
3420 		ASSERT(!IN6_IS_ADDR_V4MAPPED(addr));
3421 		ire = ire_create_v6(
3422 		    addr,				/* dest address */
3423 		    &ipv6_all_ones,			/* mask */
3424 		    &ire_if->ire_gateway_addr_v6,	/* gateway addr */
3425 		    IRE_IF_CLONE,			/* IRE type */
3426 		    ire_if->ire_ill,
3427 		    ire_if->ire_zoneid,
3428 		    ire_if->ire_flags | RTF_HOST,
3429 		    NULL,		/* No security attr for IRE_IF_ALL */
3430 		    ire_if->ire_ipst);
3431 	}
3432 	if (ire == NULL)
3433 		return (NULL);
3434 
3435 	/* Take the metrics, in particular the mtu, from the IRE_IF */
3436 	ire->ire_metrics = ire_if->ire_metrics;
3437 
3438 	nire = ire_add(ire);
3439 	if (nire == NULL) /* Some failure */
3440 		return (NULL);
3441 
3442 	if (generationp != NULL)
3443 		*generationp = nire->ire_generation;
3444 
3445 	/*
3446 	 * Make sure races don't add a duplicate by
3447 	 * catching the case when an identical was returned.
3448 	 */
3449 	if (nire != ire) {
3450 		ASSERT(nire->ire_identical_ref > 1);
3451 		ire_delete(nire);
3452 	}
3453 	return (nire);
3454 }
3455 
3456 /*
3457  * The argument is an IRE_INTERFACE. Delete all of IRE_IF_CLONE in the
3458  * ire_dep_children (just walk the ire_dep_sib_next since they are all
3459  * immediate children.)
3460  * Since we hold a lock while we remove them we need to defer the actual
3461  * calls to ire_delete() until we have dropped the lock. This makes things
3462  * less efficient since we restart at the top after dropping the lock. But
3463  * we only run when an IRE_INTERFACE is deleted which is infrquent.
3464  *
3465  * Note that ire_dep_children can be any mixture of offlink routes and
3466  * IRE_IF_CLONE entries.
3467  */
3468 void
3469 ire_dep_delete_if_clone(ire_t *parent)
3470 {
3471 	ip_stack_t	*ipst = parent->ire_ipst;
3472 	ire_t		*child, *next;
3473 
3474 restart:
3475 	rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
3476 	if (parent->ire_dep_children == NULL) {
3477 		rw_exit(&ipst->ips_ire_dep_lock);
3478 		return;
3479 	}
3480 	child = parent->ire_dep_children;
3481 	while (child != NULL) {
3482 		next = child->ire_dep_sib_next;
3483 		if ((child->ire_type & IRE_IF_CLONE) &&
3484 		    !IRE_IS_CONDEMNED(child)) {
3485 			ire_refhold(child);
3486 			rw_exit(&ipst->ips_ire_dep_lock);
3487 			ire_delete(child);
3488 			ASSERT(IRE_IS_CONDEMNED(child));
3489 			ire_refrele(child);
3490 			goto restart;
3491 		}
3492 		child = next;
3493 	}
3494 	rw_exit(&ipst->ips_ire_dep_lock);
3495 }
3496 
3497 /*
3498  * ire_pref() is used in recursive route-resolution for a destination to
3499  * determine the preference of an ire, where "preference" is determined
3500  * based on the level of indirection to the destination of the ire.
3501  * A higher preference indicates that fewer lookups are needed to complete
3502  * recursive route lookup. Thus
3503  * ire_pref(RTF_INDIRECT) < ire_pref(IRE_IF_RESOLVER) < ire_pref(IRE_PREF_CLONE)
3504  */
3505 int
3506 ire_pref(ire_t *ire)
3507 {
3508 	if (ire->ire_flags & RTF_INDIRECT)
3509 		return (1);
3510 	if (ire->ire_type & IRE_OFFLINK)
3511 		return (2);
3512 	if (ire->ire_type & (IRE_IF_RESOLVER|IRE_IF_NORESOLVER))
3513 		return (3);
3514 	if (ire->ire_type & IRE_IF_CLONE)
3515 		return (4);
3516 	if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK|IRE_BROADCAST))
3517 		return (5);
3518 	return (-1); /* unknown ire_type */
3519 }
3520