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