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