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