xref: /titanic_52/usr/src/uts/common/inet/ip/ip_ire.c (revision 2f172c55ef76964744bc62b4500ece87f3089b4d)
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 = ire->ire_ill;
865 
866 	ASSERT(match_flags != 0 || zoneid != ALL_ZONES);
867 
868 	if (zoneid != ALL_ZONES && zoneid != ire->ire_zoneid &&
869 	    ire->ire_zoneid != ALL_ZONES) {
870 		/*
871 		 * We're walking the IREs for a specific zone. The only relevant
872 		 * IREs are:
873 		 * - all IREs with a matching ire_zoneid
874 		 * - IRE_IF_ALL IREs for interfaces with a usable source addr
875 		 *   with a matching zone
876 		 * - IRE_OFFLINK with a gateway reachable from the zone
877 		 * Note that ealier we only did the IRE_OFFLINK check for
878 		 * IRE_DEFAULT (and only when we had multiple IRE_DEFAULTs).
879 		 */
880 		if (ire->ire_type & IRE_ONLINK) {
881 			uint_t	ifindex;
882 
883 			/*
884 			 * Note there is no IRE_INTERFACE on vniN thus
885 			 * can't do an IRE lookup for a matching route.
886 			 */
887 			ifindex = dst_ill->ill_usesrc_ifindex;
888 			if (ifindex == 0)
889 				return (B_FALSE);
890 
891 			/*
892 			 * If there is a usable source address in the
893 			 * zone, then it's ok to return an
894 			 * IRE_INTERFACE
895 			 */
896 			if (!ipif_zone_avail(ifindex, dst_ill->ill_isv6,
897 			    zoneid, ipst)) {
898 				return (B_FALSE);
899 			}
900 		}
901 		if (dst_ill != NULL && (ire->ire_type & IRE_OFFLINK)) {
902 			ipif_t	*tipif;
903 
904 			mutex_enter(&dst_ill->ill_lock);
905 			for (tipif = dst_ill->ill_ipif;
906 			    tipif != NULL; tipif = tipif->ipif_next) {
907 				if (!IPIF_IS_CONDEMNED(tipif) &&
908 				    (tipif->ipif_flags & IPIF_UP) &&
909 				    (tipif->ipif_zoneid == zoneid ||
910 				    tipif->ipif_zoneid == ALL_ZONES))
911 					break;
912 			}
913 			mutex_exit(&dst_ill->ill_lock);
914 			if (tipif == NULL) {
915 				return (B_FALSE);
916 			}
917 		}
918 	}
919 	/*
920 	 * Except for ALL_ZONES, we only match the offlink routes
921 	 * where ire_gateway_addr has an IRE_INTERFACE for the zoneid.
922 	 */
923 	if ((ire->ire_type & IRE_OFFLINK) && zoneid != ALL_ZONES) {
924 		in6_addr_t gw_addr_v6;
925 
926 		if (ire->ire_ipversion == IPV4_VERSION) {
927 			if (!ire_gateway_ok_zone_v4(ire->ire_gateway_addr,
928 			    zoneid, dst_ill, NULL, ipst, B_FALSE))
929 				return (B_FALSE);
930 		} else {
931 			ASSERT(ire->ire_ipversion == IPV6_VERSION);
932 			mutex_enter(&ire->ire_lock);
933 			gw_addr_v6 = ire->ire_gateway_addr_v6;
934 			mutex_exit(&ire->ire_lock);
935 
936 			if (!ire_gateway_ok_zone_v6(&gw_addr_v6, zoneid,
937 			    dst_ill, NULL, ipst, B_FALSE))
938 				return (B_FALSE);
939 		}
940 	}
941 
942 	if (((!(match_flags & MATCH_IRE_TYPE)) ||
943 	    (ire->ire_type & ire_type)) &&
944 	    ((!(match_flags & MATCH_IRE_ILL)) ||
945 	    (dst_ill == ill ||
946 	    dst_ill != NULL && IS_IN_SAME_ILLGRP(dst_ill, ill)))) {
947 		return (B_TRUE);
948 	}
949 	return (B_FALSE);
950 }
951 
952 int
953 rtfunc(struct radix_node *rn, void *arg)
954 {
955 	struct rtfuncarg *rtf = arg;
956 	struct rt_entry *rt;
957 	irb_t *irb;
958 	ire_t *ire;
959 	boolean_t ret;
960 
961 	rt = (struct rt_entry *)rn;
962 	ASSERT(rt != NULL);
963 	irb = &rt->rt_irb;
964 	for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
965 		if ((rtf->rt_match_flags != 0) ||
966 		    (rtf->rt_zoneid != ALL_ZONES)) {
967 			ret = ire_walk_ill_match(rtf->rt_match_flags,
968 			    rtf->rt_ire_type, ire,
969 			    rtf->rt_ill, rtf->rt_zoneid, rtf->rt_ipst);
970 		} else {
971 			ret = B_TRUE;
972 		}
973 		if (ret)
974 			(*rtf->rt_func)(ire, rtf->rt_arg);
975 	}
976 	return (0);
977 }
978 
979 /*
980  * Walk the ftable entries that match the ill.
981  */
982 void
983 ire_walk_ill_tables(uint_t match_flags, uint_t ire_type, pfv_t func,
984     void *arg, size_t ftbl_sz, size_t htbl_sz, irb_t **ipftbl,
985     ill_t *ill, zoneid_t zoneid,
986     ip_stack_t *ipst)
987 {
988 	irb_t	*irb_ptr;
989 	irb_t	*irb;
990 	ire_t	*ire;
991 	int i, j;
992 	boolean_t ret;
993 	struct rtfuncarg rtfarg;
994 
995 	ASSERT((!(match_flags & MATCH_IRE_ILL)) || (ill != NULL));
996 	ASSERT(!(match_flags & MATCH_IRE_TYPE) || (ire_type != 0));
997 
998 	/* knobs such that routine is called only for v6 case */
999 	if (ipftbl == ipst->ips_ip_forwarding_table_v6) {
1000 		for (i = (ftbl_sz - 1);  i >= 0; i--) {
1001 			if ((irb_ptr = ipftbl[i]) == NULL)
1002 				continue;
1003 			for (j = 0; j < htbl_sz; j++) {
1004 				irb = &irb_ptr[j];
1005 				if (irb->irb_ire == NULL)
1006 					continue;
1007 
1008 				irb_refhold(irb);
1009 				for (ire = irb->irb_ire; ire != NULL;
1010 				    ire = ire->ire_next) {
1011 					if (match_flags == 0 &&
1012 					    zoneid == ALL_ZONES) {
1013 						ret = B_TRUE;
1014 					} else {
1015 						ret =
1016 						    ire_walk_ill_match(
1017 						    match_flags,
1018 						    ire_type, ire, ill,
1019 						    zoneid, ipst);
1020 					}
1021 					if (ret)
1022 						(*func)(ire, arg);
1023 				}
1024 				irb_refrele(irb);
1025 			}
1026 		}
1027 	} else {
1028 		bzero(&rtfarg, sizeof (rtfarg));
1029 		rtfarg.rt_func = func;
1030 		rtfarg.rt_arg = arg;
1031 		if (match_flags != 0) {
1032 			rtfarg.rt_match_flags = match_flags;
1033 		}
1034 		rtfarg.rt_ire_type = ire_type;
1035 		rtfarg.rt_ill = ill;
1036 		rtfarg.rt_zoneid = zoneid;
1037 		rtfarg.rt_ipst = ipst;	/* No netstack_hold */
1038 		(void) ipst->ips_ip_ftable->rnh_walktree_mt(
1039 		    ipst->ips_ip_ftable,
1040 		    rtfunc, &rtfarg, irb_refhold_rn, irb_refrele_rn);
1041 	}
1042 }
1043 
1044 /*
1045  * This function takes a mask and returns
1046  * number of bits set in the mask. If no
1047  * bit is set it returns 0.
1048  * Assumes a contiguous mask.
1049  */
1050 int
1051 ip_mask_to_plen(ipaddr_t mask)
1052 {
1053 	return (mask == 0 ? 0 : IP_ABITS - (ffs(ntohl(mask)) -1));
1054 }
1055 
1056 /*
1057  * Convert length for a mask to the mask.
1058  */
1059 ipaddr_t
1060 ip_plen_to_mask(uint_t masklen)
1061 {
1062 	if (masklen == 0)
1063 		return (0);
1064 
1065 	return (htonl(IP_HOST_MASK << (IP_ABITS - masklen)));
1066 }
1067 
1068 void
1069 ire_atomic_end(irb_t *irb_ptr, ire_t *ire)
1070 {
1071 	ill_t		*ill;
1072 
1073 	ill = ire->ire_ill;
1074 	if (ill != NULL)
1075 		mutex_exit(&ill->ill_lock);
1076 	rw_exit(&irb_ptr->irb_lock);
1077 }
1078 
1079 /*
1080  * ire_add_v[46] atomically make sure that the ill associated
1081  * with the new ire is not going away i.e., we check ILL_CONDEMNED.
1082  */
1083 int
1084 ire_atomic_start(irb_t *irb_ptr, ire_t *ire)
1085 {
1086 	ill_t		*ill;
1087 
1088 	ill = ire->ire_ill;
1089 
1090 	rw_enter(&irb_ptr->irb_lock, RW_WRITER);
1091 	if (ill != NULL) {
1092 		mutex_enter(&ill->ill_lock);
1093 
1094 		/*
1095 		 * Don't allow IRE's to be created on dying ills.
1096 		 */
1097 		if (ill->ill_state_flags & ILL_CONDEMNED) {
1098 			ire_atomic_end(irb_ptr, ire);
1099 			return (ENXIO);
1100 		}
1101 
1102 		if (IS_UNDER_IPMP(ill)) {
1103 			int	error = 0;
1104 			mutex_enter(&ill->ill_phyint->phyint_lock);
1105 			if (!ipmp_ill_is_active(ill) &&
1106 			    IRE_HIDDEN_TYPE(ire->ire_type) &&
1107 			    !ire->ire_testhidden) {
1108 				error = EINVAL;
1109 			}
1110 			mutex_exit(&ill->ill_phyint->phyint_lock);
1111 			if (error != 0) {
1112 				ire_atomic_end(irb_ptr, ire);
1113 				return (error);
1114 			}
1115 		}
1116 
1117 	}
1118 	return (0);
1119 }
1120 
1121 /*
1122  * Add a fully initialized IRE to the forwarding table.
1123  * This returns NULL on failure, or a held IRE on success.
1124  * Normally the returned IRE is the same as the argument. But a different
1125  * IRE will be returned if the added IRE is deemed identical to an existing
1126  * one. In that case ire_identical_ref will be increased.
1127  * The caller always needs to do an ire_refrele() on the returned IRE.
1128  */
1129 ire_t *
1130 ire_add(ire_t *ire)
1131 {
1132 	if (IRE_HIDDEN_TYPE(ire->ire_type) &&
1133 	    ire->ire_ill != NULL && IS_UNDER_IPMP(ire->ire_ill)) {
1134 		/*
1135 		 * IREs hosted on interfaces that are under IPMP
1136 		 * should be hidden so that applications don't
1137 		 * accidentally end up sending packets with test
1138 		 * addresses as their source addresses, or
1139 		 * sending out interfaces that are e.g. IFF_INACTIVE.
1140 		 * Hide them here.
1141 		 */
1142 		ire->ire_testhidden = B_TRUE;
1143 	}
1144 
1145 	if (ire->ire_ipversion == IPV6_VERSION)
1146 		return (ire_add_v6(ire));
1147 	else
1148 		return (ire_add_v4(ire));
1149 }
1150 
1151 /*
1152  * Add a fully initialized IPv4 IRE to the forwarding table.
1153  * This returns NULL on failure, or a held IRE on success.
1154  * Normally the returned IRE is the same as the argument. But a different
1155  * IRE will be returned if the added IRE is deemed identical to an existing
1156  * one. In that case ire_identical_ref will be increased.
1157  * The caller always needs to do an ire_refrele() on the returned IRE.
1158  */
1159 static ire_t *
1160 ire_add_v4(ire_t *ire)
1161 {
1162 	ire_t	*ire1;
1163 	irb_t	*irb_ptr;
1164 	ire_t	**irep;
1165 	int	match_flags;
1166 	int	error;
1167 	ip_stack_t	*ipst = ire->ire_ipst;
1168 
1169 	if (ire->ire_ill != NULL)
1170 		ASSERT(!MUTEX_HELD(&ire->ire_ill->ill_lock));
1171 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
1172 
1173 	/* Make sure the address is properly masked. */
1174 	ire->ire_addr &= ire->ire_mask;
1175 
1176 	match_flags = (MATCH_IRE_MASK | MATCH_IRE_TYPE | MATCH_IRE_GW);
1177 
1178 	if (ire->ire_ill != NULL) {
1179 		match_flags |= MATCH_IRE_ILL;
1180 	}
1181 	irb_ptr = ire_get_bucket(ire);
1182 	if (irb_ptr == NULL) {
1183 		printf("no bucket for %p\n", (void *)ire);
1184 		ire_delete(ire);
1185 		return (NULL);
1186 	}
1187 
1188 	/*
1189 	 * Start the atomic add of the ire. Grab the ill lock,
1190 	 * the bucket lock. Check for condemned.
1191 	 */
1192 	error = ire_atomic_start(irb_ptr, ire);
1193 	if (error != 0) {
1194 		printf("no ire_atomic_start for %p\n", (void *)ire);
1195 		ire_delete(ire);
1196 		irb_refrele(irb_ptr);
1197 		return (NULL);
1198 	}
1199 	/*
1200 	 * If we are creating a hidden IRE, make sure we search for
1201 	 * hidden IREs when searching for duplicates below.
1202 	 * Otherwise, we might find an IRE on some other interface
1203 	 * that's not marked hidden.
1204 	 */
1205 	if (ire->ire_testhidden)
1206 		match_flags |= MATCH_IRE_TESTHIDDEN;
1207 
1208 	/*
1209 	 * Atomically check for duplicate and insert in the table.
1210 	 */
1211 	for (ire1 = irb_ptr->irb_ire; ire1 != NULL; ire1 = ire1->ire_next) {
1212 		if (IRE_IS_CONDEMNED(ire1))
1213 			continue;
1214 		/*
1215 		 * Here we need an exact match on zoneid, i.e.,
1216 		 * ire_match_args doesn't fit.
1217 		 */
1218 		if (ire1->ire_zoneid != ire->ire_zoneid)
1219 			continue;
1220 
1221 		if (ire1->ire_type != ire->ire_type)
1222 			continue;
1223 
1224 		/*
1225 		 * Note: We do not allow multiple routes that differ only
1226 		 * in the gateway security attributes; such routes are
1227 		 * considered duplicates.
1228 		 * To change that we explicitly have to treat them as
1229 		 * different here.
1230 		 */
1231 		if (ire_match_args(ire1, ire->ire_addr, ire->ire_mask,
1232 		    ire->ire_gateway_addr, ire->ire_type, ire->ire_ill,
1233 		    ire->ire_zoneid, NULL, match_flags)) {
1234 			/*
1235 			 * Return the old ire after doing a REFHOLD.
1236 			 * As most of the callers continue to use the IRE
1237 			 * after adding, we return a held ire. This will
1238 			 * avoid a lookup in the caller again. If the callers
1239 			 * don't want to use it, they need to do a REFRELE.
1240 			 */
1241 			atomic_add_32(&ire1->ire_identical_ref, 1);
1242 			DTRACE_PROBE2(ire__add__exist, ire_t *, ire1,
1243 			    ire_t *, ire);
1244 			ire_refhold(ire1);
1245 			ire_atomic_end(irb_ptr, ire);
1246 			ire_delete(ire);
1247 			irb_refrele(irb_ptr);
1248 			return (ire1);
1249 		}
1250 	}
1251 
1252 	/*
1253 	 * Normally we do head insertion since most things do not care about
1254 	 * the order of the IREs in the bucket. Note that ip_cgtp_bcast_add
1255 	 * assumes we at least do head insertion so that its IRE_BROADCAST
1256 	 * arrive ahead of existing IRE_HOST for the same address.
1257 	 * However, due to shared-IP zones (and restrict_interzone_loopback)
1258 	 * we can have an IRE_LOCAL as well as IRE_IF_CLONE for the same
1259 	 * address. For that reason we do tail insertion for IRE_IF_CLONE.
1260 	 * Due to the IRE_BROADCAST on cgtp0, which must be last in the bucket,
1261 	 * we do tail insertion of IRE_BROADCASTs that do not have RTF_MULTIRT
1262 	 * set.
1263 	 */
1264 	irep = (ire_t **)irb_ptr;
1265 	if ((ire->ire_type & IRE_IF_CLONE) ||
1266 	    ((ire->ire_type & IRE_BROADCAST) &&
1267 	    !(ire->ire_flags & RTF_MULTIRT))) {
1268 		while ((ire1 = *irep) != NULL)
1269 			irep = &ire1->ire_next;
1270 	}
1271 	/* Insert at *irep */
1272 	ire1 = *irep;
1273 	if (ire1 != NULL)
1274 		ire1->ire_ptpn = &ire->ire_next;
1275 	ire->ire_next = ire1;
1276 	/* Link the new one in. */
1277 	ire->ire_ptpn = irep;
1278 
1279 	/*
1280 	 * ire_walk routines de-reference ire_next without holding
1281 	 * a lock. Before we point to the new ire, we want to make
1282 	 * sure the store that sets the ire_next of the new ire
1283 	 * reaches global visibility, so that ire_walk routines
1284 	 * don't see a truncated list of ires i.e if the ire_next
1285 	 * of the new ire gets set after we do "*irep = ire" due
1286 	 * to re-ordering, the ire_walk thread will see a NULL
1287 	 * once it accesses the ire_next of the new ire.
1288 	 * membar_producer() makes sure that the following store
1289 	 * happens *after* all of the above stores.
1290 	 */
1291 	membar_producer();
1292 	*irep = ire;
1293 	ire->ire_bucket = irb_ptr;
1294 	/*
1295 	 * We return a bumped up IRE above. Keep it symmetrical
1296 	 * so that the callers will always have to release. This
1297 	 * helps the callers of this function because they continue
1298 	 * to use the IRE after adding and hence they don't have to
1299 	 * lookup again after we return the IRE.
1300 	 *
1301 	 * NOTE : We don't have to use atomics as this is appearing
1302 	 * in the list for the first time and no one else can bump
1303 	 * up the reference count on this yet.
1304 	 */
1305 	ire_refhold_locked(ire);
1306 	BUMP_IRE_STATS(ipst->ips_ire_stats_v4, ire_stats_inserted);
1307 
1308 	irb_ptr->irb_ire_cnt++;
1309 	if (irb_ptr->irb_marks & IRB_MARK_DYNAMIC)
1310 		irb_ptr->irb_nire++;
1311 
1312 	if (ire->ire_ill != NULL) {
1313 		ire->ire_ill->ill_ire_cnt++;
1314 		ASSERT(ire->ire_ill->ill_ire_cnt != 0);	/* Wraparound */
1315 	}
1316 
1317 	ire_atomic_end(irb_ptr, ire);
1318 
1319 	/* Make any caching of the IREs be notified or updated */
1320 	ire_flush_cache_v4(ire, IRE_FLUSH_ADD);
1321 
1322 	if (ire->ire_ill != NULL)
1323 		ASSERT(!MUTEX_HELD(&ire->ire_ill->ill_lock));
1324 	irb_refrele(irb_ptr);
1325 	return (ire);
1326 }
1327 
1328 /*
1329  * irb_refrele is the only caller of the function. ire_unlink calls to
1330  * do the final cleanup for this ire.
1331  */
1332 void
1333 ire_cleanup(ire_t *ire)
1334 {
1335 	ire_t *ire_next;
1336 	ip_stack_t *ipst = ire->ire_ipst;
1337 
1338 	ASSERT(ire != NULL);
1339 
1340 	while (ire != NULL) {
1341 		ire_next = ire->ire_next;
1342 		if (ire->ire_ipversion == IPV4_VERSION) {
1343 			ire_delete_v4(ire);
1344 			BUMP_IRE_STATS(ipst->ips_ire_stats_v4,
1345 			    ire_stats_deleted);
1346 		} else {
1347 			ASSERT(ire->ire_ipversion == IPV6_VERSION);
1348 			ire_delete_v6(ire);
1349 			BUMP_IRE_STATS(ipst->ips_ire_stats_v6,
1350 			    ire_stats_deleted);
1351 		}
1352 		/*
1353 		 * Now it's really out of the list. Before doing the
1354 		 * REFRELE, set ire_next to NULL as ire_inactive asserts
1355 		 * so.
1356 		 */
1357 		ire->ire_next = NULL;
1358 		ire_refrele_notr(ire);
1359 		ire = ire_next;
1360 	}
1361 }
1362 
1363 /*
1364  * irb_refrele is the only caller of the function. It calls to unlink
1365  * all the CONDEMNED ires from this bucket.
1366  */
1367 ire_t *
1368 ire_unlink(irb_t *irb)
1369 {
1370 	ire_t *ire;
1371 	ire_t *ire1;
1372 	ire_t **ptpn;
1373 	ire_t *ire_list = NULL;
1374 
1375 	ASSERT(RW_WRITE_HELD(&irb->irb_lock));
1376 	ASSERT(((irb->irb_marks & IRB_MARK_DYNAMIC) && irb->irb_refcnt == 1) ||
1377 	    (irb->irb_refcnt == 0));
1378 	ASSERT(irb->irb_marks & IRB_MARK_CONDEMNED);
1379 	ASSERT(irb->irb_ire != NULL);
1380 
1381 	for (ire = irb->irb_ire; ire != NULL; ire = ire1) {
1382 		ire1 = ire->ire_next;
1383 		if (IRE_IS_CONDEMNED(ire)) {
1384 			ptpn = ire->ire_ptpn;
1385 			ire1 = ire->ire_next;
1386 			if (ire1)
1387 				ire1->ire_ptpn = ptpn;
1388 			*ptpn = ire1;
1389 			ire->ire_ptpn = NULL;
1390 			ire->ire_next = NULL;
1391 
1392 			/*
1393 			 * We need to call ire_delete_v4 or ire_delete_v6 to
1394 			 * clean up dependents and the redirects pointing at
1395 			 * the default gateway. We need to drop the lock
1396 			 * as ire_flush_cache/ire_delete_host_redircts require
1397 			 * so. But we can't drop the lock, as ire_unlink needs
1398 			 * to atomically remove the ires from the list.
1399 			 * So, create a temporary list of CONDEMNED ires
1400 			 * for doing ire_delete_v4/ire_delete_v6 operations
1401 			 * later on.
1402 			 */
1403 			ire->ire_next = ire_list;
1404 			ire_list = ire;
1405 		}
1406 	}
1407 	irb->irb_marks &= ~IRB_MARK_CONDEMNED;
1408 	return (ire_list);
1409 }
1410 
1411 /*
1412  * Clean up the radix node for this ire. Must be called by irb_refrele
1413  * when there are no ire's left in the bucket. Returns TRUE if the bucket
1414  * is deleted and freed.
1415  */
1416 boolean_t
1417 irb_inactive(irb_t *irb)
1418 {
1419 	struct rt_entry *rt;
1420 	struct radix_node *rn;
1421 	ip_stack_t *ipst = irb->irb_ipst;
1422 
1423 	ASSERT(irb->irb_ipst != NULL);
1424 
1425 	rt = IRB2RT(irb);
1426 	rn = (struct radix_node *)rt;
1427 
1428 	/* first remove it from the radix tree. */
1429 	RADIX_NODE_HEAD_WLOCK(ipst->ips_ip_ftable);
1430 	rw_enter(&irb->irb_lock, RW_WRITER);
1431 	if (irb->irb_refcnt == 1 && irb->irb_nire == 0) {
1432 		rn = ipst->ips_ip_ftable->rnh_deladdr(rn->rn_key, rn->rn_mask,
1433 		    ipst->ips_ip_ftable);
1434 		DTRACE_PROBE1(irb__free, rt_t *,  rt);
1435 		ASSERT((void *)rn == (void *)rt);
1436 		Free(rt, rt_entry_cache);
1437 		/* irb_lock is freed */
1438 		RADIX_NODE_HEAD_UNLOCK(ipst->ips_ip_ftable);
1439 		return (B_TRUE);
1440 	}
1441 	rw_exit(&irb->irb_lock);
1442 	RADIX_NODE_HEAD_UNLOCK(ipst->ips_ip_ftable);
1443 	return (B_FALSE);
1444 }
1445 
1446 /*
1447  * Delete the specified IRE.
1448  * We assume that if ire_bucket is not set then ire_ill->ill_ire_cnt was
1449  * not incremented i.e., that the insertion in the bucket and the increment
1450  * of that counter is done atomically.
1451  */
1452 void
1453 ire_delete(ire_t *ire)
1454 {
1455 	ire_t	*ire1;
1456 	ire_t	**ptpn;
1457 	irb_t	*irb;
1458 	nce_t	*nce;
1459 	ip_stack_t	*ipst = ire->ire_ipst;
1460 
1461 	/* We can clear ire_nce_cache under ire_lock even if the IRE is used */
1462 	mutex_enter(&ire->ire_lock);
1463 	nce = ire->ire_nce_cache;
1464 	ire->ire_nce_cache = NULL;
1465 	mutex_exit(&ire->ire_lock);
1466 	if (nce != NULL)
1467 		nce_refrele(nce);
1468 
1469 	if ((irb = ire->ire_bucket) == NULL) {
1470 		/*
1471 		 * It was never inserted in the list. Should call REFRELE
1472 		 * to free this IRE.
1473 		 */
1474 		ire_refrele_notr(ire);
1475 		return;
1476 	}
1477 
1478 	/*
1479 	 * Move the use counts from an IRE_IF_CLONE to its parent
1480 	 * IRE_INTERFACE.
1481 	 * We need to do this before acquiring irb_lock.
1482 	 */
1483 	if (ire->ire_type & IRE_IF_CLONE) {
1484 		ire_t *parent;
1485 
1486 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
1487 		if ((parent = ire->ire_dep_parent) != NULL) {
1488 			parent->ire_ob_pkt_count += ire->ire_ob_pkt_count;
1489 			parent->ire_ib_pkt_count += ire->ire_ib_pkt_count;
1490 			ire->ire_ob_pkt_count = 0;
1491 			ire->ire_ib_pkt_count = 0;
1492 		}
1493 		rw_exit(&ipst->ips_ire_dep_lock);
1494 	}
1495 
1496 	rw_enter(&irb->irb_lock, RW_WRITER);
1497 	if (ire->ire_ptpn == NULL) {
1498 		/*
1499 		 * Some other thread has removed us from the list.
1500 		 * It should have done the REFRELE for us.
1501 		 */
1502 		rw_exit(&irb->irb_lock);
1503 		return;
1504 	}
1505 
1506 	if (!IRE_IS_CONDEMNED(ire)) {
1507 		/* Is this an IRE representing multiple duplicate entries? */
1508 		ASSERT(ire->ire_identical_ref >= 1);
1509 		if (atomic_add_32_nv(&ire->ire_identical_ref, -1) != 0) {
1510 			/* Removed one of the identical parties */
1511 			rw_exit(&irb->irb_lock);
1512 			return;
1513 		}
1514 
1515 		irb->irb_ire_cnt--;
1516 		ire_make_condemned(ire);
1517 	}
1518 
1519 	if (irb->irb_refcnt != 0) {
1520 		/*
1521 		 * The last thread to leave this bucket will
1522 		 * delete this ire.
1523 		 */
1524 		irb->irb_marks |= IRB_MARK_CONDEMNED;
1525 		rw_exit(&irb->irb_lock);
1526 		return;
1527 	}
1528 
1529 	/*
1530 	 * Normally to delete an ire, we walk the bucket. While we
1531 	 * walk the bucket, we normally bump up irb_refcnt and hence
1532 	 * we return from above where we mark CONDEMNED and the ire
1533 	 * gets deleted from ire_unlink. This case is where somebody
1534 	 * knows the ire e.g by doing a lookup, and wants to delete the
1535 	 * IRE. irb_refcnt would be 0 in this case if nobody is walking
1536 	 * the bucket.
1537 	 */
1538 	ptpn = ire->ire_ptpn;
1539 	ire1 = ire->ire_next;
1540 	if (ire1 != NULL)
1541 		ire1->ire_ptpn = ptpn;
1542 	ASSERT(ptpn != NULL);
1543 	*ptpn = ire1;
1544 	ire->ire_ptpn = NULL;
1545 	ire->ire_next = NULL;
1546 	if (ire->ire_ipversion == IPV6_VERSION) {
1547 		BUMP_IRE_STATS(ipst->ips_ire_stats_v6, ire_stats_deleted);
1548 	} else {
1549 		BUMP_IRE_STATS(ipst->ips_ire_stats_v4, ire_stats_deleted);
1550 	}
1551 	rw_exit(&irb->irb_lock);
1552 
1553 	/* Cleanup dependents and related stuff */
1554 	if (ire->ire_ipversion == IPV6_VERSION) {
1555 		ire_delete_v6(ire);
1556 	} else {
1557 		ire_delete_v4(ire);
1558 	}
1559 	/*
1560 	 * We removed it from the list. Decrement the
1561 	 * reference count.
1562 	 */
1563 	ire_refrele_notr(ire);
1564 }
1565 
1566 /*
1567  * Delete the specified IRE.
1568  * All calls should use ire_delete().
1569  * Sometimes called as writer though not required by this function.
1570  *
1571  * NOTE : This function is called only if the ire was added
1572  * in the list.
1573  */
1574 static void
1575 ire_delete_v4(ire_t *ire)
1576 {
1577 	ip_stack_t	*ipst = ire->ire_ipst;
1578 
1579 	ASSERT(ire->ire_refcnt >= 1);
1580 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
1581 
1582 	ire_flush_cache_v4(ire, IRE_FLUSH_DELETE);
1583 	if (ire->ire_type == IRE_DEFAULT) {
1584 		/*
1585 		 * when a default gateway is going away
1586 		 * delete all the host redirects pointing at that
1587 		 * gateway.
1588 		 */
1589 		ire_delete_host_redirects(ire->ire_gateway_addr, ipst);
1590 	}
1591 
1592 	/*
1593 	 * If we are deleting an IRE_INTERFACE then we make sure we also
1594 	 * delete any IRE_IF_CLONE that has been created from it.
1595 	 * Those are always in ire_dep_children.
1596 	 */
1597 	if ((ire->ire_type & IRE_INTERFACE) && ire->ire_dep_children != NULL)
1598 		ire_dep_delete_if_clone(ire);
1599 
1600 	/* Remove from parent dependencies and child */
1601 	rw_enter(&ipst->ips_ire_dep_lock, RW_WRITER);
1602 	if (ire->ire_dep_parent != NULL)
1603 		ire_dep_remove(ire);
1604 
1605 	while (ire->ire_dep_children != NULL)
1606 		ire_dep_remove(ire->ire_dep_children);
1607 	rw_exit(&ipst->ips_ire_dep_lock);
1608 }
1609 
1610 /*
1611  * ire_refrele is the only caller of the function. It calls
1612  * to free the ire when the reference count goes to zero.
1613  */
1614 void
1615 ire_inactive(ire_t *ire)
1616 {
1617 	ill_t	*ill;
1618 	irb_t 	*irb;
1619 	ip_stack_t	*ipst = ire->ire_ipst;
1620 
1621 	ASSERT(ire->ire_refcnt == 0);
1622 	ASSERT(ire->ire_ptpn == NULL);
1623 	ASSERT(ire->ire_next == NULL);
1624 
1625 	/* Count how many condemned ires for kmem_cache callback */
1626 	if (IRE_IS_CONDEMNED(ire))
1627 		atomic_add_32(&ipst->ips_num_ire_condemned, -1);
1628 
1629 	if (ire->ire_gw_secattr != NULL) {
1630 		ire_gw_secattr_free(ire->ire_gw_secattr);
1631 		ire->ire_gw_secattr = NULL;
1632 	}
1633 
1634 	/*
1635 	 * ire_nce_cache is cleared in ire_delete, and we make sure we don't
1636 	 * set it once the ire is marked condemned.
1637 	 */
1638 	ASSERT(ire->ire_nce_cache == NULL);
1639 
1640 	/*
1641 	 * Since any parent would have a refhold on us they would already
1642 	 * have been removed.
1643 	 */
1644 	ASSERT(ire->ire_dep_parent == NULL);
1645 	ASSERT(ire->ire_dep_sib_next == NULL);
1646 	ASSERT(ire->ire_dep_sib_ptpn == NULL);
1647 
1648 	/*
1649 	 * Since any children would have a refhold on us they should have
1650 	 * already been removed.
1651 	 */
1652 	ASSERT(ire->ire_dep_children == NULL);
1653 
1654 	/*
1655 	 * ill_ire_ref is increased when the IRE is inserted in the
1656 	 * bucket - not when the IRE is created.
1657 	 */
1658 	irb = ire->ire_bucket;
1659 	ill = ire->ire_ill;
1660 	if (irb != NULL && ill != NULL) {
1661 		mutex_enter(&ill->ill_lock);
1662 		ASSERT(ill->ill_ire_cnt != 0);
1663 		DTRACE_PROBE3(ill__decr__cnt, (ill_t *), ill,
1664 		    (char *), "ire", (void *), ire);
1665 		ill->ill_ire_cnt--;
1666 		if (ILL_DOWN_OK(ill)) {
1667 			/* Drops the ill lock */
1668 			ipif_ill_refrele_tail(ill);
1669 		} else {
1670 			mutex_exit(&ill->ill_lock);
1671 		}
1672 	}
1673 	ire->ire_ill = NULL;
1674 
1675 	/* This should be true for both V4 and V6 */
1676 	if (irb != NULL && (irb->irb_marks & IRB_MARK_DYNAMIC)) {
1677 		rw_enter(&irb->irb_lock, RW_WRITER);
1678 		irb->irb_nire--;
1679 		/*
1680 		 * Instead of examining the conditions for freeing
1681 		 * the radix node here, we do it by calling
1682 		 * irb_refrele which is a single point in the code
1683 		 * that embeds that logic. Bump up the refcnt to
1684 		 * be able to call irb_refrele
1685 		 */
1686 		irb_refhold_locked(irb);
1687 		rw_exit(&irb->irb_lock);
1688 		irb_refrele(irb);
1689 	}
1690 
1691 #ifdef DEBUG
1692 	ire_trace_cleanup(ire);
1693 #endif
1694 	mutex_destroy(&ire->ire_lock);
1695 	if (ire->ire_ipversion == IPV6_VERSION) {
1696 		BUMP_IRE_STATS(ipst->ips_ire_stats_v6, ire_stats_freed);
1697 	} else {
1698 		BUMP_IRE_STATS(ipst->ips_ire_stats_v4, ire_stats_freed);
1699 	}
1700 	kmem_cache_free(ire_cache, ire);
1701 }
1702 
1703 /*
1704  * ire_update_generation is the callback function provided by
1705  * ire_get_bucket() to update the generation number of any
1706  * matching shorter route when a new route is added.
1707  *
1708  * This fucntion always returns a failure return (B_FALSE)
1709  * to force the caller (rn_matchaddr_args)
1710  * to back-track up the tree looking for shorter matches.
1711  */
1712 /* ARGSUSED */
1713 static boolean_t
1714 ire_update_generation(struct radix_node *rn, void *arg)
1715 {
1716 	struct rt_entry *rt = (struct rt_entry *)rn;
1717 
1718 	/* We need to handle all in the same bucket */
1719 	irb_increment_generation(&rt->rt_irb);
1720 	return (B_FALSE);
1721 }
1722 
1723 /*
1724  * Take care of all the generation numbers in the bucket.
1725  */
1726 void
1727 irb_increment_generation(irb_t *irb)
1728 {
1729 	ire_t *ire;
1730 
1731 	if (irb == NULL || irb->irb_ire_cnt == 0)
1732 		return;
1733 
1734 	irb_refhold(irb);
1735 	for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
1736 		if (!IRE_IS_CONDEMNED(ire))
1737 			ire_increment_generation(ire);	/* Ourselves */
1738 		ire_dep_incr_generation(ire);	/* Dependants */
1739 	}
1740 	irb_refrele(irb);
1741 }
1742 
1743 /*
1744  * When an IRE is added or deleted this routine is called to make sure
1745  * any caching of IRE information is notified or updated.
1746  *
1747  * The flag argument indicates if the flush request is due to addition
1748  * of new route (IRE_FLUSH_ADD), deletion of old route (IRE_FLUSH_DELETE),
1749  * or a change to ire_gateway_addr (IRE_FLUSH_GWCHANGE).
1750  */
1751 void
1752 ire_flush_cache_v4(ire_t *ire, int flag)
1753 {
1754 	irb_t *irb = ire->ire_bucket;
1755 	struct rt_entry *rt = IRB2RT(irb);
1756 	ip_stack_t *ipst = ire->ire_ipst;
1757 
1758 	/*
1759 	 * IRE_IF_CLONE ire's don't provide any new information
1760 	 * than the parent from which they are cloned, so don't
1761 	 * perturb the generation numbers.
1762 	 */
1763 	if (ire->ire_type & IRE_IF_CLONE)
1764 		return;
1765 
1766 	/*
1767 	 * Ensure that an ire_add during a lookup serializes the updates of the
1768 	 * generation numbers under the radix head lock so that the lookup gets
1769 	 * either the old ire and old generation number, or a new ire and new
1770 	 * generation number.
1771 	 */
1772 	RADIX_NODE_HEAD_WLOCK(ipst->ips_ip_ftable);
1773 
1774 	/*
1775 	 * If a route was just added, we need to notify everybody that
1776 	 * has cached an IRE_NOROUTE since there might now be a better
1777 	 * route for them.
1778 	 */
1779 	if (flag == IRE_FLUSH_ADD) {
1780 		ire_increment_generation(ipst->ips_ire_reject_v4);
1781 		ire_increment_generation(ipst->ips_ire_blackhole_v4);
1782 	}
1783 
1784 	/* Adding a default can't otherwise provide a better route */
1785 	if (ire->ire_type == IRE_DEFAULT && flag == IRE_FLUSH_ADD) {
1786 		RADIX_NODE_HEAD_UNLOCK(ipst->ips_ip_ftable);
1787 		return;
1788 	}
1789 
1790 	switch (flag) {
1791 	case IRE_FLUSH_DELETE:
1792 	case IRE_FLUSH_GWCHANGE:
1793 		/*
1794 		 * Update ire_generation for all ire_dep_children chains
1795 		 * starting with this IRE
1796 		 */
1797 		ire_dep_incr_generation(ire);
1798 		break;
1799 	case IRE_FLUSH_ADD:
1800 		/*
1801 		 * Update the generation numbers of all shorter matching routes.
1802 		 * ire_update_generation takes care of the dependants by
1803 		 * using ire_dep_incr_generation.
1804 		 */
1805 		(void) ipst->ips_ip_ftable->rnh_matchaddr_args(&rt->rt_dst,
1806 		    ipst->ips_ip_ftable, ire_update_generation, NULL);
1807 		break;
1808 	}
1809 	RADIX_NODE_HEAD_UNLOCK(ipst->ips_ip_ftable);
1810 }
1811 
1812 /*
1813  * Matches the arguments passed with the values in the ire.
1814  *
1815  * Note: for match types that match using "ill" passed in, ill
1816  * must be checked for non-NULL before calling this routine.
1817  */
1818 boolean_t
1819 ire_match_args(ire_t *ire, ipaddr_t addr, ipaddr_t mask, ipaddr_t gateway,
1820     int type, const ill_t *ill, zoneid_t zoneid,
1821     const ts_label_t *tsl, int match_flags)
1822 {
1823 	ill_t *ire_ill = NULL, *dst_ill;
1824 	ip_stack_t *ipst = ire->ire_ipst;
1825 
1826 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
1827 	ASSERT((ire->ire_addr & ~ire->ire_mask) == 0);
1828 	ASSERT((!(match_flags & MATCH_IRE_ILL)) ||
1829 	    (ill != NULL && !ill->ill_isv6));
1830 
1831 	/*
1832 	 * If MATCH_IRE_TESTHIDDEN is set, then only return the IRE if it is
1833 	 * in fact hidden, to ensure the caller gets the right one.
1834 	 */
1835 	if (ire->ire_testhidden) {
1836 		if (!(match_flags & MATCH_IRE_TESTHIDDEN))
1837 			return (B_FALSE);
1838 	}
1839 
1840 	if (zoneid != ALL_ZONES && zoneid != ire->ire_zoneid &&
1841 	    ire->ire_zoneid != ALL_ZONES) {
1842 		/*
1843 		 * If MATCH_IRE_ZONEONLY has been set and the supplied zoneid
1844 		 * does not match that of ire_zoneid, a failure to
1845 		 * match is reported at this point. Otherwise, since some IREs
1846 		 * that are available in the global zone can be used in local
1847 		 * zones, additional checks need to be performed:
1848 		 *
1849 		 * IRE_LOOPBACK
1850 		 *	entries should never be matched in this situation.
1851 		 *	Each zone has its own IRE_LOOPBACK.
1852 		 *
1853 		 * IRE_LOCAL
1854 		 *	We allow them for any zoneid. ire_route_recursive
1855 		 *	does additional checks when
1856 		 *	ip_restrict_interzone_loopback is set.
1857 		 *
1858 		 * If ill_usesrc_ifindex is set
1859 		 *	Then we check if the zone has a valid source address
1860 		 *	on the usesrc ill.
1861 		 *
1862 		 * If ire_ill is set, then check that the zone has an ipif
1863 		 *	on that ill.
1864 		 *
1865 		 * Outside of this function (in ire_round_robin) we check
1866 		 * that any IRE_OFFLINK has a gateway that reachable from the
1867 		 * zone when we have multiple choices (ECMP).
1868 		 */
1869 		if (match_flags & MATCH_IRE_ZONEONLY)
1870 			return (B_FALSE);
1871 		if (ire->ire_type & IRE_LOOPBACK)
1872 			return (B_FALSE);
1873 
1874 		if (ire->ire_type & IRE_LOCAL)
1875 			goto matchit;
1876 
1877 		/*
1878 		 * The normal case of IRE_ONLINK has a matching zoneid.
1879 		 * Here we handle the case when shared-IP zones have been
1880 		 * configured with IP addresses on vniN. In that case it
1881 		 * is ok for traffic from a zone to use IRE_ONLINK routes
1882 		 * if the ill has a usesrc pointing at vniN
1883 		 */
1884 		dst_ill = ire->ire_ill;
1885 		if (ire->ire_type & IRE_ONLINK) {
1886 			uint_t	ifindex;
1887 
1888 			/*
1889 			 * Note there is no IRE_INTERFACE on vniN thus
1890 			 * can't do an IRE lookup for a matching route.
1891 			 */
1892 			ifindex = dst_ill->ill_usesrc_ifindex;
1893 			if (ifindex == 0)
1894 				return (B_FALSE);
1895 
1896 			/*
1897 			 * If there is a usable source address in the
1898 			 * zone, then it's ok to return this IRE_INTERFACE
1899 			 */
1900 			if (!ipif_zone_avail(ifindex, dst_ill->ill_isv6,
1901 			    zoneid, ipst)) {
1902 				ip3dbg(("ire_match_args: no usrsrc for zone"
1903 				    " dst_ill %p\n", (void *)dst_ill));
1904 				return (B_FALSE);
1905 			}
1906 		}
1907 		/*
1908 		 * For exampe, with
1909 		 * route add 11.0.0.0 gw1 -ifp bge0
1910 		 * route add 11.0.0.0 gw2 -ifp bge1
1911 		 * this code would differentiate based on
1912 		 * where the sending zone has addresses.
1913 		 * Only if the zone has an address on bge0 can it use the first
1914 		 * route. It isn't clear if this behavior is documented
1915 		 * anywhere.
1916 		 */
1917 		if (dst_ill != NULL && (ire->ire_type & IRE_OFFLINK)) {
1918 			ipif_t	*tipif;
1919 
1920 			mutex_enter(&dst_ill->ill_lock);
1921 			for (tipif = dst_ill->ill_ipif;
1922 			    tipif != NULL; tipif = tipif->ipif_next) {
1923 				if (!IPIF_IS_CONDEMNED(tipif) &&
1924 				    (tipif->ipif_flags & IPIF_UP) &&
1925 				    (tipif->ipif_zoneid == zoneid ||
1926 				    tipif->ipif_zoneid == ALL_ZONES))
1927 					break;
1928 			}
1929 			mutex_exit(&dst_ill->ill_lock);
1930 			if (tipif == NULL) {
1931 				return (B_FALSE);
1932 			}
1933 		}
1934 	}
1935 
1936 matchit:
1937 	if (match_flags & MATCH_IRE_ILL) {
1938 		ire_ill = ire->ire_ill;
1939 
1940 		/*
1941 		 * If asked to match an ill, we *must* match
1942 		 * on the ire_ill for ipmp test addresses, or
1943 		 * any of the ill in the group for data addresses.
1944 		 * If we don't, we may as well fail.
1945 		 * However, we need an exception for IRE_LOCALs to ensure
1946 		 * we loopback packets even sent to test addresses on different
1947 		 * interfaces in the group.
1948 		 */
1949 		if ((match_flags & MATCH_IRE_TESTHIDDEN) &&
1950 		    !(ire->ire_type & IRE_LOCAL)) {
1951 			if (ire->ire_ill != ill)
1952 				return (B_FALSE);
1953 		} else  {
1954 			match_flags &= ~MATCH_IRE_TESTHIDDEN;
1955 			/*
1956 			 * We know that ill is not NULL, but ire_ill could be
1957 			 * NULL
1958 			 */
1959 			if (ire_ill == NULL || !IS_ON_SAME_LAN(ill, ire_ill))
1960 				return (B_FALSE);
1961 		}
1962 	}
1963 
1964 	if ((ire->ire_addr == (addr & mask)) &&
1965 	    ((!(match_flags & MATCH_IRE_GW)) ||
1966 	    (ire->ire_gateway_addr == gateway)) &&
1967 	    ((!(match_flags & MATCH_IRE_TYPE)) || (ire->ire_type & type)) &&
1968 	    ((!(match_flags & MATCH_IRE_TESTHIDDEN)) || ire->ire_testhidden) &&
1969 	    ((!(match_flags & MATCH_IRE_MASK)) || (ire->ire_mask == mask)) &&
1970 	    ((!(match_flags & MATCH_IRE_SECATTR)) ||
1971 	    (!is_system_labeled()) ||
1972 	    (tsol_ire_match_gwattr(ire, tsl) == 0))) {
1973 		/* We found the matched IRE */
1974 		return (B_TRUE);
1975 	}
1976 	return (B_FALSE);
1977 }
1978 
1979 /*
1980  * Check if the IRE_LOCAL uses the same ill as another route would use.
1981  * If there is no alternate route, or the alternate is a REJECT or BLACKHOLE,
1982  * then we don't allow this IRE_LOCAL to be used.
1983  * We always return an IRE; will be RTF_REJECT if no route available.
1984  */
1985 ire_t *
1986 ire_alt_local(ire_t *ire, zoneid_t zoneid, const ts_label_t *tsl,
1987     const ill_t *ill, uint_t *generationp)
1988 {
1989 	ip_stack_t	*ipst = ire->ire_ipst;
1990 	ire_t		*alt_ire;
1991 	uint_t		ire_type;
1992 	uint_t		generation;
1993 	uint_t		match_flags;
1994 
1995 	ASSERT(ire->ire_type & IRE_LOCAL);
1996 	ASSERT(ire->ire_ill != NULL);
1997 
1998 	/*
1999 	 * Need to match on everything but local.
2000 	 * This might result in the creation of a IRE_IF_CLONE for the
2001 	 * same address as the IRE_LOCAL when restrict_interzone_loopback is
2002 	 * set. ire_add_*() ensures that the IRE_IF_CLONE are tail inserted
2003 	 * to make sure the IRE_LOCAL is always found first.
2004 	 */
2005 	ire_type = (IRE_ONLINK | IRE_OFFLINK) & ~(IRE_LOCAL|IRE_LOOPBACK);
2006 	match_flags = MATCH_IRE_TYPE | MATCH_IRE_SECATTR;
2007 	if (ill != NULL)
2008 		match_flags |= MATCH_IRE_ILL;
2009 
2010 	if (ire->ire_ipversion == IPV4_VERSION) {
2011 		alt_ire = ire_route_recursive_v4(ire->ire_addr, ire_type,
2012 		    ill, zoneid, tsl, match_flags, B_TRUE, 0, ipst, NULL, NULL,
2013 		    &generation);
2014 	} else {
2015 		alt_ire = ire_route_recursive_v6(&ire->ire_addr_v6, ire_type,
2016 		    ill, zoneid, tsl, match_flags, B_TRUE, 0, ipst, NULL, NULL,
2017 		    &generation);
2018 	}
2019 	ASSERT(alt_ire != NULL);
2020 
2021 	if (alt_ire->ire_ill == ire->ire_ill) {
2022 		/* Going out the same ILL - ok to send to IRE_LOCAL */
2023 		ire_refrele(alt_ire);
2024 	} else {
2025 		/* Different ill - ignore IRE_LOCAL */
2026 		ire_refrele(ire);
2027 		ire = alt_ire;
2028 		if (generationp != NULL)
2029 			*generationp = generation;
2030 	}
2031 	return (ire);
2032 }
2033 
2034 boolean_t
2035 ire_find_zoneid(struct radix_node *rn, void *arg)
2036 {
2037 	struct rt_entry *rt = (struct rt_entry *)rn;
2038 	irb_t *irb;
2039 	ire_t *ire;
2040 	ire_ftable_args_t *margs = arg;
2041 
2042 	ASSERT(rt != NULL);
2043 
2044 	irb = &rt->rt_irb;
2045 
2046 	if (irb->irb_ire_cnt == 0)
2047 		return (B_FALSE);
2048 
2049 	rw_enter(&irb->irb_lock, RW_READER);
2050 	for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
2051 		if (IRE_IS_CONDEMNED(ire))
2052 			continue;
2053 
2054 		if (!(ire->ire_type & IRE_INTERFACE))
2055 			continue;
2056 
2057 		if (ire->ire_zoneid != ALL_ZONES &&
2058 		    ire->ire_zoneid != margs->ift_zoneid)
2059 			continue;
2060 
2061 		if (margs->ift_ill != NULL && margs->ift_ill != ire->ire_ill)
2062 			continue;
2063 
2064 		if (is_system_labeled() &&
2065 		    tsol_ire_match_gwattr(ire, margs->ift_tsl) != 0)
2066 			continue;
2067 
2068 		rw_exit(&irb->irb_lock);
2069 		return (B_TRUE);
2070 	}
2071 	rw_exit(&irb->irb_lock);
2072 	return (B_FALSE);
2073 }
2074 
2075 /*
2076  * Check if the zoneid (not ALL_ZONES) has an IRE_INTERFACE for the specified
2077  * gateway address. If ill is non-NULL we also match on it.
2078  * The caller must hold a read lock on RADIX_NODE_HEAD if lock_held is set.
2079  */
2080 boolean_t
2081 ire_gateway_ok_zone_v4(ipaddr_t gateway, zoneid_t zoneid, ill_t *ill,
2082     const ts_label_t *tsl, ip_stack_t *ipst, boolean_t lock_held)
2083 {
2084 	struct rt_sockaddr rdst;
2085 	struct rt_entry *rt;
2086 	ire_ftable_args_t margs;
2087 
2088 	ASSERT(ill == NULL || !ill->ill_isv6);
2089 	if (lock_held)
2090 		ASSERT(RW_READ_HELD(&ipst->ips_ip_ftable->rnh_lock));
2091 	else
2092 		RADIX_NODE_HEAD_RLOCK(ipst->ips_ip_ftable);
2093 
2094 	bzero(&rdst, sizeof (rdst));
2095 	rdst.rt_sin_len = sizeof (rdst);
2096 	rdst.rt_sin_family = AF_INET;
2097 	rdst.rt_sin_addr.s_addr = gateway;
2098 
2099 	/*
2100 	 * We only use margs for ill, zoneid, and tsl matching in
2101 	 * ire_find_zoneid
2102 	 */
2103 	bzero(&margs, sizeof (margs));
2104 	margs.ift_ill = ill;
2105 	margs.ift_zoneid = zoneid;
2106 	margs.ift_tsl = tsl;
2107 	rt = (struct rt_entry *)ipst->ips_ip_ftable->rnh_matchaddr_args(&rdst,
2108 	    ipst->ips_ip_ftable, ire_find_zoneid, (void *)&margs);
2109 
2110 	if (!lock_held)
2111 		RADIX_NODE_HEAD_UNLOCK(ipst->ips_ip_ftable);
2112 
2113 	return (rt != NULL);
2114 }
2115 
2116 /*
2117  * ire_walk routine to delete a fraction of redirect IREs and IRE_CLONE_IF IREs.
2118  * The fraction argument tells us what fraction of the IREs to delete.
2119  * Common for IPv4 and IPv6.
2120  * Used when memory backpressure.
2121  */
2122 static void
2123 ire_delete_reclaim(ire_t *ire, char *arg)
2124 {
2125 	ip_stack_t	*ipst = ire->ire_ipst;
2126 	uint_t		fraction = *(uint_t *)arg;
2127 	uint_t		rand;
2128 
2129 	if ((ire->ire_flags & RTF_DYNAMIC) ||
2130 	    (ire->ire_type & IRE_IF_CLONE)) {
2131 
2132 		/* Pick a random number */
2133 		rand = (uint_t)ddi_get_lbolt() +
2134 		    IRE_ADDR_HASH_V6(ire->ire_addr_v6, 256);
2135 
2136 		/* Use truncation */
2137 		if ((rand/fraction)*fraction == rand) {
2138 			IP_STAT(ipst, ip_ire_reclaim_deleted);
2139 			ire_delete(ire);
2140 		}
2141 	}
2142 
2143 }
2144 
2145 /*
2146  * kmem_cache callback to free up memory.
2147  *
2148  * Free a fraction (ips_ip_ire_reclaim_fraction) of things IP added dynamically
2149  * (RTF_DYNAMIC and IRE_IF_CLONE).
2150  */
2151 static void
2152 ip_ire_reclaim_stack(ip_stack_t *ipst)
2153 {
2154 	uint_t	fraction = ipst->ips_ip_ire_reclaim_fraction;
2155 
2156 	IP_STAT(ipst, ip_ire_reclaim_calls);
2157 
2158 	ire_walk(ire_delete_reclaim, &fraction, ipst);
2159 
2160 	/*
2161 	 * Walk all CONNs that can have a reference on an ire, nce or dce.
2162 	 * Get them to update any stale references to drop any refholds they
2163 	 * have.
2164 	 */
2165 	ipcl_walk(conn_ixa_cleanup, (void *)B_FALSE, ipst);
2166 }
2167 
2168 /*
2169  * Called by the memory allocator subsystem directly, when the system
2170  * is running low on memory.
2171  */
2172 /* ARGSUSED */
2173 void
2174 ip_ire_reclaim(void *args)
2175 {
2176 	netstack_handle_t nh;
2177 	netstack_t *ns;
2178 
2179 	netstack_next_init(&nh);
2180 	while ((ns = netstack_next(&nh)) != NULL) {
2181 		ip_ire_reclaim_stack(ns->netstack_ip);
2182 		netstack_rele(ns);
2183 	}
2184 	netstack_next_fini(&nh);
2185 }
2186 
2187 static void
2188 power2_roundup(uint32_t *value)
2189 {
2190 	int i;
2191 
2192 	for (i = 1; i < 31; i++) {
2193 		if (*value <= (1 << i))
2194 			break;
2195 	}
2196 	*value = (1 << i);
2197 }
2198 
2199 /* Global init for all zones */
2200 void
2201 ip_ire_g_init()
2202 {
2203 	/*
2204 	 * Create kmem_caches.  ip_ire_reclaim() and ip_nce_reclaim()
2205 	 * will give disposable IREs back to system when needed.
2206 	 * This needs to be done here before anything else, since
2207 	 * ire_add() expects the cache to be created.
2208 	 */
2209 	ire_cache = kmem_cache_create("ire_cache",
2210 	    sizeof (ire_t), 0, NULL, NULL,
2211 	    ip_ire_reclaim, NULL, NULL, 0);
2212 
2213 	ncec_cache = kmem_cache_create("ncec_cache",
2214 	    sizeof (ncec_t), 0, NULL, NULL,
2215 	    ip_nce_reclaim, NULL, NULL, 0);
2216 	nce_cache = kmem_cache_create("nce_cache",
2217 	    sizeof (nce_t), 0, NULL, NULL,
2218 	    NULL, NULL, NULL, 0);
2219 
2220 	rt_entry_cache = kmem_cache_create("rt_entry",
2221 	    sizeof (struct rt_entry), 0, NULL, NULL, NULL, NULL, NULL, 0);
2222 
2223 	/*
2224 	 * Have radix code setup kmem caches etc.
2225 	 */
2226 	rn_init();
2227 }
2228 
2229 void
2230 ip_ire_init(ip_stack_t *ipst)
2231 {
2232 	ire_t	*ire;
2233 	int	error;
2234 
2235 	mutex_init(&ipst->ips_ire_ft_init_lock, NULL, MUTEX_DEFAULT, 0);
2236 
2237 	(void) rn_inithead((void **)&ipst->ips_ip_ftable, 32);
2238 
2239 	/*
2240 	 * Make sure that the forwarding table size is a power of 2.
2241 	 * The IRE*_ADDR_HASH() macroes depend on that.
2242 	 */
2243 	ipst->ips_ip6_ftable_hash_size = ip6_ftable_hash_size;
2244 	power2_roundup(&ipst->ips_ip6_ftable_hash_size);
2245 
2246 	/*
2247 	 * Allocate/initialize a pair of IRE_NOROUTEs for each of IPv4 and IPv6.
2248 	 * The ire_reject_v* has RTF_REJECT set, and the ire_blackhole_v* has
2249 	 * RTF_BLACKHOLE set. We use the latter for transient errors such
2250 	 * as memory allocation failures and tripping on IRE_IS_CONDEMNED
2251 	 * entries.
2252 	 */
2253 	ire = kmem_cache_alloc(ire_cache, KM_SLEEP);
2254 	*ire = ire_null;
2255 	error = ire_init_v4(ire, 0, 0, 0, IRE_NOROUTE, NULL, ALL_ZONES,
2256 	    RTF_REJECT|RTF_UP, NULL, ipst);
2257 	ASSERT(error == 0);
2258 	ipst->ips_ire_reject_v4 = ire;
2259 
2260 	ire = kmem_cache_alloc(ire_cache, KM_SLEEP);
2261 	*ire = ire_null;
2262 	error = ire_init_v6(ire, 0, 0, 0, IRE_NOROUTE, NULL, ALL_ZONES,
2263 	    RTF_REJECT|RTF_UP, NULL, ipst);
2264 	ASSERT(error == 0);
2265 	ipst->ips_ire_reject_v6 = ire;
2266 
2267 	ire = kmem_cache_alloc(ire_cache, KM_SLEEP);
2268 	*ire = ire_null;
2269 	error = ire_init_v4(ire, 0, 0, 0, IRE_NOROUTE, NULL, ALL_ZONES,
2270 	    RTF_BLACKHOLE|RTF_UP, NULL, ipst);
2271 	ASSERT(error == 0);
2272 	ipst->ips_ire_blackhole_v4 = ire;
2273 
2274 	ire = kmem_cache_alloc(ire_cache, KM_SLEEP);
2275 	*ire = ire_null;
2276 	error = ire_init_v6(ire, 0, 0, 0, IRE_NOROUTE, NULL, ALL_ZONES,
2277 	    RTF_BLACKHOLE|RTF_UP, NULL, ipst);
2278 	ASSERT(error == 0);
2279 	ipst->ips_ire_blackhole_v6 = ire;
2280 
2281 	rw_init(&ipst->ips_ip6_ire_head_lock, NULL, RW_DEFAULT, NULL);
2282 	rw_init(&ipst->ips_ire_dep_lock, NULL, RW_DEFAULT, NULL);
2283 }
2284 
2285 void
2286 ip_ire_g_fini(void)
2287 {
2288 	kmem_cache_destroy(ire_cache);
2289 	kmem_cache_destroy(ncec_cache);
2290 	kmem_cache_destroy(nce_cache);
2291 	kmem_cache_destroy(rt_entry_cache);
2292 
2293 	rn_fini();
2294 }
2295 
2296 void
2297 ip_ire_fini(ip_stack_t *ipst)
2298 {
2299 	int i;
2300 
2301 	rw_destroy(&ipst->ips_ire_dep_lock);
2302 	rw_destroy(&ipst->ips_ip6_ire_head_lock);
2303 
2304 	ire_refrele_notr(ipst->ips_ire_reject_v6);
2305 	ipst->ips_ire_reject_v6 = NULL;
2306 	ire_refrele_notr(ipst->ips_ire_reject_v4);
2307 	ipst->ips_ire_reject_v4 = NULL;
2308 	ire_refrele_notr(ipst->ips_ire_blackhole_v6);
2309 	ipst->ips_ire_blackhole_v6 = NULL;
2310 	ire_refrele_notr(ipst->ips_ire_blackhole_v4);
2311 	ipst->ips_ire_blackhole_v4 = NULL;
2312 
2313 	/*
2314 	 * Delete all IREs - assumes that the ill/ipifs have
2315 	 * been removed so what remains are just the ftable to handle.
2316 	 */
2317 	ire_walk(ire_delete, NULL, ipst);
2318 
2319 	rn_freehead(ipst->ips_ip_ftable);
2320 	ipst->ips_ip_ftable = NULL;
2321 
2322 	mutex_destroy(&ipst->ips_ire_ft_init_lock);
2323 
2324 	for (i = 0; i < IP6_MASK_TABLE_SIZE; i++) {
2325 		irb_t *ptr;
2326 		int j;
2327 
2328 		if ((ptr = ipst->ips_ip_forwarding_table_v6[i]) == NULL)
2329 			continue;
2330 
2331 		for (j = 0; j < ipst->ips_ip6_ftable_hash_size; j++) {
2332 			ASSERT(ptr[j].irb_ire == NULL);
2333 			rw_destroy(&ptr[j].irb_lock);
2334 		}
2335 		mi_free(ptr);
2336 		ipst->ips_ip_forwarding_table_v6[i] = NULL;
2337 	}
2338 }
2339 
2340 #ifdef DEBUG
2341 void
2342 ire_trace_ref(ire_t *ire)
2343 {
2344 	mutex_enter(&ire->ire_lock);
2345 	if (ire->ire_trace_disable) {
2346 		mutex_exit(&ire->ire_lock);
2347 		return;
2348 	}
2349 
2350 	if (th_trace_ref(ire, ire->ire_ipst)) {
2351 		mutex_exit(&ire->ire_lock);
2352 	} else {
2353 		ire->ire_trace_disable = B_TRUE;
2354 		mutex_exit(&ire->ire_lock);
2355 		ire_trace_cleanup(ire);
2356 	}
2357 }
2358 
2359 void
2360 ire_untrace_ref(ire_t *ire)
2361 {
2362 	mutex_enter(&ire->ire_lock);
2363 	if (!ire->ire_trace_disable)
2364 		th_trace_unref(ire);
2365 	mutex_exit(&ire->ire_lock);
2366 }
2367 
2368 static void
2369 ire_trace_cleanup(const ire_t *ire)
2370 {
2371 	th_trace_cleanup(ire, ire->ire_trace_disable);
2372 }
2373 #endif /* DEBUG */
2374 
2375 /*
2376  * Find, or create if needed, the nce_t pointer to the neighbor cache
2377  * entry ncec_t for an IPv4 address. The nce_t will be created on the ill_t
2378  * in the non-IPMP case, or on the cast-ill in the IPMP bcast/mcast case, or
2379  * on the next available under-ill (selected by the IPMP rotor) in the
2380  * unicast IPMP case.
2381  *
2382  * If a neighbor-cache entry has to be created (i.e., one does not already
2383  * exist in the nce list) the ncec_lladdr and ncec_state of the neighbor cache
2384  * entry are initialized in nce_add_v4(). The broadcast, multicast, and
2385  * link-layer type determine the contents of {ncec_state, ncec_lladdr} of
2386  * the ncec_t created. The ncec_lladdr is non-null for all link types with
2387  * non-zero ill_phys_addr_length, though the contents may be zero in cases
2388  * where the link-layer type is not known at the time of creation
2389  * (e.g., IRE_IFRESOLVER links)
2390  *
2391  * All IRE_BROADCAST entries have ncec_state = ND_REACHABLE, and the nce_lladr
2392  * has the physical broadcast address of the outgoing interface.
2393  * For unicast ire entries,
2394  *   - if the outgoing interface is of type IRE_IF_RESOLVER, a newly created
2395  *     ncec_t with 0 nce_lladr contents, and will be in the ND_INITIAL state.
2396  *   - if the outgoing interface is a IRE_IF_NORESOLVER interface, no link
2397  *     layer resolution is necessary, so that the ncec_t will be in the
2398  *     ND_REACHABLE state
2399  *
2400  * The link layer information needed for broadcast addresses, and for
2401  * packets sent on IRE_IF_NORESOLVER interfaces is a constant mapping that
2402  * never needs re-verification for the lifetime of the ncec_t. These are
2403  * therefore marked NCE_F_NONUD.
2404  *
2405  * The nce returned will be created such that the nce_ill == ill that
2406  * is passed in. Note that the nce itself may not have ncec_ill == ill
2407  * where IPMP links are involved.
2408  */
2409 static nce_t *
2410 ire_nce_init(ill_t *ill, const void *addr, int ire_type)
2411 {
2412 	int		err;
2413 	nce_t		*nce = NULL;
2414 	uint16_t	ncec_flags;
2415 	uchar_t		*hwaddr;
2416 	boolean_t	need_refrele = B_FALSE;
2417 	ill_t		*in_ill = ill;
2418 	boolean_t	is_unicast;
2419 	uint_t		hwaddr_len;
2420 
2421 	is_unicast = ((ire_type & (IRE_MULTICAST|IRE_BROADCAST)) == 0);
2422 	if (IS_IPMP(ill) ||
2423 	    ((ire_type & IRE_BROADCAST) && IS_UNDER_IPMP(ill))) {
2424 		if ((ill = ipmp_ill_get_xmit_ill(ill, is_unicast)) == NULL)
2425 			return (NULL);
2426 		need_refrele = B_TRUE;
2427 	}
2428 	ncec_flags = (ill->ill_flags & ILLF_NONUD) ? NCE_F_NONUD : 0;
2429 
2430 	switch (ire_type) {
2431 	case IRE_BROADCAST:
2432 		ASSERT(!ill->ill_isv6);
2433 		ncec_flags |= (NCE_F_BCAST|NCE_F_NONUD);
2434 		break;
2435 	case IRE_MULTICAST:
2436 		ncec_flags |= (NCE_F_MCAST|NCE_F_NONUD);
2437 		break;
2438 	}
2439 
2440 	if (ill->ill_net_type == IRE_IF_NORESOLVER && is_unicast) {
2441 		hwaddr = ill->ill_dest_addr;
2442 	} else {
2443 		hwaddr = NULL;
2444 	}
2445 	hwaddr_len = ill->ill_phys_addr_length;
2446 
2447 retry:
2448 	/* nce_state will be computed by nce_add_common() */
2449 	if (!ill->ill_isv6) {
2450 		err = nce_lookup_then_add_v4(ill, hwaddr, hwaddr_len, addr,
2451 		    ncec_flags, ND_UNCHANGED, &nce);
2452 	} else {
2453 		err = nce_lookup_then_add_v6(ill, hwaddr, hwaddr_len, addr,
2454 		    ncec_flags, ND_UNCHANGED, &nce);
2455 	}
2456 
2457 	switch (err) {
2458 	case 0:
2459 		break;
2460 	case EEXIST:
2461 		/*
2462 		 * When subnets change or partially overlap what was once
2463 		 * a broadcast address could now be a unicast, or vice versa.
2464 		 */
2465 		if (((ncec_flags ^ nce->nce_common->ncec_flags) &
2466 		    NCE_F_BCAST) != 0) {
2467 			ASSERT(!ill->ill_isv6);
2468 			ncec_delete(nce->nce_common);
2469 			nce_refrele(nce);
2470 			goto retry;
2471 		}
2472 		break;
2473 	default:
2474 		DTRACE_PROBE2(nce__init__fail, ill_t *, ill, int, err);
2475 		if (need_refrele)
2476 			ill_refrele(ill);
2477 		return (NULL);
2478 	}
2479 	/*
2480 	 * If the ill was an under-ill of an IPMP group, we need to verify
2481 	 * that it is still active so that we select an active interface in
2482 	 * the group. However, since ipmp_ill_is_active ASSERTs for
2483 	 * IS_UNDER_IPMP(), we first need to verify that the ill is an
2484 	 * under-ill, and since this is being done in the data path, the
2485 	 * only way to ascertain this is by holding the ill_g_lock.
2486 	 */
2487 	rw_enter(&ill->ill_ipst->ips_ill_g_lock, RW_READER);
2488 	mutex_enter(&ill->ill_lock);
2489 	mutex_enter(&ill->ill_phyint->phyint_lock);
2490 	if (need_refrele && IS_UNDER_IPMP(ill) && !ipmp_ill_is_active(ill)) {
2491 		/*
2492 		 * need_refrele implies that the under ill was selected by
2493 		 * ipmp_ill_get_xmit_ill() because either the in_ill was an
2494 		 * ipmp_ill, or we are sending a non-unicast packet on
2495 		 * an under_ill. However, when we get here, the ill selected by
2496 		 * ipmp_ill_get_xmit_ill  was pulled out of the active set
2497 		 * (for unicast)  or cast_ill nomination (for
2498 		 * !unicast) after it was  picked as the outgoing ill.
2499 		 * We have to pick an active interface and/or cast_ill in the
2500 		 * group.
2501 		 */
2502 		mutex_exit(&ill->ill_phyint->phyint_lock);
2503 		nce_delete(nce);
2504 		mutex_exit(&ill->ill_lock);
2505 		rw_exit(&ill->ill_ipst->ips_ill_g_lock);
2506 		nce_refrele(nce);
2507 		ill_refrele(ill);
2508 		if ((ill = ipmp_ill_get_xmit_ill(in_ill, is_unicast)) == NULL)
2509 			return (NULL);
2510 		goto retry;
2511 	} else {
2512 		mutex_exit(&ill->ill_phyint->phyint_lock);
2513 		mutex_exit(&ill->ill_lock);
2514 		rw_exit(&ill->ill_ipst->ips_ill_g_lock);
2515 	}
2516 done:
2517 	ASSERT(nce->nce_ill == ill);
2518 	if (need_refrele)
2519 		ill_refrele(ill);
2520 	return (nce);
2521 }
2522 
2523 nce_t *
2524 arp_nce_init(ill_t *ill, in_addr_t addr4, int ire_type)
2525 {
2526 	return (ire_nce_init(ill, &addr4, ire_type));
2527 }
2528 
2529 nce_t *
2530 ndp_nce_init(ill_t *ill, const in6_addr_t *addr6, int ire_type)
2531 {
2532 	ASSERT((ire_type & IRE_BROADCAST) == 0);
2533 	return (ire_nce_init(ill, addr6, ire_type));
2534 }
2535 
2536 /*
2537  * The caller should hold irb_lock as a writer if the ire is in a bucket.
2538  */
2539 void
2540 ire_make_condemned(ire_t *ire)
2541 {
2542 	ip_stack_t	*ipst = ire->ire_ipst;
2543 
2544 	mutex_enter(&ire->ire_lock);
2545 	ASSERT(ire->ire_bucket == NULL ||
2546 	    RW_WRITE_HELD(&ire->ire_bucket->irb_lock));
2547 	ASSERT(!IRE_IS_CONDEMNED(ire));
2548 	ire->ire_generation = IRE_GENERATION_CONDEMNED;
2549 	/* Count how many condemned ires for kmem_cache callback */
2550 	atomic_add_32(&ipst->ips_num_ire_condemned, 1);
2551 	mutex_exit(&ire->ire_lock);
2552 }
2553 
2554 /*
2555  * Increment the generation avoiding the special condemned value
2556  */
2557 void
2558 ire_increment_generation(ire_t *ire)
2559 {
2560 	uint_t generation;
2561 
2562 	mutex_enter(&ire->ire_lock);
2563 	/*
2564 	 * Even though the caller has a hold it can't prevent a concurrent
2565 	 * ire_delete marking the IRE condemned
2566 	 */
2567 	if (!IRE_IS_CONDEMNED(ire)) {
2568 		generation = ire->ire_generation + 1;
2569 		if (generation == IRE_GENERATION_CONDEMNED)
2570 			generation = IRE_GENERATION_INITIAL;
2571 		ASSERT(generation != IRE_GENERATION_VERIFY);
2572 		ire->ire_generation = generation;
2573 	}
2574 	mutex_exit(&ire->ire_lock);
2575 }
2576 
2577 /*
2578  * Increment ire_generation on all the IRE_MULTICASTs
2579  * Used when the default multicast interface (as determined by
2580  * ill_lookup_multicast) might have changed.
2581  *
2582  * That includes the zoneid, IFF_ flags, the IPv6 scope of the address, and
2583  * ill unplumb.
2584  */
2585 void
2586 ire_increment_multicast_generation(ip_stack_t *ipst, boolean_t isv6)
2587 {
2588 	ill_t	*ill;
2589 	ill_walk_context_t ctx;
2590 
2591 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
2592 	if (isv6)
2593 		ill = ILL_START_WALK_V6(&ctx, ipst);
2594 	else
2595 		ill = ILL_START_WALK_V4(&ctx, ipst);
2596 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
2597 		if (ILL_IS_CONDEMNED(ill))
2598 			continue;
2599 		if (ill->ill_ire_multicast != NULL)
2600 			ire_increment_generation(ill->ill_ire_multicast);
2601 	}
2602 	rw_exit(&ipst->ips_ill_g_lock);
2603 }
2604 
2605 /*
2606  * Return a held IRE_NOROUTE with RTF_REJECT set
2607  */
2608 ire_t *
2609 ire_reject(ip_stack_t *ipst, boolean_t isv6)
2610 {
2611 	ire_t *ire;
2612 
2613 	if (isv6)
2614 		ire = ipst->ips_ire_reject_v6;
2615 	else
2616 		ire = ipst->ips_ire_reject_v4;
2617 
2618 	ASSERT(ire->ire_generation != IRE_GENERATION_CONDEMNED);
2619 	ire_refhold(ire);
2620 	return (ire);
2621 }
2622 
2623 /*
2624  * Return a held IRE_NOROUTE with RTF_BLACKHOLE set
2625  */
2626 ire_t *
2627 ire_blackhole(ip_stack_t *ipst, boolean_t isv6)
2628 {
2629 	ire_t *ire;
2630 
2631 	if (isv6)
2632 		ire = ipst->ips_ire_blackhole_v6;
2633 	else
2634 		ire = ipst->ips_ire_blackhole_v4;
2635 
2636 	ASSERT(ire->ire_generation != IRE_GENERATION_CONDEMNED);
2637 	ire_refhold(ire);
2638 	return (ire);
2639 }
2640 
2641 /*
2642  * Return a held IRE_MULTICAST.
2643  */
2644 ire_t *
2645 ire_multicast(ill_t *ill)
2646 {
2647 	ire_t *ire = ill->ill_ire_multicast;
2648 
2649 	ASSERT(ire == NULL || ire->ire_generation != IRE_GENERATION_CONDEMNED);
2650 	if (ire == NULL)
2651 		ire = ire_blackhole(ill->ill_ipst, ill->ill_isv6);
2652 	else
2653 		ire_refhold(ire);
2654 	return (ire);
2655 }
2656 
2657 /*
2658  * Given an IRE return its nexthop IRE. The nexthop IRE is an IRE_ONLINK
2659  * that is an exact match (i.e., a /32 for IPv4 and /128 for IPv6).
2660  * This can return an RTF_REJECT|RTF_BLACKHOLE.
2661  * The returned IRE is held.
2662  * The assumption is that ip_select_route() has been called and returned the
2663  * IRE (thus ip_select_route would have set up the ire_dep* information.)
2664  * If some IRE is deleteted then ire_dep_remove() will have been called and
2665  * we might not find a nexthop IRE, in which case we return NULL.
2666  */
2667 ire_t *
2668 ire_nexthop(ire_t *ire)
2669 {
2670 	ip_stack_t	*ipst = ire->ire_ipst;
2671 
2672 	/* Acquire lock to walk ire_dep_parent */
2673 	rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
2674 	while (ire != NULL) {
2675 		if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
2676 			goto done;
2677 		}
2678 		/*
2679 		 * If we find an IRE_ONLINK we are done. This includes
2680 		 * the case of IRE_MULTICAST.
2681 		 * Note that in order to send packets we need a host-specific
2682 		 * IRE_IF_ALL first in the ire_dep_parent chain. Normally this
2683 		 * is done by inserting an IRE_IF_CLONE if the IRE_INTERFACE
2684 		 * was not host specific.
2685 		 * However, ip_rts_request doesn't want to send packets
2686 		 * hence doesn't want to allocate an IRE_IF_CLONE. Yet
2687 		 * it needs an IRE_IF_ALL to get to the ill. Thus
2688 		 * we return IRE_IF_ALL that are not host specific here.
2689 		 */
2690 		if (ire->ire_type & IRE_ONLINK)
2691 			goto done;
2692 		ire = ire->ire_dep_parent;
2693 	}
2694 	rw_exit(&ipst->ips_ire_dep_lock);
2695 	return (NULL);
2696 
2697 done:
2698 	ire_refhold(ire);
2699 	rw_exit(&ipst->ips_ire_dep_lock);
2700 	return (ire);
2701 }
2702 
2703 /*
2704  * Find the ill used to send packets. This will be NULL in case
2705  * of a reject or blackhole.
2706  * The returned ill is held; caller needs to do ill_refrele when done.
2707  */
2708 ill_t *
2709 ire_nexthop_ill(ire_t *ire)
2710 {
2711 	ill_t		*ill;
2712 
2713 	ire = ire_nexthop(ire);
2714 	if (ire == NULL)
2715 		return (NULL);
2716 
2717 	/* ire_ill can not change for an existing ire */
2718 	ill = ire->ire_ill;
2719 	if (ill != NULL)
2720 		ill_refhold(ill);
2721 	ire_refrele(ire);
2722 	return (ill);
2723 }
2724 
2725 #ifdef DEBUG
2726 static boolean_t
2727 parent_has_child(ire_t *parent, ire_t *child)
2728 {
2729 	ire_t	*ire;
2730 	ire_t	*prev;
2731 
2732 	ire = parent->ire_dep_children;
2733 	prev = NULL;
2734 	while (ire != NULL) {
2735 		if (prev == NULL) {
2736 			ASSERT(ire->ire_dep_sib_ptpn ==
2737 			    &(parent->ire_dep_children));
2738 		} else {
2739 			ASSERT(ire->ire_dep_sib_ptpn ==
2740 			    &(prev->ire_dep_sib_next));
2741 		}
2742 		if (ire == child)
2743 			return (B_TRUE);
2744 		prev = ire;
2745 		ire = ire->ire_dep_sib_next;
2746 	}
2747 	return (B_FALSE);
2748 }
2749 
2750 static void
2751 ire_dep_verify(ire_t *ire)
2752 {
2753 	ire_t		*parent = ire->ire_dep_parent;
2754 	ire_t		*child = ire->ire_dep_children;
2755 
2756 	ASSERT(ire->ire_ipversion == IPV4_VERSION ||
2757 	    ire->ire_ipversion == IPV6_VERSION);
2758 	if (parent != NULL) {
2759 		ASSERT(parent->ire_ipversion == IPV4_VERSION ||
2760 		    parent->ire_ipversion == IPV6_VERSION);
2761 		ASSERT(parent->ire_refcnt >= 1);
2762 		ASSERT(parent_has_child(parent, ire));
2763 	}
2764 	if (child != NULL) {
2765 		ASSERT(child->ire_ipversion == IPV4_VERSION ||
2766 		    child->ire_ipversion == IPV6_VERSION);
2767 		ASSERT(child->ire_dep_parent == ire);
2768 		ASSERT(child->ire_dep_sib_ptpn != NULL);
2769 		ASSERT(parent_has_child(ire, child));
2770 	}
2771 }
2772 #endif /* DEBUG */
2773 
2774 /*
2775  * Assumes ire_dep_parent is set. Remove this child from its parent's linkage.
2776  */
2777 void
2778 ire_dep_remove(ire_t *ire)
2779 {
2780 	ip_stack_t	*ipst = ire->ire_ipst;
2781 	ire_t		*parent = ire->ire_dep_parent;
2782 	ire_t		*next;
2783 	nce_t		*nce;
2784 
2785 	ASSERT(RW_WRITE_HELD(&ipst->ips_ire_dep_lock));
2786 	ASSERT(ire->ire_dep_parent != NULL);
2787 	ASSERT(ire->ire_dep_sib_ptpn != NULL);
2788 
2789 #ifdef DEBUG
2790 	ire_dep_verify(ire);
2791 	ire_dep_verify(parent);
2792 #endif
2793 
2794 	next = ire->ire_dep_sib_next;
2795 	if (next != NULL)
2796 		next->ire_dep_sib_ptpn = ire->ire_dep_sib_ptpn;
2797 
2798 	ASSERT(*(ire->ire_dep_sib_ptpn) == ire);
2799 	*(ire->ire_dep_sib_ptpn) = ire->ire_dep_sib_next;
2800 
2801 	ire->ire_dep_sib_ptpn = NULL;
2802 	ire->ire_dep_sib_next = NULL;
2803 
2804 	mutex_enter(&ire->ire_lock);
2805 	parent = ire->ire_dep_parent;
2806 	ire->ire_dep_parent = NULL;
2807 	mutex_exit(&ire->ire_lock);
2808 
2809 	/*
2810 	 * Make sure all our children, grandchildren, etc set
2811 	 * ire_dep_parent_generation to IRE_GENERATION_VERIFY since
2812 	 * we can no longer guarantee than the children have a current
2813 	 * ire_nce_cache and ire_nexthop_ill().
2814 	 */
2815 	if (ire->ire_dep_children != NULL)
2816 		ire_dep_invalidate_children(ire->ire_dep_children);
2817 
2818 	/*
2819 	 * Since the parent is gone we make sure we clear ire_nce_cache.
2820 	 * We can clear it under ire_lock even if the IRE is used
2821 	 */
2822 	mutex_enter(&ire->ire_lock);
2823 	nce = ire->ire_nce_cache;
2824 	ire->ire_nce_cache = NULL;
2825 	mutex_exit(&ire->ire_lock);
2826 	if (nce != NULL)
2827 		nce_refrele(nce);
2828 
2829 #ifdef DEBUG
2830 	ire_dep_verify(ire);
2831 	ire_dep_verify(parent);
2832 #endif
2833 
2834 	ire_refrele_notr(parent);
2835 	ire_refrele_notr(ire);
2836 }
2837 
2838 /*
2839  * Insert the child in the linkage of the parent
2840  */
2841 static void
2842 ire_dep_parent_insert(ire_t *child, ire_t *parent)
2843 {
2844 	ip_stack_t	*ipst = child->ire_ipst;
2845 	ire_t		*next;
2846 
2847 	ASSERT(RW_WRITE_HELD(&ipst->ips_ire_dep_lock));
2848 	ASSERT(child->ire_dep_parent == NULL);
2849 
2850 #ifdef DEBUG
2851 	ire_dep_verify(child);
2852 	ire_dep_verify(parent);
2853 #endif
2854 	/* No parents => no siblings */
2855 	ASSERT(child->ire_dep_sib_ptpn == NULL);
2856 	ASSERT(child->ire_dep_sib_next == NULL);
2857 
2858 	ire_refhold_notr(parent);
2859 	ire_refhold_notr(child);
2860 
2861 	/* Head insertion */
2862 	next = parent->ire_dep_children;
2863 	if (next != NULL) {
2864 		ASSERT(next->ire_dep_sib_ptpn == &(parent->ire_dep_children));
2865 		child->ire_dep_sib_next = next;
2866 		next->ire_dep_sib_ptpn = &(child->ire_dep_sib_next);
2867 	}
2868 	parent->ire_dep_children = child;
2869 	child->ire_dep_sib_ptpn = &(parent->ire_dep_children);
2870 
2871 	mutex_enter(&child->ire_lock);
2872 	child->ire_dep_parent = parent;
2873 	mutex_exit(&child->ire_lock);
2874 
2875 #ifdef DEBUG
2876 	ire_dep_verify(child);
2877 	ire_dep_verify(parent);
2878 #endif
2879 }
2880 
2881 
2882 /*
2883  * Given count worth of ires and generations, build ire_dep_* relationships
2884  * from ires[0] to ires[count-1]. Record generations[i+1] in
2885  * ire_dep_parent_generation for ires[i].
2886  * We graft onto an existing parent chain by making sure that we don't
2887  * touch ire_dep_parent for ires[count-1].
2888  *
2889  * We check for any condemned ire_generation count and return B_FALSE in
2890  * that case so that the caller can tear it apart.
2891  *
2892  * Note that generations[0] is not used. Caller handles that.
2893  */
2894 boolean_t
2895 ire_dep_build(ire_t *ires[], uint_t generations[], uint_t count)
2896 {
2897 	ire_t		*ire = ires[0];
2898 	ip_stack_t	*ipst;
2899 	uint_t		i;
2900 
2901 	ASSERT(count > 0);
2902 	if (count == 1) {
2903 		/* No work to do */
2904 		return (B_TRUE);
2905 	}
2906 	ipst = ire->ire_ipst;
2907 	rw_enter(&ipst->ips_ire_dep_lock, RW_WRITER);
2908 	/*
2909 	 * Do not remove the linkage for any existing parent chain i.e.,
2910 	 * ires[count-1] is left alone.
2911 	 */
2912 	for (i = 0; i < count-1; i++) {
2913 		/* Remove existing parent if we need to change it */
2914 		if (ires[i]->ire_dep_parent != NULL &&
2915 		    ires[i]->ire_dep_parent != ires[i+1])
2916 			ire_dep_remove(ires[i]);
2917 	}
2918 
2919 	for (i = 0; i < count - 1; i++) {
2920 		ASSERT(ires[i]->ire_ipversion == IPV4_VERSION ||
2921 		    ires[i]->ire_ipversion == IPV6_VERSION);
2922 		/* Does it need to change? */
2923 		if (ires[i]->ire_dep_parent != ires[i+1])
2924 			ire_dep_parent_insert(ires[i], ires[i+1]);
2925 
2926 		mutex_enter(&ires[i+1]->ire_lock);
2927 		if (IRE_IS_CONDEMNED(ires[i+1])) {
2928 			mutex_exit(&ires[i+1]->ire_lock);
2929 			rw_exit(&ipst->ips_ire_dep_lock);
2930 			return (B_FALSE);
2931 		}
2932 		mutex_exit(&ires[i+1]->ire_lock);
2933 
2934 		mutex_enter(&ires[i]->ire_lock);
2935 		ires[i]->ire_dep_parent_generation = generations[i+1];
2936 		mutex_exit(&ires[i]->ire_lock);
2937 	}
2938 	rw_exit(&ipst->ips_ire_dep_lock);
2939 	return (B_TRUE);
2940 }
2941 
2942 /*
2943  * Given count worth of ires, unbuild ire_dep_* relationships
2944  * from ires[0] to ires[count-1].
2945  */
2946 void
2947 ire_dep_unbuild(ire_t *ires[], uint_t count)
2948 {
2949 	ip_stack_t	*ipst;
2950 	uint_t		i;
2951 
2952 	if (count == 0) {
2953 		/* No work to do */
2954 		return;
2955 	}
2956 	ipst = ires[0]->ire_ipst;
2957 	rw_enter(&ipst->ips_ire_dep_lock, RW_WRITER);
2958 	for (i = 0; i < count; i++) {
2959 		ASSERT(ires[i]->ire_ipversion == IPV4_VERSION ||
2960 		    ires[i]->ire_ipversion == IPV6_VERSION);
2961 		if (ires[i]->ire_dep_parent != NULL)
2962 			ire_dep_remove(ires[i]);
2963 		mutex_enter(&ires[i]->ire_lock);
2964 		ires[i]->ire_dep_parent_generation = IRE_GENERATION_VERIFY;
2965 		mutex_exit(&ires[i]->ire_lock);
2966 	}
2967 	rw_exit(&ipst->ips_ire_dep_lock);
2968 }
2969 
2970 /*
2971  * Both the forwarding and the outbound code paths can trip on
2972  * a condemned NCE, in which case we call this function.
2973  * We have two different behaviors: if the NCE was UNREACHABLE
2974  * it is an indication that something failed. In that case
2975  * we see if we should look for a different IRE (for example,
2976  * delete any matching redirect IRE, or try a different
2977  * IRE_DEFAULT (ECMP)). We mark the ire as bad so a hopefully
2978  * different IRE will be picked next time we send/forward.
2979  *
2980  * If we are called by the output path then fail_if_better is set
2981  * and we return NULL if there could be a better IRE. This is because the
2982  * output path retries the IRE lookup. (The input/forward path can not retry.)
2983  *
2984  * If the NCE was not unreachable then we pick/allocate a
2985  * new (most likely ND_INITIAL) NCE and proceed with it.
2986  *
2987  * ipha/ip6h are needed for multicast packets; ipha needs to be
2988  * set for IPv4 and ip6h needs to be set for IPv6 packets.
2989  */
2990 nce_t *
2991 ire_handle_condemned_nce(nce_t *nce, ire_t *ire, ipha_t *ipha, ip6_t *ip6h,
2992     boolean_t fail_if_better)
2993 {
2994 	if (nce->nce_common->ncec_state == ND_UNREACHABLE) {
2995 		if (ire_no_good(ire) && fail_if_better) {
2996 			/*
2997 			 * Did some changes, or ECMP likely to exist.
2998 			 * Make ip_output look for a different IRE
2999 			 */
3000 			return (NULL);
3001 		}
3002 	}
3003 	if (ire_revalidate_nce(ire) == ENETUNREACH) {
3004 		/* The ire_dep_parent chain went bad, or no memory? */
3005 		(void) ire_no_good(ire);
3006 		return (NULL);
3007 	}
3008 	if (ire->ire_ipversion == IPV4_VERSION) {
3009 		ASSERT(ipha != NULL);
3010 		nce = ire_to_nce(ire, ipha->ipha_dst, NULL);
3011 	} else {
3012 		ASSERT(ip6h != NULL);
3013 		nce = ire_to_nce(ire, INADDR_ANY, &ip6h->ip6_dst);
3014 	}
3015 
3016 	if (nce == NULL)
3017 		return (NULL);
3018 	if (nce->nce_is_condemned) {
3019 		nce_refrele(nce);
3020 		return (NULL);
3021 	}
3022 	return (nce);
3023 }
3024 
3025 /*
3026  * The caller has found that the ire is bad, either due to a reference to an NCE
3027  * in ND_UNREACHABLE state, or a MULTIRT route whose gateway can't be resolved.
3028  * We update things so a subsequent attempt to send to the destination
3029  * is likely to find different IRE, or that a new NCE would be created.
3030  *
3031  * Returns B_TRUE if it is likely that a subsequent ire_ftable_lookup would
3032  * find a different route (either due to having deleted a redirect, or there
3033  * being ECMP routes.)
3034  *
3035  * If we have a redirect (RTF_DYNAMIC) we delete it.
3036  * Otherwise we increment ire_badcnt and increment the generation number so
3037  * that a cached ixa_ire will redo the route selection. ire_badcnt is taken
3038  * into account in the route selection when we have multiple choices (multiple
3039  * default routes or ECMP in general).
3040  * Any time ip_select_route find an ire with a condemned ire_nce_cache
3041  * (e.g., if no equal cost route to the bad one) ip_select_route will make
3042  * sure the NCE is revalidated to avoid getting stuck on a
3043  * NCE_F_CONDMNED ncec that caused ire_no_good to be called.
3044  */
3045 boolean_t
3046 ire_no_good(ire_t *ire)
3047 {
3048 	ip_stack_t	*ipst = ire->ire_ipst;
3049 	ire_t		*ire2;
3050 	nce_t		*nce;
3051 
3052 	if (ire->ire_flags & RTF_DYNAMIC) {
3053 		ire_delete(ire);
3054 		return (B_TRUE);
3055 	}
3056 	if (ire->ire_flags & RTF_INDIRECT) {
3057 		/* Check if next IRE is a redirect */
3058 		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
3059 		if (ire->ire_dep_parent != NULL &&
3060 		    (ire->ire_dep_parent->ire_flags & RTF_DYNAMIC)) {
3061 			ire2 = ire->ire_dep_parent;
3062 			ire_refhold(ire2);
3063 		} else {
3064 			ire2 = NULL;
3065 		}
3066 		rw_exit(&ipst->ips_ire_dep_lock);
3067 		if (ire2 != NULL) {
3068 			ire_delete(ire2);
3069 			ire_refrele(ire2);
3070 			return (B_TRUE);
3071 		}
3072 	}
3073 	/*
3074 	 * No redirect involved. Increment badcnt so that if we have ECMP
3075 	 * routes we are likely to pick a different one for the next packet.
3076 	 *
3077 	 * If the NCE is unreachable and condemned we should drop the reference
3078 	 * to it so that a new NCE can be created.
3079 	 *
3080 	 * Finally we increment the generation number so that any ixa_ire
3081 	 * cache will be revalidated.
3082 	 */
3083 	mutex_enter(&ire->ire_lock);
3084 	ire->ire_badcnt++;
3085 	ire->ire_last_badcnt = TICK_TO_SEC(ddi_get_lbolt64());
3086 	nce = ire->ire_nce_cache;
3087 	if (nce != NULL && nce->nce_is_condemned &&
3088 	    nce->nce_common->ncec_state == ND_UNREACHABLE)
3089 		ire->ire_nce_cache = NULL;
3090 	else
3091 		nce = NULL;
3092 	mutex_exit(&ire->ire_lock);
3093 	if (nce != NULL)
3094 		nce_refrele(nce);
3095 
3096 	ire_increment_generation(ire);
3097 	ire_dep_incr_generation(ire);
3098 
3099 	return (ire->ire_bucket->irb_ire_cnt > 1);
3100 }
3101 
3102 /*
3103  * Walk ire_dep_parent chain and validate that ire_dep_parent->ire_generation ==
3104  * ire_dep_parent_generation.
3105  * If they all match we just return ire_generation from the topmost IRE.
3106  * Otherwise we propagate the mismatch by setting all ire_dep_parent_generation
3107  * above the mismatch to IRE_GENERATION_VERIFY and also returning
3108  * IRE_GENERATION_VERIFY.
3109  */
3110 uint_t
3111 ire_dep_validate_generations(ire_t *ire)
3112 {
3113 	ip_stack_t	*ipst = ire->ire_ipst;
3114 	uint_t		generation;
3115 	ire_t		*ire1;
3116 
3117 	rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
3118 	generation = ire->ire_generation;	/* Assuming things match */
3119 	for (ire1 = ire; ire1 != NULL; ire1 = ire1->ire_dep_parent) {
3120 		ASSERT(ire1->ire_ipversion == IPV4_VERSION ||
3121 		    ire1->ire_ipversion == IPV6_VERSION);
3122 		if (ire1->ire_dep_parent == NULL)
3123 			break;
3124 		if (ire1->ire_dep_parent_generation !=
3125 		    ire1->ire_dep_parent->ire_generation)
3126 			goto mismatch;
3127 	}
3128 	rw_exit(&ipst->ips_ire_dep_lock);
3129 	return (generation);
3130 
3131 mismatch:
3132 	generation = IRE_GENERATION_VERIFY;
3133 	/* Fill from top down to the mismatch with _VERIFY */
3134 	while (ire != ire1) {
3135 		ASSERT(ire->ire_ipversion == IPV4_VERSION ||
3136 		    ire->ire_ipversion == IPV6_VERSION);
3137 		mutex_enter(&ire->ire_lock);
3138 		ire->ire_dep_parent_generation = IRE_GENERATION_VERIFY;
3139 		mutex_exit(&ire->ire_lock);
3140 		ire = ire->ire_dep_parent;
3141 	}
3142 	rw_exit(&ipst->ips_ire_dep_lock);
3143 	return (generation);
3144 }
3145 
3146 /*
3147  * Used when we need to return an ire with ire_dep_parent, but we
3148  * know the chain is invalid for instance we didn't create an IRE_IF_CLONE
3149  * Using IRE_GENERATION_VERIFY means that next time we'll redo the
3150  * recursive lookup.
3151  */
3152 void
3153 ire_dep_invalidate_generations(ire_t *ire)
3154 {
3155 	ip_stack_t	*ipst = ire->ire_ipst;
3156 
3157 	rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
3158 	while (ire != NULL) {
3159 		ASSERT(ire->ire_ipversion == IPV4_VERSION ||
3160 		    ire->ire_ipversion == IPV6_VERSION);
3161 		mutex_enter(&ire->ire_lock);
3162 		ire->ire_dep_parent_generation = IRE_GENERATION_VERIFY;
3163 		mutex_exit(&ire->ire_lock);
3164 		ire = ire->ire_dep_parent;
3165 	}
3166 	rw_exit(&ipst->ips_ire_dep_lock);
3167 }
3168 
3169 /* Set _VERIFY ire_dep_parent_generation for all children recursively */
3170 static void
3171 ire_dep_invalidate_children(ire_t *child)
3172 {
3173 	ip_stack_t	*ipst = child->ire_ipst;
3174 
3175 	ASSERT(RW_WRITE_HELD(&ipst->ips_ire_dep_lock));
3176 	/* Depth first */
3177 	if (child->ire_dep_children != NULL)
3178 		ire_dep_invalidate_children(child->ire_dep_children);
3179 
3180 	while (child != NULL) {
3181 		mutex_enter(&child->ire_lock);
3182 		child->ire_dep_parent_generation = IRE_GENERATION_VERIFY;
3183 		mutex_exit(&child->ire_lock);
3184 		child = child->ire_dep_sib_next;
3185 	}
3186 }
3187 
3188 static void
3189 ire_dep_increment_children(ire_t *child)
3190 {
3191 	ip_stack_t	*ipst = child->ire_ipst;
3192 
3193 	ASSERT(RW_READ_HELD(&ipst->ips_ire_dep_lock));
3194 	/* Depth first */
3195 	if (child->ire_dep_children != NULL)
3196 		ire_dep_increment_children(child->ire_dep_children);
3197 
3198 	while (child != NULL) {
3199 		if (!IRE_IS_CONDEMNED(child))
3200 			ire_increment_generation(child);
3201 		child = child->ire_dep_sib_next;
3202 	}
3203 }
3204 
3205 /*
3206  * Walk all the children of this ire recursively and increment their
3207  * generation number.
3208  */
3209 void
3210 ire_dep_incr_generation(ire_t *parent)
3211 {
3212 	ip_stack_t	*ipst = parent->ire_ipst;
3213 
3214 	rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
3215 	if (parent->ire_dep_children != NULL)
3216 		ire_dep_increment_children(parent->ire_dep_children);
3217 	rw_exit(&ipst->ips_ire_dep_lock);
3218 }
3219 
3220 /*
3221  * Get a new ire_nce_cache for this IRE as well as its nexthop.
3222  * Returns zero if it succeeds. Can fail due to lack of memory or when
3223  * the route has become unreachable. Returns ENOMEM and ENETUNREACH in those
3224  * cases.
3225  *
3226  * In the in.mpathd case, the ire will have ire_testhidden
3227  * set; so we should create the ncec for the underlying ill.
3228  *
3229  * Note that the error returned by ire_revalidate_nce() is ignored by most
3230  * callers except ire_handle_condemned_nce(), which handles the ENETUNREACH
3231  * error to mark potentially bad ire's. For all the other callers, an
3232  * error return could indicate a transient condition like ENOMEM, or could
3233  * be the result of an interface that is going down/unplumbing. In the former
3234  * case (transient error), we would leave the old stale ire/ire_nce_cache
3235  * in place, and possibly use incorrect link-layer information to send packets
3236  * but would eventually recover. In the latter case (ill down/replumb),
3237  * ire_revalidate_nce() might return a condemned nce back, but we would then
3238  * recover in the packet output path.
3239  */
3240 int
3241 ire_revalidate_nce(ire_t *ire)
3242 {
3243 	nce_t		*nce, *old_nce;
3244 	ire_t		*nexthop;
3245 
3246 	/*
3247 	 * For multicast we conceptually have an NCE but we don't store it
3248 	 * in ire_nce_cache; when ire_to_nce is called we allocate the nce.
3249 	 */
3250 	if (ire->ire_type & IRE_MULTICAST)
3251 		return (0);
3252 
3253 	/* ire_testhidden should only be set on under-interfaces */
3254 	ASSERT(!ire->ire_testhidden || !IS_IPMP(ire->ire_ill));
3255 
3256 	nexthop = ire_nexthop(ire);
3257 	if (nexthop == NULL) {
3258 		/* The route is potentially bad */
3259 		(void) ire_no_good(ire);
3260 		return (ENETUNREACH);
3261 	}
3262 	if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) {
3263 		ASSERT(ire->ire_ill != NULL);
3264 
3265 		if (ire->ire_ipversion == IPV4_VERSION)
3266 			nce = nce_lookup_v4(ire->ire_ill, &ire->ire_addr);
3267 		else
3268 			nce = nce_lookup_v6(ire->ire_ill, &ire->ire_addr_v6);
3269 	} else {
3270 		ASSERT(nexthop->ire_type & IRE_ONLINK);
3271 		if (ire->ire_ipversion == IPV4_VERSION) {
3272 			nce = arp_nce_init(nexthop->ire_ill, nexthop->ire_addr,
3273 			    nexthop->ire_type);
3274 		} else {
3275 			nce = ndp_nce_init(nexthop->ire_ill,
3276 			    &nexthop->ire_addr_v6, nexthop->ire_type);
3277 		}
3278 	}
3279 	if (nce == NULL) {
3280 		/*
3281 		 * Leave the old stale one in place to avoid a NULL
3282 		 * ire_nce_cache.
3283 		 */
3284 		ire_refrele(nexthop);
3285 		return (ENOMEM);
3286 	}
3287 
3288 	if (nexthop != ire) {
3289 		/* Update the nexthop ire */
3290 		mutex_enter(&nexthop->ire_lock);
3291 		old_nce = nexthop->ire_nce_cache;
3292 		if (!IRE_IS_CONDEMNED(nexthop)) {
3293 			nce_refhold(nce);
3294 			nexthop->ire_nce_cache = nce;
3295 		} else {
3296 			nexthop->ire_nce_cache = NULL;
3297 		}
3298 		mutex_exit(&nexthop->ire_lock);
3299 		if (old_nce != NULL)
3300 			nce_refrele(old_nce);
3301 	}
3302 	ire_refrele(nexthop);
3303 
3304 	mutex_enter(&ire->ire_lock);
3305 	old_nce = ire->ire_nce_cache;
3306 	if (!IRE_IS_CONDEMNED(ire)) {
3307 		nce_refhold(nce);
3308 		ire->ire_nce_cache = nce;
3309 	} else {
3310 		ire->ire_nce_cache = NULL;
3311 	}
3312 	mutex_exit(&ire->ire_lock);
3313 	if (old_nce != NULL)
3314 		nce_refrele(old_nce);
3315 
3316 	nce_refrele(nce);
3317 	return (0);
3318 }
3319 
3320 /*
3321  * Get a held nce for a given ire.
3322  * In the common case this is just from ire_nce_cache.
3323  * For IRE_MULTICAST this needs to do an explicit lookup since we do not
3324  * have an IRE_MULTICAST per address.
3325  * Note that this explicitly returns CONDEMNED NCEs. The caller needs those
3326  * so they can check whether the NCE went unreachable (as opposed to was
3327  * condemned for some other reason).
3328  */
3329 nce_t *
3330 ire_to_nce(ire_t *ire, ipaddr_t v4nexthop, const in6_addr_t *v6nexthop)
3331 {
3332 	nce_t	*nce;
3333 
3334 	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
3335 		return (NULL);
3336 
3337 	/* ire_testhidden should only be set on under-interfaces */
3338 	ASSERT(!ire->ire_testhidden || !IS_IPMP(ire->ire_ill));
3339 
3340 	mutex_enter(&ire->ire_lock);
3341 	nce = ire->ire_nce_cache;
3342 	if (nce != NULL) {
3343 		nce_refhold(nce);
3344 		mutex_exit(&ire->ire_lock);
3345 		return (nce);
3346 	}
3347 	mutex_exit(&ire->ire_lock);
3348 
3349 	if (ire->ire_type & IRE_MULTICAST) {
3350 		ASSERT(ire->ire_ill != NULL);
3351 
3352 		if (ire->ire_ipversion == IPV4_VERSION) {
3353 			ASSERT(v6nexthop == NULL);
3354 
3355 			nce = arp_nce_init(ire->ire_ill, v4nexthop,
3356 			    ire->ire_type);
3357 		} else {
3358 			ASSERT(v6nexthop != NULL);
3359 			ASSERT(v4nexthop == 0);
3360 			nce = ndp_nce_init(ire->ire_ill, v6nexthop,
3361 			    ire->ire_type);
3362 		}
3363 		return (nce);
3364 	}
3365 	return (NULL);
3366 }
3367 
3368 nce_t *
3369 ire_to_nce_pkt(ire_t *ire, mblk_t *mp)
3370 {
3371 	ipha_t		*ipha;
3372 	ip6_t		*ip6h;
3373 
3374 	if (IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION) {
3375 		ipha = (ipha_t *)mp->b_rptr;
3376 		return (ire_to_nce(ire, ipha->ipha_dst, NULL));
3377 	} else {
3378 		ip6h = (ip6_t *)mp->b_rptr;
3379 		return (ire_to_nce(ire, INADDR_ANY, &ip6h->ip6_dst));
3380 	}
3381 }
3382 
3383 /*
3384  * Given an IRE_INTERFACE (that matches more than one address) create
3385  * and return an IRE_IF_CLONE for the specific address.
3386  * Return the generation number.
3387  * Returns NULL is no memory for the IRE.
3388  * Handles both IPv4 and IPv6.
3389  */
3390 ire_t *
3391 ire_create_if_clone(ire_t *ire_if, const in6_addr_t *addr, uint_t *generationp)
3392 {
3393 	ire_t		*ire;
3394 	ire_t		*nire;
3395 
3396 	if (ire_if->ire_ipversion == IPV4_VERSION) {
3397 		ipaddr_t	v4addr;
3398 		ipaddr_t	mask = IP_HOST_MASK;
3399 
3400 		ASSERT(IN6_IS_ADDR_V4MAPPED(addr));
3401 		IN6_V4MAPPED_TO_IPADDR(addr, v4addr);
3402 
3403 		ire = ire_create(
3404 		    (uchar_t *)&v4addr,			/* dest address */
3405 		    (uchar_t *)&mask,			/* mask */
3406 		    (uchar_t *)&ire_if->ire_gateway_addr,
3407 		    IRE_IF_CLONE,			/* IRE type */
3408 		    ire_if->ire_ill,
3409 		    ire_if->ire_zoneid,
3410 		    ire_if->ire_flags | RTF_HOST,
3411 		    NULL,		/* No security attr for IRE_IF_ALL */
3412 		    ire_if->ire_ipst);
3413 	} else {
3414 		ASSERT(!IN6_IS_ADDR_V4MAPPED(addr));
3415 		ire = ire_create_v6(
3416 		    addr,				/* dest address */
3417 		    &ipv6_all_ones,			/* mask */
3418 		    &ire_if->ire_gateway_addr_v6,	/* gateway addr */
3419 		    IRE_IF_CLONE,			/* IRE type */
3420 		    ire_if->ire_ill,
3421 		    ire_if->ire_zoneid,
3422 		    ire_if->ire_flags | RTF_HOST,
3423 		    NULL,		/* No security attr for IRE_IF_ALL */
3424 		    ire_if->ire_ipst);
3425 	}
3426 	if (ire == NULL)
3427 		return (NULL);
3428 
3429 	/* Take the metrics, in particular the mtu, from the IRE_IF */
3430 	ire->ire_metrics = ire_if->ire_metrics;
3431 
3432 	nire = ire_add(ire);
3433 	if (nire == NULL) /* Some failure */
3434 		return (NULL);
3435 
3436 	if (generationp != NULL)
3437 		*generationp = nire->ire_generation;
3438 
3439 	/*
3440 	 * Make sure races don't add a duplicate by
3441 	 * catching the case when an identical was returned.
3442 	 */
3443 	if (nire != ire) {
3444 		ASSERT(nire->ire_identical_ref > 1);
3445 		ire_delete(nire);
3446 	}
3447 	return (nire);
3448 }
3449 
3450 /*
3451  * The argument is an IRE_INTERFACE. Delete all of IRE_IF_CLONE in the
3452  * ire_dep_children (just walk the ire_dep_sib_next since they are all
3453  * immediate children.)
3454  * Since we hold a lock while we remove them we need to defer the actual
3455  * calls to ire_delete() until we have dropped the lock. This makes things
3456  * less efficient since we restart at the top after dropping the lock. But
3457  * we only run when an IRE_INTERFACE is deleted which is infrquent.
3458  *
3459  * Note that ire_dep_children can be any mixture of offlink routes and
3460  * IRE_IF_CLONE entries.
3461  */
3462 void
3463 ire_dep_delete_if_clone(ire_t *parent)
3464 {
3465 	ip_stack_t	*ipst = parent->ire_ipst;
3466 	ire_t		*child, *next;
3467 
3468 restart:
3469 	rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
3470 	if (parent->ire_dep_children == NULL) {
3471 		rw_exit(&ipst->ips_ire_dep_lock);
3472 		return;
3473 	}
3474 	child = parent->ire_dep_children;
3475 	while (child != NULL) {
3476 		next = child->ire_dep_sib_next;
3477 		if ((child->ire_type & IRE_IF_CLONE) &&
3478 		    !IRE_IS_CONDEMNED(child)) {
3479 			ire_refhold(child);
3480 			rw_exit(&ipst->ips_ire_dep_lock);
3481 			ire_delete(child);
3482 			ASSERT(IRE_IS_CONDEMNED(child));
3483 			ire_refrele(child);
3484 			goto restart;
3485 		}
3486 		child = next;
3487 	}
3488 	rw_exit(&ipst->ips_ire_dep_lock);
3489 }
3490 
3491 /*
3492  * ire_pref() is used in recursive route-resolution for a destination to
3493  * determine the preference of an ire, where "preference" is determined
3494  * based on the level of indirection to the destination of the ire.
3495  * A higher preference indicates that fewer lookups are needed to complete
3496  * recursive route lookup. Thus
3497  * ire_pref(RTF_INDIRECT) < ire_pref(IRE_IF_RESOLVER) < ire_pref(IRE_PREF_CLONE)
3498  */
3499 int
3500 ire_pref(ire_t *ire)
3501 {
3502 	if (ire->ire_flags & RTF_INDIRECT)
3503 		return (1);
3504 	if (ire->ire_type & IRE_OFFLINK)
3505 		return (2);
3506 	if (ire->ire_type & (IRE_IF_RESOLVER|IRE_IF_NORESOLVER))
3507 		return (3);
3508 	if (ire->ire_type & IRE_IF_CLONE)
3509 		return (4);
3510 	if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK|IRE_BROADCAST))
3511 		return (5);
3512 	return (-1); /* unknown ire_type */
3513 }
3514