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