xref: /titanic_44/usr/src/uts/common/inet/ip/ip_ire.c (revision 4165f46543b20d435f7ef0aced6239f7e97b12ff)
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 <net/pfkeyv2.h>
64 #include <inet/ipsec_info.h>
65 #include <inet/sadb.h>
66 #include <inet/tcp.h>
67 #include <inet/ipclassifier.h>
68 #include <sys/zone.h>
69 #include <sys/cpuvar.h>
70 
71 #include <sys/tsol/label.h>
72 #include <sys/tsol/tnet.h>
73 
74 struct kmem_cache *rt_entry_cache;
75 
76 /*
77  * Synchronization notes:
78  *
79  * The fields of the ire_t struct are protected in the following way :
80  *
81  * ire_next/ire_ptpn
82  *
83  *	- bucket lock of the respective tables (cache or forwarding tables).
84  *
85  * ire_mp, ire_rfq, ire_stq, ire_u *except* ire_gateway_addr[v6], ire_mask,
86  * ire_type, ire_create_time, ire_masklen, ire_ipversion, ire_flags, ire_ipif,
87  * ire_ihandle, ire_phandle, ire_nce, ire_bucket, ire_in_ill, ire_in_src_addr
88  *
89  *	- Set in ire_create_v4/v6 and never changes after that. Thus,
90  *	  we don't need a lock whenever these fields are accessed.
91  *
92  *	- ire_bucket and ire_masklen (also set in ire_create) is set in
93  *        ire_add_v4/ire_add_v6 before inserting in the bucket and never
94  *        changes after that. Thus we don't need a lock whenever these
95  *	  fields are accessed.
96  *
97  * ire_gateway_addr_v4[v6]
98  *
99  *	- ire_gateway_addr_v4[v6] is set during ire_create and later modified
100  *	  by rts_setgwr[v6]. As ire_gateway_addr is a uint32_t, updates to
101  *	  it assumed to be atomic and hence the other parts of the code
102  *	  does not use any locks. ire_gateway_addr_v6 updates are not atomic
103  *	  and hence any access to it uses ire_lock to get/set the right value.
104  *
105  * ire_ident, ire_refcnt
106  *
107  *	- Updated atomically using atomic_add_32
108  *
109  * ire_ssthresh, ire_rtt_sd, ire_rtt, ire_ib_pkt_count, ire_ob_pkt_count
110  *
111  *	- Assumes that 32 bit writes are atomic. No locks. ire_lock is
112  *	  used to serialize updates to ire_ssthresh, ire_rtt_sd, ire_rtt.
113  *
114  * ire_max_frag, ire_frag_flag
115  *
116  *	- ire_lock is used to set/read both of them together.
117  *
118  * ire_tire_mark
119  *
120  *	- Set in ire_create and updated in ire_expire, which is called
121  *	  by only one function namely ip_trash_timer_expire. Thus only
122  *	  one function updates and examines the value.
123  *
124  * ire_marks
125  *	- bucket lock protects this.
126  *
127  * ire_ll_hdr_length
128  *
129  *	- Place holder for returning the information to the upper layers
130  *	  when IRE_DB_REQ comes down.
131  *
132  *
133  * ipv6_ire_default_count is protected by the bucket lock of
134  * ip_forwarding_table_v6[0][0].
135  *
136  * ipv6_ire_default_index is not protected as it  is just a hint
137  * at which default gateway to use. There is nothing
138  * wrong in using the same gateway for two different connections.
139  *
140  * As we always hold the bucket locks in all the places while accessing
141  * the above values, it is natural to use them for protecting them.
142  *
143  * We have a separate cache table and forwarding table for IPv4 and IPv6.
144  * Cache table (ip_cache_table/ip_cache_table_v6) is a pointer to an
145  * array of irb_t structures. The IPv6 forwarding table
146  * (ip_forwarding_table_v6) is an array of pointers to arrays of irb_t
147  *  structure. ip_forwarding_table_v6 is allocated dynamically in
148  * ire_add_v6. ire_ft_init_lock is used to serialize multiple threads
149  * initializing the same bucket. Once a bucket is initialized, it is never
150  * de-alloacted. This assumption enables us to access
151  * ip_forwarding_table_v6[i] without any locks.
152  *
153  * The forwarding table for IPv4 is a radix tree whose leaves
154  * are rt_entry structures containing the irb_t for the rt_dst. The irb_t
155  * for IPv4 is dynamically allocated and freed.
156  *
157  * Each irb_t - ire bucket structure has a lock to protect
158  * a bucket and the ires residing in the bucket have a back pointer to
159  * the bucket structure. It also has a reference count for the number
160  * of threads walking the bucket - irb_refcnt which is bumped up
161  * using the macro IRB_REFHOLD macro. The flags irb_flags can be
162  * set to IRE_MARK_CONDEMNED indicating that there are some ires
163  * in this bucket that are marked with IRE_MARK_CONDEMNED and the
164  * last thread to leave the bucket should delete the ires. Usually
165  * this is done by the IRB_REFRELE macro which is used to decrement
166  * the reference count on a bucket. See comments above irb_t structure
167  * definition in ip.h for further details.
168  *
169  * IRE_REFHOLD/IRE_REFRELE macros operate on the ire which increments/
170  * decrements the reference count, ire_refcnt, atomically on the ire.
171  * ire_refcnt is modified only using this macro. Operations on the IRE
172  * could be described as follows :
173  *
174  * CREATE an ire with reference count initialized to 1.
175  *
176  * ADDITION of an ire holds the bucket lock, checks for duplicates
177  * and then adds the ire. ire_add_v4/ire_add_v6 returns the ire after
178  * bumping up once more i.e the reference count is 2. This is to avoid
179  * an extra lookup in the functions calling ire_add which wants to
180  * work with the ire after adding.
181  *
182  * LOOKUP of an ire bumps up the reference count using IRE_REFHOLD
183  * macro. It is valid to bump up the referece count of the IRE,
184  * after the lookup has returned an ire. Following are the lookup
185  * functions that return an HELD ire :
186  *
187  * ire_lookup_local[_v6], ire_ctable_lookup[_v6], ire_ftable_lookup[_v6],
188  * ire_cache_lookup[_v6], ire_lookup_multi[_v6], ire_route_lookup[_v6],
189  * ipif_to_ire[_v6].
190  *
191  * DELETION of an ire holds the bucket lock, removes it from the list
192  * and then decrements the reference count for having removed from the list
193  * by using the IRE_REFRELE macro. If some other thread has looked up
194  * the ire, the reference count would have been bumped up and hence
195  * this ire will not be freed once deleted. It will be freed once the
196  * reference count drops to zero.
197  *
198  * Add and Delete acquires the bucket lock as RW_WRITER, while all the
199  * lookups acquire the bucket lock as RW_READER.
200  *
201  * NOTE : The only functions that does the IRE_REFRELE when an ire is
202  *	  passed as an argument are :
203  *
204  *	  1) ip_wput_ire : This is because it IRE_REFHOLD/RELEs the
205  *			   broadcast ires it looks up internally within
206  *			   the function. Currently, for simplicity it does
207  *			   not differentiate the one that is passed in and
208  *			   the ones it looks up internally. It always
209  *			   IRE_REFRELEs.
210  *	  2) ire_send
211  *	     ire_send_v6 : As ire_send calls ip_wput_ire and other functions
212  *			   that take ire as an argument, it has to selectively
213  *			   IRE_REFRELE the ire. To maintain symmetry,
214  *			   ire_send_v6 does the same.
215  *
216  * Otherwise, the general rule is to do the IRE_REFRELE in the function
217  * that is passing the ire as an argument.
218  *
219  * In trying to locate ires the following points are to be noted.
220  *
221  * IRE_MARK_CONDEMNED signifies that the ire has been logically deleted and is
222  * to be ignored when walking the ires using ire_next.
223  *
224  * Zones note:
225  *	Walking IREs within a given zone also walks certain ires in other
226  *	zones.  This is done intentionally.  IRE walks with a specified
227  *	zoneid are used only when doing informational reports, and
228  *	zone users want to see things that they can access. See block
229  *	comment in ire_walk_ill_match().
230  */
231 
232 /*
233  * The minimum size of IRE cache table.  It will be recalcuated in
234  * ip_ire_init().
235  * Setable in /etc/system
236  */
237 uint32_t ip_cache_table_size = IP_CACHE_TABLE_SIZE;
238 uint32_t ip6_cache_table_size = IP6_CACHE_TABLE_SIZE;
239 
240 /*
241  * The size of the forwarding table.  We will make sure that it is a
242  * power of 2 in ip_ire_init().
243  * Setable in /etc/system
244  */
245 uint32_t ip6_ftable_hash_size = IP6_FTABLE_HASH_SIZE;
246 
247 struct	kmem_cache	*ire_cache;
248 static ire_t	ire_null;
249 
250 /*
251  * The threshold number of IRE in a bucket when the IREs are
252  * cleaned up.  This threshold is calculated later in ip_open()
253  * based on the speed of CPU and available memory.  This default
254  * value is the maximum.
255  *
256  * We have two kinds of cached IRE, temporary and
257  * non-temporary.  Temporary IREs are marked with
258  * IRE_MARK_TEMPORARY.  They are IREs created for non
259  * TCP traffic and for forwarding purposes.  All others
260  * are non-temporary IREs.  We don't mark IRE created for
261  * TCP as temporary because TCP is stateful and there are
262  * info stored in the IRE which can be shared by other TCP
263  * connections to the same destination.  For connected
264  * endpoint, we also don't want to mark the IRE used as
265  * temporary because the same IRE will be used frequently,
266  * otherwise, the app should not do a connect().  We change
267  * the marking at ip_bind_connected_*() if necessary.
268  *
269  * We want to keep the cache IRE hash bucket length reasonably
270  * short, otherwise IRE lookup functions will take "forever."
271  * We use the "crude" function that the IRE bucket
272  * length should be based on the CPU speed, which is 1 entry
273  * per x MHz, depending on the shift factor ip_ire_cpu_ratio
274  * (n).  This means that with a 750MHz CPU, the max bucket
275  * length can be (750 >> n) entries.
276  *
277  * Note that this threshold is separate for temp and non-temp
278  * IREs.  This means that the actual bucket length can be
279  * twice as that.  And while we try to keep temporary IRE
280  * length at most at the threshold value, we do not attempt to
281  * make the length for non-temporary IREs fixed, for the
282  * reason stated above.  Instead, we start trying to find
283  * "unused" non-temporary IREs when the bucket length reaches
284  * this threshold and clean them up.
285  *
286  * We also want to limit the amount of memory used by
287  * IREs.  So if we are allowed to use ~3% of memory (M)
288  * for those IREs, each bucket should not have more than
289  *
290  * 	M / num of cache bucket / sizeof (ire_t)
291  *
292  * Again the above memory uses are separate for temp and
293  * non-temp cached IREs.
294  *
295  * We may also want the limit to be a function of the number
296  * of interfaces and number of CPUs.  Doing the initialization
297  * in ip_open() means that every time an interface is plumbed,
298  * the max is re-calculated.  Right now, we don't do anything
299  * different.  In future, when we have more experience, we
300  * may want to change this behavior.
301  */
302 uint32_t ip_ire_max_bucket_cnt = 10;	/* Setable in /etc/system */
303 uint32_t ip6_ire_max_bucket_cnt = 10;
304 uint32_t ip_ire_cleanup_cnt = 2;
305 
306 /*
307  * The minimum of the temporary IRE bucket count.  We do not want
308  * the length of each bucket to be too short.  This may hurt
309  * performance of some apps as the temporary IREs are removed too
310  * often.
311  */
312 uint32_t ip_ire_min_bucket_cnt = 3;	/* /etc/system - not used */
313 uint32_t ip6_ire_min_bucket_cnt = 3;
314 
315 /*
316  * The ratio of memory consumed by IRE used for temporary to available
317  * memory.  This is a shift factor, so 6 means the ratio 1 to 64.  This
318  * value can be changed in /etc/system.  6 is a reasonable number.
319  */
320 uint32_t ip_ire_mem_ratio = 6;	/* /etc/system */
321 /* The shift factor for CPU speed to calculate the max IRE bucket length. */
322 uint32_t ip_ire_cpu_ratio = 7;	/* /etc/system */
323 
324 typedef struct nce_clookup_s {
325 	ipaddr_t ncecl_addr;
326 	boolean_t ncecl_found;
327 } nce_clookup_t;
328 
329 /*
330  * The maximum number of buckets in IRE cache table.  In future, we may
331  * want to make it a dynamic hash table.  For the moment, we fix the
332  * size and allocate the table in ip_ire_init() when IP is first loaded.
333  * We take into account the amount of memory a system has.
334  */
335 #define	IP_MAX_CACHE_TABLE_SIZE	4096
336 
337 /* Setable in /etc/system */
338 static uint32_t	ip_max_cache_table_size = IP_MAX_CACHE_TABLE_SIZE;
339 static uint32_t	ip6_max_cache_table_size = IP_MAX_CACHE_TABLE_SIZE;
340 
341 /* Zero iulp_t for initialization. */
342 const iulp_t	ire_uinfo_null = { 0 };
343 
344 static int	ire_add_v4(ire_t **ire_p, queue_t *q, mblk_t *mp,
345     ipsq_func_t func, boolean_t);
346 static void	ire_delete_v4(ire_t *ire);
347 static void	ire_walk_ipvers(pfv_t func, void *arg, uchar_t vers,
348     zoneid_t zoneid, ip_stack_t *);
349 static void	ire_walk_ill_ipvers(uint_t match_flags, uint_t ire_type,
350     pfv_t func, void *arg, uchar_t vers, ill_t *ill);
351 static void	ire_cache_cleanup(irb_t *irb, uint32_t threshold,
352     ire_t *ref_ire);
353 static	void	ip_nce_clookup_and_delete(nce_t *nce, void *arg);
354 static	ire_t	*ip4_ctable_lookup_impl(ire_ctable_args_t *margs);
355 #ifdef DEBUG
356 static void	ire_trace_cleanup(const ire_t *);
357 #endif
358 
359 /*
360  * To avoid bloating the code, we call this function instead of
361  * using the macro IRE_REFRELE. Use macro only in performance
362  * critical paths.
363  *
364  * Must not be called while holding any locks. Otherwise if this is
365  * the last reference to be released there is a chance of recursive mutex
366  * panic due to ire_refrele -> ipif_ill_refrele_tail -> qwriter_ip trying
367  * to restart an ioctl. The one exception is when the caller is sure that
368  * this is not the last reference to be released. Eg. if the caller is
369  * sure that the ire has not been deleted and won't be deleted.
370  */
371 void
372 ire_refrele(ire_t *ire)
373 {
374 	IRE_REFRELE(ire);
375 }
376 
377 void
378 ire_refrele_notr(ire_t *ire)
379 {
380 	IRE_REFRELE_NOTR(ire);
381 }
382 
383 /*
384  * kmem_cache_alloc constructor for IRE in kma space.
385  * Note that when ire_mp is set the IRE is stored in that mblk and
386  * not in this cache.
387  */
388 /* ARGSUSED */
389 static int
390 ip_ire_constructor(void *buf, void *cdrarg, int kmflags)
391 {
392 	ire_t	*ire = buf;
393 
394 	ire->ire_nce = NULL;
395 
396 	return (0);
397 }
398 
399 /* ARGSUSED1 */
400 static void
401 ip_ire_destructor(void *buf, void *cdrarg)
402 {
403 	ire_t	*ire = buf;
404 
405 	ASSERT(ire->ire_nce == NULL);
406 }
407 
408 /*
409  * This function is associated with the IP_IOC_IRE_ADVISE_NO_REPLY
410  * IOCTL.  It is used by TCP (or other ULPs) to supply revised information
411  * for an existing CACHED IRE.
412  */
413 /* ARGSUSED */
414 int
415 ip_ire_advise(queue_t *q, mblk_t *mp, cred_t *ioc_cr)
416 {
417 	uchar_t	*addr_ucp;
418 	ipic_t	*ipic;
419 	ire_t	*ire;
420 	ipaddr_t	addr;
421 	in6_addr_t	v6addr;
422 	irb_t	*irb;
423 	zoneid_t	zoneid;
424 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
425 
426 	ASSERT(q->q_next == NULL);
427 	zoneid = Q_TO_CONN(q)->conn_zoneid;
428 
429 	/*
430 	 * Check privilege using the ioctl credential; if it is NULL
431 	 * then this is a kernel message and therefor privileged.
432 	 */
433 	if (ioc_cr != NULL && secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
434 		return (EPERM);
435 
436 	ipic = (ipic_t *)mp->b_rptr;
437 	if (!(addr_ucp = mi_offset_param(mp, ipic->ipic_addr_offset,
438 	    ipic->ipic_addr_length))) {
439 		return (EINVAL);
440 	}
441 	if (!OK_32PTR(addr_ucp))
442 		return (EINVAL);
443 	switch (ipic->ipic_addr_length) {
444 	case IP_ADDR_LEN: {
445 		/* Extract the destination address. */
446 		addr = *(ipaddr_t *)addr_ucp;
447 		/* Find the corresponding IRE. */
448 		ire = ire_cache_lookup(addr, zoneid, NULL, ipst);
449 		break;
450 	}
451 	case IPV6_ADDR_LEN: {
452 		/* Extract the destination address. */
453 		v6addr = *(in6_addr_t *)addr_ucp;
454 		/* Find the corresponding IRE. */
455 		ire = ire_cache_lookup_v6(&v6addr, zoneid, NULL, ipst);
456 		break;
457 	}
458 	default:
459 		return (EINVAL);
460 	}
461 
462 	if (ire == NULL)
463 		return (ENOENT);
464 	/*
465 	 * Update the round trip time estimate and/or the max frag size
466 	 * and/or the slow start threshold.
467 	 *
468 	 * We serialize multiple advises using ire_lock.
469 	 */
470 	mutex_enter(&ire->ire_lock);
471 	if (ipic->ipic_rtt) {
472 		/*
473 		 * If there is no old cached values, initialize them
474 		 * conservatively.  Set them to be (1.5 * new value).
475 		 */
476 		if (ire->ire_uinfo.iulp_rtt != 0) {
477 			ire->ire_uinfo.iulp_rtt = (ire->ire_uinfo.iulp_rtt +
478 			    ipic->ipic_rtt) >> 1;
479 		} else {
480 			ire->ire_uinfo.iulp_rtt = ipic->ipic_rtt +
481 			    (ipic->ipic_rtt >> 1);
482 		}
483 		if (ire->ire_uinfo.iulp_rtt_sd != 0) {
484 			ire->ire_uinfo.iulp_rtt_sd =
485 			    (ire->ire_uinfo.iulp_rtt_sd +
486 			    ipic->ipic_rtt_sd) >> 1;
487 		} else {
488 			ire->ire_uinfo.iulp_rtt_sd = ipic->ipic_rtt_sd +
489 			    (ipic->ipic_rtt_sd >> 1);
490 		}
491 	}
492 	if (ipic->ipic_max_frag)
493 		ire->ire_max_frag = MIN(ipic->ipic_max_frag, IP_MAXPACKET);
494 	if (ipic->ipic_ssthresh != 0) {
495 		if (ire->ire_uinfo.iulp_ssthresh != 0)
496 			ire->ire_uinfo.iulp_ssthresh =
497 			    (ipic->ipic_ssthresh +
498 			    ire->ire_uinfo.iulp_ssthresh) >> 1;
499 		else
500 			ire->ire_uinfo.iulp_ssthresh = ipic->ipic_ssthresh;
501 	}
502 	/*
503 	 * Don't need the ire_lock below this. ire_type does not change
504 	 * after initialization. ire_marks is protected by irb_lock.
505 	 */
506 	mutex_exit(&ire->ire_lock);
507 
508 	if (ipic->ipic_ire_marks != 0 && ire->ire_type == IRE_CACHE) {
509 		/*
510 		 * Only increment the temporary IRE count if the original
511 		 * IRE is not already marked temporary.
512 		 */
513 		irb = ire->ire_bucket;
514 		rw_enter(&irb->irb_lock, RW_WRITER);
515 		if ((ipic->ipic_ire_marks & IRE_MARK_TEMPORARY) &&
516 		    !(ire->ire_marks & IRE_MARK_TEMPORARY)) {
517 			irb->irb_tmp_ire_cnt++;
518 		}
519 		ire->ire_marks |= ipic->ipic_ire_marks;
520 		rw_exit(&irb->irb_lock);
521 	}
522 
523 	ire_refrele(ire);
524 	return (0);
525 }
526 
527 /*
528  * This function is associated with the IP_IOC_IRE_DELETE[_NO_REPLY]
529  * IOCTL[s].  The NO_REPLY form is used by TCP to delete a route IRE
530  * for a host that is not responding.  This will force an attempt to
531  * establish a new route, if available, and flush out the ARP entry so
532  * it will re-resolve.  Management processes may want to use the
533  * version that generates a reply.
534  *
535  * This function does not support IPv6 since Neighbor Unreachability Detection
536  * means that negative advise like this is useless.
537  */
538 /* ARGSUSED */
539 int
540 ip_ire_delete(queue_t *q, mblk_t *mp, cred_t *ioc_cr)
541 {
542 	uchar_t		*addr_ucp;
543 	ipaddr_t	addr;
544 	ire_t		*ire;
545 	ipid_t		*ipid;
546 	boolean_t	routing_sock_info = B_FALSE;	/* Sent info? */
547 	zoneid_t	zoneid;
548 	ire_t		*gire = NULL;
549 	ill_t		*ill;
550 	mblk_t		*arp_mp;
551 	ip_stack_t	*ipst;
552 
553 	ASSERT(q->q_next == NULL);
554 	zoneid = Q_TO_CONN(q)->conn_zoneid;
555 	ipst = CONNQ_TO_IPST(q);
556 
557 	/*
558 	 * Check privilege using the ioctl credential; if it is NULL
559 	 * then this is a kernel message and therefor privileged.
560 	 */
561 	if (ioc_cr != NULL && secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
562 		return (EPERM);
563 
564 	ipid = (ipid_t *)mp->b_rptr;
565 
566 	/* Only actions on IRE_CACHEs are acceptable at present. */
567 	if (ipid->ipid_ire_type != IRE_CACHE)
568 		return (EINVAL);
569 
570 	addr_ucp = mi_offset_param(mp, ipid->ipid_addr_offset,
571 	    ipid->ipid_addr_length);
572 	if (addr_ucp == NULL || !OK_32PTR(addr_ucp))
573 		return (EINVAL);
574 	switch (ipid->ipid_addr_length) {
575 	case IP_ADDR_LEN:
576 		/* addr_ucp points at IP addr */
577 		break;
578 	case sizeof (sin_t): {
579 		sin_t	*sin;
580 		/*
581 		 * got complete (sockaddr) address - increment addr_ucp to point
582 		 * at the ip_addr field.
583 		 */
584 		sin = (sin_t *)addr_ucp;
585 		addr_ucp = (uchar_t *)&sin->sin_addr.s_addr;
586 		break;
587 	}
588 	default:
589 		return (EINVAL);
590 	}
591 	/* Extract the destination address. */
592 	bcopy(addr_ucp, &addr, IP_ADDR_LEN);
593 
594 	/* Try to find the CACHED IRE. */
595 	ire = ire_cache_lookup(addr, zoneid, NULL, ipst);
596 
597 	/* Nail it. */
598 	if (ire) {
599 		/* Allow delete only on CACHE entries */
600 		if (ire->ire_type != IRE_CACHE) {
601 			ire_refrele(ire);
602 			return (EINVAL);
603 		}
604 
605 		/*
606 		 * Verify that the IRE has been around for a while.
607 		 * This is to protect against transport protocols
608 		 * that are too eager in sending delete messages.
609 		 */
610 		if (gethrestime_sec() <
611 		    ire->ire_create_time + ipst->ips_ip_ignore_delete_time) {
612 			ire_refrele(ire);
613 			return (EINVAL);
614 		}
615 		/*
616 		 * Now we have a potentially dead cache entry. We need
617 		 * to remove it.
618 		 * If this cache entry is generated from a
619 		 * default route (i.e., ire_cmask == 0),
620 		 * search the default list and mark it dead and some
621 		 * background process will try to activate it.
622 		 */
623 		if ((ire->ire_gateway_addr != 0) && (ire->ire_cmask == 0)) {
624 			/*
625 			 * Make sure that we pick a different
626 			 * IRE_DEFAULT next time.
627 			 */
628 			ire_t *gw_ire;
629 			irb_t *irb = NULL;
630 			uint_t match_flags;
631 
632 			match_flags = (MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE);
633 
634 			gire = ire_ftable_lookup(ire->ire_addr,
635 			    ire->ire_cmask, 0, 0,
636 			    ire->ire_ipif, NULL, zoneid, 0, NULL, match_flags,
637 			    ipst);
638 
639 			ip3dbg(("ire_ftable_lookup() returned gire %p\n",
640 			    (void *)gire));
641 
642 			if (gire != NULL) {
643 				irb = gire->ire_bucket;
644 
645 				/*
646 				 * We grab it as writer just to serialize
647 				 * multiple threads trying to bump up
648 				 * irb_rr_origin
649 				 */
650 				rw_enter(&irb->irb_lock, RW_WRITER);
651 				if ((gw_ire = irb->irb_rr_origin) == NULL) {
652 					rw_exit(&irb->irb_lock);
653 					goto done;
654 				}
655 
656 				DTRACE_PROBE1(ip__ire__del__origin,
657 				    (ire_t *), gw_ire);
658 
659 				/* Skip past the potentially bad gateway */
660 				if (ire->ire_gateway_addr ==
661 				    gw_ire->ire_gateway_addr) {
662 					ire_t *next = gw_ire->ire_next;
663 
664 					DTRACE_PROBE2(ip__ire__del,
665 					    (ire_t *), gw_ire, (irb_t *), irb);
666 					IRE_FIND_NEXT_ORIGIN(next);
667 					irb->irb_rr_origin = next;
668 				}
669 				rw_exit(&irb->irb_lock);
670 			}
671 		}
672 done:
673 		if (gire != NULL)
674 			IRE_REFRELE(gire);
675 		/* report the bad route to routing sockets */
676 		ip_rts_change(RTM_LOSING, ire->ire_addr, ire->ire_gateway_addr,
677 		    ire->ire_mask, ire->ire_src_addr, 0, 0, 0,
678 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_IFA), ipst);
679 		routing_sock_info = B_TRUE;
680 
681 		/*
682 		 * TCP is really telling us to start over completely, and it
683 		 * expects that we'll resend the ARP query.  Tell ARP to
684 		 * discard the entry, if this is a local destination.
685 		 *
686 		 * But, if the ARP entry is permanent then it shouldn't be
687 		 * deleted, so we set ARED_F_PRESERVE_PERM.
688 		 */
689 		ill = ire->ire_stq->q_ptr;
690 		if (ire->ire_gateway_addr == 0 &&
691 		    (arp_mp = ill_ared_alloc(ill, addr)) != NULL) {
692 			ared_t *ared = (ared_t *)arp_mp->b_rptr;
693 
694 			ASSERT(ared->ared_cmd == AR_ENTRY_DELETE);
695 			ared->ared_flags |= ARED_F_PRESERVE_PERM;
696 			putnext(ill->ill_rq, arp_mp);
697 		}
698 
699 		ire_delete(ire);
700 		ire_refrele(ire);
701 	}
702 	/*
703 	 * Also look for an IRE_HOST type redirect ire and
704 	 * remove it if present.
705 	 */
706 	ire = ire_route_lookup(addr, 0, 0, IRE_HOST, NULL, NULL,
707 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
708 
709 	/* Nail it. */
710 	if (ire != NULL) {
711 		if (ire->ire_flags & RTF_DYNAMIC) {
712 			if (!routing_sock_info) {
713 				ip_rts_change(RTM_LOSING, ire->ire_addr,
714 				    ire->ire_gateway_addr, ire->ire_mask,
715 				    ire->ire_src_addr, 0, 0, 0,
716 				    (RTA_DST | RTA_GATEWAY |
717 				    RTA_NETMASK | RTA_IFA),
718 				    ipst);
719 			}
720 			ire_delete(ire);
721 		}
722 		ire_refrele(ire);
723 	}
724 	return (0);
725 }
726 
727 /*
728  * ip_ire_req is called by ip_wput when an IRE_DB_REQ_TYPE message is handed
729  * down from the Upper Level Protocol to request a copy of the IRE (to check
730  * its type or to extract information like round-trip time estimates or the
731  * MTU.)
732  * The address is assumed to be in the ire_addr field. If no IRE is found
733  * an IRE is returned with ire_type being zero.
734  * Note that the upper lavel protocol has to check for broadcast
735  * (IRE_BROADCAST) and multicast (CLASSD(addr)).
736  * If there is a b_cont the resulting IRE_DB_TYPE mblk is placed at the
737  * end of the returned message.
738  *
739  * TCP sends down a message of this type with a connection request packet
740  * chained on. UDP and ICMP send it down to verify that a route exists for
741  * the destination address when they get connected.
742  */
743 void
744 ip_ire_req(queue_t *q, mblk_t *mp)
745 {
746 	ire_t	*inire;
747 	ire_t	*ire;
748 	mblk_t	*mp1;
749 	ire_t	*sire = NULL;
750 	zoneid_t zoneid = Q_TO_CONN(q)->conn_zoneid;
751 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
752 
753 	ASSERT(q->q_next == NULL);
754 
755 	if ((mp->b_wptr - mp->b_rptr) < sizeof (ire_t) ||
756 	    !OK_32PTR(mp->b_rptr)) {
757 		freemsg(mp);
758 		return;
759 	}
760 	inire = (ire_t *)mp->b_rptr;
761 	/*
762 	 * Got it, now take our best shot at an IRE.
763 	 */
764 	if (inire->ire_ipversion == IPV6_VERSION) {
765 		ire = ire_route_lookup_v6(&inire->ire_addr_v6, 0, 0, 0,
766 		    NULL, &sire, zoneid, NULL,
767 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT), ipst);
768 	} else {
769 		ASSERT(inire->ire_ipversion == IPV4_VERSION);
770 		ire = ire_route_lookup(inire->ire_addr, 0, 0, 0,
771 		    NULL, &sire, zoneid, NULL,
772 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT), ipst);
773 	}
774 
775 	/*
776 	 * We prevent returning IRES with source address INADDR_ANY
777 	 * as these were temporarily created for sending packets
778 	 * from endpoints that have conn_unspec_src set.
779 	 */
780 	if (ire == NULL ||
781 	    (ire->ire_ipversion == IPV4_VERSION &&
782 	    ire->ire_src_addr == INADDR_ANY) ||
783 	    (ire->ire_ipversion == IPV6_VERSION &&
784 	    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6))) {
785 		inire->ire_type = 0;
786 	} else {
787 		bcopy(ire, inire, sizeof (ire_t));
788 		/* Copy the route metrics from the parent. */
789 		if (sire != NULL) {
790 			bcopy(&(sire->ire_uinfo), &(inire->ire_uinfo),
791 			    sizeof (iulp_t));
792 		}
793 
794 		/* Pass the latest setting of the ip_path_mtu_discovery */
795 		inire->ire_frag_flag |=
796 		    (ipst->ips_ip_path_mtu_discovery) ? IPH_DF : 0;
797 	}
798 	if (ire != NULL)
799 		ire_refrele(ire);
800 	if (sire != NULL)
801 		ire_refrele(sire);
802 	mp->b_wptr = &mp->b_rptr[sizeof (ire_t)];
803 	mp->b_datap->db_type = IRE_DB_TYPE;
804 
805 	/* Put the IRE_DB_TYPE mblk last in the chain */
806 	mp1 = mp->b_cont;
807 	if (mp1 != NULL) {
808 		mp->b_cont = NULL;
809 		linkb(mp1, mp);
810 		mp = mp1;
811 	}
812 	qreply(q, mp);
813 }
814 
815 /*
816  * Send a packet using the specified IRE.
817  * If ire_src_addr_v6 is all zero then discard the IRE after
818  * the packet has been sent.
819  */
820 static void
821 ire_send(queue_t *q, mblk_t *pkt, ire_t *ire)
822 {
823 	mblk_t *ipsec_mp;
824 	boolean_t is_secure;
825 	uint_t ifindex;
826 	ill_t	*ill;
827 	zoneid_t zoneid = ire->ire_zoneid;
828 	ip_stack_t	*ipst = ire->ire_ipst;
829 
830 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
831 	ASSERT(!(ire->ire_type & IRE_LOCAL)); /* Has different ire_zoneid */
832 	ipsec_mp = pkt;
833 	is_secure = (pkt->b_datap->db_type == M_CTL);
834 	if (is_secure) {
835 		ipsec_out_t *io;
836 
837 		pkt = pkt->b_cont;
838 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
839 		if (io->ipsec_out_type == IPSEC_OUT)
840 			zoneid = io->ipsec_out_zoneid;
841 	}
842 
843 	/* If the packet originated externally then */
844 	if (pkt->b_prev) {
845 		ire_refrele(ire);
846 		/*
847 		 * Extract the ifindex from b_prev (set in ip_rput_noire).
848 		 * Look up interface to see if it still exists (it could have
849 		 * been unplumbed by the time the reply came back from ARP)
850 		 */
851 		ifindex = (uint_t)(uintptr_t)pkt->b_prev;
852 		ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
853 		    NULL, NULL, NULL, NULL, ipst);
854 		if (ill == NULL) {
855 			pkt->b_prev = NULL;
856 			pkt->b_next = NULL;
857 			freemsg(ipsec_mp);
858 			return;
859 		}
860 		q = ill->ill_rq;
861 		pkt->b_prev = NULL;
862 		/*
863 		 * This packet has not gone through IPSEC processing
864 		 * and hence we should not have any IPSEC message
865 		 * prepended.
866 		 */
867 		ASSERT(ipsec_mp == pkt);
868 		put(q, pkt);
869 		ill_refrele(ill);
870 	} else if (pkt->b_next) {
871 		/* Packets from multicast router */
872 		pkt->b_next = NULL;
873 		/*
874 		 * We never get the IPSEC_OUT while forwarding the
875 		 * packet for multicast router.
876 		 */
877 		ASSERT(ipsec_mp == pkt);
878 		ip_rput_forward(ire, (ipha_t *)pkt->b_rptr, ipsec_mp, NULL);
879 		ire_refrele(ire);
880 	} else {
881 		/* Locally originated packets */
882 		boolean_t delete_ire = B_FALSE;
883 		ipha_t *ipha = (ipha_t *)pkt->b_rptr;
884 
885 		/*
886 		 * If this IRE shouldn't be kept in the table (because its
887 		 * source address is unspecified), hold a reference to it so
888 		 * we can delete it even after e.g. ip_wput_ire() has dropped
889 		 * its reference.
890 		 */
891 		if (!(ire->ire_marks & IRE_MARK_NOADD) &&
892 		    ire->ire_src_addr == INADDR_ANY) {
893 			delete_ire = B_TRUE;
894 			IRE_REFHOLD(ire);
895 		}
896 
897 		/*
898 		 * If we were resolving a router we can not use the
899 		 * routers IRE for sending the packet (since it would
900 		 * violate the uniqness of the IP idents) thus we
901 		 * make another pass through ip_wput to create the IRE_CACHE
902 		 * for the destination.
903 		 * When IRE_MARK_NOADD is set, ire_add() is not called.
904 		 * Thus ip_wput() will never find a ire and result in an
905 		 * infinite loop. Thus we check whether IRE_MARK_NOADD is
906 		 * is set. This also implies that IRE_MARK_NOADD can only be
907 		 * used to send packets to directly connected hosts.
908 		 */
909 		if (ipha->ipha_dst != ire->ire_addr &&
910 		    !(ire->ire_marks & IRE_MARK_NOADD)) {
911 			ire_refrele(ire);	/* Held in ire_add */
912 			if (CONN_Q(q)) {
913 				(void) ip_output(Q_TO_CONN(q), ipsec_mp, q,
914 				    IRE_SEND);
915 			} else {
916 				(void) ip_output((void *)(uintptr_t)zoneid,
917 				    ipsec_mp, q, IRE_SEND);
918 			}
919 		} else {
920 			if (is_secure) {
921 				ipsec_out_t *oi;
922 				ipha_t *ipha;
923 
924 				oi = (ipsec_out_t *)ipsec_mp->b_rptr;
925 				ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
926 				if (oi->ipsec_out_proc_begin) {
927 					/*
928 					 * This is the case where
929 					 * ip_wput_ipsec_out could not find
930 					 * the IRE and recreated a new one.
931 					 * As ip_wput_ipsec_out does ire
932 					 * lookups, ire_refrele for the extra
933 					 * bump in ire_add.
934 					 */
935 					ire_refrele(ire);
936 					ip_wput_ipsec_out(q, ipsec_mp, ipha,
937 					    NULL, NULL);
938 				} else {
939 					/*
940 					 * IRE_REFRELE will be done in
941 					 * ip_wput_ire.
942 					 */
943 					ip_wput_ire(q, ipsec_mp, ire, NULL,
944 					    IRE_SEND, zoneid);
945 				}
946 			} else {
947 				/*
948 				 * IRE_REFRELE will be done in ip_wput_ire.
949 				 */
950 				ip_wput_ire(q, ipsec_mp, ire, NULL,
951 				    IRE_SEND, zoneid);
952 			}
953 		}
954 		/*
955 		 * Special code to support sending a single packet with
956 		 * conn_unspec_src using an IRE which has no source address.
957 		 * The IRE is deleted here after sending the packet to avoid
958 		 * having other code trip on it. But before we delete the
959 		 * ire, somebody could have looked up this ire.
960 		 * We prevent returning/using this IRE by the upper layers
961 		 * by making checks to NULL source address in other places
962 		 * like e.g ip_ire_append, ip_ire_req and ip_bind_connected.
963 		 * Though this does not completely prevent other threads
964 		 * from using this ire, this should not cause any problems.
965 		 */
966 		if (delete_ire) {
967 			ip1dbg(("ire_send: delete IRE\n"));
968 			ire_delete(ire);
969 			ire_refrele(ire);	/* Held above */
970 		}
971 	}
972 }
973 
974 /*
975  * Send a packet using the specified IRE.
976  * If ire_src_addr_v6 is all zero then discard the IRE after
977  * the packet has been sent.
978  */
979 static void
980 ire_send_v6(queue_t *q, mblk_t *pkt, ire_t *ire)
981 {
982 	mblk_t *ipsec_mp;
983 	boolean_t secure;
984 	uint_t ifindex;
985 	zoneid_t zoneid = ire->ire_zoneid;
986 	ip_stack_t	*ipst = ire->ire_ipst;
987 
988 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
989 	ASSERT(!(ire->ire_type & IRE_LOCAL)); /* Has different ire_zoneid */
990 	if (pkt->b_datap->db_type == M_CTL) {
991 		ipsec_out_t *io;
992 
993 		ipsec_mp = pkt;
994 		pkt = pkt->b_cont;
995 		secure = B_TRUE;
996 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
997 		if (io->ipsec_out_type == IPSEC_OUT)
998 			zoneid = io->ipsec_out_zoneid;
999 	} else {
1000 		ipsec_mp = pkt;
1001 		secure = B_FALSE;
1002 	}
1003 
1004 	/* If the packet originated externally then */
1005 	if (pkt->b_prev) {
1006 		ill_t	*ill;
1007 		/*
1008 		 * Extract the ifindex from b_prev (set in ip_rput_data_v6).
1009 		 * Look up interface to see if it still exists (it could have
1010 		 * been unplumbed by the time the reply came back from the
1011 		 * resolver).
1012 		 */
1013 		ifindex = (uint_t)(uintptr_t)pkt->b_prev;
1014 		ill = ill_lookup_on_ifindex(ifindex, B_TRUE,
1015 		    NULL, NULL, NULL, NULL, ipst);
1016 		if (ill == NULL) {
1017 			pkt->b_prev = NULL;
1018 			pkt->b_next = NULL;
1019 			freemsg(ipsec_mp);
1020 			ire_refrele(ire);	/* Held in ire_add */
1021 			return;
1022 		}
1023 		q = ill->ill_rq;
1024 		pkt->b_prev = NULL;
1025 		/*
1026 		 * This packet has not gone through IPSEC processing
1027 		 * and hence we should not have any IPSEC message
1028 		 * prepended.
1029 		 */
1030 		ASSERT(ipsec_mp == pkt);
1031 		put(q, pkt);
1032 		ill_refrele(ill);
1033 	} else if (pkt->b_next) {
1034 		/* Packets from multicast router */
1035 		pkt->b_next = NULL;
1036 		/*
1037 		 * We never get the IPSEC_OUT while forwarding the
1038 		 * packet for multicast router.
1039 		 */
1040 		ASSERT(ipsec_mp == pkt);
1041 		/*
1042 		 * XXX TODO IPv6.
1043 		 */
1044 		freemsg(pkt);
1045 #ifdef XXX
1046 		ip_rput_forward(ire, (ipha_t *)pkt->b_rptr, pkt, NULL);
1047 #endif
1048 	} else {
1049 		if (secure) {
1050 			ipsec_out_t *oi;
1051 			ip6_t *ip6h;
1052 
1053 			oi = (ipsec_out_t *)ipsec_mp->b_rptr;
1054 			ip6h = (ip6_t *)ipsec_mp->b_cont->b_rptr;
1055 			if (oi->ipsec_out_proc_begin) {
1056 				/*
1057 				 * This is the case where
1058 				 * ip_wput_ipsec_out could not find
1059 				 * the IRE and recreated a new one.
1060 				 */
1061 				ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h,
1062 				    NULL, NULL);
1063 			} else {
1064 				if (CONN_Q(q)) {
1065 					(void) ip_output_v6(Q_TO_CONN(q),
1066 					    ipsec_mp, q, IRE_SEND);
1067 				} else {
1068 					(void) ip_output_v6(
1069 					    (void *)(uintptr_t)zoneid,
1070 					    ipsec_mp, q, IRE_SEND);
1071 				}
1072 			}
1073 		} else {
1074 			/*
1075 			 * Send packets through ip_output_v6 so that any
1076 			 * ip6_info header can be processed again.
1077 			 */
1078 			if (CONN_Q(q)) {
1079 				(void) ip_output_v6(Q_TO_CONN(q), ipsec_mp, q,
1080 				    IRE_SEND);
1081 			} else {
1082 				(void) ip_output_v6((void *)(uintptr_t)zoneid,
1083 				    ipsec_mp, q, IRE_SEND);
1084 			}
1085 		}
1086 		/*
1087 		 * Special code to support sending a single packet with
1088 		 * conn_unspec_src using an IRE which has no source address.
1089 		 * The IRE is deleted here after sending the packet to avoid
1090 		 * having other code trip on it. But before we delete the
1091 		 * ire, somebody could have looked up this ire.
1092 		 * We prevent returning/using this IRE by the upper layers
1093 		 * by making checks to NULL source address in other places
1094 		 * like e.g ip_ire_append_v6, ip_ire_req and
1095 		 * ip_bind_connected_v6. Though, this does not completely
1096 		 * prevent other threads from using this ire, this should
1097 		 * not cause any problems.
1098 		 */
1099 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6)) {
1100 			ip1dbg(("ire_send_v6: delete IRE\n"));
1101 			ire_delete(ire);
1102 		}
1103 	}
1104 	ire_refrele(ire);	/* Held in ire_add */
1105 }
1106 
1107 /*
1108  * Make sure that IRE bucket does not get too long.
1109  * This can cause lock up because ire_cache_lookup()
1110  * may take "forever" to finish.
1111  *
1112  * We only remove a maximum of cnt IREs each time.  This
1113  * should keep the bucket length approximately constant,
1114  * depending on cnt.  This should be enough to defend
1115  * against DoS attack based on creating temporary IREs
1116  * (for forwarding and non-TCP traffic).
1117  *
1118  * We also pass in the address of the newly created IRE
1119  * as we do not want to remove this straight after adding
1120  * it. New IREs are normally added at the tail of the
1121  * bucket.  This means that we are removing the "oldest"
1122  * temporary IREs added.  Only if there are IREs with
1123  * the same ire_addr, do we not add it at the tail.  Refer
1124  * to ire_add_v*().  It should be OK for our purpose.
1125  *
1126  * For non-temporary cached IREs, we make sure that they
1127  * have not been used for some time (defined below), they
1128  * are non-local destinations, and there is no one using
1129  * them at the moment (refcnt == 1).
1130  *
1131  * The above means that the IRE bucket length may become
1132  * very long, consisting of mostly non-temporary IREs.
1133  * This can happen when the hash function does a bad job
1134  * so that most TCP connections cluster to a specific bucket.
1135  * This "hopefully" should never happen.  It can also
1136  * happen if most TCP connections have very long lives.
1137  * Even with the minimal hash table size of 256, there
1138  * has to be a lot of such connections to make the bucket
1139  * length unreasonably long.  This should probably not
1140  * happen either.  The third can when this can happen is
1141  * when the machine is under attack, such as SYN flooding.
1142  * TCP should already have the proper mechanism to protect
1143  * that.  So we should be safe.
1144  *
1145  * This function is called by ire_add_then_send() after
1146  * a new IRE is added and the packet is sent.
1147  *
1148  * The idle cutoff interval is set to 60s.  It can be
1149  * changed using /etc/system.
1150  */
1151 uint32_t ire_idle_cutoff_interval = 60000;
1152 
1153 static void
1154 ire_cache_cleanup(irb_t *irb, uint32_t threshold, ire_t *ref_ire)
1155 {
1156 	ire_t *ire;
1157 	clock_t cut_off = drv_usectohz(ire_idle_cutoff_interval * 1000);
1158 	int cnt = ip_ire_cleanup_cnt;
1159 
1160 	/*
1161 	 * Try to remove cnt temporary IREs first.
1162 	 */
1163 	for (ire = irb->irb_ire; cnt > 0 && ire != NULL; ire = ire->ire_next) {
1164 		if (ire == ref_ire)
1165 			continue;
1166 		if (ire->ire_marks & IRE_MARK_CONDEMNED)
1167 			continue;
1168 		if (ire->ire_marks & IRE_MARK_TEMPORARY) {
1169 			ASSERT(ire->ire_type == IRE_CACHE);
1170 			ire_delete(ire);
1171 			cnt--;
1172 		}
1173 	}
1174 	if (cnt == 0)
1175 		return;
1176 
1177 	/*
1178 	 * If we didn't satisfy our removal target from temporary IREs
1179 	 * we see how many non-temporary IREs are currently in the bucket.
1180 	 * If this quantity is above the threshold then we see if there are any
1181 	 * candidates for removal. We are still limited to removing a maximum
1182 	 * of cnt IREs.
1183 	 */
1184 	if ((irb->irb_ire_cnt - irb->irb_tmp_ire_cnt) > threshold) {
1185 		for (ire = irb->irb_ire; cnt > 0 && ire != NULL;
1186 		    ire = ire->ire_next) {
1187 			if (ire == ref_ire)
1188 				continue;
1189 			if (ire->ire_type != IRE_CACHE)
1190 				continue;
1191 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
1192 				continue;
1193 			if ((ire->ire_refcnt == 1) &&
1194 			    (lbolt - ire->ire_last_used_time > cut_off)) {
1195 				ire_delete(ire);
1196 				cnt--;
1197 			}
1198 		}
1199 	}
1200 }
1201 
1202 /*
1203  * ire_add_then_send is called when a new IRE has been created in order to
1204  * route an outgoing packet.  Typically, it is called from ip_wput when
1205  * a response comes back down from a resolver.  We add the IRE, and then
1206  * possibly run the packet through ip_wput or ip_rput, as appropriate.
1207  * However, we do not add the newly created IRE in the cache when
1208  * IRE_MARK_NOADD is set in the IRE. IRE_MARK_NOADD is set at
1209  * ip_newroute_ipif(). The ires with IRE_MARK_NOADD are ire_refrele'd by
1210  * ip_wput_ire() and get deleted.
1211  * Multirouting support: the packet is silently discarded when the new IRE
1212  * holds the RTF_MULTIRT flag, but is not the first IRE to be added with the
1213  * RTF_MULTIRT flag for the same destination address.
1214  * In this case, we just want to register this additional ire without
1215  * sending the packet, as it has already been replicated through
1216  * existing multirt routes in ip_wput().
1217  */
1218 void
1219 ire_add_then_send(queue_t *q, ire_t *ire, mblk_t *mp)
1220 {
1221 	irb_t *irb;
1222 	boolean_t drop = B_FALSE;
1223 	boolean_t mctl_present;
1224 	mblk_t *first_mp = NULL;
1225 	mblk_t *data_mp = NULL;
1226 	ire_t *dst_ire;
1227 	ipha_t *ipha;
1228 	ip6_t *ip6h;
1229 	ip_stack_t	*ipst = ire->ire_ipst;
1230 	int		ire_limit;
1231 
1232 	if (mp != NULL) {
1233 		/*
1234 		 * We first have to retrieve the destination address carried
1235 		 * by the packet.
1236 		 * We can't rely on ire as it can be related to a gateway.
1237 		 * The destination address will help in determining if
1238 		 * other RTF_MULTIRT ires are already registered.
1239 		 *
1240 		 * We first need to know where we are going : v4 or V6.
1241 		 * the ire version is enough, as there is no risk that
1242 		 * we resolve an IPv6 address with an IPv4 ire
1243 		 * or vice versa.
1244 		 */
1245 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1246 		data_mp = mp;
1247 		mp = first_mp;
1248 		if (ire->ire_ipversion == IPV4_VERSION) {
1249 			ipha = (ipha_t *)data_mp->b_rptr;
1250 			dst_ire = ire_cache_lookup(ipha->ipha_dst,
1251 			    ire->ire_zoneid, msg_getlabel(mp), ipst);
1252 		} else {
1253 			ASSERT(ire->ire_ipversion == IPV6_VERSION);
1254 			ip6h = (ip6_t *)data_mp->b_rptr;
1255 			dst_ire = ire_cache_lookup_v6(&ip6h->ip6_dst,
1256 			    ire->ire_zoneid, msg_getlabel(mp), ipst);
1257 		}
1258 		if (dst_ire != NULL) {
1259 			if (dst_ire->ire_flags & RTF_MULTIRT) {
1260 				/*
1261 				 * At least one resolved multirt route
1262 				 * already exists for the destination,
1263 				 * don't sent this packet: either drop it
1264 				 * or complete the pending resolution,
1265 				 * depending on the ire.
1266 				 */
1267 				drop = B_TRUE;
1268 			}
1269 			ip1dbg(("ire_add_then_send: dst_ire %p "
1270 			    "[dst %08x, gw %08x], drop %d\n",
1271 			    (void *)dst_ire,
1272 			    (dst_ire->ire_ipversion == IPV4_VERSION) ? \
1273 			    ntohl(dst_ire->ire_addr) : \
1274 			    ntohl(V4_PART_OF_V6(dst_ire->ire_addr_v6)),
1275 			    (dst_ire->ire_ipversion == IPV4_VERSION) ? \
1276 			    ntohl(dst_ire->ire_gateway_addr) : \
1277 			    ntohl(V4_PART_OF_V6(
1278 			    dst_ire->ire_gateway_addr_v6)),
1279 			    drop));
1280 			ire_refrele(dst_ire);
1281 		}
1282 	}
1283 
1284 	if (!(ire->ire_marks & IRE_MARK_NOADD)) {
1285 		/* Regular packets with cache bound ires are here. */
1286 		(void) ire_add(&ire, NULL, NULL, NULL, B_FALSE);
1287 
1288 		if (ire == NULL) {
1289 			mp->b_prev = NULL;
1290 			mp->b_next = NULL;
1291 			MULTIRT_DEBUG_UNTAG(mp);
1292 			freemsg(mp);
1293 			return;
1294 		}
1295 		if (mp == NULL) {
1296 			ire_refrele(ire);	/* Held in ire_add_v4/v6 */
1297 			return;
1298 		}
1299 	}
1300 	if (drop) {
1301 		/*
1302 		 * If we're adding an RTF_MULTIRT ire, the resolution
1303 		 * is over: we just drop the packet.
1304 		 */
1305 		if (ire->ire_flags & RTF_MULTIRT) {
1306 			data_mp->b_prev = NULL;
1307 			data_mp->b_next = NULL;
1308 			MULTIRT_DEBUG_UNTAG(mp);
1309 			freemsg(mp);
1310 		} else {
1311 			/*
1312 			 * Otherwise, we're adding the ire to a gateway
1313 			 * for a multirt route.
1314 			 * Invoke ip_newroute() to complete the resolution
1315 			 * of the route. We will then come back here and
1316 			 * finally drop this packet in the above code.
1317 			 */
1318 			if (ire->ire_ipversion == IPV4_VERSION) {
1319 				/*
1320 				 * TODO: in order for CGTP to work in non-global
1321 				 * zones, ip_newroute() must create the IRE
1322 				 * cache in the zone indicated by
1323 				 * ire->ire_zoneid.
1324 				 */
1325 				ip_newroute(q, mp, ipha->ipha_dst,
1326 				    (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
1327 				    ire->ire_zoneid, ipst);
1328 			} else {
1329 				int minlen = sizeof (ip6i_t) + IPV6_HDR_LEN;
1330 
1331 				ASSERT(ire->ire_ipversion == IPV6_VERSION);
1332 
1333 				/*
1334 				 * If necessary, skip over the ip6i_t to find
1335 				 * the header with the actual source address.
1336 				 */
1337 				if (ip6h->ip6_nxt == IPPROTO_RAW) {
1338 					if (MBLKL(data_mp) < minlen &&
1339 					    pullupmsg(data_mp, -1) == 0) {
1340 						ip1dbg(("ire_add_then_send: "
1341 						    "cannot pullupmsg ip6i\n"));
1342 						if (mctl_present)
1343 							freeb(first_mp);
1344 						ire_refrele(ire);
1345 						return;
1346 					}
1347 					ASSERT(MBLKL(data_mp) >= IPV6_HDR_LEN);
1348 					ip6h = (ip6_t *)(data_mp->b_rptr +
1349 					    sizeof (ip6i_t));
1350 				}
1351 				ip_newroute_v6(q, mp, &ip6h->ip6_dst,
1352 				    &ip6h->ip6_src, NULL, ire->ire_zoneid,
1353 				    ipst);
1354 			}
1355 		}
1356 
1357 		ire_refrele(ire); /* As done by ire_send(). */
1358 		return;
1359 	}
1360 	/*
1361 	 * Need to remember ire_bucket here as ire_send*() may delete
1362 	 * the ire so we cannot reference it after that.
1363 	 */
1364 	irb = ire->ire_bucket;
1365 	if (ire->ire_ipversion == IPV4_VERSION) {
1366 		ire_send(q, mp, ire);
1367 		ire_limit = ip_ire_max_bucket_cnt;
1368 	} else {
1369 		ire_send_v6(q, mp, ire);
1370 		ire_limit = ip6_ire_max_bucket_cnt;
1371 	}
1372 
1373 	/*
1374 	 * irb is NULL if the IRE was not added to the hash. This happens
1375 	 * when IRE_MARK_NOADD is set and when IREs are returned from
1376 	 * ire_update_srcif_v4().
1377 	 */
1378 	if (irb != NULL) {
1379 		IRB_REFHOLD(irb);
1380 		if (irb->irb_ire_cnt > ire_limit)
1381 			ire_cache_cleanup(irb, ire_limit, ire);
1382 		IRB_REFRELE(irb);
1383 	}
1384 }
1385 
1386 /*
1387  * Initialize the ire that is specific to IPv4 part and call
1388  * ire_init_common to finish it.
1389  */
1390 ire_t *
1391 ire_init(ire_t *ire, uchar_t *addr, uchar_t *mask, uchar_t *src_addr,
1392     uchar_t *gateway, uint_t *max_fragp, nce_t *src_nce, queue_t *rfq,
1393     queue_t *stq, ushort_t type, ipif_t *ipif, ipaddr_t cmask, uint32_t phandle,
1394     uint32_t ihandle, uint32_t flags, const iulp_t *ulp_info, tsol_gc_t *gc,
1395     tsol_gcgrp_t *gcgrp, ip_stack_t *ipst)
1396 {
1397 	ASSERT(type != IRE_CACHE || stq != NULL);
1398 	/*
1399 	 * Reject IRE security attribute creation/initialization
1400 	 * if system is not running in Trusted mode.
1401 	 */
1402 	if ((gc != NULL || gcgrp != NULL) && !is_system_labeled())
1403 		return (NULL);
1404 
1405 	BUMP_IRE_STATS(ipst->ips_ire_stats_v4, ire_stats_alloced);
1406 
1407 	if (addr != NULL)
1408 		bcopy(addr, &ire->ire_addr, IP_ADDR_LEN);
1409 	if (src_addr != NULL)
1410 		bcopy(src_addr, &ire->ire_src_addr, IP_ADDR_LEN);
1411 	if (mask != NULL) {
1412 		bcopy(mask, &ire->ire_mask, IP_ADDR_LEN);
1413 		ire->ire_masklen = ip_mask_to_plen(ire->ire_mask);
1414 	}
1415 	if (gateway != NULL) {
1416 		bcopy(gateway, &ire->ire_gateway_addr, IP_ADDR_LEN);
1417 	}
1418 
1419 	if (type == IRE_CACHE)
1420 		ire->ire_cmask = cmask;
1421 
1422 	/* ire_init_common will free the mblks upon encountering any failure */
1423 	if (!ire_init_common(ire, max_fragp, src_nce, rfq, stq, type, ipif,
1424 	    phandle, ihandle, flags, IPV4_VERSION, ulp_info, gc, gcgrp, ipst))
1425 		return (NULL);
1426 
1427 	return (ire);
1428 }
1429 
1430 /*
1431  * Similar to ire_create except that it is called only when
1432  * we want to allocate ire as an mblk e.g. we have an external
1433  * resolver ARP.
1434  */
1435 ire_t *
1436 ire_create_mp(uchar_t *addr, uchar_t *mask, uchar_t *src_addr, uchar_t *gateway,
1437     uint_t max_frag, nce_t *src_nce, queue_t *rfq, queue_t *stq, ushort_t type,
1438     ipif_t *ipif, ipaddr_t cmask, uint32_t phandle, uint32_t ihandle,
1439     uint32_t flags, const iulp_t *ulp_info, tsol_gc_t *gc, tsol_gcgrp_t *gcgrp,
1440     ip_stack_t *ipst)
1441 {
1442 	ire_t	*ire, *buf;
1443 	ire_t	*ret_ire;
1444 	mblk_t	*mp;
1445 	size_t	bufsize;
1446 	frtn_t	*frtnp;
1447 	ill_t	*ill;
1448 
1449 	bufsize = sizeof (ire_t) + sizeof (frtn_t);
1450 	buf = kmem_alloc(bufsize, KM_NOSLEEP);
1451 	if (buf == NULL) {
1452 		ip1dbg(("ire_create_mp: alloc failed\n"));
1453 		return (NULL);
1454 	}
1455 	frtnp = (frtn_t *)(buf + 1);
1456 	frtnp->free_arg = (caddr_t)buf;
1457 	frtnp->free_func = ire_freemblk;
1458 
1459 	/*
1460 	 * Allocate the new IRE. The ire created will hold a ref on
1461 	 * an nce_t after ire_nce_init, and this ref must either be
1462 	 * (a)  transferred to the ire_cache entry created when ire_add_v4
1463 	 *	is called after successful arp resolution, or,
1464 	 * (b)  released, when arp resolution fails
1465 	 * Case (b) is handled in ire_freemblk() which will be called
1466 	 * when mp is freed as a result of failed arp.
1467 	 */
1468 	mp = esballoc((unsigned char *)buf, bufsize, BPRI_MED, frtnp);
1469 	if (mp == NULL) {
1470 		ip1dbg(("ire_create_mp: alloc failed\n"));
1471 		kmem_free(buf, bufsize);
1472 		return (NULL);
1473 	}
1474 	ire = (ire_t *)mp->b_rptr;
1475 	mp->b_wptr = (uchar_t *)&ire[1];
1476 
1477 	/* Start clean. */
1478 	*ire = ire_null;
1479 	ire->ire_mp = mp;
1480 	mp->b_datap->db_type = IRE_DB_TYPE;
1481 	ire->ire_marks |= IRE_MARK_UNCACHED;
1482 
1483 	ret_ire = ire_init(ire, addr, mask, src_addr, gateway, NULL, src_nce,
1484 	    rfq, stq, type, ipif, cmask, phandle, ihandle, flags, ulp_info, gc,
1485 	    gcgrp, ipst);
1486 
1487 	ill = (ill_t *)(stq->q_ptr);
1488 	if (ret_ire == NULL) {
1489 		/* ire_freemblk needs these set */
1490 		ire->ire_stq_ifindex = ill->ill_phyint->phyint_ifindex;
1491 		ire->ire_stackid = ipst->ips_netstack->netstack_stackid;
1492 		ire->ire_ipst = ipst;
1493 		freeb(ire->ire_mp);
1494 		return (NULL);
1495 	}
1496 	ret_ire->ire_stq_ifindex = ill->ill_phyint->phyint_ifindex;
1497 	ret_ire->ire_stackid = ipst->ips_netstack->netstack_stackid;
1498 	ASSERT(ret_ire == ire);
1499 	ASSERT(ret_ire->ire_ipst == ipst);
1500 	/*
1501 	 * ire_max_frag is normally zero here and is atomically set
1502 	 * under the irebucket lock in ire_add_v[46] except for the
1503 	 * case of IRE_MARK_NOADD. In that event the the ire_max_frag
1504 	 * is non-zero here.
1505 	 */
1506 	ire->ire_max_frag = max_frag;
1507 	return (ire);
1508 }
1509 
1510 /*
1511  * ire_create is called to allocate and initialize a new IRE.
1512  *
1513  * NOTE : This is called as writer sometimes though not required
1514  * by this function.
1515  */
1516 ire_t *
1517 ire_create(uchar_t *addr, uchar_t *mask, uchar_t *src_addr, uchar_t *gateway,
1518     uint_t *max_fragp, nce_t *src_nce, queue_t *rfq, queue_t *stq,
1519     ushort_t type, ipif_t *ipif, ipaddr_t cmask, uint32_t phandle,
1520     uint32_t ihandle, uint32_t flags, const iulp_t *ulp_info, tsol_gc_t *gc,
1521     tsol_gcgrp_t *gcgrp, ip_stack_t *ipst)
1522 {
1523 	ire_t	*ire;
1524 	ire_t	*ret_ire;
1525 
1526 	ire = kmem_cache_alloc(ire_cache, KM_NOSLEEP);
1527 	if (ire == NULL) {
1528 		ip1dbg(("ire_create: alloc failed\n"));
1529 		return (NULL);
1530 	}
1531 	*ire = ire_null;
1532 
1533 	ret_ire = ire_init(ire, addr, mask, src_addr, gateway, max_fragp,
1534 	    src_nce, rfq, stq, type, ipif, cmask, phandle, ihandle, flags,
1535 	    ulp_info, gc, gcgrp, ipst);
1536 
1537 	if (ret_ire == NULL) {
1538 		kmem_cache_free(ire_cache, ire);
1539 		return (NULL);
1540 	}
1541 	ASSERT(ret_ire == ire);
1542 	return (ire);
1543 }
1544 
1545 /*
1546  * Common to IPv4 and IPv6
1547  */
1548 boolean_t
1549 ire_init_common(ire_t *ire, uint_t *max_fragp, nce_t *src_nce, queue_t *rfq,
1550     queue_t *stq, ushort_t type, ipif_t *ipif, uint32_t phandle,
1551     uint32_t ihandle, uint32_t flags, uchar_t ipversion, const iulp_t *ulp_info,
1552     tsol_gc_t *gc, tsol_gcgrp_t *gcgrp, ip_stack_t *ipst)
1553 {
1554 	ire->ire_max_fragp = max_fragp;
1555 	ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ? IPH_DF : 0;
1556 
1557 #ifdef DEBUG
1558 	if (ipif != NULL) {
1559 		if (ipif->ipif_isv6)
1560 			ASSERT(ipversion == IPV6_VERSION);
1561 		else
1562 			ASSERT(ipversion == IPV4_VERSION);
1563 	}
1564 #endif /* DEBUG */
1565 
1566 	/*
1567 	 * Create/initialize IRE security attribute only in Trusted mode;
1568 	 * if the passed in gc/gcgrp is non-NULL, we expect that the caller
1569 	 * has held a reference to it and will release it when this routine
1570 	 * returns a failure, otherwise we own the reference.  We do this
1571 	 * prior to initializing the rest IRE fields.
1572 	 *
1573 	 * Don't allocate ire_gw_secattr for the resolver case to prevent
1574 	 * memory leak (in case of external resolution failure). We'll
1575 	 * allocate it after a successful external resolution, in ire_add().
1576 	 * Note that ire->ire_mp != NULL here means this ire is headed
1577 	 * to an external resolver.
1578 	 */
1579 	if (is_system_labeled()) {
1580 		if ((type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST |
1581 		    IRE_INTERFACE)) != 0) {
1582 			/* release references on behalf of caller */
1583 			if (gc != NULL)
1584 				GC_REFRELE(gc);
1585 			if (gcgrp != NULL)
1586 				GCGRP_REFRELE(gcgrp);
1587 		} else if ((ire->ire_mp == NULL) &&
1588 		    tsol_ire_init_gwattr(ire, ipversion, gc, gcgrp) != 0) {
1589 			return (B_FALSE);
1590 		}
1591 	}
1592 
1593 	ire->ire_stq = stq;
1594 	ire->ire_rfq = rfq;
1595 	ire->ire_type = type;
1596 	ire->ire_flags = RTF_UP | flags;
1597 	ire->ire_ident = TICK_TO_MSEC(lbolt);
1598 	bcopy(ulp_info, &ire->ire_uinfo, sizeof (iulp_t));
1599 
1600 	ire->ire_tire_mark = ire->ire_ob_pkt_count + ire->ire_ib_pkt_count;
1601 	ire->ire_last_used_time = lbolt;
1602 	ire->ire_create_time = (uint32_t)gethrestime_sec();
1603 
1604 	/*
1605 	 * If this IRE is an IRE_CACHE, inherit the handles from the
1606 	 * parent IREs. For others in the forwarding table, assign appropriate
1607 	 * new ones.
1608 	 *
1609 	 * The mutex protecting ire_handle is because ire_create is not always
1610 	 * called as a writer.
1611 	 */
1612 	if (ire->ire_type & IRE_OFFSUBNET) {
1613 		mutex_enter(&ipst->ips_ire_handle_lock);
1614 		ire->ire_phandle = (uint32_t)ipst->ips_ire_handle++;
1615 		mutex_exit(&ipst->ips_ire_handle_lock);
1616 	} else if (ire->ire_type & IRE_INTERFACE) {
1617 		mutex_enter(&ipst->ips_ire_handle_lock);
1618 		ire->ire_ihandle = (uint32_t)ipst->ips_ire_handle++;
1619 		mutex_exit(&ipst->ips_ire_handle_lock);
1620 	} else if (ire->ire_type == IRE_CACHE) {
1621 		ire->ire_phandle = phandle;
1622 		ire->ire_ihandle = ihandle;
1623 	}
1624 	ire->ire_ipif = ipif;
1625 	if (ipif != NULL) {
1626 		ire->ire_ipif_seqid = ipif->ipif_seqid;
1627 		ire->ire_ipif_ifindex =
1628 		    ipif->ipif_ill->ill_phyint->phyint_ifindex;
1629 		ire->ire_zoneid = ipif->ipif_zoneid;
1630 	} else {
1631 		ire->ire_zoneid = GLOBAL_ZONEID;
1632 	}
1633 	ire->ire_ipversion = ipversion;
1634 	mutex_init(&ire->ire_lock, NULL, MUTEX_DEFAULT, NULL);
1635 	if (ipversion == IPV4_VERSION) {
1636 		/*
1637 		 * IPv6 initializes the ire_nce in ire_add_v6, which expects
1638 		 * to find the ire_nce to be null when it is called.
1639 		 */
1640 		if (ire_nce_init(ire, src_nce) != 0) {
1641 			/* some failure occurred. propagate error back */
1642 			return (B_FALSE);
1643 		}
1644 	}
1645 	ire->ire_refcnt = 1;
1646 	ire->ire_ipst = ipst;	/* No netstack_hold */
1647 	ire->ire_trace_disable = B_FALSE;
1648 
1649 	return (B_TRUE);
1650 }
1651 
1652 /*
1653  * This routine is called repeatedly by ipif_up to create broadcast IREs.
1654  * It is passed a pointer to a slot in an IRE pointer array into which to
1655  * place the pointer to the new IRE, if indeed we create one.  If the
1656  * IRE corresponding to the address passed in would be a duplicate of an
1657  * existing one, we don't create the new one.  irep is incremented before
1658  * return only if we do create a new IRE.  (Always called as writer.)
1659  *
1660  * Note that with the "match_flags" parameter, we can match on either
1661  * a particular logical interface (MATCH_IRE_IPIF) or for all logical
1662  * interfaces for a given physical interface (MATCH_IRE_ILL).  Currently,
1663  * we only create broadcast ire's on a per physical interface basis. If
1664  * someone is going to be mucking with logical interfaces, it is important
1665  * to call "ipif_check_bcast_ires()" to make sure that any change to a
1666  * logical interface will not cause critical broadcast IRE's to be deleted.
1667  */
1668 ire_t **
1669 ire_check_and_create_bcast(ipif_t *ipif, ipaddr_t  addr, ire_t **irep,
1670     int match_flags)
1671 {
1672 	ire_t *ire;
1673 	uint64_t check_flags = IPIF_DEPRECATED | IPIF_NOLOCAL | IPIF_ANYCAST;
1674 	boolean_t prefer;
1675 	ill_t *ill = ipif->ipif_ill;
1676 	ip_stack_t *ipst = ill->ill_ipst;
1677 
1678 	/*
1679 	 * No broadcast IREs for the LOOPBACK interface
1680 	 * or others such as point to point and IPIF_NOXMIT.
1681 	 */
1682 	if (!(ipif->ipif_flags & IPIF_BROADCAST) ||
1683 	    (ipif->ipif_flags & IPIF_NOXMIT))
1684 		return (irep);
1685 
1686 	/*
1687 	 * If this new IRE would be a duplicate, only prefer it if one of
1688 	 * the following is true:
1689 	 *
1690 	 * 1. The existing one has IPIF_DEPRECATED|IPIF_LOCAL|IPIF_ANYCAST
1691 	 *    set and the new one has all of those clear.
1692 	 *
1693 	 * 2. The existing one corresponds to an underlying ILL in an IPMP
1694 	 *    group and the new one corresponds to an IPMP group interface.
1695 	 */
1696 	if ((ire = ire_ctable_lookup(addr, 0, IRE_BROADCAST, ipif,
1697 	    ipif->ipif_zoneid, NULL, match_flags, ipst)) != NULL) {
1698 		prefer = ((ire->ire_ipif->ipif_flags & check_flags) &&
1699 		    !(ipif->ipif_flags & check_flags)) ||
1700 		    (IS_UNDER_IPMP(ire->ire_ipif->ipif_ill) && IS_IPMP(ill));
1701 		if (!prefer) {
1702 			ire_refrele(ire);
1703 			return (irep);
1704 		}
1705 
1706 		/*
1707 		 * Bcast ires exist in pairs. Both have to be deleted,
1708 		 * Since we are exclusive we can make the above assertion.
1709 		 * The 1st has to be refrele'd since it was ctable_lookup'd.
1710 		 */
1711 		ASSERT(IAM_WRITER_IPIF(ipif));
1712 		ASSERT(ire->ire_next->ire_addr == ire->ire_addr);
1713 		ire_delete(ire->ire_next);
1714 		ire_delete(ire);
1715 		ire_refrele(ire);
1716 	}
1717 	return (ire_create_bcast(ipif, addr, irep));
1718 }
1719 
1720 uint_t ip_loopback_mtu = IP_LOOPBACK_MTU;
1721 
1722 /*
1723  * This routine is called from ipif_check_bcast_ires and ire_check_bcast.
1724  * It leaves all the verifying and deleting to those routines. So it always
1725  * creates 2 bcast ires and chains them into the ire array passed in.
1726  */
1727 ire_t **
1728 ire_create_bcast(ipif_t *ipif, ipaddr_t  addr, ire_t **irep)
1729 {
1730 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
1731 	ill_t		*ill = ipif->ipif_ill;
1732 
1733 	ASSERT(IAM_WRITER_IPIF(ipif));
1734 
1735 	if (IS_IPMP(ill)) {
1736 		/*
1737 		 * Broadcast IREs for the IPMP meta-interface use the
1738 		 * nominated broadcast interface to send and receive packets.
1739 		 * If there's no nominated interface, send the packets down to
1740 		 * the IPMP stub driver, which will discard them.  If the
1741 		 * nominated broadcast interface changes, ill_refresh_bcast()
1742 		 * will refresh the broadcast IREs.
1743 		 */
1744 		if ((ill = ipmp_illgrp_cast_ill(ill->ill_grp)) == NULL)
1745 			ill = ipif->ipif_ill;
1746 	}
1747 
1748 	*irep++ = ire_create(
1749 	    (uchar_t *)&addr,			/* dest addr */
1750 	    (uchar_t *)&ip_g_all_ones,		/* mask */
1751 	    (uchar_t *)&ipif->ipif_src_addr,	/* source addr */
1752 	    NULL,				/* no gateway */
1753 	    &ipif->ipif_mtu,			/* max frag */
1754 	    NULL,				/* no src nce */
1755 	    ill->ill_rq,			/* recv-from queue */
1756 	    ill->ill_wq,			/* send-to queue */
1757 	    IRE_BROADCAST,
1758 	    ipif,
1759 	    0,
1760 	    0,
1761 	    0,
1762 	    0,
1763 	    &ire_uinfo_null,
1764 	    NULL,
1765 	    NULL,
1766 	    ipst);
1767 
1768 	*irep++ = ire_create(
1769 	    (uchar_t *)&addr,			/* dest address */
1770 	    (uchar_t *)&ip_g_all_ones,		/* mask */
1771 	    (uchar_t *)&ipif->ipif_src_addr,	/* source address */
1772 	    NULL,				/* no gateway */
1773 	    &ip_loopback_mtu,			/* max frag size */
1774 	    NULL,				/* no src_nce */
1775 	    ill->ill_rq,			/* recv-from queue */
1776 	    NULL,				/* no send-to queue */
1777 	    IRE_BROADCAST,			/* Needed for fanout in wput */
1778 	    ipif,
1779 	    0,
1780 	    0,
1781 	    0,
1782 	    0,
1783 	    &ire_uinfo_null,
1784 	    NULL,
1785 	    NULL,
1786 	    ipst);
1787 
1788 	return (irep);
1789 }
1790 
1791 /*
1792  * ire_walk routine to delete or update any IRE_CACHE that might contain
1793  * stale information.
1794  * The flags state which entries to delete or update.
1795  * Garbage collection is done separately using kmem alloc callbacks to
1796  * ip_trash_ire_reclaim.
1797  * Used for both IPv4 and IPv6. However, IPv6 only uses FLUSH_MTU_TIME
1798  * since other stale information is cleaned up using NUD.
1799  */
1800 void
1801 ire_expire(ire_t *ire, char *arg)
1802 {
1803 	ire_expire_arg_t	*ieap = (ire_expire_arg_t *)(uintptr_t)arg;
1804 	ill_t			*stq_ill;
1805 	int			flush_flags = ieap->iea_flush_flag;
1806 	ip_stack_t		*ipst = ieap->iea_ipst;
1807 
1808 	if ((flush_flags & FLUSH_REDIRECT_TIME) &&
1809 	    (ire->ire_flags & RTF_DYNAMIC)) {
1810 		/* Make sure we delete the corresponding IRE_CACHE */
1811 		ip1dbg(("ire_expire: all redirects\n"));
1812 		ip_rts_rtmsg(RTM_DELETE, ire, 0, ipst);
1813 		ire_delete(ire);
1814 		atomic_dec_32(&ipst->ips_ip_redirect_cnt);
1815 		return;
1816 	}
1817 	if (ire->ire_type != IRE_CACHE)
1818 		return;
1819 
1820 	if (flush_flags & FLUSH_ARP_TIME) {
1821 		/*
1822 		 * Remove all IRE_CACHE except IPv4 multicast ires. These
1823 		 * ires will be deleted by ip_trash_ire_reclaim_stack()
1824 		 * when system runs low in memory.
1825 		 * Verify that create time is more than ip_ire_arp_interval
1826 		 * milliseconds ago.
1827 		 */
1828 
1829 		if (!(ire->ire_ipversion == IPV4_VERSION &&
1830 		    CLASSD(ire->ire_addr)) && NCE_EXPIRED(ire->ire_nce, ipst)) {
1831 			ire_delete(ire);
1832 			return;
1833 		}
1834 	}
1835 
1836 	if (ipst->ips_ip_path_mtu_discovery && (flush_flags & FLUSH_MTU_TIME) &&
1837 	    (ire->ire_ipif != NULL)) {
1838 		/* Increase pmtu if it is less than the interface mtu */
1839 		mutex_enter(&ire->ire_lock);
1840 		/*
1841 		 * If the ipif is a vni (whose mtu is 0, since it's virtual)
1842 		 * get the mtu from the sending interfaces' ipif
1843 		 */
1844 		if (IS_VNI(ire->ire_ipif->ipif_ill)) {
1845 			stq_ill = ire->ire_stq->q_ptr;
1846 			ire->ire_max_frag = MIN(stq_ill->ill_ipif->ipif_mtu,
1847 			    IP_MAXPACKET);
1848 		} else {
1849 			ire->ire_max_frag = MIN(ire->ire_ipif->ipif_mtu,
1850 			    IP_MAXPACKET);
1851 		}
1852 		ire->ire_marks &= ~IRE_MARK_PMTU;
1853 		ire->ire_frag_flag |= IPH_DF;
1854 		mutex_exit(&ire->ire_lock);
1855 	}
1856 }
1857 
1858 /*
1859  * Return any local address.  We use this to target ourselves
1860  * when the src address was specified as 'default'.
1861  * Preference for IRE_LOCAL entries.
1862  */
1863 ire_t *
1864 ire_lookup_local(zoneid_t zoneid, ip_stack_t *ipst)
1865 {
1866 	ire_t	*ire;
1867 	irb_t	*irb;
1868 	ire_t	*maybe = NULL;
1869 	int i;
1870 
1871 	for (i = 0; i < ipst->ips_ip_cache_table_size;  i++) {
1872 		irb = &ipst->ips_ip_cache_table[i];
1873 		if (irb->irb_ire == NULL)
1874 			continue;
1875 		rw_enter(&irb->irb_lock, RW_READER);
1876 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
1877 			if ((ire->ire_marks & IRE_MARK_CONDEMNED) ||
1878 			    (ire->ire_zoneid != zoneid &&
1879 			    ire->ire_zoneid != ALL_ZONES))
1880 				continue;
1881 			switch (ire->ire_type) {
1882 			case IRE_LOOPBACK:
1883 				if (maybe == NULL) {
1884 					IRE_REFHOLD(ire);
1885 					maybe = ire;
1886 				}
1887 				break;
1888 			case IRE_LOCAL:
1889 				if (maybe != NULL) {
1890 					ire_refrele(maybe);
1891 				}
1892 				IRE_REFHOLD(ire);
1893 				rw_exit(&irb->irb_lock);
1894 				return (ire);
1895 			}
1896 		}
1897 		rw_exit(&irb->irb_lock);
1898 	}
1899 	return (maybe);
1900 }
1901 
1902 /*
1903  * If the specified IRE is associated with a particular ILL, return
1904  * that ILL pointer (May be called as writer.).
1905  *
1906  * NOTE : This is not a generic function that can be used always.
1907  * This function always returns the ill of the outgoing packets
1908  * if this ire is used.
1909  */
1910 ill_t *
1911 ire_to_ill(const ire_t *ire)
1912 {
1913 	ill_t *ill = NULL;
1914 
1915 	/*
1916 	 * 1) For an IRE_CACHE, ire_ipif is the one where it obtained
1917 	 *    the source address from. ire_stq is the one where the
1918 	 *    packets will be sent out on. We return that here.
1919 	 *
1920 	 * 2) IRE_BROADCAST normally has a loopback and a non-loopback
1921 	 *    copy and they always exist next to each other with loopback
1922 	 *    copy being the first one. If we are called on the non-loopback
1923 	 *    copy, return the one pointed by ire_stq. If it was called on
1924 	 *    a loopback copy, we still return the one pointed by the next
1925 	 *    ire's ire_stq pointer i.e the one pointed by the non-loopback
1926 	 *    copy. We don't want use ire_ipif as it might represent the
1927 	 *    source address (if we borrow source addresses for
1928 	 *    IRE_BROADCASTS in the future).
1929 	 *    However if an interface is currently coming up, the above
1930 	 *    condition may not hold during that period since the ires
1931 	 *    are added one at a time. Thus one of the pair could have been
1932 	 *    added and the other not yet added.
1933 	 * 3) For many other IREs (e.g., IRE_LOCAL), ire_rfq indicates the ill.
1934 	 * 4) For all others return the ones pointed by ire_ipif->ipif_ill.
1935 	 *    That handles IRE_LOOPBACK.
1936 	 */
1937 
1938 	if (ire->ire_type == IRE_CACHE) {
1939 		ill = (ill_t *)ire->ire_stq->q_ptr;
1940 	} else if (ire->ire_type == IRE_BROADCAST) {
1941 		if (ire->ire_stq != NULL) {
1942 			ill = (ill_t *)ire->ire_stq->q_ptr;
1943 		} else {
1944 			ire_t  *ire_next;
1945 
1946 			ire_next = ire->ire_next;
1947 			if (ire_next != NULL &&
1948 			    ire_next->ire_type == IRE_BROADCAST &&
1949 			    ire_next->ire_addr == ire->ire_addr &&
1950 			    ire_next->ire_ipif == ire->ire_ipif) {
1951 				ill = (ill_t *)ire_next->ire_stq->q_ptr;
1952 			}
1953 		}
1954 	} else if (ire->ire_rfq != NULL) {
1955 		ill = ire->ire_rfq->q_ptr;
1956 	} else if (ire->ire_ipif != NULL) {
1957 		ill = ire->ire_ipif->ipif_ill;
1958 	}
1959 	return (ill);
1960 }
1961 
1962 /* Arrange to call the specified function for every IRE in the world. */
1963 void
1964 ire_walk(pfv_t func, void *arg, ip_stack_t *ipst)
1965 {
1966 	ire_walk_ipvers(func, arg, 0, ALL_ZONES, ipst);
1967 }
1968 
1969 void
1970 ire_walk_v4(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
1971 {
1972 	ire_walk_ipvers(func, arg, IPV4_VERSION, zoneid, ipst);
1973 }
1974 
1975 void
1976 ire_walk_v6(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
1977 {
1978 	ire_walk_ipvers(func, arg, IPV6_VERSION, zoneid, ipst);
1979 }
1980 
1981 /*
1982  * Walk a particular version. version == 0 means both v4 and v6.
1983  */
1984 static void
1985 ire_walk_ipvers(pfv_t func, void *arg, uchar_t vers, zoneid_t zoneid,
1986     ip_stack_t *ipst)
1987 {
1988 	if (vers != IPV6_VERSION) {
1989 		/*
1990 		 * ip_forwarding_table variable doesn't matter for IPv4 since
1991 		 * ire_walk_ill_tables uses ips_ip_ftable for IPv4.
1992 		 */
1993 		ire_walk_ill_tables(0, 0, func, arg, IP_MASK_TABLE_SIZE,
1994 		    0, NULL,
1995 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
1996 		    NULL, zoneid, ipst);
1997 	}
1998 	if (vers != IPV4_VERSION) {
1999 		ire_walk_ill_tables(0, 0, func, arg, IP6_MASK_TABLE_SIZE,
2000 		    ipst->ips_ip6_ftable_hash_size,
2001 		    ipst->ips_ip_forwarding_table_v6,
2002 		    ipst->ips_ip6_cache_table_size,
2003 		    ipst->ips_ip_cache_table_v6, NULL, zoneid, ipst);
2004 	}
2005 }
2006 
2007 /*
2008  * Arrange to call the specified function for every IRE that matches the ill.
2009  */
2010 void
2011 ire_walk_ill(uint_t match_flags, uint_t ire_type, pfv_t func, void *arg,
2012     ill_t *ill)
2013 {
2014 	uchar_t vers = (ill->ill_isv6 ? IPV6_VERSION : IPV4_VERSION);
2015 
2016 	ire_walk_ill_ipvers(match_flags, ire_type, func, arg, vers, ill);
2017 }
2018 
2019 void
2020 ire_walk_ill_v4(uint_t match_flags, uint_t ire_type, pfv_t func, void *arg,
2021     ill_t *ill)
2022 {
2023 	ire_walk_ill_ipvers(match_flags, ire_type, func, arg, IPV4_VERSION,
2024 	    ill);
2025 }
2026 
2027 void
2028 ire_walk_ill_v6(uint_t match_flags, uint_t ire_type, pfv_t func, void *arg,
2029     ill_t *ill)
2030 {
2031 	ire_walk_ill_ipvers(match_flags, ire_type, func, arg, IPV6_VERSION,
2032 	    ill);
2033 }
2034 
2035 /*
2036  * Walk a particular ill and version.
2037  */
2038 static void
2039 ire_walk_ill_ipvers(uint_t match_flags, uint_t ire_type, pfv_t func,
2040     void *arg, uchar_t vers, ill_t *ill)
2041 {
2042 	ip_stack_t	*ipst = ill->ill_ipst;
2043 
2044 	if (vers == IPV4_VERSION) {
2045 		ire_walk_ill_tables(match_flags, ire_type, func, arg,
2046 		    IP_MASK_TABLE_SIZE, 0,
2047 		    NULL, ipst->ips_ip_cache_table_size,
2048 		    ipst->ips_ip_cache_table, ill, ALL_ZONES, ipst);
2049 	} else if (vers == IPV6_VERSION) {
2050 		ire_walk_ill_tables(match_flags, ire_type, func, arg,
2051 		    IP6_MASK_TABLE_SIZE, ipst->ips_ip6_ftable_hash_size,
2052 		    ipst->ips_ip_forwarding_table_v6,
2053 		    ipst->ips_ip6_cache_table_size,
2054 		    ipst->ips_ip_cache_table_v6, ill, ALL_ZONES, ipst);
2055 	}
2056 }
2057 
2058 boolean_t
2059 ire_walk_ill_match(uint_t match_flags, uint_t ire_type, ire_t *ire,
2060     ill_t *ill, zoneid_t zoneid, ip_stack_t *ipst)
2061 {
2062 	ill_t *ire_stq_ill = NULL;
2063 	ill_t *ire_ipif_ill = NULL;
2064 
2065 	ASSERT(match_flags != 0 || zoneid != ALL_ZONES);
2066 	/*
2067 	 * MATCH_IRE_ILL: We match both on ill pointed by ire_stq and
2068 	 *    ire_ipif.  Only in the case of IRE_CACHEs can ire_stq and
2069 	 *    ire_ipif be pointing to different ills. But we want to keep
2070 	 *    this function generic enough for future use. So, we always
2071 	 *    try to match on both.  The only caller of this function
2072 	 *    ire_walk_ill_tables, will call "func" after we return from
2073 	 *    this function. We expect "func" to do the right filtering
2074 	 *    of ires in this case.
2075 	 */
2076 	if (match_flags & MATCH_IRE_ILL) {
2077 		if (ire->ire_stq != NULL)
2078 			ire_stq_ill = ire->ire_stq->q_ptr;
2079 		if (ire->ire_ipif != NULL)
2080 			ire_ipif_ill = ire->ire_ipif->ipif_ill;
2081 	}
2082 
2083 	if (zoneid != ALL_ZONES) {
2084 		/*
2085 		 * We're walking the IREs for a specific zone. The only relevant
2086 		 * IREs are:
2087 		 * - all IREs with a matching ire_zoneid
2088 		 * - all IRE_OFFSUBNETs as they're shared across all zones
2089 		 * - IRE_INTERFACE IREs for interfaces with a usable source addr
2090 		 *   with a matching zone
2091 		 * - IRE_DEFAULTs with a gateway reachable from the zone
2092 		 * We should really match on IRE_OFFSUBNETs and IRE_DEFAULTs
2093 		 * using the same rule; but the above rules are consistent with
2094 		 * the behavior of ire_ftable_lookup[_v6]() so that all the
2095 		 * routes that can be matched during lookup are also matched
2096 		 * here.
2097 		 */
2098 		if (zoneid != ire->ire_zoneid && ire->ire_zoneid != ALL_ZONES) {
2099 			/*
2100 			 * Note, IRE_INTERFACE can have the stq as NULL. For
2101 			 * example, if the default multicast route is tied to
2102 			 * the loopback address.
2103 			 */
2104 			if ((ire->ire_type & IRE_INTERFACE) &&
2105 			    (ire->ire_stq != NULL)) {
2106 				ire_stq_ill = (ill_t *)ire->ire_stq->q_ptr;
2107 				if (ire->ire_ipversion == IPV4_VERSION) {
2108 					if (!ipif_usesrc_avail(ire_stq_ill,
2109 					    zoneid))
2110 						/* No usable src addr in zone */
2111 						return (B_FALSE);
2112 				} else if (ire_stq_ill->ill_usesrc_ifindex
2113 				    != 0) {
2114 					/*
2115 					 * For IPv6 use ipif_select_source_v6()
2116 					 * so the right scope selection is done
2117 					 */
2118 					ipif_t *src_ipif;
2119 					src_ipif =
2120 					    ipif_select_source_v6(ire_stq_ill,
2121 					    &ire->ire_addr_v6, B_FALSE,
2122 					    IPV6_PREFER_SRC_DEFAULT,
2123 					    zoneid);
2124 					if (src_ipif != NULL) {
2125 						ipif_refrele(src_ipif);
2126 					} else {
2127 						return (B_FALSE);
2128 					}
2129 				} else {
2130 					return (B_FALSE);
2131 				}
2132 
2133 			} else if (!(ire->ire_type & IRE_OFFSUBNET)) {
2134 				return (B_FALSE);
2135 			}
2136 		}
2137 
2138 		/*
2139 		 * Match all default routes from the global zone, irrespective
2140 		 * of reachability. For a non-global zone only match those
2141 		 * where ire_gateway_addr has a IRE_INTERFACE for the zoneid.
2142 		 */
2143 		if (ire->ire_type == IRE_DEFAULT && zoneid != GLOBAL_ZONEID) {
2144 			int ire_match_flags = 0;
2145 			in6_addr_t gw_addr_v6;
2146 			ire_t *rire;
2147 
2148 			ire_match_flags |= MATCH_IRE_TYPE;
2149 			if (ire->ire_ipif != NULL)
2150 				ire_match_flags |= MATCH_IRE_ILL;
2151 
2152 			if (ire->ire_ipversion == IPV4_VERSION) {
2153 				rire = ire_route_lookup(ire->ire_gateway_addr,
2154 				    0, 0, IRE_INTERFACE, ire->ire_ipif, NULL,
2155 				    zoneid, NULL, ire_match_flags, ipst);
2156 			} else {
2157 				ASSERT(ire->ire_ipversion == IPV6_VERSION);
2158 				mutex_enter(&ire->ire_lock);
2159 				gw_addr_v6 = ire->ire_gateway_addr_v6;
2160 				mutex_exit(&ire->ire_lock);
2161 				rire = ire_route_lookup_v6(&gw_addr_v6,
2162 				    NULL, NULL, IRE_INTERFACE, ire->ire_ipif,
2163 				    NULL, zoneid, NULL, ire_match_flags, ipst);
2164 			}
2165 			if (rire == NULL) {
2166 				return (B_FALSE);
2167 			}
2168 			ire_refrele(rire);
2169 		}
2170 	}
2171 
2172 	if (((!(match_flags & MATCH_IRE_TYPE)) ||
2173 	    (ire->ire_type & ire_type)) &&
2174 	    ((!(match_flags & MATCH_IRE_ILL)) ||
2175 	    (ire_stq_ill == ill || ire_ipif_ill == ill ||
2176 	    ire_ipif_ill != NULL && IS_IN_SAME_ILLGRP(ire_ipif_ill, ill)))) {
2177 		return (B_TRUE);
2178 	}
2179 	return (B_FALSE);
2180 }
2181 
2182 int
2183 rtfunc(struct radix_node *rn, void *arg)
2184 {
2185 	struct rtfuncarg *rtf = arg;
2186 	struct rt_entry *rt;
2187 	irb_t *irb;
2188 	ire_t *ire;
2189 	boolean_t ret;
2190 
2191 	rt = (struct rt_entry *)rn;
2192 	ASSERT(rt != NULL);
2193 	irb = &rt->rt_irb;
2194 	for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
2195 		if ((rtf->rt_match_flags != 0) ||
2196 		    (rtf->rt_zoneid != ALL_ZONES)) {
2197 			ret = ire_walk_ill_match(rtf->rt_match_flags,
2198 			    rtf->rt_ire_type, ire,
2199 			    rtf->rt_ill, rtf->rt_zoneid, rtf->rt_ipst);
2200 		} else
2201 			ret = B_TRUE;
2202 		if (ret)
2203 			(*rtf->rt_func)(ire, rtf->rt_arg);
2204 	}
2205 	return (0);
2206 }
2207 
2208 /*
2209  * Walk the ftable and the ctable entries that match the ill.
2210  */
2211 void
2212 ire_walk_ill_tables(uint_t match_flags, uint_t ire_type, pfv_t func,
2213     void *arg, size_t ftbl_sz, size_t htbl_sz, irb_t **ipftbl,
2214     size_t ctbl_sz, irb_t *ipctbl, ill_t *ill, zoneid_t zoneid,
2215     ip_stack_t *ipst)
2216 {
2217 	irb_t	*irb_ptr;
2218 	irb_t	*irb;
2219 	ire_t	*ire;
2220 	int i, j;
2221 	boolean_t ret;
2222 	struct rtfuncarg rtfarg;
2223 
2224 	ASSERT((!(match_flags & MATCH_IRE_ILL)) || (ill != NULL));
2225 	ASSERT(!(match_flags & MATCH_IRE_TYPE) || (ire_type != 0));
2226 	/*
2227 	 * Optimize by not looking at the forwarding table if there
2228 	 * is a MATCH_IRE_TYPE specified with no IRE_FORWARDTABLE
2229 	 * specified in ire_type.
2230 	 */
2231 	if (!(match_flags & MATCH_IRE_TYPE) ||
2232 	    ((ire_type & IRE_FORWARDTABLE) != 0)) {
2233 		/* knobs such that routine is called only for v6 case */
2234 		if (ipftbl == ipst->ips_ip_forwarding_table_v6) {
2235 			for (i = (ftbl_sz - 1);  i >= 0; i--) {
2236 				if ((irb_ptr = ipftbl[i]) == NULL)
2237 					continue;
2238 				for (j = 0; j < htbl_sz; j++) {
2239 					irb = &irb_ptr[j];
2240 					if (irb->irb_ire == NULL)
2241 						continue;
2242 
2243 					IRB_REFHOLD(irb);
2244 					for (ire = irb->irb_ire; ire != NULL;
2245 					    ire = ire->ire_next) {
2246 						if (match_flags == 0 &&
2247 						    zoneid == ALL_ZONES) {
2248 							ret = B_TRUE;
2249 						} else {
2250 							ret =
2251 							    ire_walk_ill_match(
2252 							    match_flags,
2253 							    ire_type, ire, ill,
2254 							    zoneid, ipst);
2255 						}
2256 						if (ret)
2257 							(*func)(ire, arg);
2258 					}
2259 					IRB_REFRELE(irb);
2260 				}
2261 			}
2262 		} else {
2263 			(void) memset(&rtfarg, 0, sizeof (rtfarg));
2264 			rtfarg.rt_func = func;
2265 			rtfarg.rt_arg = arg;
2266 			if (match_flags != 0) {
2267 				rtfarg.rt_match_flags = match_flags;
2268 			}
2269 			rtfarg.rt_ire_type = ire_type;
2270 			rtfarg.rt_ill = ill;
2271 			rtfarg.rt_zoneid = zoneid;
2272 			rtfarg.rt_ipst = ipst;	/* No netstack_hold */
2273 			(void) ipst->ips_ip_ftable->rnh_walktree_mt(
2274 			    ipst->ips_ip_ftable,
2275 			    rtfunc, &rtfarg, irb_refhold_rn, irb_refrele_rn);
2276 		}
2277 	}
2278 
2279 	/*
2280 	 * Optimize by not looking at the cache table if there
2281 	 * is a MATCH_IRE_TYPE specified with no IRE_CACHETABLE
2282 	 * specified in ire_type.
2283 	 */
2284 	if (!(match_flags & MATCH_IRE_TYPE) ||
2285 	    ((ire_type & IRE_CACHETABLE) != 0)) {
2286 		for (i = 0; i < ctbl_sz;  i++) {
2287 			irb = &ipctbl[i];
2288 			if (irb->irb_ire == NULL)
2289 				continue;
2290 			IRB_REFHOLD(irb);
2291 			for (ire = irb->irb_ire; ire != NULL;
2292 			    ire = ire->ire_next) {
2293 				if (match_flags == 0 && zoneid == ALL_ZONES) {
2294 					ret = B_TRUE;
2295 				} else {
2296 					ret = ire_walk_ill_match(
2297 					    match_flags, ire_type,
2298 					    ire, ill, zoneid, ipst);
2299 				}
2300 				if (ret)
2301 					(*func)(ire, arg);
2302 			}
2303 			IRB_REFRELE(irb);
2304 		}
2305 	}
2306 }
2307 
2308 /*
2309  * This function takes a mask and returns
2310  * number of bits set in the mask. If no
2311  * bit is set it returns 0.
2312  * Assumes a contiguous mask.
2313  */
2314 int
2315 ip_mask_to_plen(ipaddr_t mask)
2316 {
2317 	return (mask == 0 ? 0 : IP_ABITS - (ffs(ntohl(mask)) -1));
2318 }
2319 
2320 /*
2321  * Convert length for a mask to the mask.
2322  */
2323 ipaddr_t
2324 ip_plen_to_mask(uint_t masklen)
2325 {
2326 	return (htonl(IP_HOST_MASK << (IP_ABITS - masklen)));
2327 }
2328 
2329 void
2330 ire_atomic_end(irb_t *irb_ptr, ire_t *ire)
2331 {
2332 	ill_t *stq_ill, *ipif_ill;
2333 	ip_stack_t *ipst = ire->ire_ipst;
2334 
2335 	stq_ill = ire->ire_stq != NULL ? ire->ire_stq->q_ptr : NULL;
2336 	ipif_ill = ire->ire_ipif != NULL ? ire->ire_ipif->ipif_ill : NULL;
2337 	RELEASE_ILL_LOCKS(ipif_ill, stq_ill);
2338 	rw_exit(&irb_ptr->irb_lock);
2339 	rw_exit(&ipst->ips_ill_g_usesrc_lock);
2340 }
2341 
2342 /*
2343  * ire_add_v[46] atomically make sure that the ipif or ill associated
2344  * with the new ire being added is stable and not IPIF_CHANGING or ILL_CHANGING
2345  * before adding the ire to the table. This ensures that we don't create
2346  * new IRE_CACHEs with stale values for parameters that are passed to
2347  * ire_create such as ire_max_frag. Note that ire_create() is passed a pointer
2348  * to the ipif_mtu, and not the value. The actual value is derived from the
2349  * parent ire or ipif under the bucket lock.
2350  */
2351 int
2352 ire_atomic_start(irb_t *irb_ptr, ire_t *ire, queue_t *q, mblk_t *mp,
2353     ipsq_func_t func)
2354 {
2355 	ill_t	*stq_ill;
2356 	ill_t	*ipif_ill;
2357 	int	error = 0;
2358 	ill_t	*ill = NULL;
2359 	ip_stack_t	*ipst = ire->ire_ipst;
2360 
2361 	stq_ill = ire->ire_stq != NULL ? ire->ire_stq->q_ptr : NULL;
2362 	ipif_ill = ire->ire_ipif != NULL ? ire->ire_ipif->ipif_ill : NULL;
2363 
2364 	ASSERT((q != NULL && mp != NULL && func != NULL) ||
2365 	    (q == NULL && mp == NULL && func == NULL));
2366 	rw_enter(&ipst->ips_ill_g_usesrc_lock, RW_READER);
2367 	GRAB_CONN_LOCK(q);
2368 	rw_enter(&irb_ptr->irb_lock, RW_WRITER);
2369 	GRAB_ILL_LOCKS(ipif_ill, stq_ill);
2370 
2371 	/*
2372 	 * While the IRE is in the process of being added, a user may have
2373 	 * invoked the ifconfig usesrc option on the stq_ill to make it a
2374 	 * usesrc client ILL. Check for this possibility here, if it is true
2375 	 * then we fail adding the IRE_CACHE. Another check is to make sure
2376 	 * that an ipif_ill of an IRE_CACHE being added is not part of a usesrc
2377 	 * group. The ill_g_usesrc_lock is released in ire_atomic_end
2378 	 */
2379 	if ((ire->ire_type & IRE_CACHE) &&
2380 	    (ire->ire_marks & IRE_MARK_USESRC_CHECK)) {
2381 		if (stq_ill->ill_usesrc_ifindex != 0) {
2382 			ASSERT(stq_ill->ill_usesrc_grp_next != NULL);
2383 			if ((ipif_ill->ill_phyint->phyint_ifindex !=
2384 			    stq_ill->ill_usesrc_ifindex) ||
2385 			    (ipif_ill->ill_usesrc_grp_next == NULL) ||
2386 			    (ipif_ill->ill_usesrc_ifindex != 0)) {
2387 				error = EINVAL;
2388 				goto done;
2389 			}
2390 		} else if (ipif_ill->ill_usesrc_grp_next != NULL) {
2391 			error = EINVAL;
2392 			goto done;
2393 		}
2394 	}
2395 
2396 	/*
2397 	 * Don't allow IRE's to be created on changing ill's.  Also, since
2398 	 * IPMP flags can be set on an ill without quiescing it, if we're not
2399 	 * a writer on stq_ill, check that the flags still allow IRE creation.
2400 	 */
2401 	if ((stq_ill != NULL) && !IAM_WRITER_ILL(stq_ill)) {
2402 		if (stq_ill->ill_state_flags & ILL_CHANGING) {
2403 			ill = stq_ill;
2404 			error = EAGAIN;
2405 		} else if (IS_UNDER_IPMP(stq_ill)) {
2406 			mutex_enter(&stq_ill->ill_phyint->phyint_lock);
2407 			if (!ipmp_ill_is_active(stq_ill) &&
2408 			    !(ire->ire_marks & IRE_MARK_TESTHIDDEN)) {
2409 				error = EINVAL;
2410 			}
2411 			mutex_exit(&stq_ill->ill_phyint->phyint_lock);
2412 		}
2413 		if (error != 0)
2414 			goto done;
2415 	}
2416 
2417 	if ((ipif_ill != NULL) && !IAM_WRITER_ILL(ipif_ill) &&
2418 	    (ipif_ill->ill_state_flags & ILL_CHANGING)) {
2419 		ill = ipif_ill;
2420 		error = EAGAIN;
2421 		goto done;
2422 	}
2423 
2424 	if ((ire->ire_ipif != NULL) && !IAM_WRITER_IPIF(ire->ire_ipif) &&
2425 	    (ire->ire_ipif->ipif_state_flags & IPIF_CHANGING)) {
2426 		ill = ire->ire_ipif->ipif_ill;
2427 		ASSERT(ill != NULL);
2428 		error = EAGAIN;
2429 		goto done;
2430 	}
2431 
2432 done:
2433 	if (error == EAGAIN && ILL_CAN_WAIT(ill, q)) {
2434 		ipsq_t *ipsq = ill->ill_phyint->phyint_ipsq;
2435 		mutex_enter(&ipsq->ipsq_lock);
2436 		mutex_enter(&ipsq->ipsq_xop->ipx_lock);
2437 		ire_atomic_end(irb_ptr, ire);
2438 		ipsq_enq(ipsq, q, mp, func, NEW_OP, ill);
2439 		mutex_exit(&ipsq->ipsq_xop->ipx_lock);
2440 		mutex_exit(&ipsq->ipsq_lock);
2441 		error = EINPROGRESS;
2442 	} else if (error != 0) {
2443 		ire_atomic_end(irb_ptr, ire);
2444 	}
2445 
2446 	RELEASE_CONN_LOCK(q);
2447 	return (error);
2448 }
2449 
2450 /*
2451  * Add a fully initialized IRE to an appropriate table based on
2452  * ire_type.
2453  *
2454  * allow_unresolved == B_FALSE indicates a legacy code-path call
2455  * that has prohibited the addition of incomplete ire's. If this
2456  * parameter is set, and we find an nce that is in a state other
2457  * than ND_REACHABLE, we fail the add. Note that nce_state could be
2458  * something other than ND_REACHABLE if the nce had just expired and
2459  * the ire_create preceding the ire_add added a new ND_INITIAL nce.
2460  */
2461 int
2462 ire_add(ire_t **irep, queue_t *q, mblk_t *mp, ipsq_func_t func,
2463     boolean_t allow_unresolved)
2464 {
2465 	ire_t	*ire1;
2466 	ill_t	*stq_ill = NULL;
2467 	ill_t	*ill;
2468 	ipif_t	*ipif = NULL;
2469 	ill_walk_context_t ctx;
2470 	ire_t	*ire = *irep;
2471 	int	error;
2472 	boolean_t ire_is_mblk = B_FALSE;
2473 	tsol_gcgrp_t *gcgrp = NULL;
2474 	tsol_gcgrp_addr_t ga;
2475 	ip_stack_t	*ipst = ire->ire_ipst;
2476 
2477 	/* get ready for the day when original ire is not created as mblk */
2478 	if (ire->ire_mp != NULL) {
2479 		ire_is_mblk = B_TRUE;
2480 		/* Copy the ire to a kmem_alloc'ed area */
2481 		ire1 = kmem_cache_alloc(ire_cache, KM_NOSLEEP);
2482 		if (ire1 == NULL) {
2483 			ip1dbg(("ire_add: alloc failed\n"));
2484 			ire_delete(ire);
2485 			*irep = NULL;
2486 			return (ENOMEM);
2487 		}
2488 		ire->ire_marks &= ~IRE_MARK_UNCACHED;
2489 		*ire1 = *ire;
2490 		ire1->ire_mp = NULL;
2491 		ire1->ire_stq_ifindex = 0;
2492 		freeb(ire->ire_mp);
2493 		ire = ire1;
2494 	}
2495 	if (ire->ire_stq != NULL)
2496 		stq_ill = ire->ire_stq->q_ptr;
2497 
2498 	if (stq_ill != NULL && ire->ire_type == IRE_CACHE &&
2499 	    stq_ill->ill_net_type == IRE_IF_RESOLVER) {
2500 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
2501 		ill = ILL_START_WALK_ALL(&ctx, ipst);
2502 		for (; ill != NULL; ill = ill_next(&ctx, ill)) {
2503 			mutex_enter(&ill->ill_lock);
2504 			if (ill->ill_state_flags & ILL_CONDEMNED) {
2505 				mutex_exit(&ill->ill_lock);
2506 				continue;
2507 			}
2508 			/*
2509 			 * We need to make sure that the ipif is a valid one
2510 			 * before adding the IRE_CACHE. This happens only
2511 			 * with IRE_CACHE when there is an external resolver.
2512 			 *
2513 			 * We can unplumb a logical interface while the
2514 			 * packet is waiting in ARP with the IRE. Then,
2515 			 * later on when we feed the IRE back, the ipif
2516 			 * has to be re-checked. This can't happen with
2517 			 * NDP currently, as we never queue the IRE with
2518 			 * the packet. We always try to recreate the IRE
2519 			 * when the resolution is completed. But, we do
2520 			 * it for IPv6 also here so that in future if
2521 			 * we have external resolvers, it will work without
2522 			 * any change.
2523 			 */
2524 			ipif = ipif_lookup_seqid(ill, ire->ire_ipif_seqid);
2525 			if (ipif != NULL) {
2526 				ipif_refhold_locked(ipif);
2527 				mutex_exit(&ill->ill_lock);
2528 				break;
2529 			}
2530 			mutex_exit(&ill->ill_lock);
2531 		}
2532 		rw_exit(&ipst->ips_ill_g_lock);
2533 		if (ipif == NULL ||
2534 		    (ipif->ipif_isv6 &&
2535 		    !IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6) &&
2536 		    !IN6_ARE_ADDR_EQUAL(&ire->ire_src_addr_v6,
2537 		    &ipif->ipif_v6src_addr)) ||
2538 		    (!ipif->ipif_isv6 &&
2539 		    ire->ire_src_addr != ipif->ipif_src_addr) ||
2540 		    ire->ire_zoneid != ipif->ipif_zoneid) {
2541 			if (ipif != NULL)
2542 				ipif_refrele(ipif);
2543 			ire->ire_ipif = NULL;
2544 			ire_delete(ire);
2545 			*irep = NULL;
2546 			return (EINVAL);
2547 		}
2548 
2549 		ASSERT(ill != NULL);
2550 
2551 		/*
2552 		 * Since we didn't attach label security attributes to the
2553 		 * ire for the resolver case, we need to add it now. (only
2554 		 * for v4 resolver and v6 xresolv case).
2555 		 */
2556 		if (is_system_labeled() && ire_is_mblk) {
2557 			if (ire->ire_ipversion == IPV4_VERSION) {
2558 				ga.ga_af = AF_INET;
2559 				IN6_IPADDR_TO_V4MAPPED(ire->ire_gateway_addr !=
2560 				    INADDR_ANY ? ire->ire_gateway_addr :
2561 				    ire->ire_addr, &ga.ga_addr);
2562 			} else {
2563 				ga.ga_af = AF_INET6;
2564 				ga.ga_addr = IN6_IS_ADDR_UNSPECIFIED(
2565 				    &ire->ire_gateway_addr_v6) ?
2566 				    ire->ire_addr_v6 :
2567 				    ire->ire_gateway_addr_v6;
2568 			}
2569 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
2570 			error = tsol_ire_init_gwattr(ire, ire->ire_ipversion,
2571 			    NULL, gcgrp);
2572 			if (error != 0) {
2573 				if (gcgrp != NULL) {
2574 					GCGRP_REFRELE(gcgrp);
2575 					gcgrp = NULL;
2576 				}
2577 				ipif_refrele(ipif);
2578 				ire->ire_ipif = NULL;
2579 				ire_delete(ire);
2580 				*irep = NULL;
2581 				return (error);
2582 			}
2583 		}
2584 	}
2585 
2586 	/*
2587 	 * In case ire was changed
2588 	 */
2589 	*irep = ire;
2590 	if (ire->ire_ipversion == IPV6_VERSION)
2591 		error = ire_add_v6(irep, q, mp, func);
2592 	else
2593 		error = ire_add_v4(irep, q, mp, func, allow_unresolved);
2594 	if (ipif != NULL)
2595 		ipif_refrele(ipif);
2596 	return (error);
2597 }
2598 
2599 /*
2600  * Add an initialized IRE to an appropriate table based on ire_type.
2601  *
2602  * The forward table contains IRE_PREFIX/IRE_HOST and
2603  * IRE_IF_RESOLVER/IRE_IF_NORESOLVER and IRE_DEFAULT.
2604  *
2605  * The cache table contains IRE_BROADCAST/IRE_LOCAL/IRE_LOOPBACK
2606  * and IRE_CACHE.
2607  *
2608  * NOTE : This function is called as writer though not required
2609  * by this function.
2610  */
2611 static int
2612 ire_add_v4(ire_t **ire_p, queue_t *q, mblk_t *mp, ipsq_func_t func,
2613     boolean_t allow_unresolved)
2614 {
2615 	ire_t	*ire1;
2616 	irb_t	*irb_ptr;
2617 	ire_t	**irep;
2618 	int	flags;
2619 	ire_t	*pire = NULL;
2620 	ill_t	*stq_ill;
2621 	ire_t	*ire = *ire_p;
2622 	int	error;
2623 	boolean_t need_refrele = B_FALSE;
2624 	nce_t	*nce;
2625 	ip_stack_t	*ipst = ire->ire_ipst;
2626 	uint_t	marks = 0;
2627 
2628 	/*
2629 	 * IREs with source addresses hosted on interfaces that are under IPMP
2630 	 * should be hidden so that applications don't accidentally end up
2631 	 * sending packets with test addresses as their source addresses, or
2632 	 * sending out interfaces that are e.g. IFF_INACTIVE.  Hide them here.
2633 	 */
2634 	if (ire->ire_ipif != NULL && IS_UNDER_IPMP(ire->ire_ipif->ipif_ill))
2635 		marks |= IRE_MARK_TESTHIDDEN;
2636 
2637 	if (ire->ire_ipif != NULL)
2638 		ASSERT(!MUTEX_HELD(&ire->ire_ipif->ipif_ill->ill_lock));
2639 	if (ire->ire_stq != NULL)
2640 		ASSERT(!MUTEX_HELD(
2641 		    &((ill_t *)(ire->ire_stq->q_ptr))->ill_lock));
2642 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
2643 	ASSERT(ire->ire_mp == NULL); /* Calls should go through ire_add */
2644 
2645 	/* Find the appropriate list head. */
2646 	switch (ire->ire_type) {
2647 	case IRE_HOST:
2648 		ire->ire_mask = IP_HOST_MASK;
2649 		ire->ire_masklen = IP_ABITS;
2650 		ire->ire_marks |= marks;
2651 		if ((ire->ire_flags & RTF_SETSRC) == 0)
2652 			ire->ire_src_addr = 0;
2653 		break;
2654 	case IRE_CACHE:
2655 		ire->ire_mask = IP_HOST_MASK;
2656 		ire->ire_masklen = IP_ABITS;
2657 		ire->ire_marks |= marks;
2658 		break;
2659 	case IRE_BROADCAST:
2660 	case IRE_LOCAL:
2661 	case IRE_LOOPBACK:
2662 		ire->ire_mask = IP_HOST_MASK;
2663 		ire->ire_masklen = IP_ABITS;
2664 		break;
2665 	case IRE_PREFIX:
2666 	case IRE_DEFAULT:
2667 		ire->ire_marks |= marks;
2668 		if ((ire->ire_flags & RTF_SETSRC) == 0)
2669 			ire->ire_src_addr = 0;
2670 		break;
2671 	case IRE_IF_RESOLVER:
2672 	case IRE_IF_NORESOLVER:
2673 		ire->ire_marks |= marks;
2674 		break;
2675 	default:
2676 		ip0dbg(("ire_add_v4: ire %p has unrecognized IRE type (%d)\n",
2677 		    (void *)ire, ire->ire_type));
2678 		ire_delete(ire);
2679 		*ire_p = NULL;
2680 		return (EINVAL);
2681 	}
2682 
2683 	/* Make sure the address is properly masked. */
2684 	ire->ire_addr &= ire->ire_mask;
2685 
2686 	/*
2687 	 * ip_newroute/ip_newroute_multi are unable to prevent the deletion
2688 	 * of the interface route while adding an IRE_CACHE for an on-link
2689 	 * destination in the IRE_IF_RESOLVER case, since the ire has to
2690 	 * go to ARP and return. We can't do a REFHOLD on the
2691 	 * associated interface ire for fear of ARP freeing the message.
2692 	 * Here we look up the interface ire in the forwarding table and
2693 	 * make sure that the interface route has not been deleted.
2694 	 */
2695 	if (ire->ire_type == IRE_CACHE && ire->ire_gateway_addr == 0 &&
2696 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_net_type == IRE_IF_RESOLVER) {
2697 
2698 		ASSERT(ire->ire_max_fragp == NULL);
2699 		if (CLASSD(ire->ire_addr) && !(ire->ire_flags & RTF_SETSRC)) {
2700 			/*
2701 			 * The ihandle that we used in ip_newroute_multi
2702 			 * comes from the interface route corresponding
2703 			 * to ire_ipif. Lookup here to see if it exists
2704 			 * still.
2705 			 * If the ire has a source address assigned using
2706 			 * RTF_SETSRC, ire_ipif is the logical interface holding
2707 			 * this source address, so we can't use it to check for
2708 			 * the existence of the interface route. Instead we rely
2709 			 * on the brute force ihandle search in
2710 			 * ire_ihandle_lookup_onlink() below.
2711 			 */
2712 			pire = ipif_to_ire(ire->ire_ipif);
2713 			if (pire == NULL) {
2714 				ire_delete(ire);
2715 				*ire_p = NULL;
2716 				return (EINVAL);
2717 			} else if (pire->ire_ihandle != ire->ire_ihandle) {
2718 				ire_refrele(pire);
2719 				ire_delete(ire);
2720 				*ire_p = NULL;
2721 				return (EINVAL);
2722 			}
2723 		} else {
2724 			pire = ire_ihandle_lookup_onlink(ire);
2725 			if (pire == NULL) {
2726 				ire_delete(ire);
2727 				*ire_p = NULL;
2728 				return (EINVAL);
2729 			}
2730 		}
2731 		/* Prevent pire from getting deleted */
2732 		IRB_REFHOLD(pire->ire_bucket);
2733 		/* Has it been removed already ? */
2734 		if (pire->ire_marks & IRE_MARK_CONDEMNED) {
2735 			IRB_REFRELE(pire->ire_bucket);
2736 			ire_refrele(pire);
2737 			ire_delete(ire);
2738 			*ire_p = NULL;
2739 			return (EINVAL);
2740 		}
2741 	} else {
2742 		ASSERT(ire->ire_max_fragp != NULL);
2743 	}
2744 	flags = (MATCH_IRE_MASK | MATCH_IRE_TYPE | MATCH_IRE_GW);
2745 
2746 	if (ire->ire_ipif != NULL) {
2747 		/*
2748 		 * We use MATCH_IRE_IPIF while adding IRE_CACHES only
2749 		 * for historic reasons and to maintain symmetry with
2750 		 * IPv6 code path. Historically this was used by
2751 		 * multicast code to create multiple IRE_CACHES on
2752 		 * a single ill with different ipifs. This was used
2753 		 * so that multicast packets leaving the node had the
2754 		 * right source address. This is no longer needed as
2755 		 * ip_wput initializes the address correctly.
2756 		 */
2757 		flags |= MATCH_IRE_IPIF;
2758 		/*
2759 		 * If we are creating a hidden IRE, make sure we search for
2760 		 * hidden IREs when searching for duplicates below.
2761 		 * Otherwise, we might find an IRE on some other interface
2762 		 * that's not marked hidden.
2763 		 */
2764 		if (ire->ire_marks & IRE_MARK_TESTHIDDEN)
2765 			flags |= MATCH_IRE_MARK_TESTHIDDEN;
2766 	}
2767 	if ((ire->ire_type & IRE_CACHETABLE) == 0) {
2768 		irb_ptr = ire_get_bucket(ire);
2769 		need_refrele = B_TRUE;
2770 		if (irb_ptr == NULL) {
2771 			/*
2772 			 * This assumes that the ire has not added
2773 			 * a reference to the ipif.
2774 			 */
2775 			ire->ire_ipif = NULL;
2776 			ire_delete(ire);
2777 			if (pire != NULL) {
2778 				IRB_REFRELE(pire->ire_bucket);
2779 				ire_refrele(pire);
2780 			}
2781 			*ire_p = NULL;
2782 			return (EINVAL);
2783 		}
2784 	} else {
2785 		irb_ptr = &(ipst->ips_ip_cache_table[IRE_ADDR_HASH(
2786 		    ire->ire_addr, ipst->ips_ip_cache_table_size)]);
2787 	}
2788 
2789 	/*
2790 	 * Start the atomic add of the ire. Grab the ill locks,
2791 	 * ill_g_usesrc_lock and the bucket lock. Check for condemned
2792 	 *
2793 	 * If ipif or ill is changing ire_atomic_start() may queue the
2794 	 * request and return EINPROGRESS.
2795 	 * To avoid lock order problems, get the ndp4->ndp_g_lock.
2796 	 */
2797 	mutex_enter(&ipst->ips_ndp4->ndp_g_lock);
2798 	error = ire_atomic_start(irb_ptr, ire, q, mp, func);
2799 	if (error != 0) {
2800 		mutex_exit(&ipst->ips_ndp4->ndp_g_lock);
2801 		/*
2802 		 * We don't know whether it is a valid ipif or not.
2803 		 * So, set it to NULL. This assumes that the ire has not added
2804 		 * a reference to the ipif.
2805 		 */
2806 		ire->ire_ipif = NULL;
2807 		ire_delete(ire);
2808 		if (pire != NULL) {
2809 			IRB_REFRELE(pire->ire_bucket);
2810 			ire_refrele(pire);
2811 		}
2812 		*ire_p = NULL;
2813 		if (need_refrele)
2814 			IRB_REFRELE(irb_ptr);
2815 		return (error);
2816 	}
2817 	/*
2818 	 * To avoid creating ires having stale values for the ire_max_frag
2819 	 * we get the latest value atomically here. For more details
2820 	 * see the block comment in ip_sioctl_mtu and in DL_NOTE_SDU_CHANGE
2821 	 * in ip_rput_dlpi_writer
2822 	 */
2823 	if (ire->ire_max_fragp == NULL) {
2824 		if (CLASSD(ire->ire_addr))
2825 			ire->ire_max_frag = ire->ire_ipif->ipif_mtu;
2826 		else
2827 			ire->ire_max_frag = pire->ire_max_frag;
2828 	} else {
2829 		uint_t	max_frag;
2830 
2831 		max_frag = *ire->ire_max_fragp;
2832 		ire->ire_max_fragp = NULL;
2833 		ire->ire_max_frag = max_frag;
2834 	}
2835 	/*
2836 	 * Atomically check for duplicate and insert in the table.
2837 	 */
2838 	for (ire1 = irb_ptr->irb_ire; ire1 != NULL; ire1 = ire1->ire_next) {
2839 		if (ire1->ire_marks & IRE_MARK_CONDEMNED)
2840 			continue;
2841 		if (ire->ire_ipif != NULL) {
2842 			/*
2843 			 * We do MATCH_IRE_ILL implicitly here for IREs
2844 			 * with a non-null ire_ipif, including IRE_CACHEs.
2845 			 * As ire_ipif and ire_stq could point to two
2846 			 * different ills, we can't pass just ire_ipif to
2847 			 * ire_match_args and get a match on both ills.
2848 			 * This is just needed for duplicate checks here and
2849 			 * so we don't add an extra argument to
2850 			 * ire_match_args for this. Do it locally.
2851 			 *
2852 			 * NOTE : Currently there is no part of the code
2853 			 * that asks for both MATH_IRE_IPIF and MATCH_IRE_ILL
2854 			 * match for IRE_CACHEs. Thus we don't want to
2855 			 * extend the arguments to ire_match_args.
2856 			 */
2857 			if (ire1->ire_stq != ire->ire_stq)
2858 				continue;
2859 			/*
2860 			 * Multiroute IRE_CACHEs for a given destination can
2861 			 * have the same ire_ipif, typically if their source
2862 			 * address is forced using RTF_SETSRC, and the same
2863 			 * send-to queue. We differentiate them using the parent
2864 			 * handle.
2865 			 */
2866 			if (ire->ire_type == IRE_CACHE &&
2867 			    (ire1->ire_flags & RTF_MULTIRT) &&
2868 			    (ire->ire_flags & RTF_MULTIRT) &&
2869 			    (ire1->ire_phandle != ire->ire_phandle))
2870 				continue;
2871 		}
2872 		if (ire1->ire_zoneid != ire->ire_zoneid)
2873 			continue;
2874 		if (ire_match_args(ire1, ire->ire_addr, ire->ire_mask,
2875 		    ire->ire_gateway_addr, ire->ire_type, ire->ire_ipif,
2876 		    ire->ire_zoneid, 0, NULL, flags, NULL)) {
2877 			/*
2878 			 * Return the old ire after doing a REFHOLD.
2879 			 * As most of the callers continue to use the IRE
2880 			 * after adding, we return a held ire. This will
2881 			 * avoid a lookup in the caller again. If the callers
2882 			 * don't want to use it, they need to do a REFRELE.
2883 			 */
2884 			ip1dbg(("found dup ire existing %p new %p\n",
2885 			    (void *)ire1, (void *)ire));
2886 			IRE_REFHOLD(ire1);
2887 			ire_atomic_end(irb_ptr, ire);
2888 			mutex_exit(&ipst->ips_ndp4->ndp_g_lock);
2889 			ire_delete(ire);
2890 			if (pire != NULL) {
2891 				/*
2892 				 * Assert that it is not removed from the
2893 				 * list yet.
2894 				 */
2895 				ASSERT(pire->ire_ptpn != NULL);
2896 				IRB_REFRELE(pire->ire_bucket);
2897 				ire_refrele(pire);
2898 			}
2899 			*ire_p = ire1;
2900 			if (need_refrele)
2901 				IRB_REFRELE(irb_ptr);
2902 			return (0);
2903 		}
2904 	}
2905 
2906 	if (ire->ire_type & IRE_CACHE) {
2907 		ASSERT(ire->ire_stq != NULL);
2908 		nce = ndp_lookup_v4(ire_to_ill(ire),
2909 		    ((ire->ire_gateway_addr != INADDR_ANY) ?
2910 		    &ire->ire_gateway_addr : &ire->ire_addr),
2911 		    B_TRUE);
2912 		if (nce != NULL)
2913 			mutex_enter(&nce->nce_lock);
2914 		/*
2915 		 * if the nce is NCE_F_CONDEMNED, or if it is not ND_REACHABLE
2916 		 * and the caller has prohibited the addition of incomplete
2917 		 * ire's, we fail the add. Note that nce_state could be
2918 		 * something other than ND_REACHABLE if the nce had
2919 		 * just expired and the ire_create preceding the
2920 		 * ire_add added a new ND_INITIAL nce.
2921 		 */
2922 		if ((nce == NULL) ||
2923 		    (nce->nce_flags & NCE_F_CONDEMNED) ||
2924 		    (!allow_unresolved &&
2925 		    (nce->nce_state != ND_REACHABLE))) {
2926 			if (nce != NULL) {
2927 				DTRACE_PROBE1(ire__bad__nce, nce_t *, nce);
2928 				mutex_exit(&nce->nce_lock);
2929 			}
2930 			ire_atomic_end(irb_ptr, ire);
2931 			mutex_exit(&ipst->ips_ndp4->ndp_g_lock);
2932 			if (nce != NULL)
2933 				NCE_REFRELE(nce);
2934 			DTRACE_PROBE1(ire__no__nce, ire_t *, ire);
2935 			ire_delete(ire);
2936 			if (pire != NULL) {
2937 				IRB_REFRELE(pire->ire_bucket);
2938 				ire_refrele(pire);
2939 			}
2940 			*ire_p = NULL;
2941 			if (need_refrele)
2942 				IRB_REFRELE(irb_ptr);
2943 			return (EINVAL);
2944 		} else {
2945 			ire->ire_nce = nce;
2946 			mutex_exit(&nce->nce_lock);
2947 			/*
2948 			 * We are associating this nce to the ire, so
2949 			 * change the nce ref taken in ndp_lookup_v4() from
2950 			 * NCE_REFHOLD to NCE_REFHOLD_NOTR
2951 			 */
2952 			NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
2953 		}
2954 	}
2955 	/*
2956 	 * Make it easy for ip_wput_ire() to hit multiple broadcast ires by
2957 	 * grouping identical addresses together on the hash chain.  We do
2958 	 * this only for IRE_BROADCASTs as ip_wput_ire is currently interested
2959 	 * in such groupings only for broadcasts.
2960 	 *
2961 	 * Find the first entry that matches ire_addr. *irep will be null
2962 	 * if no match.
2963 	 *
2964 	 * Note: the loopback and non-loopback broadcast entries for an
2965 	 * interface MUST be added before any MULTIRT entries.
2966 	 */
2967 	irep = (ire_t **)irb_ptr;
2968 	while ((ire1 = *irep) != NULL && ire->ire_addr != ire1->ire_addr)
2969 		irep = &ire1->ire_next;
2970 	if (ire->ire_type == IRE_BROADCAST && *irep != NULL) {
2971 		/*
2972 		 * We found some ire (i.e *irep) with a matching addr. We
2973 		 * want to group ires with same addr.
2974 		 */
2975 		for (;;) {
2976 			ire1 = *irep;
2977 			if ((ire1->ire_next == NULL) ||
2978 			    (ire1->ire_next->ire_addr != ire->ire_addr) ||
2979 			    (ire1->ire_type != IRE_BROADCAST) ||
2980 			    (ire1->ire_flags & RTF_MULTIRT) ||
2981 			    (ire1->ire_ipif->ipif_ill->ill_grp ==
2982 			    ire->ire_ipif->ipif_ill->ill_grp))
2983 				break;
2984 			irep = &ire1->ire_next;
2985 		}
2986 		ASSERT(*irep != NULL);
2987 		/*
2988 		 * The ire will be added before *irep, so
2989 		 * if irep is a MULTIRT ire, just break to
2990 		 * ire insertion code.
2991 		 */
2992 		if (((*irep)->ire_flags & RTF_MULTIRT) != 0)
2993 			goto insert_ire;
2994 
2995 		irep = &((*irep)->ire_next);
2996 
2997 		/*
2998 		 * Either we have hit the end of the list or the address
2999 		 * did not match.
3000 		 */
3001 		while (*irep != NULL) {
3002 			ire1 = *irep;
3003 			if ((ire1->ire_addr != ire->ire_addr) ||
3004 			    (ire1->ire_type != IRE_BROADCAST))
3005 				break;
3006 			if (ire1->ire_ipif == ire->ire_ipif) {
3007 				irep = &ire1->ire_next;
3008 				break;
3009 			}
3010 			irep = &ire1->ire_next;
3011 		}
3012 	} else if (*irep != NULL) {
3013 		/*
3014 		 * Find the last ire which matches ire_addr.
3015 		 * Needed to do tail insertion among entries with the same
3016 		 * ire_addr.
3017 		 */
3018 		while (ire->ire_addr == ire1->ire_addr) {
3019 			irep = &ire1->ire_next;
3020 			ire1 = *irep;
3021 			if (ire1 == NULL)
3022 				break;
3023 		}
3024 	}
3025 
3026 insert_ire:
3027 	/* Insert at *irep */
3028 	ire1 = *irep;
3029 	if (ire1 != NULL)
3030 		ire1->ire_ptpn = &ire->ire_next;
3031 	ire->ire_next = ire1;
3032 	/* Link the new one in. */
3033 	ire->ire_ptpn = irep;
3034 
3035 	/*
3036 	 * ire_walk routines de-reference ire_next without holding
3037 	 * a lock. Before we point to the new ire, we want to make
3038 	 * sure the store that sets the ire_next of the new ire
3039 	 * reaches global visibility, so that ire_walk routines
3040 	 * don't see a truncated list of ires i.e if the ire_next
3041 	 * of the new ire gets set after we do "*irep = ire" due
3042 	 * to re-ordering, the ire_walk thread will see a NULL
3043 	 * once it accesses the ire_next of the new ire.
3044 	 * membar_producer() makes sure that the following store
3045 	 * happens *after* all of the above stores.
3046 	 */
3047 	membar_producer();
3048 	*irep = ire;
3049 	ire->ire_bucket = irb_ptr;
3050 	/*
3051 	 * We return a bumped up IRE above. Keep it symmetrical
3052 	 * so that the callers will always have to release. This
3053 	 * helps the callers of this function because they continue
3054 	 * to use the IRE after adding and hence they don't have to
3055 	 * lookup again after we return the IRE.
3056 	 *
3057 	 * NOTE : We don't have to use atomics as this is appearing
3058 	 * in the list for the first time and no one else can bump
3059 	 * up the reference count on this yet.
3060 	 */
3061 	IRE_REFHOLD_LOCKED(ire);
3062 	BUMP_IRE_STATS(ipst->ips_ire_stats_v4, ire_stats_inserted);
3063 
3064 	irb_ptr->irb_ire_cnt++;
3065 	if (irb_ptr->irb_marks & IRB_MARK_FTABLE)
3066 		irb_ptr->irb_nire++;
3067 
3068 	if (ire->ire_marks & IRE_MARK_TEMPORARY)
3069 		irb_ptr->irb_tmp_ire_cnt++;
3070 
3071 	if (ire->ire_ipif != NULL) {
3072 		DTRACE_PROBE3(ipif__incr__cnt, (ipif_t *), ire->ire_ipif,
3073 		    (char *), "ire", (void *), ire);
3074 		ire->ire_ipif->ipif_ire_cnt++;
3075 		if (ire->ire_stq != NULL) {
3076 			stq_ill = (ill_t *)ire->ire_stq->q_ptr;
3077 			DTRACE_PROBE3(ill__incr__cnt, (ill_t *), stq_ill,
3078 			    (char *), "ire", (void *), ire);
3079 			stq_ill->ill_ire_cnt++;
3080 		}
3081 	} else {
3082 		ASSERT(ire->ire_stq == NULL);
3083 	}
3084 
3085 	ire_atomic_end(irb_ptr, ire);
3086 	mutex_exit(&ipst->ips_ndp4->ndp_g_lock);
3087 
3088 	if (pire != NULL) {
3089 		/* Assert that it is not removed from the list yet */
3090 		ASSERT(pire->ire_ptpn != NULL);
3091 		IRB_REFRELE(pire->ire_bucket);
3092 		ire_refrele(pire);
3093 	}
3094 
3095 	if (ire->ire_type != IRE_CACHE) {
3096 		/*
3097 		 * For ire's with host mask see if there is an entry
3098 		 * in the cache. If there is one flush the whole cache as
3099 		 * there might be multiple entries due to RTF_MULTIRT (CGTP).
3100 		 * If no entry is found than there is no need to flush the
3101 		 * cache.
3102 		 */
3103 		if (ire->ire_mask == IP_HOST_MASK) {
3104 			ire_t *lire;
3105 			lire = ire_ctable_lookup(ire->ire_addr, NULL, IRE_CACHE,
3106 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3107 			if (lire != NULL) {
3108 				ire_refrele(lire);
3109 				ire_flush_cache_v4(ire, IRE_FLUSH_ADD);
3110 			}
3111 		} else {
3112 			ire_flush_cache_v4(ire, IRE_FLUSH_ADD);
3113 		}
3114 	}
3115 	/*
3116 	 * We had to delay the fast path probe until the ire is inserted
3117 	 * in the list. Otherwise the fast path ack won't find the ire in
3118 	 * the table.
3119 	 */
3120 	if (ire->ire_type == IRE_CACHE ||
3121 	    (ire->ire_type == IRE_BROADCAST && ire->ire_stq != NULL)) {
3122 		ASSERT(ire->ire_nce != NULL);
3123 		if (ire->ire_nce->nce_state == ND_REACHABLE)
3124 			nce_fastpath(ire->ire_nce);
3125 	}
3126 	if (ire->ire_ipif != NULL)
3127 		ASSERT(!MUTEX_HELD(&ire->ire_ipif->ipif_ill->ill_lock));
3128 	*ire_p = ire;
3129 	if (need_refrele) {
3130 		IRB_REFRELE(irb_ptr);
3131 	}
3132 	return (0);
3133 }
3134 
3135 /*
3136  * IRB_REFRELE is the only caller of the function. ire_unlink calls to
3137  * do the final cleanup for this ire.
3138  */
3139 void
3140 ire_cleanup(ire_t *ire)
3141 {
3142 	ire_t *ire_next;
3143 	ip_stack_t *ipst = ire->ire_ipst;
3144 
3145 	ASSERT(ire != NULL);
3146 
3147 	while (ire != NULL) {
3148 		ire_next = ire->ire_next;
3149 		if (ire->ire_ipversion == IPV4_VERSION) {
3150 			ire_delete_v4(ire);
3151 			BUMP_IRE_STATS(ipst->ips_ire_stats_v4,
3152 			    ire_stats_deleted);
3153 		} else {
3154 			ASSERT(ire->ire_ipversion == IPV6_VERSION);
3155 			ire_delete_v6(ire);
3156 			BUMP_IRE_STATS(ipst->ips_ire_stats_v6,
3157 			    ire_stats_deleted);
3158 		}
3159 		/*
3160 		 * Now it's really out of the list. Before doing the
3161 		 * REFRELE, set ire_next to NULL as ire_inactive asserts
3162 		 * so.
3163 		 */
3164 		ire->ire_next = NULL;
3165 		IRE_REFRELE_NOTR(ire);
3166 		ire = ire_next;
3167 	}
3168 }
3169 
3170 /*
3171  * IRB_REFRELE is the only caller of the function. It calls to unlink
3172  * all the CONDEMNED ires from this bucket.
3173  */
3174 ire_t *
3175 ire_unlink(irb_t *irb)
3176 {
3177 	ire_t *ire;
3178 	ire_t *ire1;
3179 	ire_t **ptpn;
3180 	ire_t *ire_list = NULL;
3181 
3182 	ASSERT(RW_WRITE_HELD(&irb->irb_lock));
3183 	ASSERT(((irb->irb_marks & IRB_MARK_FTABLE) && irb->irb_refcnt == 1) ||
3184 	    (irb->irb_refcnt == 0));
3185 	ASSERT(irb->irb_marks & IRB_MARK_CONDEMNED);
3186 	ASSERT(irb->irb_ire != NULL);
3187 
3188 	for (ire = irb->irb_ire; ire != NULL; ire = ire1) {
3189 		ip_stack_t	*ipst = ire->ire_ipst;
3190 
3191 		ire1 = ire->ire_next;
3192 		if (ire->ire_marks & IRE_MARK_CONDEMNED) {
3193 			ptpn = ire->ire_ptpn;
3194 			ire1 = ire->ire_next;
3195 			if (ire1)
3196 				ire1->ire_ptpn = ptpn;
3197 			*ptpn = ire1;
3198 			ire->ire_ptpn = NULL;
3199 			ire->ire_next = NULL;
3200 			if (ire->ire_type == IRE_DEFAULT) {
3201 				/*
3202 				 * IRE is out of the list. We need to adjust
3203 				 * the accounting before the caller drops
3204 				 * the lock.
3205 				 */
3206 				if (ire->ire_ipversion == IPV6_VERSION) {
3207 					ASSERT(ipst->
3208 					    ips_ipv6_ire_default_count !=
3209 					    0);
3210 					ipst->ips_ipv6_ire_default_count--;
3211 				}
3212 			}
3213 			/*
3214 			 * We need to call ire_delete_v4 or ire_delete_v6
3215 			 * to clean up the cache or the redirects pointing at
3216 			 * the default gateway. We need to drop the lock
3217 			 * as ire_flush_cache/ire_delete_host_redircts require
3218 			 * so. But we can't drop the lock, as ire_unlink needs
3219 			 * to atomically remove the ires from the list.
3220 			 * So, create a temporary list of CONDEMNED ires
3221 			 * for doing ire_delete_v4/ire_delete_v6 operations
3222 			 * later on.
3223 			 */
3224 			ire->ire_next = ire_list;
3225 			ire_list = ire;
3226 		}
3227 	}
3228 	irb->irb_marks &= ~IRB_MARK_CONDEMNED;
3229 	return (ire_list);
3230 }
3231 
3232 /*
3233  * Delete all the cache entries with this 'addr'.  When IP gets a gratuitous
3234  * ARP message on any of its interface queue, it scans the nce table and
3235  * deletes and calls ndp_delete() for the appropriate nce. This action
3236  * also deletes all the neighbor/ire cache entries for that address.
3237  * This function is called from ip_arp_news in ip.c and also for
3238  * ARP ioctl processing in ip_if.c. ip_ire_clookup_and_delete returns
3239  * true if it finds a nce entry which is used by ip_arp_news to determine if
3240  * it needs to do an ire_walk_v4. The return value is also  used for the
3241  * same purpose by ARP IOCTL processing * in ip_if.c when deleting
3242  * ARP entries. For SIOC*IFARP ioctls in addition to the address,
3243  * ip_if->ipif_ill also needs to be matched.
3244  */
3245 boolean_t
3246 ip_ire_clookup_and_delete(ipaddr_t addr, ipif_t *ipif, ip_stack_t *ipst)
3247 {
3248 	ill_t	*ill;
3249 	nce_t	*nce;
3250 
3251 	ill = (ipif ? ipif->ipif_ill : NULL);
3252 
3253 	if (ill != NULL) {
3254 		/*
3255 		 * clean up the nce (and any relevant ire's) that matches
3256 		 * on addr and ill.
3257 		 */
3258 		nce = ndp_lookup_v4(ill, &addr, B_FALSE);
3259 		if (nce != NULL) {
3260 			ndp_delete(nce);
3261 			return (B_TRUE);
3262 		}
3263 	} else {
3264 		/*
3265 		 * ill is wildcard. clean up all nce's and
3266 		 * ire's that match on addr
3267 		 */
3268 		nce_clookup_t cl;
3269 
3270 		cl.ncecl_addr = addr;
3271 		cl.ncecl_found = B_FALSE;
3272 
3273 		ndp_walk_common(ipst->ips_ndp4, NULL,
3274 		    (pfi_t)ip_nce_clookup_and_delete, (uchar_t *)&cl, B_TRUE);
3275 
3276 		/*
3277 		 *  ncecl_found would be set by ip_nce_clookup_and_delete if
3278 		 *  we found a matching nce.
3279 		 */
3280 		return (cl.ncecl_found);
3281 	}
3282 	return (B_FALSE);
3283 
3284 }
3285 
3286 /* Delete the supplied nce if its nce_addr matches the supplied address */
3287 static void
3288 ip_nce_clookup_and_delete(nce_t *nce, void *arg)
3289 {
3290 	nce_clookup_t *cl = (nce_clookup_t *)arg;
3291 	ipaddr_t nce_addr;
3292 
3293 	IN6_V4MAPPED_TO_IPADDR(&nce->nce_addr, nce_addr);
3294 	if (nce_addr == cl->ncecl_addr) {
3295 		cl->ncecl_found = B_TRUE;
3296 		/* clean up the nce (and any relevant ire's) */
3297 		ndp_delete(nce);
3298 	}
3299 }
3300 
3301 /*
3302  * Clean up the radix node for this ire. Must be called by IRB_REFRELE
3303  * when there are no ire's left in the bucket. Returns TRUE if the bucket
3304  * is deleted and freed.
3305  */
3306 boolean_t
3307 irb_inactive(irb_t *irb)
3308 {
3309 	struct rt_entry *rt;
3310 	struct radix_node *rn;
3311 	ip_stack_t *ipst = irb->irb_ipst;
3312 
3313 	ASSERT(irb->irb_ipst != NULL);
3314 
3315 	rt = IRB2RT(irb);
3316 	rn = (struct radix_node *)rt;
3317 
3318 	/* first remove it from the radix tree. */
3319 	RADIX_NODE_HEAD_WLOCK(ipst->ips_ip_ftable);
3320 	rw_enter(&irb->irb_lock, RW_WRITER);
3321 	if (irb->irb_refcnt == 1 && irb->irb_nire == 0) {
3322 		rn = ipst->ips_ip_ftable->rnh_deladdr(rn->rn_key, rn->rn_mask,
3323 		    ipst->ips_ip_ftable);
3324 		DTRACE_PROBE1(irb__free, rt_t *,  rt);
3325 		ASSERT((void *)rn == (void *)rt);
3326 		Free(rt, rt_entry_cache);
3327 		/* irb_lock is freed */
3328 		RADIX_NODE_HEAD_UNLOCK(ipst->ips_ip_ftable);
3329 		return (B_TRUE);
3330 	}
3331 	rw_exit(&irb->irb_lock);
3332 	RADIX_NODE_HEAD_UNLOCK(ipst->ips_ip_ftable);
3333 	return (B_FALSE);
3334 }
3335 
3336 /*
3337  * Delete the specified IRE.
3338  */
3339 void
3340 ire_delete(ire_t *ire)
3341 {
3342 	ire_t	*ire1;
3343 	ire_t	**ptpn;
3344 	irb_t *irb;
3345 	ip_stack_t	*ipst = ire->ire_ipst;
3346 
3347 	if ((irb = ire->ire_bucket) == NULL) {
3348 		/*
3349 		 * It was never inserted in the list. Should call REFRELE
3350 		 * to free this IRE.
3351 		 */
3352 		IRE_REFRELE_NOTR(ire);
3353 		return;
3354 	}
3355 
3356 	rw_enter(&irb->irb_lock, RW_WRITER);
3357 
3358 	if (irb->irb_rr_origin == ire) {
3359 		irb->irb_rr_origin = NULL;
3360 	}
3361 
3362 	/*
3363 	 * In case of V4 we might still be waiting for fastpath ack.
3364 	 */
3365 	if (ire->ire_ipversion == IPV4_VERSION &&
3366 	    (ire->ire_type == IRE_CACHE ||
3367 	    (ire->ire_type == IRE_BROADCAST && ire->ire_stq != NULL))) {
3368 		ASSERT(ire->ire_nce != NULL);
3369 		nce_fastpath_list_delete(ire->ire_nce);
3370 	}
3371 
3372 	if (ire->ire_ptpn == NULL) {
3373 		/*
3374 		 * Some other thread has removed us from the list.
3375 		 * It should have done the REFRELE for us.
3376 		 */
3377 		rw_exit(&irb->irb_lock);
3378 		return;
3379 	}
3380 
3381 	if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
3382 		irb->irb_ire_cnt--;
3383 		ire->ire_marks |= IRE_MARK_CONDEMNED;
3384 		if (ire->ire_marks & IRE_MARK_TEMPORARY) {
3385 			irb->irb_tmp_ire_cnt--;
3386 			ire->ire_marks &= ~IRE_MARK_TEMPORARY;
3387 		}
3388 	}
3389 
3390 	if (irb->irb_refcnt != 0) {
3391 		/*
3392 		 * The last thread to leave this bucket will
3393 		 * delete this ire.
3394 		 */
3395 		irb->irb_marks |= IRB_MARK_CONDEMNED;
3396 		rw_exit(&irb->irb_lock);
3397 		return;
3398 	}
3399 
3400 	/*
3401 	 * Normally to delete an ire, we walk the bucket. While we
3402 	 * walk the bucket, we normally bump up irb_refcnt and hence
3403 	 * we return from above where we mark CONDEMNED and the ire
3404 	 * gets deleted from ire_unlink. This case is where somebody
3405 	 * knows the ire e.g by doing a lookup, and wants to delete the
3406 	 * IRE. irb_refcnt would be 0 in this case if nobody is walking
3407 	 * the bucket.
3408 	 */
3409 	ptpn = ire->ire_ptpn;
3410 	ire1 = ire->ire_next;
3411 	if (ire1 != NULL)
3412 		ire1->ire_ptpn = ptpn;
3413 	ASSERT(ptpn != NULL);
3414 	*ptpn = ire1;
3415 	ire->ire_ptpn = NULL;
3416 	ire->ire_next = NULL;
3417 	if (ire->ire_ipversion == IPV6_VERSION) {
3418 		BUMP_IRE_STATS(ipst->ips_ire_stats_v6, ire_stats_deleted);
3419 	} else {
3420 		BUMP_IRE_STATS(ipst->ips_ire_stats_v4, ire_stats_deleted);
3421 	}
3422 	/*
3423 	 * ip_wput/ip_wput_v6 checks this flag to see whether
3424 	 * it should still use the cached ire or not.
3425 	 */
3426 	if (ire->ire_type == IRE_DEFAULT) {
3427 		/*
3428 		 * IRE is out of the list. We need to adjust the
3429 		 * accounting before we drop the lock.
3430 		 */
3431 		if (ire->ire_ipversion == IPV6_VERSION) {
3432 			ASSERT(ipst->ips_ipv6_ire_default_count != 0);
3433 			ipst->ips_ipv6_ire_default_count--;
3434 		}
3435 	}
3436 	rw_exit(&irb->irb_lock);
3437 
3438 	if (ire->ire_ipversion == IPV6_VERSION) {
3439 		ire_delete_v6(ire);
3440 	} else {
3441 		ire_delete_v4(ire);
3442 	}
3443 	/*
3444 	 * We removed it from the list. Decrement the
3445 	 * reference count.
3446 	 */
3447 	IRE_REFRELE_NOTR(ire);
3448 }
3449 
3450 /*
3451  * Delete the specified IRE.
3452  * All calls should use ire_delete().
3453  * Sometimes called as writer though not required by this function.
3454  *
3455  * NOTE : This function is called only if the ire was added
3456  * in the list.
3457  */
3458 static void
3459 ire_delete_v4(ire_t *ire)
3460 {
3461 	ip_stack_t	*ipst = ire->ire_ipst;
3462 
3463 	ASSERT(ire->ire_refcnt >= 1);
3464 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
3465 
3466 	if (ire->ire_type != IRE_CACHE)
3467 		ire_flush_cache_v4(ire, IRE_FLUSH_DELETE);
3468 	if (ire->ire_type == IRE_DEFAULT) {
3469 		/*
3470 		 * when a default gateway is going away
3471 		 * delete all the host redirects pointing at that
3472 		 * gateway.
3473 		 */
3474 		ire_delete_host_redirects(ire->ire_gateway_addr, ipst);
3475 	}
3476 }
3477 
3478 /*
3479  * IRE_REFRELE/ire_refrele are the only caller of the function. It calls
3480  * to free the ire when the reference count goes to zero.
3481  */
3482 void
3483 ire_inactive(ire_t *ire)
3484 {
3485 	nce_t	*nce;
3486 	ill_t	*ill = NULL;
3487 	ill_t	*stq_ill = NULL;
3488 	ipif_t	*ipif;
3489 	boolean_t	need_wakeup = B_FALSE;
3490 	irb_t 	*irb;
3491 	ip_stack_t	*ipst = ire->ire_ipst;
3492 
3493 	ASSERT(ire->ire_refcnt == 0);
3494 	ASSERT(ire->ire_ptpn == NULL);
3495 	ASSERT(ire->ire_next == NULL);
3496 
3497 	if (ire->ire_gw_secattr != NULL) {
3498 		ire_gw_secattr_free(ire->ire_gw_secattr);
3499 		ire->ire_gw_secattr = NULL;
3500 	}
3501 
3502 	if (ire->ire_mp != NULL) {
3503 		ASSERT(ire->ire_bucket == NULL);
3504 		mutex_destroy(&ire->ire_lock);
3505 		BUMP_IRE_STATS(ipst->ips_ire_stats_v4, ire_stats_freed);
3506 		if (ire->ire_nce != NULL)
3507 			NCE_REFRELE_NOTR(ire->ire_nce);
3508 		freeb(ire->ire_mp);
3509 		return;
3510 	}
3511 
3512 	if ((nce = ire->ire_nce) != NULL) {
3513 		NCE_REFRELE_NOTR(nce);
3514 		ire->ire_nce = NULL;
3515 	}
3516 
3517 	if (ire->ire_ipif == NULL)
3518 		goto end;
3519 
3520 	ipif = ire->ire_ipif;
3521 	ill = ipif->ipif_ill;
3522 
3523 	if (ire->ire_bucket == NULL) {
3524 		/* The ire was never inserted in the table. */
3525 		goto end;
3526 	}
3527 
3528 	/*
3529 	 * ipif_ire_cnt on this ipif goes down by 1. If the ire_stq is
3530 	 * non-null ill_ire_count also goes down by 1.
3531 	 *
3532 	 * The ipif that is associated with an ire is ire->ire_ipif and
3533 	 * hence when the ire->ire_ipif->ipif_ire_cnt drops to zero we call
3534 	 * ipif_ill_refrele_tail. Usually stq_ill is null or the same as
3535 	 * ire->ire_ipif->ipif_ill. So nothing more needs to be done.
3536 	 * However, for VNI or IPMP IRE entries, stq_ill can be different.
3537 	 * If this is different from ire->ire_ipif->ipif_ill and if the
3538 	 * ill_ire_cnt on the stq_ill also has dropped to zero, we call
3539 	 * ipif_ill_refrele_tail on the stq_ill.
3540 	 */
3541 	if (ire->ire_stq != NULL)
3542 		stq_ill = ire->ire_stq->q_ptr;
3543 
3544 	if (stq_ill == NULL || stq_ill == ill) {
3545 		/* Optimize the most common case */
3546 		mutex_enter(&ill->ill_lock);
3547 		ASSERT(ipif->ipif_ire_cnt != 0);
3548 		DTRACE_PROBE3(ipif__decr__cnt, (ipif_t *), ipif,
3549 		    (char *), "ire", (void *), ire);
3550 		ipif->ipif_ire_cnt--;
3551 		if (IPIF_DOWN_OK(ipif))
3552 			need_wakeup = B_TRUE;
3553 		if (stq_ill != NULL) {
3554 			ASSERT(stq_ill->ill_ire_cnt != 0);
3555 			DTRACE_PROBE3(ill__decr__cnt, (ill_t *), stq_ill,
3556 			    (char *), "ire", (void *), ire);
3557 			stq_ill->ill_ire_cnt--;
3558 			if (ILL_DOWN_OK(stq_ill))
3559 				need_wakeup = B_TRUE;
3560 		}
3561 		if (need_wakeup) {
3562 			/* Drops the ill lock */
3563 			ipif_ill_refrele_tail(ill);
3564 		} else {
3565 			mutex_exit(&ill->ill_lock);
3566 		}
3567 	} else {
3568 		/*
3569 		 * We can't grab all the ill locks at the same time.
3570 		 * It can lead to recursive lock enter in the call to
3571 		 * ipif_ill_refrele_tail and later. Instead do it 1 at
3572 		 * a time.
3573 		 */
3574 		mutex_enter(&ill->ill_lock);
3575 		ASSERT(ipif->ipif_ire_cnt != 0);
3576 		DTRACE_PROBE3(ipif__decr__cnt, (ipif_t *), ipif,
3577 		    (char *), "ire", (void *), ire);
3578 		ipif->ipif_ire_cnt--;
3579 		if (IPIF_DOWN_OK(ipif)) {
3580 			/* Drops the lock */
3581 			ipif_ill_refrele_tail(ill);
3582 		} else {
3583 			mutex_exit(&ill->ill_lock);
3584 		}
3585 		if (stq_ill != NULL) {
3586 			mutex_enter(&stq_ill->ill_lock);
3587 			ASSERT(stq_ill->ill_ire_cnt != 0);
3588 			DTRACE_PROBE3(ill__decr__cnt, (ill_t *), stq_ill,
3589 			    (char *), "ire", (void *), ire);
3590 			stq_ill->ill_ire_cnt--;
3591 			if (ILL_DOWN_OK(stq_ill)) {
3592 				/* Drops the ill lock */
3593 				ipif_ill_refrele_tail(stq_ill);
3594 			} else {
3595 				mutex_exit(&stq_ill->ill_lock);
3596 			}
3597 		}
3598 	}
3599 end:
3600 	/* This should be true for both V4 and V6 */
3601 
3602 	if ((ire->ire_type & IRE_FORWARDTABLE) &&
3603 	    (ire->ire_ipversion == IPV4_VERSION) &&
3604 	    ((irb = ire->ire_bucket) != NULL)) {
3605 		rw_enter(&irb->irb_lock, RW_WRITER);
3606 		irb->irb_nire--;
3607 		/*
3608 		 * Instead of examining the conditions for freeing
3609 		 * the radix node here, we do it by calling
3610 		 * IRB_REFRELE which is a single point in the code
3611 		 * that embeds that logic. Bump up the refcnt to
3612 		 * be able to call IRB_REFRELE
3613 		 */
3614 		IRB_REFHOLD_LOCKED(irb);
3615 		rw_exit(&irb->irb_lock);
3616 		IRB_REFRELE(irb);
3617 	}
3618 	ire->ire_ipif = NULL;
3619 
3620 #ifdef DEBUG
3621 	ire_trace_cleanup(ire);
3622 #endif
3623 	mutex_destroy(&ire->ire_lock);
3624 	if (ire->ire_ipversion == IPV6_VERSION) {
3625 		BUMP_IRE_STATS(ipst->ips_ire_stats_v6, ire_stats_freed);
3626 	} else {
3627 		BUMP_IRE_STATS(ipst->ips_ire_stats_v4, ire_stats_freed);
3628 	}
3629 	ASSERT(ire->ire_mp == NULL);
3630 	/* Has been allocated out of the cache */
3631 	kmem_cache_free(ire_cache, ire);
3632 }
3633 
3634 /*
3635  * ire_walk routine to delete all IRE_CACHE/IRE_HOST types redirect
3636  * entries that have a given gateway address.
3637  */
3638 void
3639 ire_delete_cache_gw(ire_t *ire, char *cp)
3640 {
3641 	ipaddr_t	gw_addr;
3642 
3643 	if (!(ire->ire_type & IRE_CACHE) &&
3644 	    !(ire->ire_flags & RTF_DYNAMIC))
3645 		return;
3646 
3647 	bcopy(cp, &gw_addr, sizeof (gw_addr));
3648 	if (ire->ire_gateway_addr == gw_addr) {
3649 		ip1dbg(("ire_delete_cache_gw: deleted 0x%x type %d to 0x%x\n",
3650 		    (int)ntohl(ire->ire_addr), ire->ire_type,
3651 		    (int)ntohl(ire->ire_gateway_addr)));
3652 		ire_delete(ire);
3653 	}
3654 }
3655 
3656 /*
3657  * Remove all IRE_CACHE entries that match the ire specified.
3658  *
3659  * The flag argument indicates if the flush request is due to addition
3660  * of new route (IRE_FLUSH_ADD) or deletion of old route (IRE_FLUSH_DELETE).
3661  *
3662  * This routine takes only the IREs from the forwarding table and flushes
3663  * the corresponding entries from the cache table.
3664  *
3665  * When flushing due to the deletion of an old route, it
3666  * just checks the cache handles (ire_phandle and ire_ihandle) and
3667  * deletes the ones that match.
3668  *
3669  * When flushing due to the creation of a new route, it checks
3670  * if a cache entry's address matches the one in the IRE and
3671  * that the cache entry's parent has a less specific mask than the
3672  * one in IRE. The destination of such a cache entry could be the
3673  * gateway for other cache entries, so we need to flush those as
3674  * well by looking for gateway addresses matching the IRE's address.
3675  */
3676 void
3677 ire_flush_cache_v4(ire_t *ire, int flag)
3678 {
3679 	int i;
3680 	ire_t *cire;
3681 	irb_t *irb;
3682 	ip_stack_t	*ipst = ire->ire_ipst;
3683 
3684 	if (ire->ire_type & IRE_CACHE)
3685 		return;
3686 
3687 	/*
3688 	 * If a default is just created, there is no point
3689 	 * in going through the cache, as there will not be any
3690 	 * cached ires.
3691 	 */
3692 	if (ire->ire_type == IRE_DEFAULT && flag == IRE_FLUSH_ADD)
3693 		return;
3694 	if (flag == IRE_FLUSH_ADD) {
3695 		/*
3696 		 * This selective flush is due to the addition of
3697 		 * new IRE.
3698 		 */
3699 		for (i = 0; i < ipst->ips_ip_cache_table_size; i++) {
3700 			irb = &ipst->ips_ip_cache_table[i];
3701 			if ((cire = irb->irb_ire) == NULL)
3702 				continue;
3703 			IRB_REFHOLD(irb);
3704 			for (cire = irb->irb_ire; cire != NULL;
3705 			    cire = cire->ire_next) {
3706 				if (cire->ire_type != IRE_CACHE)
3707 					continue;
3708 				/*
3709 				 * If 'cire' belongs to the same subnet
3710 				 * as the new ire being added, and 'cire'
3711 				 * is derived from a prefix that is less
3712 				 * specific than the new ire being added,
3713 				 * we need to flush 'cire'; for instance,
3714 				 * when a new interface comes up.
3715 				 */
3716 				if (((cire->ire_addr & ire->ire_mask) ==
3717 				    (ire->ire_addr & ire->ire_mask)) &&
3718 				    (ip_mask_to_plen(cire->ire_cmask) <=
3719 				    ire->ire_masklen)) {
3720 					ire_delete(cire);
3721 					continue;
3722 				}
3723 				/*
3724 				 * This is the case when the ire_gateway_addr
3725 				 * of 'cire' belongs to the same subnet as
3726 				 * the new ire being added.
3727 				 * Flushing such ires is sometimes required to
3728 				 * avoid misrouting: say we have a machine with
3729 				 * two interfaces (I1 and I2), a default router
3730 				 * R on the I1 subnet, and a host route to an
3731 				 * off-link destination D with a gateway G on
3732 				 * the I2 subnet.
3733 				 * Under normal operation, we will have an
3734 				 * on-link cache entry for G and an off-link
3735 				 * cache entry for D with G as ire_gateway_addr,
3736 				 * traffic to D will reach its destination
3737 				 * through gateway G.
3738 				 * If the administrator does 'ifconfig I2 down',
3739 				 * the cache entries for D and G will be
3740 				 * flushed. However, G will now be resolved as
3741 				 * an off-link destination using R (the default
3742 				 * router) as gateway. Then D will also be
3743 				 * resolved as an off-link destination using G
3744 				 * as gateway - this behavior is due to
3745 				 * compatibility reasons, see comment in
3746 				 * ire_ihandle_lookup_offlink(). Traffic to D
3747 				 * will go to the router R and probably won't
3748 				 * reach the destination.
3749 				 * The administrator then does 'ifconfig I2 up'.
3750 				 * Since G is on the I2 subnet, this routine
3751 				 * will flush its cache entry. It must also
3752 				 * flush the cache entry for D, otherwise
3753 				 * traffic will stay misrouted until the IRE
3754 				 * times out.
3755 				 */
3756 				if ((cire->ire_gateway_addr & ire->ire_mask) ==
3757 				    (ire->ire_addr & ire->ire_mask)) {
3758 					ire_delete(cire);
3759 					continue;
3760 				}
3761 			}
3762 			IRB_REFRELE(irb);
3763 		}
3764 	} else {
3765 		/*
3766 		 * delete the cache entries based on
3767 		 * handle in the IRE as this IRE is
3768 		 * being deleted/changed.
3769 		 */
3770 		for (i = 0; i < ipst->ips_ip_cache_table_size; i++) {
3771 			irb = &ipst->ips_ip_cache_table[i];
3772 			if ((cire = irb->irb_ire) == NULL)
3773 				continue;
3774 			IRB_REFHOLD(irb);
3775 			for (cire = irb->irb_ire; cire != NULL;
3776 			    cire = cire->ire_next) {
3777 				if (cire->ire_type != IRE_CACHE)
3778 					continue;
3779 				if ((cire->ire_phandle == 0 ||
3780 				    cire->ire_phandle != ire->ire_phandle) &&
3781 				    (cire->ire_ihandle == 0 ||
3782 				    cire->ire_ihandle != ire->ire_ihandle))
3783 					continue;
3784 				ire_delete(cire);
3785 			}
3786 			IRB_REFRELE(irb);
3787 		}
3788 	}
3789 }
3790 
3791 /*
3792  * Matches the arguments passed with the values in the ire.
3793  *
3794  * Note: for match types that match using "ipif" passed in, ipif
3795  * must be checked for non-NULL before calling this routine.
3796  */
3797 boolean_t
3798 ire_match_args(ire_t *ire, ipaddr_t addr, ipaddr_t mask, ipaddr_t gateway,
3799     int type, const ipif_t *ipif, zoneid_t zoneid, uint32_t ihandle,
3800     const ts_label_t *tsl, int match_flags, queue_t *wq)
3801 {
3802 	ill_t *ire_ill = NULL, *dst_ill;
3803 	ill_t *ipif_ill = NULL;
3804 
3805 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
3806 	ASSERT((ire->ire_addr & ~ire->ire_mask) == 0);
3807 	ASSERT((!(match_flags & MATCH_IRE_ILL)) ||
3808 	    (ipif != NULL && !ipif->ipif_isv6));
3809 	ASSERT(!(match_flags & MATCH_IRE_WQ) || wq != NULL);
3810 
3811 	/*
3812 	 * If MATCH_IRE_MARK_TESTHIDDEN is set, then only return the IRE if it
3813 	 * is in fact hidden, to ensure the caller gets the right one.  One
3814 	 * exception: if the caller passed MATCH_IRE_IHANDLE, then they
3815 	 * already know the identity of the given IRE_INTERFACE entry and
3816 	 * there's no point trying to hide it from them.
3817 	 */
3818 	if (ire->ire_marks & IRE_MARK_TESTHIDDEN) {
3819 		if (match_flags & MATCH_IRE_IHANDLE)
3820 			match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
3821 
3822 		if (!(match_flags & MATCH_IRE_MARK_TESTHIDDEN))
3823 			return (B_FALSE);
3824 	}
3825 
3826 	/*
3827 	 * MATCH_IRE_MARK_PRIVATE_ADDR is set when IP_NEXTHOP option
3828 	 * is used. In that case the routing table is bypassed and the
3829 	 * packets are sent directly to the specified nexthop. The
3830 	 * IRE_CACHE entry representing this route should be marked
3831 	 * with IRE_MARK_PRIVATE_ADDR.
3832 	 */
3833 
3834 	if (!(match_flags & MATCH_IRE_MARK_PRIVATE_ADDR) &&
3835 	    (ire->ire_marks & IRE_MARK_PRIVATE_ADDR))
3836 		return (B_FALSE);
3837 
3838 	if (zoneid != ALL_ZONES && zoneid != ire->ire_zoneid &&
3839 	    ire->ire_zoneid != ALL_ZONES) {
3840 		/*
3841 		 * If MATCH_IRE_ZONEONLY has been set and the supplied zoneid is
3842 		 * valid and does not match that of ire_zoneid, a failure to
3843 		 * match is reported at this point. Otherwise, since some IREs
3844 		 * that are available in the global zone can be used in local
3845 		 * zones, additional checks need to be performed:
3846 		 *
3847 		 *	IRE_BROADCAST, IRE_CACHE and IRE_LOOPBACK
3848 		 *	entries should never be matched in this situation.
3849 		 *
3850 		 *	IRE entries that have an interface associated with them
3851 		 *	should in general not match unless they are an IRE_LOCAL
3852 		 *	or in the case when MATCH_IRE_DEFAULT has been set in
3853 		 *	the caller.  In the case of the former, checking of the
3854 		 *	other fields supplied should take place.
3855 		 *
3856 		 *	In the case where MATCH_IRE_DEFAULT has been set,
3857 		 *	all of the ipif's associated with the IRE's ill are
3858 		 *	checked to see if there is a matching zoneid.  If any
3859 		 *	one ipif has a matching zoneid, this IRE is a
3860 		 *	potential candidate so checking of the other fields
3861 		 *	takes place.
3862 		 *
3863 		 *	In the case where the IRE_INTERFACE has a usable source
3864 		 *	address (indicated by ill_usesrc_ifindex) in the
3865 		 *	correct zone then it's permitted to return this IRE
3866 		 */
3867 		if (match_flags & MATCH_IRE_ZONEONLY)
3868 			return (B_FALSE);
3869 		if (ire->ire_type & (IRE_BROADCAST | IRE_CACHE | IRE_LOOPBACK))
3870 			return (B_FALSE);
3871 		/*
3872 		 * Note, IRE_INTERFACE can have the stq as NULL. For
3873 		 * example, if the default multicast route is tied to
3874 		 * the loopback address.
3875 		 */
3876 		if ((ire->ire_type & IRE_INTERFACE) &&
3877 		    (ire->ire_stq != NULL)) {
3878 			dst_ill = (ill_t *)ire->ire_stq->q_ptr;
3879 			/*
3880 			 * If there is a usable source address in the
3881 			 * zone, then it's ok to return an
3882 			 * IRE_INTERFACE
3883 			 */
3884 			if (ipif_usesrc_avail(dst_ill, zoneid)) {
3885 				ip3dbg(("ire_match_args: dst_ill %p match %d\n",
3886 				    (void *)dst_ill,
3887 				    (ire->ire_addr == (addr & mask))));
3888 			} else {
3889 				ip3dbg(("ire_match_args: src_ipif NULL"
3890 				    " dst_ill %p\n", (void *)dst_ill));
3891 				return (B_FALSE);
3892 			}
3893 		}
3894 		if (ire->ire_ipif != NULL && ire->ire_type != IRE_LOCAL &&
3895 		    !(ire->ire_type & IRE_INTERFACE)) {
3896 			ipif_t	*tipif;
3897 
3898 			if ((match_flags & MATCH_IRE_DEFAULT) == 0) {
3899 				return (B_FALSE);
3900 			}
3901 			mutex_enter(&ire->ire_ipif->ipif_ill->ill_lock);
3902 			for (tipif = ire->ire_ipif->ipif_ill->ill_ipif;
3903 			    tipif != NULL; tipif = tipif->ipif_next) {
3904 				if (IPIF_CAN_LOOKUP(tipif) &&
3905 				    (tipif->ipif_flags & IPIF_UP) &&
3906 				    (tipif->ipif_zoneid == zoneid ||
3907 				    tipif->ipif_zoneid == ALL_ZONES))
3908 					break;
3909 			}
3910 			mutex_exit(&ire->ire_ipif->ipif_ill->ill_lock);
3911 			if (tipif == NULL) {
3912 				return (B_FALSE);
3913 			}
3914 		}
3915 	}
3916 
3917 	/*
3918 	 * For IRE_CACHE entries, MATCH_IRE_ILL means that somebody wants to
3919 	 * send out ire_stq (ire_ipif for IRE_CACHE entries is just the means
3920 	 * of getting a source address -- i.e., ire_src_addr ==
3921 	 * ire->ire_ipif->ipif_src_addr).  ire_to_ill() handles this.
3922 	 *
3923 	 * NOTE: For IPMP, MATCH_IRE_ILL usually matches any ill in the group.
3924 	 * However, if MATCH_IRE_MARK_TESTHIDDEN is set (i.e., the IRE is for
3925 	 * IPMP test traffic), then the ill must match exactly.
3926 	 */
3927 	if (match_flags & MATCH_IRE_ILL) {
3928 		ire_ill = ire_to_ill(ire);
3929 		ipif_ill = ipif->ipif_ill;
3930 	}
3931 
3932 	if ((ire->ire_addr == (addr & mask)) &&
3933 	    ((!(match_flags & MATCH_IRE_GW)) ||
3934 	    (ire->ire_gateway_addr == gateway)) &&
3935 	    ((!(match_flags & MATCH_IRE_TYPE)) ||
3936 	    (ire->ire_type & type)) &&
3937 	    ((!(match_flags & MATCH_IRE_SRC)) ||
3938 	    (ire->ire_src_addr == ipif->ipif_src_addr)) &&
3939 	    ((!(match_flags & MATCH_IRE_IPIF)) ||
3940 	    (ire->ire_ipif == ipif)) &&
3941 	    ((!(match_flags & MATCH_IRE_MARK_TESTHIDDEN)) ||
3942 	    (ire->ire_marks & IRE_MARK_TESTHIDDEN)) &&
3943 	    ((!(match_flags & MATCH_IRE_MARK_PRIVATE_ADDR)) ||
3944 	    (ire->ire_type != IRE_CACHE ||
3945 	    ire->ire_marks & IRE_MARK_PRIVATE_ADDR)) &&
3946 	    ((!(match_flags & MATCH_IRE_WQ)) ||
3947 	    (ire->ire_stq == wq)) &&
3948 	    ((!(match_flags & MATCH_IRE_ILL)) ||
3949 	    (ire_ill == ipif_ill ||
3950 	    (!(match_flags & MATCH_IRE_MARK_TESTHIDDEN) &&
3951 	    ire_ill != NULL && IS_IN_SAME_ILLGRP(ipif_ill, ire_ill)))) &&
3952 	    ((!(match_flags & MATCH_IRE_IHANDLE)) ||
3953 	    (ire->ire_ihandle == ihandle)) &&
3954 	    ((!(match_flags & MATCH_IRE_MASK)) ||
3955 	    (ire->ire_mask == mask)) &&
3956 	    ((!(match_flags & MATCH_IRE_SECATTR)) ||
3957 	    (!is_system_labeled()) ||
3958 	    (tsol_ire_match_gwattr(ire, tsl) == 0))) {
3959 		/* We found the matched IRE */
3960 		return (B_TRUE);
3961 	}
3962 	return (B_FALSE);
3963 }
3964 
3965 /*
3966  * Lookup for a route in all the tables
3967  */
3968 ire_t *
3969 ire_route_lookup(ipaddr_t addr, ipaddr_t mask, ipaddr_t gateway,
3970     int type, const ipif_t *ipif, ire_t **pire, zoneid_t zoneid,
3971     const ts_label_t *tsl, int flags, ip_stack_t *ipst)
3972 {
3973 	ire_t *ire = NULL;
3974 
3975 	/*
3976 	 * ire_match_args() will dereference ipif MATCH_IRE_SRC or
3977 	 * MATCH_IRE_ILL is set.
3978 	 */
3979 	if ((flags & (MATCH_IRE_SRC | MATCH_IRE_ILL)) && (ipif == NULL))
3980 		return (NULL);
3981 
3982 	/*
3983 	 * might be asking for a cache lookup,
3984 	 * This is not best way to lookup cache,
3985 	 * user should call ire_cache_lookup directly.
3986 	 *
3987 	 * If MATCH_IRE_TYPE was set, first lookup in the cache table and then
3988 	 * in the forwarding table, if the applicable type flags were set.
3989 	 */
3990 	if ((flags & MATCH_IRE_TYPE) == 0 || (type & IRE_CACHETABLE) != 0) {
3991 		ire = ire_ctable_lookup(addr, gateway, type, ipif, zoneid,
3992 		    tsl, flags, ipst);
3993 		if (ire != NULL)
3994 			return (ire);
3995 	}
3996 	if ((flags & MATCH_IRE_TYPE) == 0 || (type & IRE_FORWARDTABLE) != 0) {
3997 		ire = ire_ftable_lookup(addr, mask, gateway, type, ipif, pire,
3998 		    zoneid, 0, tsl, flags, ipst);
3999 	}
4000 	return (ire);
4001 }
4002 
4003 /*
4004  * Delete the IRE cache for the gateway and all IRE caches whose
4005  * ire_gateway_addr points to this gateway, and allow them to
4006  * be created on demand by ip_newroute.
4007  */
4008 void
4009 ire_clookup_delete_cache_gw(ipaddr_t addr, zoneid_t zoneid, ip_stack_t *ipst)
4010 {
4011 	irb_t *irb;
4012 	ire_t *ire;
4013 
4014 	irb = &ipst->ips_ip_cache_table[IRE_ADDR_HASH(addr,
4015 	    ipst->ips_ip_cache_table_size)];
4016 	IRB_REFHOLD(irb);
4017 	for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
4018 		if (ire->ire_marks & IRE_MARK_CONDEMNED)
4019 			continue;
4020 
4021 		ASSERT(ire->ire_mask == IP_HOST_MASK);
4022 		if (ire_match_args(ire, addr, ire->ire_mask, 0, IRE_CACHE,
4023 		    NULL, zoneid, 0, NULL, MATCH_IRE_TYPE, NULL)) {
4024 			ire_delete(ire);
4025 		}
4026 	}
4027 	IRB_REFRELE(irb);
4028 
4029 	ire_walk_v4(ire_delete_cache_gw, &addr, zoneid, ipst);
4030 }
4031 
4032 /*
4033  * Looks up cache table for a route.
4034  * specific lookup can be indicated by
4035  * passing the MATCH_* flags and the
4036  * necessary parameters.
4037  */
4038 ire_t *
4039 ire_ctable_lookup(ipaddr_t addr, ipaddr_t gateway, int type, const ipif_t *ipif,
4040     zoneid_t zoneid, const ts_label_t *tsl, int flags, ip_stack_t *ipst)
4041 {
4042 	ire_ctable_args_t	margs;
4043 
4044 	margs.ict_addr = &addr;
4045 	margs.ict_gateway = &gateway;
4046 	margs.ict_type = type;
4047 	margs.ict_ipif = ipif;
4048 	margs.ict_zoneid = zoneid;
4049 	margs.ict_tsl = tsl;
4050 	margs.ict_flags = flags;
4051 	margs.ict_ipst = ipst;
4052 	margs.ict_wq = NULL;
4053 
4054 	return (ip4_ctable_lookup_impl(&margs));
4055 }
4056 
4057 /*
4058  * Check whether the IRE_LOCAL and the IRE potentially used to transmit
4059  * (could be an IRE_CACHE, IRE_BROADCAST, or IRE_INTERFACE) are identical
4060  * or part of the same illgrp.  (In the IPMP case, usually the two IREs
4061  * will both belong to the IPMP ill, but exceptions are possible -- e.g.
4062  * if IPMP test addresses are on their own subnet.)
4063  */
4064 boolean_t
4065 ire_local_same_lan(ire_t *ire_local, ire_t *xmit_ire)
4066 {
4067 	ill_t *recv_ill, *xmit_ill;
4068 
4069 	ASSERT(ire_local->ire_type & (IRE_LOCAL|IRE_LOOPBACK));
4070 	ASSERT(xmit_ire->ire_type & (IRE_CACHETABLE|IRE_INTERFACE));
4071 
4072 	recv_ill = ire_to_ill(ire_local);
4073 	xmit_ill = ire_to_ill(xmit_ire);
4074 
4075 	ASSERT(recv_ill != NULL);
4076 	ASSERT(xmit_ill != NULL);
4077 
4078 	return (IS_ON_SAME_LAN(recv_ill, xmit_ill));
4079 }
4080 
4081 /*
4082  * Check if the IRE_LOCAL uses the same ill as another route would use.
4083  * If there is no alternate route, or the alternate is a REJECT or BLACKHOLE,
4084  * then we don't allow this IRE_LOCAL to be used.
4085  */
4086 boolean_t
4087 ire_local_ok_across_zones(ire_t *ire_local, zoneid_t zoneid, void *addr,
4088     const ts_label_t *tsl, ip_stack_t *ipst)
4089 {
4090 	ire_t		*alt_ire;
4091 	boolean_t	rval;
4092 	int		flags;
4093 
4094 	flags = MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE;
4095 
4096 	if (ire_local->ire_ipversion == IPV4_VERSION) {
4097 		alt_ire = ire_ftable_lookup(*((ipaddr_t *)addr), 0, 0, 0, NULL,
4098 		    NULL, zoneid, 0, tsl, flags, ipst);
4099 	} else {
4100 		alt_ire = ire_ftable_lookup_v6(addr, NULL, NULL, 0, NULL,
4101 		    NULL, zoneid, 0, tsl, flags, ipst);
4102 	}
4103 
4104 	if (alt_ire == NULL)
4105 		return (B_FALSE);
4106 
4107 	if (alt_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4108 		ire_refrele(alt_ire);
4109 		return (B_FALSE);
4110 	}
4111 	rval = ire_local_same_lan(ire_local, alt_ire);
4112 
4113 	ire_refrele(alt_ire);
4114 	return (rval);
4115 }
4116 
4117 /*
4118  * Lookup cache
4119  *
4120  * In general the zoneid has to match (where ALL_ZONES match all of them).
4121  * But for IRE_LOCAL we also need to handle the case where L2 should
4122  * conceptually loop back the packet. This is necessary since neither
4123  * Ethernet drivers nor Ethernet hardware loops back packets sent to their
4124  * own MAC address. This loopback is needed when the normal
4125  * routes (ignoring IREs with different zoneids) would send out the packet on
4126  * the same ill as the ill with which this IRE_LOCAL is associated.
4127  *
4128  * Earlier versions of this code always matched an IRE_LOCAL independently of
4129  * the zoneid. We preserve that earlier behavior when
4130  * ip_restrict_interzone_loopback is turned off.
4131  */
4132 ire_t *
4133 ire_cache_lookup(ipaddr_t addr, zoneid_t zoneid, const ts_label_t *tsl,
4134     ip_stack_t *ipst)
4135 {
4136 	irb_t *irb_ptr;
4137 	ire_t *ire;
4138 
4139 	irb_ptr = &ipst->ips_ip_cache_table[IRE_ADDR_HASH(addr,
4140 	    ipst->ips_ip_cache_table_size)];
4141 	rw_enter(&irb_ptr->irb_lock, RW_READER);
4142 	for (ire = irb_ptr->irb_ire; ire != NULL; ire = ire->ire_next) {
4143 		if (ire->ire_marks & (IRE_MARK_CONDEMNED |
4144 		    IRE_MARK_TESTHIDDEN | IRE_MARK_PRIVATE_ADDR)) {
4145 			continue;
4146 		}
4147 		if (ire->ire_addr == addr) {
4148 			/*
4149 			 * Finally, check if the security policy has any
4150 			 * restriction on using this route for the specified
4151 			 * message.
4152 			 */
4153 			if (tsl != NULL &&
4154 			    ire->ire_gw_secattr != NULL &&
4155 			    tsol_ire_match_gwattr(ire, tsl) != 0) {
4156 				continue;
4157 			}
4158 
4159 			if (zoneid == ALL_ZONES || ire->ire_zoneid == zoneid ||
4160 			    ire->ire_zoneid == ALL_ZONES) {
4161 				IRE_REFHOLD(ire);
4162 				rw_exit(&irb_ptr->irb_lock);
4163 				return (ire);
4164 			}
4165 
4166 			if (ire->ire_type == IRE_LOCAL) {
4167 				if (ipst->ips_ip_restrict_interzone_loopback &&
4168 				    !ire_local_ok_across_zones(ire, zoneid,
4169 				    &addr, tsl, ipst))
4170 					continue;
4171 
4172 				IRE_REFHOLD(ire);
4173 				rw_exit(&irb_ptr->irb_lock);
4174 				return (ire);
4175 			}
4176 		}
4177 	}
4178 	rw_exit(&irb_ptr->irb_lock);
4179 	return (NULL);
4180 }
4181 
4182 ire_t *
4183 ire_cache_lookup_simple(ipaddr_t dst, ip_stack_t *ipst)
4184 {
4185 	irb_t *irb_ptr;
4186 	ire_t *ire;
4187 
4188 	/*
4189 	 * Look for an ire in the cachetable whose
4190 	 * ire_addr matches the destination.
4191 	 * Since we are being called by forwarding fastpath
4192 	 * no need to check for Trusted Solaris label.
4193 	 */
4194 	irb_ptr = &ipst->ips_ip_cache_table[IRE_ADDR_HASH(
4195 	    dst, ipst->ips_ip_cache_table_size)];
4196 	rw_enter(&irb_ptr->irb_lock, RW_READER);
4197 	for (ire = irb_ptr->irb_ire; ire != NULL; ire = ire->ire_next) {
4198 		if (ire->ire_marks & (IRE_MARK_CONDEMNED | IRE_MARK_TESTHIDDEN |
4199 		    IRE_MARK_PRIVATE_ADDR)) {
4200 			continue;
4201 		}
4202 		if (ire->ire_addr == dst) {
4203 			IRE_REFHOLD(ire);
4204 			rw_exit(&irb_ptr->irb_lock);
4205 			return (ire);
4206 		}
4207 	}
4208 	rw_exit(&irb_ptr->irb_lock);
4209 	return (NULL);
4210 }
4211 
4212 /*
4213  * Locate the interface ire that is tied to the cache ire 'cire' via
4214  * cire->ire_ihandle.
4215  *
4216  * We are trying to create the cache ire for an offlink destn based
4217  * on the cache ire of the gateway in 'cire'. 'pire' is the prefix ire
4218  * as found by ip_newroute(). We are called from ip_newroute() in
4219  * the IRE_CACHE case.
4220  */
4221 ire_t *
4222 ire_ihandle_lookup_offlink(ire_t *cire, ire_t *pire)
4223 {
4224 	ire_t	*ire;
4225 	int	match_flags;
4226 	ipaddr_t gw_addr;
4227 	ipif_t	*gw_ipif;
4228 	ip_stack_t	*ipst = cire->ire_ipst;
4229 
4230 	ASSERT(cire != NULL && pire != NULL);
4231 
4232 	/*
4233 	 * We don't need to specify the zoneid to ire_ftable_lookup() below
4234 	 * because the ihandle refers to an ipif which can be in only one zone.
4235 	 */
4236 	match_flags =  MATCH_IRE_TYPE | MATCH_IRE_IHANDLE | MATCH_IRE_MASK;
4237 	if (pire->ire_ipif != NULL)
4238 		match_flags |= MATCH_IRE_ILL;
4239 	/*
4240 	 * We know that the mask of the interface ire equals cire->ire_cmask.
4241 	 * (When ip_newroute() created 'cire' for the gateway it set its
4242 	 * cmask from the interface ire's mask)
4243 	 */
4244 	ire = ire_ftable_lookup(cire->ire_addr, cire->ire_cmask, 0,
4245 	    IRE_INTERFACE, pire->ire_ipif, NULL, ALL_ZONES, cire->ire_ihandle,
4246 	    NULL, match_flags, ipst);
4247 	if (ire != NULL)
4248 		return (ire);
4249 	/*
4250 	 * If we didn't find an interface ire above, we can't declare failure.
4251 	 * For backwards compatibility, we need to support prefix routes
4252 	 * pointing to next hop gateways that are not on-link.
4253 	 *
4254 	 * Assume we are trying to ping some offlink destn, and we have the
4255 	 * routing table below.
4256 	 *
4257 	 * Eg.	default	- gw1		<--- pire	(line 1)
4258 	 *	gw1	- gw2				(line 2)
4259 	 *	gw2	- hme0				(line 3)
4260 	 *
4261 	 * If we already have a cache ire for gw1 in 'cire', the
4262 	 * ire_ftable_lookup above would have failed, since there is no
4263 	 * interface ire to reach gw1. We will fallthru below.
4264 	 *
4265 	 * Here we duplicate the steps that ire_ftable_lookup() did in
4266 	 * getting 'cire' from 'pire', in the MATCH_IRE_RECURSIVE case.
4267 	 * The differences are the following
4268 	 * i.   We want the interface ire only, so we call ire_ftable_lookup()
4269 	 *	instead of ire_route_lookup()
4270 	 * ii.  We look for only prefix routes in the 1st call below.
4271 	 * ii.  We want to match on the ihandle in the 2nd call below.
4272 	 */
4273 	match_flags =  MATCH_IRE_TYPE;
4274 	if (pire->ire_ipif != NULL)
4275 		match_flags |= MATCH_IRE_ILL;
4276 	ire = ire_ftable_lookup(pire->ire_gateway_addr, 0, 0, IRE_OFFSUBNET,
4277 	    pire->ire_ipif, NULL, ALL_ZONES, 0, NULL, match_flags, ipst);
4278 	if (ire == NULL)
4279 		return (NULL);
4280 	/*
4281 	 * At this point 'ire' corresponds to the entry shown in line 2.
4282 	 * gw_addr is 'gw2' in the example above.
4283 	 */
4284 	gw_addr = ire->ire_gateway_addr;
4285 	gw_ipif = ire->ire_ipif;
4286 	ire_refrele(ire);
4287 
4288 	match_flags |= MATCH_IRE_IHANDLE;
4289 	ire = ire_ftable_lookup(gw_addr, 0, 0, IRE_INTERFACE,
4290 	    gw_ipif, NULL, ALL_ZONES, cire->ire_ihandle, NULL, match_flags,
4291 	    ipst);
4292 	return (ire);
4293 }
4294 
4295 /*
4296  * Return the IRE_LOOPBACK, IRE_IF_RESOLVER or IRE_IF_NORESOLVER
4297  * ire associated with the specified ipif.
4298  *
4299  * This might occasionally be called when IPIF_UP is not set since
4300  * the IP_MULTICAST_IF as well as creating interface routes
4301  * allows specifying a down ipif (ipif_lookup* match ipifs that are down).
4302  *
4303  * Note that if IPIF_NOLOCAL, IPIF_NOXMIT, or IPIF_DEPRECATED is set on
4304  * the ipif, this routine might return NULL.
4305  */
4306 ire_t *
4307 ipif_to_ire(const ipif_t *ipif)
4308 {
4309 	ire_t	*ire;
4310 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
4311 	uint_t	match_flags = MATCH_IRE_TYPE | MATCH_IRE_IPIF | MATCH_IRE_MASK;
4312 
4313 	/*
4314 	 * IRE_INTERFACE entries for ills under IPMP are IRE_MARK_TESTHIDDEN
4315 	 * so that they aren't accidentally returned.  However, if the
4316 	 * caller's ipif is on an ill under IPMP, there's no need to hide 'em.
4317 	 */
4318 	if (IS_UNDER_IPMP(ipif->ipif_ill))
4319 		match_flags |= MATCH_IRE_MARK_TESTHIDDEN;
4320 
4321 	ASSERT(!ipif->ipif_isv6);
4322 	if (ipif->ipif_ire_type == IRE_LOOPBACK) {
4323 		ire = ire_ctable_lookup(ipif->ipif_lcl_addr, 0, IRE_LOOPBACK,
4324 		    ipif, ALL_ZONES, NULL, (MATCH_IRE_TYPE | MATCH_IRE_IPIF),
4325 		    ipst);
4326 	} else if (ipif->ipif_flags & IPIF_POINTOPOINT) {
4327 		/* In this case we need to lookup destination address. */
4328 		ire = ire_ftable_lookup(ipif->ipif_pp_dst_addr, IP_HOST_MASK, 0,
4329 		    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0, NULL, match_flags,
4330 		    ipst);
4331 	} else {
4332 		ire = ire_ftable_lookup(ipif->ipif_subnet,
4333 		    ipif->ipif_net_mask, 0, IRE_INTERFACE, ipif, NULL,
4334 		    ALL_ZONES, 0, NULL, match_flags, ipst);
4335 	}
4336 	return (ire);
4337 }
4338 
4339 /*
4340  * ire_walk function.
4341  * Count the number of IRE_CACHE entries in different categories.
4342  */
4343 void
4344 ire_cache_count(ire_t *ire, char *arg)
4345 {
4346 	ire_cache_count_t *icc = (ire_cache_count_t *)arg;
4347 
4348 	if (ire->ire_type != IRE_CACHE)
4349 		return;
4350 
4351 	icc->icc_total++;
4352 
4353 	if (ire->ire_ipversion == IPV6_VERSION) {
4354 		mutex_enter(&ire->ire_lock);
4355 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6)) {
4356 			mutex_exit(&ire->ire_lock);
4357 			icc->icc_onlink++;
4358 			return;
4359 		}
4360 		mutex_exit(&ire->ire_lock);
4361 	} else {
4362 		if (ire->ire_gateway_addr == 0) {
4363 			icc->icc_onlink++;
4364 			return;
4365 		}
4366 	}
4367 
4368 	ASSERT(ire->ire_ipif != NULL);
4369 	if (ire->ire_max_frag < ire->ire_ipif->ipif_mtu)
4370 		icc->icc_pmtu++;
4371 	else if (ire->ire_tire_mark != ire->ire_ob_pkt_count +
4372 	    ire->ire_ib_pkt_count)
4373 		icc->icc_offlink++;
4374 	else
4375 		icc->icc_unused++;
4376 }
4377 
4378 /*
4379  * ire_walk function called by ip_trash_ire_reclaim().
4380  * Free a fraction of the IRE_CACHE cache entries. The fractions are
4381  * different for different categories of IRE_CACHE entries.
4382  * A fraction of zero means to not free any in that category.
4383  * Use the hash bucket id plus lbolt as a random number. Thus if the fraction
4384  * is N then every Nth hash bucket chain will be freed.
4385  */
4386 void
4387 ire_cache_reclaim(ire_t *ire, char *arg)
4388 {
4389 	ire_cache_reclaim_t *icr = (ire_cache_reclaim_t *)arg;
4390 	uint_t rand;
4391 	ip_stack_t	*ipst = icr->icr_ipst;
4392 
4393 	if (ire->ire_type != IRE_CACHE)
4394 		return;
4395 
4396 	if (ire->ire_ipversion == IPV6_VERSION) {
4397 		rand = (uint_t)lbolt +
4398 		    IRE_ADDR_HASH_V6(ire->ire_addr_v6,
4399 		    ipst->ips_ip6_cache_table_size);
4400 		mutex_enter(&ire->ire_lock);
4401 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6)) {
4402 			mutex_exit(&ire->ire_lock);
4403 			if (icr->icr_onlink != 0 &&
4404 			    (rand/icr->icr_onlink)*icr->icr_onlink == rand) {
4405 				ire_delete(ire);
4406 				return;
4407 			}
4408 			goto done;
4409 		}
4410 		mutex_exit(&ire->ire_lock);
4411 	} else {
4412 		rand = (uint_t)lbolt +
4413 		    IRE_ADDR_HASH(ire->ire_addr, ipst->ips_ip_cache_table_size);
4414 		if (ire->ire_gateway_addr == 0) {
4415 			if (icr->icr_onlink != 0 &&
4416 			    (rand/icr->icr_onlink)*icr->icr_onlink == rand) {
4417 				ire_delete(ire);
4418 				return;
4419 			}
4420 			goto done;
4421 		}
4422 	}
4423 	/* Not onlink IRE */
4424 	ASSERT(ire->ire_ipif != NULL);
4425 	if (ire->ire_max_frag < ire->ire_ipif->ipif_mtu) {
4426 		/* Use ptmu fraction */
4427 		if (icr->icr_pmtu != 0 &&
4428 		    (rand/icr->icr_pmtu)*icr->icr_pmtu == rand) {
4429 			ire_delete(ire);
4430 			return;
4431 		}
4432 	} else if (ire->ire_tire_mark != ire->ire_ob_pkt_count +
4433 	    ire->ire_ib_pkt_count) {
4434 		/* Use offlink fraction */
4435 		if (icr->icr_offlink != 0 &&
4436 		    (rand/icr->icr_offlink)*icr->icr_offlink == rand) {
4437 			ire_delete(ire);
4438 			return;
4439 		}
4440 	} else {
4441 		/* Use unused fraction */
4442 		if (icr->icr_unused != 0 &&
4443 		    (rand/icr->icr_unused)*icr->icr_unused == rand) {
4444 			ire_delete(ire);
4445 			return;
4446 		}
4447 	}
4448 done:
4449 	/*
4450 	 * Update tire_mark so that those that haven't been used since this
4451 	 * reclaim will be considered unused next time we reclaim.
4452 	 */
4453 	ire->ire_tire_mark = ire->ire_ob_pkt_count + ire->ire_ib_pkt_count;
4454 }
4455 
4456 static void
4457 power2_roundup(uint32_t *value)
4458 {
4459 	int i;
4460 
4461 	for (i = 1; i < 31; i++) {
4462 		if (*value <= (1 << i))
4463 			break;
4464 	}
4465 	*value = (1 << i);
4466 }
4467 
4468 /* Global init for all zones */
4469 void
4470 ip_ire_g_init()
4471 {
4472 	/*
4473 	 * Create ire caches, ire_reclaim()
4474 	 * will give IRE_CACHE back to system when needed.
4475 	 * This needs to be done here before anything else, since
4476 	 * ire_add() expects the cache to be created.
4477 	 */
4478 	ire_cache = kmem_cache_create("ire_cache",
4479 	    sizeof (ire_t), 0, ip_ire_constructor,
4480 	    ip_ire_destructor, ip_trash_ire_reclaim, NULL, NULL, 0);
4481 
4482 	rt_entry_cache = kmem_cache_create("rt_entry",
4483 	    sizeof (struct rt_entry), 0, NULL, NULL, NULL, NULL, NULL, 0);
4484 
4485 	/*
4486 	 * Have radix code setup kmem caches etc.
4487 	 */
4488 	rn_init();
4489 }
4490 
4491 void
4492 ip_ire_init(ip_stack_t *ipst)
4493 {
4494 	int i;
4495 	uint32_t mem_cnt;
4496 	uint32_t cpu_cnt;
4497 	uint32_t min_cnt;
4498 	pgcnt_t mem_avail;
4499 
4500 	/*
4501 	 * ip_ire_max_bucket_cnt is sized below based on the memory
4502 	 * size and the cpu speed of the machine. This is upper
4503 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
4504 	 * and is lower bounded by the compile time value of
4505 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
4506 	 * ip6_ire_max_bucket_cnt.
4507 	 *
4508 	 * We calculate this for each IP Instances in order to use
4509 	 * the kmem_avail and ip_ire_{min,max}_bucket_cnt that are
4510 	 * in effect when the zone is booted.
4511 	 */
4512 	mem_avail = kmem_avail();
4513 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
4514 	    ip_cache_table_size / sizeof (ire_t);
4515 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
4516 
4517 	min_cnt = MIN(cpu_cnt, mem_cnt);
4518 	if (min_cnt < ip_ire_min_bucket_cnt)
4519 		min_cnt = ip_ire_min_bucket_cnt;
4520 	if (ip_ire_max_bucket_cnt > min_cnt) {
4521 		ip_ire_max_bucket_cnt = min_cnt;
4522 	}
4523 
4524 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
4525 	    ip6_cache_table_size / sizeof (ire_t);
4526 	min_cnt = MIN(cpu_cnt, mem_cnt);
4527 	if (min_cnt < ip6_ire_min_bucket_cnt)
4528 		min_cnt = ip6_ire_min_bucket_cnt;
4529 	if (ip6_ire_max_bucket_cnt > min_cnt) {
4530 		ip6_ire_max_bucket_cnt = min_cnt;
4531 	}
4532 
4533 	mutex_init(&ipst->ips_ire_ft_init_lock, NULL, MUTEX_DEFAULT, 0);
4534 	mutex_init(&ipst->ips_ire_handle_lock, NULL, MUTEX_DEFAULT, NULL);
4535 
4536 	(void) rn_inithead((void **)&ipst->ips_ip_ftable, 32);
4537 
4538 	/* Calculate the IPv4 cache table size. */
4539 	ipst->ips_ip_cache_table_size = MAX(ip_cache_table_size,
4540 	    ((mem_avail >> ip_ire_mem_ratio) / sizeof (ire_t) /
4541 	    ip_ire_max_bucket_cnt));
4542 	if (ipst->ips_ip_cache_table_size > ip_max_cache_table_size)
4543 		ipst->ips_ip_cache_table_size = ip_max_cache_table_size;
4544 	/*
4545 	 * Make sure that the table size is always a power of 2.  The
4546 	 * hash macro IRE_ADDR_HASH() depends on that.
4547 	 */
4548 	power2_roundup(&ipst->ips_ip_cache_table_size);
4549 
4550 	ipst->ips_ip_cache_table = kmem_zalloc(ipst->ips_ip_cache_table_size *
4551 	    sizeof (irb_t), KM_SLEEP);
4552 
4553 	for (i = 0; i < ipst->ips_ip_cache_table_size; i++) {
4554 		rw_init(&ipst->ips_ip_cache_table[i].irb_lock, NULL,
4555 		    RW_DEFAULT, NULL);
4556 	}
4557 
4558 	/* Calculate the IPv6 cache table size. */
4559 	ipst->ips_ip6_cache_table_size = MAX(ip6_cache_table_size,
4560 	    ((mem_avail >> ip_ire_mem_ratio) / sizeof (ire_t) /
4561 	    ip6_ire_max_bucket_cnt));
4562 	if (ipst->ips_ip6_cache_table_size > ip6_max_cache_table_size)
4563 		ipst->ips_ip6_cache_table_size = ip6_max_cache_table_size;
4564 	/*
4565 	 * Make sure that the table size is always a power of 2.  The
4566 	 * hash macro IRE_ADDR_HASH_V6() depends on that.
4567 	 */
4568 	power2_roundup(&ipst->ips_ip6_cache_table_size);
4569 
4570 	ipst->ips_ip_cache_table_v6 = kmem_zalloc(
4571 	    ipst->ips_ip6_cache_table_size * sizeof (irb_t), KM_SLEEP);
4572 
4573 	for (i = 0; i < ipst->ips_ip6_cache_table_size; i++) {
4574 		rw_init(&ipst->ips_ip_cache_table_v6[i].irb_lock, NULL,
4575 		    RW_DEFAULT, NULL);
4576 	}
4577 
4578 	/*
4579 	 * Make sure that the forwarding table size is a power of 2.
4580 	 * The IRE*_ADDR_HASH() macroes depend on that.
4581 	 */
4582 	ipst->ips_ip6_ftable_hash_size = ip6_ftable_hash_size;
4583 	power2_roundup(&ipst->ips_ip6_ftable_hash_size);
4584 
4585 	ipst->ips_ire_handle = 1;
4586 }
4587 
4588 void
4589 ip_ire_g_fini(void)
4590 {
4591 	kmem_cache_destroy(ire_cache);
4592 	kmem_cache_destroy(rt_entry_cache);
4593 
4594 	rn_fini();
4595 }
4596 
4597 void
4598 ip_ire_fini(ip_stack_t *ipst)
4599 {
4600 	int i;
4601 
4602 	/*
4603 	 * Delete all IREs - assumes that the ill/ipifs have
4604 	 * been removed so what remains are just the ftable and IRE_CACHE.
4605 	 */
4606 	ire_walk(ire_delete, NULL, ipst);
4607 
4608 	rn_freehead(ipst->ips_ip_ftable);
4609 	ipst->ips_ip_ftable = NULL;
4610 
4611 	mutex_destroy(&ipst->ips_ire_ft_init_lock);
4612 	mutex_destroy(&ipst->ips_ire_handle_lock);
4613 
4614 	for (i = 0; i < ipst->ips_ip_cache_table_size; i++) {
4615 		ASSERT(ipst->ips_ip_cache_table[i].irb_ire == NULL);
4616 		rw_destroy(&ipst->ips_ip_cache_table[i].irb_lock);
4617 	}
4618 	kmem_free(ipst->ips_ip_cache_table,
4619 	    ipst->ips_ip_cache_table_size * sizeof (irb_t));
4620 	ipst->ips_ip_cache_table = NULL;
4621 
4622 	for (i = 0; i < ipst->ips_ip6_cache_table_size; i++) {
4623 		ASSERT(ipst->ips_ip_cache_table_v6[i].irb_ire == NULL);
4624 		rw_destroy(&ipst->ips_ip_cache_table_v6[i].irb_lock);
4625 	}
4626 	kmem_free(ipst->ips_ip_cache_table_v6,
4627 	    ipst->ips_ip6_cache_table_size * sizeof (irb_t));
4628 	ipst->ips_ip_cache_table_v6 = NULL;
4629 
4630 	for (i = 0; i < IP6_MASK_TABLE_SIZE; i++) {
4631 		irb_t *ptr;
4632 		int j;
4633 
4634 		if ((ptr = ipst->ips_ip_forwarding_table_v6[i]) == NULL)
4635 			continue;
4636 
4637 		for (j = 0; j < ipst->ips_ip6_ftable_hash_size; j++) {
4638 			ASSERT(ptr[j].irb_ire == NULL);
4639 			rw_destroy(&ptr[j].irb_lock);
4640 		}
4641 		mi_free(ptr);
4642 		ipst->ips_ip_forwarding_table_v6[i] = NULL;
4643 	}
4644 }
4645 
4646 /*
4647  * Check if another multirt route resolution is needed.
4648  * B_TRUE is returned is there remain a resolvable route,
4649  * or if no route for that dst is resolved yet.
4650  * B_FALSE is returned if all routes for that dst are resolved
4651  * or if the remaining unresolved routes are actually not
4652  * resolvable.
4653  * This only works in the global zone.
4654  */
4655 boolean_t
4656 ire_multirt_need_resolve(ipaddr_t dst, const ts_label_t *tsl, ip_stack_t *ipst)
4657 {
4658 	ire_t	*first_fire;
4659 	ire_t	*first_cire;
4660 	ire_t	*fire;
4661 	ire_t	*cire;
4662 	irb_t	*firb;
4663 	irb_t	*cirb;
4664 	int	unres_cnt = 0;
4665 	boolean_t resolvable = B_FALSE;
4666 
4667 	/* Retrieve the first IRE_HOST that matches the destination */
4668 	first_fire = ire_ftable_lookup(dst, IP_HOST_MASK, 0, IRE_HOST, NULL,
4669 	    NULL, ALL_ZONES, 0, tsl,
4670 	    MATCH_IRE_MASK | MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
4671 
4672 	/* No route at all */
4673 	if (first_fire == NULL) {
4674 		return (B_TRUE);
4675 	}
4676 
4677 	firb = first_fire->ire_bucket;
4678 	ASSERT(firb != NULL);
4679 
4680 	/* Retrieve the first IRE_CACHE ire for that destination. */
4681 	first_cire = ire_cache_lookup(dst, GLOBAL_ZONEID, tsl, ipst);
4682 
4683 	/* No resolved route. */
4684 	if (first_cire == NULL) {
4685 		ire_refrele(first_fire);
4686 		return (B_TRUE);
4687 	}
4688 
4689 	/*
4690 	 * At least one route is resolved. Here we look through the forward
4691 	 * and cache tables, to compare the number of declared routes
4692 	 * with the number of resolved routes. The search for a resolvable
4693 	 * route is performed only if at least one route remains
4694 	 * unresolved.
4695 	 */
4696 	cirb = first_cire->ire_bucket;
4697 	ASSERT(cirb != NULL);
4698 
4699 	/* Count the number of routes to that dest that are declared. */
4700 	IRB_REFHOLD(firb);
4701 	for (fire = first_fire; fire != NULL; fire = fire->ire_next) {
4702 		if (!(fire->ire_flags & RTF_MULTIRT))
4703 			continue;
4704 		if (fire->ire_addr != dst)
4705 			continue;
4706 		unres_cnt++;
4707 	}
4708 	IRB_REFRELE(firb);
4709 
4710 	/* Then subtract the number of routes to that dst that are resolved */
4711 	IRB_REFHOLD(cirb);
4712 	for (cire = first_cire; cire != NULL; cire = cire->ire_next) {
4713 		if (!(cire->ire_flags & RTF_MULTIRT))
4714 			continue;
4715 		if (cire->ire_addr != dst)
4716 			continue;
4717 		if (cire->ire_marks & (IRE_MARK_CONDEMNED|IRE_MARK_TESTHIDDEN))
4718 			continue;
4719 		unres_cnt--;
4720 	}
4721 	IRB_REFRELE(cirb);
4722 
4723 	/* At least one route is unresolved; search for a resolvable route. */
4724 	if (unres_cnt > 0)
4725 		resolvable = ire_multirt_lookup(&first_cire, &first_fire,
4726 		    MULTIRT_USESTAMP | MULTIRT_CACHEGW, NULL, tsl, ipst);
4727 
4728 	if (first_fire != NULL)
4729 		ire_refrele(first_fire);
4730 
4731 	if (first_cire != NULL)
4732 		ire_refrele(first_cire);
4733 
4734 	return (resolvable);
4735 }
4736 
4737 /*
4738  * Explore a forward_table bucket, starting from fire_arg.
4739  * fire_arg MUST be an IRE_HOST entry.
4740  *
4741  * Return B_TRUE and update *ire_arg and *fire_arg
4742  * if at least one resolvable route is found. *ire_arg
4743  * is the IRE entry for *fire_arg's gateway.
4744  *
4745  * Return B_FALSE otherwise (all routes are resolved or
4746  * the remaining unresolved routes are all unresolvable).
4747  *
4748  * The IRE selection relies on a priority mechanism
4749  * driven by the flags passed in by the caller.
4750  * The caller, such as ip_newroute_ipif(), can get the most
4751  * relevant ire at each stage of a multiple route resolution.
4752  *
4753  * The rules are:
4754  *
4755  * - if MULTIRT_CACHEGW is specified in flags, IRE_CACHETABLE
4756  *   ires are preferred for the gateway. This gives the highest
4757  *   priority to routes that can be resolved without using
4758  *   a resolver.
4759  *
4760  * - if MULTIRT_CACHEGW is not specified, or if MULTIRT_CACHEGW
4761  *   is specified but no IRE_CACHETABLE ire entry for the gateway
4762  *   is found, the following rules apply.
4763  *
4764  * - if MULTIRT_USESTAMP is specified in flags, IRE_INTERFACE
4765  *   ires for the gateway, that have not been tried since
4766  *   a configurable amount of time, are preferred.
4767  *   This applies when a resolver must be invoked for
4768  *   a missing route, but we don't want to use the resolver
4769  *   upon each packet emission. If no such resolver is found,
4770  *   B_FALSE is returned.
4771  *   The MULTIRT_USESTAMP flag can be combined with
4772  *   MULTIRT_CACHEGW.
4773  *
4774  * - if MULTIRT_USESTAMP is not specified in flags, the first
4775  *   unresolved but resolvable route is selected.
4776  *
4777  * - Otherwise, there is no resolvable route, and
4778  *   B_FALSE is returned.
4779  *
4780  * At last, MULTIRT_SETSTAMP can be specified in flags to
4781  * request the timestamp of unresolvable routes to
4782  * be refreshed. This prevents the useless exploration
4783  * of those routes for a while, when MULTIRT_USESTAMP is used.
4784  *
4785  * The argument already_resolved_count is an output variable to track number
4786  * of already resolved multirt routes.
4787  *
4788  * This only works in the global zone.
4789  */
4790 boolean_t
4791 ire_multirt_lookup(ire_t **ire_arg, ire_t **fire_arg, uint32_t flags,
4792     int *already_resolved_count, const ts_label_t *tsl, ip_stack_t *ipst)
4793 {
4794 	clock_t	delta;
4795 	ire_t	*best_fire = NULL;
4796 	ire_t	*best_cire = NULL;
4797 	ire_t	*first_fire;
4798 	ire_t	*first_cire;
4799 	ire_t	*fire;
4800 	ire_t	*cire;
4801 	irb_t	*firb = NULL;
4802 	irb_t	*cirb = NULL;
4803 	ire_t	*gw_ire;
4804 	boolean_t	already_resolved;
4805 	boolean_t	res;
4806 	ipaddr_t	dst;
4807 	ipaddr_t	gw;
4808 
4809 	ip2dbg(("ire_multirt_lookup: *ire_arg %p, *fire_arg %p, flags %04x\n",
4810 	    (void *)*ire_arg, (void *)*fire_arg, flags));
4811 
4812 	ASSERT(ire_arg != NULL);
4813 	ASSERT(fire_arg != NULL);
4814 
4815 	/* Not an IRE_HOST ire; give up. */
4816 	if ((*fire_arg == NULL) || ((*fire_arg)->ire_type != IRE_HOST)) {
4817 		return (B_FALSE);
4818 	}
4819 
4820 	/* This is the first IRE_HOST ire for that destination. */
4821 	first_fire = *fire_arg;
4822 	firb = first_fire->ire_bucket;
4823 	ASSERT(firb != NULL);
4824 
4825 	dst = first_fire->ire_addr;
4826 
4827 	ip2dbg(("ire_multirt_lookup: dst %08x\n", ntohl(dst)));
4828 
4829 	/*
4830 	 * Retrieve the first IRE_CACHE ire for that destination;
4831 	 * if we don't find one, no route for that dest is
4832 	 * resolved yet.
4833 	 */
4834 	first_cire = ire_cache_lookup(dst, GLOBAL_ZONEID, tsl, ipst);
4835 	if (first_cire != NULL) {
4836 		cirb = first_cire->ire_bucket;
4837 	}
4838 
4839 	ip2dbg(("ire_multirt_lookup: first_cire %p\n", (void *)first_cire));
4840 
4841 	/*
4842 	 * Search for a resolvable route, giving the top priority
4843 	 * to routes that can be resolved without any call to the resolver.
4844 	 */
4845 	IRB_REFHOLD(firb);
4846 
4847 	if (!CLASSD(dst)) {
4848 		/*
4849 		 * For all multiroute IRE_HOST ires for that destination,
4850 		 * check if the route via the IRE_HOST's gateway is
4851 		 * resolved yet.
4852 		 */
4853 		for (fire = first_fire; fire != NULL; fire = fire->ire_next) {
4854 
4855 			if (!(fire->ire_flags & RTF_MULTIRT))
4856 				continue;
4857 			if (fire->ire_addr != dst)
4858 				continue;
4859 
4860 			if (fire->ire_gw_secattr != NULL &&
4861 			    tsol_ire_match_gwattr(fire, tsl) != 0) {
4862 				continue;
4863 			}
4864 
4865 			gw = fire->ire_gateway_addr;
4866 
4867 			ip2dbg(("ire_multirt_lookup: fire %p, "
4868 			    "ire_addr %08x, ire_gateway_addr %08x\n",
4869 			    (void *)fire, ntohl(fire->ire_addr), ntohl(gw)));
4870 
4871 			already_resolved = B_FALSE;
4872 
4873 			if (first_cire != NULL) {
4874 				ASSERT(cirb != NULL);
4875 
4876 				IRB_REFHOLD(cirb);
4877 				/*
4878 				 * For all IRE_CACHE ires for that
4879 				 * destination.
4880 				 */
4881 				for (cire = first_cire;
4882 				    cire != NULL;
4883 				    cire = cire->ire_next) {
4884 
4885 					if (!(cire->ire_flags & RTF_MULTIRT))
4886 						continue;
4887 					if (cire->ire_addr != dst)
4888 						continue;
4889 					if (cire->ire_marks &
4890 					    (IRE_MARK_CONDEMNED |
4891 					    IRE_MARK_TESTHIDDEN))
4892 						continue;
4893 
4894 					if (cire->ire_gw_secattr != NULL &&
4895 					    tsol_ire_match_gwattr(cire,
4896 					    tsl) != 0) {
4897 						continue;
4898 					}
4899 
4900 					/*
4901 					 * Check if the IRE_CACHE's gateway
4902 					 * matches the IRE_HOST's gateway.
4903 					 */
4904 					if (cire->ire_gateway_addr == gw) {
4905 						already_resolved = B_TRUE;
4906 						break;
4907 					}
4908 				}
4909 				IRB_REFRELE(cirb);
4910 			}
4911 
4912 			/*
4913 			 * This route is already resolved;
4914 			 * proceed with next one.
4915 			 */
4916 			if (already_resolved) {
4917 				ip2dbg(("ire_multirt_lookup: found cire %p, "
4918 				    "already resolved\n", (void *)cire));
4919 
4920 				if (already_resolved_count != NULL)
4921 					(*already_resolved_count)++;
4922 				continue;
4923 			}
4924 
4925 			/*
4926 			 * The route is unresolved; is it actually
4927 			 * resolvable, i.e. is there a cache or a resolver
4928 			 * for the gateway?
4929 			 */
4930 			gw_ire = ire_route_lookup(gw, 0, 0, 0, NULL, NULL,
4931 			    ALL_ZONES, tsl,
4932 			    MATCH_IRE_RECURSIVE | MATCH_IRE_SECATTR, ipst);
4933 
4934 			ip2dbg(("ire_multirt_lookup: looked up gw_ire %p\n",
4935 			    (void *)gw_ire));
4936 
4937 			/*
4938 			 * If gw_ire is typed IRE_CACHETABLE,
4939 			 * this route can be resolved without any call to the
4940 			 * resolver. If the MULTIRT_CACHEGW flag is set,
4941 			 * give the top priority to this ire and exit the
4942 			 * loop.
4943 			 * This is typically the case when an ARP reply
4944 			 * is processed through ip_wput_nondata().
4945 			 */
4946 			if ((flags & MULTIRT_CACHEGW) &&
4947 			    (gw_ire != NULL) &&
4948 			    (gw_ire->ire_type & IRE_CACHETABLE)) {
4949 				ASSERT(gw_ire->ire_nce == NULL ||
4950 				    gw_ire->ire_nce->nce_state == ND_REACHABLE);
4951 				/*
4952 				 * Release the resolver associated to the
4953 				 * previous candidate best ire, if any.
4954 				 */
4955 				if (best_cire != NULL) {
4956 					ire_refrele(best_cire);
4957 					ASSERT(best_fire != NULL);
4958 				}
4959 
4960 				best_fire = fire;
4961 				best_cire = gw_ire;
4962 
4963 				ip2dbg(("ire_multirt_lookup: found top prio "
4964 				    "best_fire %p, best_cire %p\n",
4965 				    (void *)best_fire, (void *)best_cire));
4966 				break;
4967 			}
4968 
4969 			/*
4970 			 * Compute the time elapsed since our preceding
4971 			 * attempt to  resolve that route.
4972 			 * If the MULTIRT_USESTAMP flag is set, we take that
4973 			 * route into account only if this time interval
4974 			 * exceeds ip_multirt_resolution_interval;
4975 			 * this prevents us from attempting to resolve a
4976 			 * broken route upon each sending of a packet.
4977 			 */
4978 			delta = lbolt - fire->ire_last_used_time;
4979 			delta = TICK_TO_MSEC(delta);
4980 
4981 			res = (boolean_t)((delta >
4982 			    ipst->ips_ip_multirt_resolution_interval) ||
4983 			    (!(flags & MULTIRT_USESTAMP)));
4984 
4985 			ip2dbg(("ire_multirt_lookup: fire %p, delta %lu, "
4986 			    "res %d\n",
4987 			    (void *)fire, delta, res));
4988 
4989 			if (res) {
4990 				/*
4991 				 * We are here if MULTIRT_USESTAMP flag is set
4992 				 * and the resolver for fire's gateway
4993 				 * has not been tried since
4994 				 * ip_multirt_resolution_interval, or if
4995 				 * MULTIRT_USESTAMP is not set but gw_ire did
4996 				 * not fill the conditions for MULTIRT_CACHEGW,
4997 				 * or if neither MULTIRT_USESTAMP nor
4998 				 * MULTIRT_CACHEGW are set.
4999 				 */
5000 				if (gw_ire != NULL) {
5001 					if (best_fire == NULL) {
5002 						ASSERT(best_cire == NULL);
5003 
5004 						best_fire = fire;
5005 						best_cire = gw_ire;
5006 
5007 						ip2dbg(("ire_multirt_lookup:"
5008 						    "found candidate "
5009 						    "best_fire %p, "
5010 						    "best_cire %p\n",
5011 						    (void *)best_fire,
5012 						    (void *)best_cire));
5013 
5014 						/*
5015 						 * If MULTIRT_CACHEGW is not
5016 						 * set, we ignore the top
5017 						 * priority ires that can
5018 						 * be resolved without any
5019 						 * call to the resolver;
5020 						 * In that case, there is
5021 						 * actually no need
5022 						 * to continue the loop.
5023 						 */
5024 						if (!(flags &
5025 						    MULTIRT_CACHEGW)) {
5026 							break;
5027 						}
5028 						continue;
5029 					}
5030 				} else {
5031 					/*
5032 					 * No resolver for the gateway: the
5033 					 * route is not resolvable.
5034 					 * If the MULTIRT_SETSTAMP flag is
5035 					 * set, we stamp the IRE_HOST ire,
5036 					 * so we will not select it again
5037 					 * during this resolution interval.
5038 					 */
5039 					if (flags & MULTIRT_SETSTAMP)
5040 						fire->ire_last_used_time =
5041 						    lbolt;
5042 				}
5043 			}
5044 
5045 			if (gw_ire != NULL)
5046 				ire_refrele(gw_ire);
5047 		}
5048 	} else { /* CLASSD(dst) */
5049 
5050 		for (fire = first_fire;
5051 		    fire != NULL;
5052 		    fire = fire->ire_next) {
5053 
5054 			if (!(fire->ire_flags & RTF_MULTIRT))
5055 				continue;
5056 			if (fire->ire_addr != dst)
5057 				continue;
5058 
5059 			if (fire->ire_gw_secattr != NULL &&
5060 			    tsol_ire_match_gwattr(fire, tsl) != 0) {
5061 				continue;
5062 			}
5063 
5064 			already_resolved = B_FALSE;
5065 
5066 			gw = fire->ire_gateway_addr;
5067 
5068 			gw_ire = ire_ftable_lookup(gw, 0, 0, IRE_INTERFACE,
5069 			    NULL, NULL, ALL_ZONES, 0, tsl,
5070 			    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE |
5071 			    MATCH_IRE_SECATTR, ipst);
5072 
5073 			/* No resolver for the gateway; we skip this ire. */
5074 			if (gw_ire == NULL) {
5075 				continue;
5076 			}
5077 			ASSERT(gw_ire->ire_nce == NULL ||
5078 			    gw_ire->ire_nce->nce_state == ND_REACHABLE);
5079 
5080 			if (first_cire != NULL) {
5081 
5082 				IRB_REFHOLD(cirb);
5083 				/*
5084 				 * For all IRE_CACHE ires for that
5085 				 * destination.
5086 				 */
5087 				for (cire = first_cire;
5088 				    cire != NULL;
5089 				    cire = cire->ire_next) {
5090 
5091 					if (!(cire->ire_flags & RTF_MULTIRT))
5092 						continue;
5093 					if (cire->ire_addr != dst)
5094 						continue;
5095 					if (cire->ire_marks &
5096 					    (IRE_MARK_CONDEMNED |
5097 					    IRE_MARK_TESTHIDDEN))
5098 						continue;
5099 
5100 					if (cire->ire_gw_secattr != NULL &&
5101 					    tsol_ire_match_gwattr(cire,
5102 					    tsl) != 0) {
5103 						continue;
5104 					}
5105 
5106 					/*
5107 					 * Cache entries are linked to the
5108 					 * parent routes using the parent handle
5109 					 * (ire_phandle). If no cache entry has
5110 					 * the same handle as fire, fire is
5111 					 * still unresolved.
5112 					 */
5113 					ASSERT(cire->ire_phandle != 0);
5114 					if (cire->ire_phandle ==
5115 					    fire->ire_phandle) {
5116 						already_resolved = B_TRUE;
5117 						break;
5118 					}
5119 				}
5120 				IRB_REFRELE(cirb);
5121 			}
5122 
5123 			/*
5124 			 * This route is already resolved; proceed with
5125 			 * next one.
5126 			 */
5127 			if (already_resolved) {
5128 				ire_refrele(gw_ire);
5129 				if (already_resolved_count != NULL)
5130 					(*already_resolved_count)++;
5131 				continue;
5132 			}
5133 
5134 			/*
5135 			 * Compute the time elapsed since our preceding
5136 			 * attempt to resolve that route.
5137 			 * If the MULTIRT_USESTAMP flag is set, we take
5138 			 * that route into account only if this time
5139 			 * interval exceeds ip_multirt_resolution_interval;
5140 			 * this prevents us from attempting to resolve a
5141 			 * broken route upon each sending of a packet.
5142 			 */
5143 			delta = lbolt - fire->ire_last_used_time;
5144 			delta = TICK_TO_MSEC(delta);
5145 
5146 			res = (boolean_t)((delta >
5147 			    ipst->ips_ip_multirt_resolution_interval) ||
5148 			    (!(flags & MULTIRT_USESTAMP)));
5149 
5150 			ip3dbg(("ire_multirt_lookup: fire %p, delta %lx, "
5151 			    "flags %04x, res %d\n",
5152 			    (void *)fire, delta, flags, res));
5153 
5154 			if (res) {
5155 				if (best_cire != NULL) {
5156 					/*
5157 					 * Release the resolver associated
5158 					 * to the preceding candidate best
5159 					 * ire, if any.
5160 					 */
5161 					ire_refrele(best_cire);
5162 					ASSERT(best_fire != NULL);
5163 				}
5164 				best_fire = fire;
5165 				best_cire = gw_ire;
5166 				continue;
5167 			}
5168 
5169 			ire_refrele(gw_ire);
5170 		}
5171 	}
5172 
5173 	if (best_fire != NULL) {
5174 		IRE_REFHOLD(best_fire);
5175 	}
5176 	IRB_REFRELE(firb);
5177 
5178 	/* Release the first IRE_CACHE we initially looked up, if any. */
5179 	if (first_cire != NULL)
5180 		ire_refrele(first_cire);
5181 
5182 	/* Found a resolvable route. */
5183 	if (best_fire != NULL) {
5184 		ASSERT(best_cire != NULL);
5185 
5186 		if (*fire_arg != NULL)
5187 			ire_refrele(*fire_arg);
5188 		if (*ire_arg != NULL)
5189 			ire_refrele(*ire_arg);
5190 
5191 		/*
5192 		 * Update the passed-in arguments with the
5193 		 * resolvable multirt route we found.
5194 		 */
5195 		*fire_arg = best_fire;
5196 		*ire_arg = best_cire;
5197 
5198 		ip2dbg(("ire_multirt_lookup: returning B_TRUE, "
5199 		    "*fire_arg %p, *ire_arg %p\n",
5200 		    (void *)best_fire, (void *)best_cire));
5201 
5202 		return (B_TRUE);
5203 	}
5204 
5205 	ASSERT(best_cire == NULL);
5206 
5207 	ip2dbg(("ire_multirt_lookup: returning B_FALSE, *fire_arg %p, "
5208 	    "*ire_arg %p\n",
5209 	    (void *)*fire_arg, (void *)*ire_arg));
5210 
5211 	/* No resolvable route. */
5212 	return (B_FALSE);
5213 }
5214 
5215 /*
5216  * IRE iterator for inbound and loopback broadcast processing.
5217  * Given an IRE_BROADCAST ire, walk the ires with the same destination
5218  * address, but skip over the passed-in ire. Returns the next ire without
5219  * a hold - assumes that the caller holds a reference on the IRE bucket.
5220  */
5221 ire_t *
5222 ire_get_next_bcast_ire(ire_t *curr, ire_t *ire)
5223 {
5224 	ill_t *ill;
5225 
5226 	if (curr == NULL) {
5227 		for (curr = ire->ire_bucket->irb_ire; curr != NULL;
5228 		    curr = curr->ire_next) {
5229 			if (curr->ire_addr == ire->ire_addr)
5230 				break;
5231 		}
5232 	} else {
5233 		curr = curr->ire_next;
5234 	}
5235 	ill = ire_to_ill(ire);
5236 	for (; curr != NULL; curr = curr->ire_next) {
5237 		if (curr->ire_addr != ire->ire_addr) {
5238 			/*
5239 			 * All the IREs to a given destination are contiguous;
5240 			 * break out once the address doesn't match.
5241 			 */
5242 			break;
5243 		}
5244 		if (curr == ire) {
5245 			/* skip over the passed-in ire */
5246 			continue;
5247 		}
5248 		if ((curr->ire_stq != NULL && ire->ire_stq == NULL) ||
5249 		    (curr->ire_stq == NULL && ire->ire_stq != NULL)) {
5250 			/*
5251 			 * If the passed-in ire is loopback, skip over
5252 			 * non-loopback ires and vice versa.
5253 			 */
5254 			continue;
5255 		}
5256 		if (ire_to_ill(curr) != ill) {
5257 			/* skip over IREs going through a different interface */
5258 			continue;
5259 		}
5260 		if (curr->ire_marks & IRE_MARK_CONDEMNED) {
5261 			/* skip over deleted IREs */
5262 			continue;
5263 		}
5264 		return (curr);
5265 	}
5266 	return (NULL);
5267 }
5268 
5269 #ifdef DEBUG
5270 void
5271 ire_trace_ref(ire_t *ire)
5272 {
5273 	mutex_enter(&ire->ire_lock);
5274 	if (ire->ire_trace_disable) {
5275 		mutex_exit(&ire->ire_lock);
5276 		return;
5277 	}
5278 
5279 	if (th_trace_ref(ire, ire->ire_ipst)) {
5280 		mutex_exit(&ire->ire_lock);
5281 	} else {
5282 		ire->ire_trace_disable = B_TRUE;
5283 		mutex_exit(&ire->ire_lock);
5284 		ire_trace_cleanup(ire);
5285 	}
5286 }
5287 
5288 void
5289 ire_untrace_ref(ire_t *ire)
5290 {
5291 	mutex_enter(&ire->ire_lock);
5292 	if (!ire->ire_trace_disable)
5293 		th_trace_unref(ire);
5294 	mutex_exit(&ire->ire_lock);
5295 }
5296 
5297 static void
5298 ire_trace_cleanup(const ire_t *ire)
5299 {
5300 	th_trace_cleanup(ire, ire->ire_trace_disable);
5301 }
5302 #endif /* DEBUG */
5303 
5304 /*
5305  * Generate a message chain with an arp request to resolve the in_ire.
5306  * It is assumed that in_ire itself is currently in the ire cache table,
5307  * so we create a fake_ire filled with enough information about ire_addr etc.
5308  * to retrieve in_ire when the DL_UNITDATA response from the resolver
5309  * comes back. The fake_ire itself is created by calling esballoc with
5310  * the fr_rtnp (free routine) set to ire_freemblk. This routine will be
5311  * invoked when the mblk containing fake_ire is freed.
5312  */
5313 void
5314 ire_arpresolve(ire_t *in_ire)
5315 {
5316 	areq_t		*areq;
5317 	ipaddr_t	*addrp;
5318 	mblk_t 		*ire_mp, *areq_mp;
5319 	ire_t 		*ire, *buf;
5320 	size_t		bufsize;
5321 	frtn_t		*frtnp;
5322 	ill_t		*dst_ill;
5323 	ip_stack_t	*ipst;
5324 
5325 	ASSERT(in_ire->ire_nce != NULL);
5326 
5327 	dst_ill = ire_to_ill(in_ire);
5328 	ipst = dst_ill->ill_ipst;
5329 
5330 	/*
5331 	 * Construct message chain for the resolver
5332 	 * of the form:
5333 	 *	ARP_REQ_MBLK-->IRE_MBLK
5334 	 *
5335 	 * NOTE : If the response does not
5336 	 * come back, ARP frees the packet. For this reason,
5337 	 * we can't REFHOLD the bucket of save_ire to prevent
5338 	 * deletions. We may not be able to REFRELE the bucket
5339 	 * if the response never comes back. Thus, before
5340 	 * adding the ire, ire_add_v4 will make sure that the
5341 	 * interface route does not get deleted. This is the
5342 	 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
5343 	 * where we can always prevent deletions because of
5344 	 * the synchronous nature of adding IRES i.e
5345 	 * ire_add_then_send is called after creating the IRE.
5346 	 */
5347 
5348 	/*
5349 	 * We use esballoc to allocate the second part (IRE_MBLK)
5350 	 * of the message chain depicted above.  This mblk will be freed
5351 	 * by arp when there is a timeout, and otherwise passed to IP
5352 	 * and IP will free it after processing the ARP response.
5353 	 */
5354 
5355 	bufsize = sizeof (ire_t) + sizeof (frtn_t);
5356 	buf = kmem_alloc(bufsize, KM_NOSLEEP);
5357 	if (buf == NULL) {
5358 		ip1dbg(("ire_arpresolve: alloc buffer failed\n"));
5359 		return;
5360 	}
5361 	frtnp = (frtn_t *)(buf + 1);
5362 	frtnp->free_arg = (caddr_t)buf;
5363 	frtnp->free_func = ire_freemblk;
5364 
5365 	ire_mp = esballoc((unsigned char *)buf, bufsize, BPRI_MED, frtnp);
5366 	if (ire_mp == NULL) {
5367 		ip1dbg(("ire_arpresolve: esballoc failed\n"));
5368 		kmem_free(buf, bufsize);
5369 		return;
5370 	}
5371 
5372 	areq_mp = copyb(dst_ill->ill_resolver_mp);
5373 	if (areq_mp == NULL) {
5374 		freemsg(ire_mp);
5375 		return;
5376 	}
5377 
5378 	ire_mp->b_datap->db_type = IRE_ARPRESOLVE_TYPE;
5379 	ire = (ire_t *)buf;
5380 	/*
5381 	 * keep enough info in the fake ire so that we can pull up
5382 	 * the incomplete ire (in_ire) after result comes back from
5383 	 * arp and make it complete.
5384 	 */
5385 	*ire = ire_null;
5386 	ire->ire_u = in_ire->ire_u;
5387 	ire->ire_ipif_seqid = in_ire->ire_ipif_seqid;
5388 	ire->ire_ipif_ifindex = in_ire->ire_ipif_ifindex;
5389 	ire->ire_ipif = in_ire->ire_ipif;
5390 	ire->ire_stq = dst_ill->ill_wq;
5391 	ire->ire_stq_ifindex = dst_ill->ill_phyint->phyint_ifindex;
5392 	ire->ire_zoneid = in_ire->ire_zoneid;
5393 	ire->ire_stackid = ipst->ips_netstack->netstack_stackid;
5394 	ire->ire_ipst = ipst;
5395 
5396 	/*
5397 	 * ire_freemblk will be called when ire_mp is freed, both for
5398 	 * successful and failed arp resolution. IRE_MARK_UNCACHED will be set
5399 	 * when the arp resolution failed.
5400 	 */
5401 	ire->ire_marks |= IRE_MARK_UNCACHED;
5402 	ire->ire_mp = ire_mp;
5403 	ire_mp->b_wptr = (uchar_t *)&ire[1];
5404 	ire_mp->b_cont = NULL;
5405 	linkb(areq_mp, ire_mp);
5406 
5407 	/*
5408 	 * Fill in the source and dest addrs for the resolver.
5409 	 * NOTE: this depends on memory layouts imposed by
5410 	 * ill_init().
5411 	 */
5412 	areq = (areq_t *)areq_mp->b_rptr;
5413 	addrp = (ipaddr_t *)((char *)areq + areq->areq_sender_addr_offset);
5414 	*addrp = ire->ire_src_addr;
5415 
5416 	addrp = (ipaddr_t *)((char *)areq + areq->areq_target_addr_offset);
5417 	if (ire->ire_gateway_addr != INADDR_ANY) {
5418 		*addrp = ire->ire_gateway_addr;
5419 	} else {
5420 		*addrp = ire->ire_addr;
5421 	}
5422 
5423 	/* Up to the resolver. */
5424 	if (canputnext(dst_ill->ill_rq)) {
5425 		putnext(dst_ill->ill_rq, areq_mp);
5426 	} else {
5427 		freemsg(areq_mp);
5428 	}
5429 }
5430 
5431 /*
5432  * Esballoc free function for AR_ENTRY_QUERY request to clean up any
5433  * unresolved ire_t and/or nce_t structures when ARP resolution fails.
5434  *
5435  * This function can be called by ARP via free routine for ire_mp or
5436  * by IPv4(both host and forwarding path) via ire_delete
5437  * in case ARP resolution fails.
5438  * NOTE: Since IP is MT, ARP can call into IP but not vice versa
5439  * (for IP to talk to ARP, it still has to send AR* messages).
5440  *
5441  * Note that the ARP/IP merge should replace the functioanlity by providing
5442  * direct function calls to clean up unresolved entries in ire/nce lists.
5443  */
5444 void
5445 ire_freemblk(ire_t *ire_mp)
5446 {
5447 	nce_t		*nce = NULL;
5448 	ill_t		*ill;
5449 	ip_stack_t	*ipst;
5450 	netstack_t	*ns = NULL;
5451 
5452 	ASSERT(ire_mp != NULL);
5453 
5454 	if ((ire_mp->ire_addr == NULL) && (ire_mp->ire_gateway_addr == NULL)) {
5455 		ip1dbg(("ire_freemblk(0x%p) ire_addr is NULL\n",
5456 		    (void *)ire_mp));
5457 		goto cleanup;
5458 	}
5459 	if ((ire_mp->ire_marks & IRE_MARK_UNCACHED) == 0) {
5460 		goto cleanup; /* everything succeeded. just free and return */
5461 	}
5462 
5463 	/*
5464 	 * the arp information corresponding to this ire_mp was not
5465 	 * transferred to an ire_cache entry. Need
5466 	 * to clean up incomplete ire's and nce, if necessary.
5467 	 */
5468 	ASSERT(ire_mp->ire_stq != NULL);
5469 	ASSERT(ire_mp->ire_stq_ifindex != 0);
5470 	ASSERT(ire_mp->ire_ipst != NULL);
5471 
5472 	ns = netstack_find_by_stackid(ire_mp->ire_stackid);
5473 	ipst = (ns ? ns->netstack_ip : NULL);
5474 	if (ipst == NULL || ipst != ire_mp->ire_ipst) /* Disapeared on us */
5475 		goto  cleanup;
5476 
5477 	/*
5478 	 * Get any nce's corresponding to this ire_mp. We first have to
5479 	 * make sure that the ill is still around.
5480 	 */
5481 	ill = ill_lookup_on_ifindex(ire_mp->ire_stq_ifindex,
5482 	    B_FALSE, NULL, NULL, NULL, NULL, ipst);
5483 	if (ill == NULL || (ire_mp->ire_stq != ill->ill_wq) ||
5484 	    (ill->ill_state_flags & ILL_CONDEMNED)) {
5485 		/*
5486 		 * ill went away. no nce to clean up.
5487 		 * Note that the ill_state_flags could be set to
5488 		 * ILL_CONDEMNED after this point, but if we know
5489 		 * that it is CONDEMNED now, we just bail out quickly.
5490 		 */
5491 		if (ill != NULL)
5492 			ill_refrele(ill);
5493 		goto cleanup;
5494 	}
5495 	nce = ndp_lookup_v4(ill,
5496 	    ((ire_mp->ire_gateway_addr != INADDR_ANY) ?
5497 	    &ire_mp->ire_gateway_addr : &ire_mp->ire_addr),
5498 	    B_FALSE);
5499 	ill_refrele(ill);
5500 
5501 	if ((nce != NULL) && (nce->nce_state != ND_REACHABLE)) {
5502 		/*
5503 		 * some incomplete nce was found.
5504 		 */
5505 		DTRACE_PROBE2(ire__freemblk__arp__resolv__fail,
5506 		    nce_t *, nce, ire_t *, ire_mp);
5507 		/*
5508 		 * Send the icmp_unreachable messages for the queued mblks in
5509 		 * ire->ire_nce->nce_qd_mp, since ARP resolution failed
5510 		 * for this ire
5511 		 */
5512 		arp_resolv_failed(nce);
5513 		/*
5514 		 * Delete the nce and clean up all ire's pointing at this nce
5515 		 * in the cachetable
5516 		 */
5517 		ndp_delete(nce);
5518 	}
5519 	if (nce != NULL)
5520 		NCE_REFRELE(nce); /* release the ref taken by ndp_lookup_v4 */
5521 
5522 cleanup:
5523 	if (ns != NULL)
5524 		netstack_rele(ns);
5525 	/*
5526 	 * Get rid of the ire buffer
5527 	 * We call kmem_free here(instead of ire_delete()), since
5528 	 * this is the freeb's callback.
5529 	 */
5530 	kmem_free(ire_mp, sizeof (ire_t) + sizeof (frtn_t));
5531 }
5532 
5533 /*
5534  * find, or create if needed, a neighbor cache entry nce_t for IRE_CACHE and
5535  * non-loopback IRE_BROADCAST ire's.
5536  *
5537  * If a neighbor-cache entry has to be created (i.e., one does not already
5538  * exist in the nce list) the nce_res_mp and nce_state of the neighbor cache
5539  * entry are initialized in ndp_add_v4(). These values are picked from
5540  * the src_nce, if one is passed in. Otherwise (if src_nce == NULL) the
5541  * ire->ire_type and the outgoing interface (ire_to_ill(ire)) values
5542  * determine the {nce_state, nce_res_mp} of the nce_t created. All
5543  * IRE_BROADCAST entries have nce_state = ND_REACHABLE, and the nce_res_mp
5544  * is set to the ill_bcast_mp of the outgoing inerface. For unicast ire
5545  * entries,
5546  *   - if the outgoing interface is of type IRE_IF_RESOLVER, a newly created
5547  *     nce_t will have a null nce_res_mp, and will be in the ND_INITIAL state.
5548  *   - if the outgoing interface is a IRE_IF_NORESOLVER interface, no link
5549  *     layer resolution is necessary, so that the nce_t will be in the
5550  *     ND_REACHABLE state and the nce_res_mp will have a copy of the
5551  *     ill_resolver_mp of the outgoing interface.
5552  *
5553  * The link layer information needed for broadcast addresses, and for
5554  * packets sent on IRE_IF_NORESOLVER interfaces is a constant mapping that
5555  * never needs re-verification for the lifetime of the nce_t. These are
5556  * therefore marked NCE_F_PERMANENT, and never allowed to expire via
5557  * NCE_EXPIRED.
5558  *
5559  * IRE_CACHE ire's contain the information for  the nexthop (ire_gateway_addr)
5560  * in the case of indirect routes, and for the dst itself (ire_addr) in the
5561  * case of direct routes, with the nce_res_mp containing a template
5562  * DL_UNITDATA request.
5563  *
5564  * The actual association of the ire_nce to the nce created here is
5565  * typically done in ire_add_v4 for IRE_CACHE entries. Exceptions
5566  * to this rule are SO_DONTROUTE ire's (IRE_MARK_NO_ADD), for which
5567  * the ire_nce assignment is done in ire_add_then_send.
5568  */
5569 int
5570 ire_nce_init(ire_t *ire, nce_t *src_nce)
5571 {
5572 	in_addr_t	addr4;
5573 	int		err;
5574 	nce_t		*nce = NULL;
5575 	ill_t		*ire_ill;
5576 	uint16_t	nce_flags = 0;
5577 	ip_stack_t	*ipst;
5578 
5579 	if (ire->ire_stq == NULL)
5580 		return (0); /* no need to create nce for local/loopback */
5581 
5582 	switch (ire->ire_type) {
5583 	case IRE_CACHE:
5584 		if (ire->ire_gateway_addr != INADDR_ANY)
5585 			addr4 = ire->ire_gateway_addr; /* 'G' route */
5586 		else
5587 			addr4 = ire->ire_addr; /* direct route */
5588 		break;
5589 	case IRE_BROADCAST:
5590 		addr4 = ire->ire_addr;
5591 		nce_flags |= (NCE_F_PERMANENT|NCE_F_BCAST);
5592 		break;
5593 	default:
5594 		return (0);
5595 	}
5596 
5597 	/*
5598 	 * ire_ipif is picked based on RTF_SETSRC, usesrc etc.
5599 	 * rules in ire_forward_src_ipif. We want the dlureq_mp
5600 	 * for the outgoing interface, which we get from the ire_stq.
5601 	 */
5602 	ire_ill = ire_to_ill(ire);
5603 	ipst = ire_ill->ill_ipst;
5604 
5605 	/*
5606 	 * IRE_IF_NORESOLVER entries never need re-verification and
5607 	 * do not expire, so we mark them as NCE_F_PERMANENT.
5608 	 */
5609 	if (ire_ill->ill_net_type == IRE_IF_NORESOLVER)
5610 		nce_flags |= NCE_F_PERMANENT;
5611 
5612 retry_nce:
5613 	err = ndp_lookup_then_add_v4(ire_ill, &addr4, nce_flags,
5614 	    &nce, src_nce);
5615 
5616 	if (err == EEXIST && NCE_EXPIRED(nce, ipst)) {
5617 		/*
5618 		 * We looked up an expired nce.
5619 		 * Go back and try to create one again.
5620 		 */
5621 		ndp_delete(nce);
5622 		NCE_REFRELE(nce);
5623 		nce = NULL;
5624 		goto retry_nce;
5625 	}
5626 
5627 	ip1dbg(("ire 0x%p addr 0x%lx type 0x%x; found nce 0x%p err %d\n",
5628 	    (void *)ire, (ulong_t)addr4, ire->ire_type, (void *)nce, err));
5629 
5630 	switch (err) {
5631 	case 0:
5632 	case EEXIST:
5633 		/*
5634 		 * return a pointer to a newly created or existing nce_t;
5635 		 * note that the ire-nce mapping is many-one, i.e.,
5636 		 * multiple ire's could point to the same nce_t.
5637 		 */
5638 		break;
5639 	default:
5640 		DTRACE_PROBE2(nce__init__fail, ill_t *, ire_ill, int, err);
5641 		return (EINVAL);
5642 	}
5643 	/*
5644 	 * IRE_BROADCAST ire's must be linked to NCE_F_BCAST nce's and
5645 	 * vice-versa (IRE_CACHE <-> unicast nce entries). We may have found an
5646 	 * existing unicast (or bcast) nce when trying to add a BROADCAST (or
5647 	 * unicast) ire, e.g., when address/netmask modifications were in
5648 	 * progress, and the ipif_ndp_down() call to quiesce existing state
5649 	 * during the addr/mask modification may have skipped the ndp_delete()
5650 	 * because the ipif being affected was not the last one on the ill.  We
5651 	 * recover from the missed ndp_delete() now, by deleting the old nce and
5652 	 * adding a new one with the correct NCE_F_BCAST state.
5653 	 */
5654 	if (ire->ire_type == IRE_BROADCAST) {
5655 		if ((nce->nce_flags & NCE_F_BCAST) == 0) {
5656 			/* IRE_BROADCAST needs NCE_F_BCAST */
5657 			ndp_delete(nce);
5658 			NCE_REFRELE(nce);
5659 			goto retry_nce;
5660 		}
5661 		/*
5662 		 * Two bcast ires are created for each interface;
5663 		 * 1. loopback copy (which does not  have an
5664 		 *    ire_stq, and therefore has no ire_nce), and,
5665 		 * 2. the non-loopback copy, which has the nce_res_mp
5666 		 *    initialized to a copy of the ill_bcast_mp, and
5667 		 *    is marked as ND_REACHABLE at this point.
5668 		 *    This nce does not undergo any further state changes,
5669 		 *    and exists as long as the interface is plumbed.
5670 		 * Note: the assignment of ire_nce here is a historical
5671 		 * artifact of old code that used to inline ire_add().
5672 		 */
5673 		ire->ire_nce = nce;
5674 		/*
5675 		 * We are associating this nce to the ire,
5676 		 * so change the nce ref taken in
5677 		 * ndp_lookup_then_add_v4() from
5678 		 * NCE_REFHOLD to NCE_REFHOLD_NOTR
5679 		 */
5680 		NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
5681 	} else {
5682 		if ((nce->nce_flags & NCE_F_BCAST) != 0) {
5683 			/* IRE_CACHE needs unicast nce */
5684 			ndp_delete(nce);
5685 			NCE_REFRELE(nce);
5686 			goto retry_nce;
5687 		}
5688 		/*
5689 		 * We are not using this nce_t just yet so release
5690 		 * the ref taken in ndp_lookup_then_add_v4()
5691 		 */
5692 		NCE_REFRELE(nce);
5693 	}
5694 	return (0);
5695 }
5696 
5697 /*
5698  * This is the implementation of the IPv4 IRE cache lookup procedure.
5699  * Separating the interface from the implementation allows additional
5700  * flexibility when specifying search criteria.
5701  */
5702 static ire_t *
5703 ip4_ctable_lookup_impl(ire_ctable_args_t *margs)
5704 {
5705 	irb_t			*irb_ptr;
5706 	ire_t			*ire;
5707 	ip_stack_t		*ipst = margs->ict_ipst;
5708 
5709 	if ((margs->ict_flags & (MATCH_IRE_SRC | MATCH_IRE_ILL)) &&
5710 	    (margs->ict_ipif == NULL)) {
5711 		return (NULL);
5712 	}
5713 
5714 	irb_ptr = &ipst->ips_ip_cache_table[IRE_ADDR_HASH(
5715 	    *((ipaddr_t *)margs->ict_addr), ipst->ips_ip_cache_table_size)];
5716 	rw_enter(&irb_ptr->irb_lock, RW_READER);
5717 	for (ire = irb_ptr->irb_ire; ire != NULL; ire = ire->ire_next) {
5718 		if (ire->ire_marks & IRE_MARK_CONDEMNED)
5719 			continue;
5720 		ASSERT(ire->ire_mask == IP_HOST_MASK);
5721 		if (ire_match_args(ire, *((ipaddr_t *)margs->ict_addr),
5722 		    ire->ire_mask, *((ipaddr_t *)margs->ict_gateway),
5723 		    margs->ict_type, margs->ict_ipif, margs->ict_zoneid, 0,
5724 		    margs->ict_tsl, margs->ict_flags, margs->ict_wq)) {
5725 			IRE_REFHOLD(ire);
5726 			rw_exit(&irb_ptr->irb_lock);
5727 			return (ire);
5728 		}
5729 	}
5730 
5731 	rw_exit(&irb_ptr->irb_lock);
5732 	return (NULL);
5733 }
5734 
5735 /*
5736  * This function locates IRE_CACHE entries which were added by the
5737  * ire_forward() path. We can fully specify the IRE we are looking for by
5738  * providing the ipif (MATCH_IRE_IPIF) *and* the stq (MATCH_IRE_WQ).
5739  */
5740 ire_t *
5741 ire_arpresolve_lookup(ipaddr_t addr, ipaddr_t gw, ipif_t *ipif,
5742     zoneid_t zoneid, ip_stack_t *ipst, queue_t *wq)
5743 {
5744 	ire_ctable_args_t	margs;
5745 
5746 	margs.ict_addr = &addr;
5747 	margs.ict_gateway = &gw;
5748 	margs.ict_type = IRE_CACHE;
5749 	margs.ict_ipif = ipif;
5750 	margs.ict_zoneid = zoneid;
5751 	margs.ict_tsl = NULL;
5752 	margs.ict_flags = MATCH_IRE_GW | MATCH_IRE_IPIF | MATCH_IRE_ZONEONLY |
5753 	    MATCH_IRE_TYPE | MATCH_IRE_WQ;
5754 	margs.ict_ipst = ipst;
5755 	margs.ict_wq = wq;
5756 
5757 	return (ip4_ctable_lookup_impl(&margs));
5758 }
5759