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