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