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