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