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