xref: /titanic_50/usr/src/uts/common/inet/ip/ip_ire.c (revision da6c28aaf62fa55f0fdb8004aa40f88f23bf53f0)
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 2007 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/ddi.h>
38 #include <sys/cmn_err.h>
39 #include <sys/policy.h>
40 
41 #include <sys/systm.h>
42 #include <sys/kmem.h>
43 #include <sys/param.h>
44 #include <sys/socket.h>
45 #include <net/if.h>
46 #include <net/route.h>
47 #include <netinet/in.h>
48 #include <net/if_dl.h>
49 #include <netinet/ip6.h>
50 #include <netinet/icmp6.h>
51 
52 #include <inet/common.h>
53 #include <inet/mi.h>
54 #include <inet/ip.h>
55 #include <inet/ip6.h>
56 #include <inet/ip_ndp.h>
57 #include <inet/arp.h>
58 #include <inet/ip_if.h>
59 #include <inet/ip_ire.h>
60 #include <inet/ip_ftable.h>
61 #include <inet/ip_rts.h>
62 #include <inet/nd.h>
63 
64 #include <net/pfkeyv2.h>
65 #include <inet/ipsec_info.h>
66 #include <inet/sadb.h>
67 #include <sys/kmem.h>
68 #include <inet/tcp.h>
69 #include <inet/ipclassifier.h>
70 #include <sys/zone.h>
71 #include <sys/cpuvar.h>
72 
73 #include <sys/tsol/label.h>
74 #include <sys/tsol/tnet.h>
75 
76 struct kmem_cache *rt_entry_cache;
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_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
153  * 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].
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 /*
235  * The minimum size of IRE cache table.  It will be recalcuated in
236  * ip_ire_init().
237  * Setable in /etc/system
238  */
239 uint32_t ip_cache_table_size = IP_CACHE_TABLE_SIZE;
240 uint32_t ip6_cache_table_size = IP6_CACHE_TABLE_SIZE;
241 
242 /*
243  * The size of the forwarding table.  We will make sure that it is a
244  * power of 2 in ip_ire_init().
245  * Setable in /etc/system
246  */
247 uint32_t ip6_ftable_hash_size = IP6_FTABLE_HASH_SIZE;
248 
249 struct	kmem_cache	*ire_cache;
250 static ire_t	ire_null;
251 
252 /*
253  * The threshold number of IRE in a bucket when the IREs are
254  * cleaned up.  This threshold is calculated later in ip_open()
255  * based on the speed of CPU and available memory.  This default
256  * value is the maximum.
257  *
258  * We have two kinds of cached IRE, temporary and
259  * non-temporary.  Temporary IREs are marked with
260  * IRE_MARK_TEMPORARY.  They are IREs created for non
261  * TCP traffic and for forwarding purposes.  All others
262  * are non-temporary IREs.  We don't mark IRE created for
263  * TCP as temporary because TCP is stateful and there are
264  * info stored in the IRE which can be shared by other TCP
265  * connections to the same destination.  For connected
266  * endpoint, we also don't want to mark the IRE used as
267  * temporary because the same IRE will be used frequently,
268  * otherwise, the app should not do a connect().  We change
269  * the marking at ip_bind_connected_*() if necessary.
270  *
271  * We want to keep the cache IRE hash bucket length reasonably
272  * short, otherwise IRE lookup functions will take "forever."
273  * We use the "crude" function that the IRE bucket
274  * length should be based on the CPU speed, which is 1 entry
275  * per x MHz, depending on the shift factor ip_ire_cpu_ratio
276  * (n).  This means that with a 750MHz CPU, the max bucket
277  * length can be (750 >> n) entries.
278  *
279  * Note that this threshold is separate for temp and non-temp
280  * IREs.  This means that the actual bucket length can be
281  * twice as that.  And while we try to keep temporary IRE
282  * length at most at the threshold value, we do not attempt to
283  * make the length for non-temporary IREs fixed, for the
284  * reason stated above.  Instead, we start trying to find
285  * "unused" non-temporary IREs when the bucket length reaches
286  * this threshold and clean them up.
287  *
288  * We also want to limit the amount of memory used by
289  * IREs.  So if we are allowed to use ~3% of memory (M)
290  * for those IREs, each bucket should not have more than
291  *
292  * 	M / num of cache bucket / sizeof (ire_t)
293  *
294  * Again the above memory uses are separate for temp and
295  * non-temp cached IREs.
296  *
297  * We may also want the limit to be a function of the number
298  * of interfaces and number of CPUs.  Doing the initialization
299  * in ip_open() means that every time an interface is plumbed,
300  * the max is re-calculated.  Right now, we don't do anything
301  * different.  In future, when we have more experience, we
302  * may want to change this behavior.
303  */
304 uint32_t ip_ire_max_bucket_cnt = 10;	/* Setable in /etc/system */
305 uint32_t ip6_ire_max_bucket_cnt = 10;
306 
307 /*
308  * The minimum of the temporary IRE bucket count.  We do not want
309  * the length of each bucket to be too short.  This may hurt
310  * performance of some apps as the temporary IREs are removed too
311  * often.
312  */
313 uint32_t ip_ire_min_bucket_cnt = 3;	/* /etc/system - not used */
314 uint32_t ip6_ire_min_bucket_cnt = 3;
315 
316 /*
317  * The ratio of memory consumed by IRE used for temporary to available
318  * memory.  This is a shift factor, so 6 means the ratio 1 to 64.  This
319  * value can be changed in /etc/system.  6 is a reasonable number.
320  */
321 uint32_t ip_ire_mem_ratio = 6;	/* /etc/system */
322 /* The shift factor for CPU speed to calculate the max IRE bucket length. */
323 uint32_t ip_ire_cpu_ratio = 7;	/* /etc/system */
324 
325 typedef struct nce_clookup_s {
326 	ipaddr_t ncecl_addr;
327 	boolean_t ncecl_found;
328 } nce_clookup_t;
329 
330 /*
331  * The maximum number of buckets in IRE cache table.  In future, we may
332  * want to make it a dynamic hash table.  For the moment, we fix the
333  * size and allocate the table in ip_ire_init() when IP is first loaded.
334  * We take into account the amount of memory a system has.
335  */
336 #define	IP_MAX_CACHE_TABLE_SIZE	4096
337 
338 /* Setable in /etc/system */
339 static uint32_t	ip_max_cache_table_size = IP_MAX_CACHE_TABLE_SIZE;
340 static uint32_t	ip6_max_cache_table_size = IP_MAX_CACHE_TABLE_SIZE;
341 
342 #define	NUM_ILLS	2	/* To build the ILL list to unlock */
343 
344 /* Zero iulp_t for initialization. */
345 const iulp_t	ire_uinfo_null = { 0 };
346 
347 static int	ire_add_v4(ire_t **ire_p, queue_t *q, mblk_t *mp,
348     ipsq_func_t func, boolean_t);
349 static void	ire_delete_v4(ire_t *ire);
350 static void	ire_report_ctable(ire_t *ire, char *mp);
351 static void	ire_walk_ipvers(pfv_t func, void *arg, uchar_t vers,
352     zoneid_t zoneid, ip_stack_t *);
353 static void	ire_walk_ill_ipvers(uint_t match_flags, uint_t ire_type,
354     pfv_t func, void *arg, uchar_t vers, ill_t *ill);
355 static void	ire_cache_cleanup(irb_t *irb, uint32_t threshold, int cnt);
356 static	void	ip_nce_clookup_and_delete(nce_t *nce, void *arg);
357 #ifdef DEBUG
358 static void	ire_trace_cleanup(const ire_t *);
359 #endif
360 
361 /*
362  * To avoid bloating the code, we call this function instead of
363  * using the macro IRE_REFRELE. Use macro only in performance
364  * critical paths.
365  *
366  * Must not be called while holding any locks. Otherwise if this is
367  * the last reference to be released there is a chance of recursive mutex
368  * panic due to ire_refrele -> ipif_ill_refrele_tail -> qwriter_ip trying
369  * to restart an ioctl. The one exception is when the caller is sure that
370  * this is not the last reference to be released. Eg. if the caller is
371  * sure that the ire has not been deleted and won't be deleted.
372  */
373 void
374 ire_refrele(ire_t *ire)
375 {
376 	IRE_REFRELE(ire);
377 }
378 
379 void
380 ire_refrele_notr(ire_t *ire)
381 {
382 	IRE_REFRELE_NOTR(ire);
383 }
384 
385 /*
386  * kmem_cache_alloc constructor for IRE in kma space.
387  * Note that when ire_mp is set the IRE is stored in that mblk and
388  * not in this cache.
389  */
390 /* ARGSUSED */
391 static int
392 ip_ire_constructor(void *buf, void *cdrarg, int kmflags)
393 {
394 	ire_t	*ire = buf;
395 
396 	ire->ire_nce = NULL;
397 
398 	return (0);
399 }
400 
401 /* ARGSUSED1 */
402 static void
403 ip_ire_destructor(void *buf, void *cdrarg)
404 {
405 	ire_t	*ire = buf;
406 
407 	ASSERT(ire->ire_nce == NULL);
408 }
409 
410 /*
411  * This function is associated with the IP_IOC_IRE_ADVISE_NO_REPLY
412  * IOCTL.  It is used by TCP (or other ULPs) to supply revised information
413  * for an existing CACHED IRE.
414  */
415 /* ARGSUSED */
416 int
417 ip_ire_advise(queue_t *q, mblk_t *mp, cred_t *ioc_cr)
418 {
419 	uchar_t	*addr_ucp;
420 	ipic_t	*ipic;
421 	ire_t	*ire;
422 	ipaddr_t	addr;
423 	in6_addr_t	v6addr;
424 	irb_t	*irb;
425 	zoneid_t	zoneid;
426 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
427 
428 	ASSERT(q->q_next == NULL);
429 	zoneid = Q_TO_CONN(q)->conn_zoneid;
430 
431 	/*
432 	 * Check privilege using the ioctl credential; if it is NULL
433 	 * then this is a kernel message and therefor privileged.
434 	 */
435 	if (ioc_cr != NULL && secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
436 		return (EPERM);
437 
438 	ipic = (ipic_t *)mp->b_rptr;
439 	if (!(addr_ucp = mi_offset_param(mp, ipic->ipic_addr_offset,
440 	    ipic->ipic_addr_length))) {
441 		return (EINVAL);
442 	}
443 	if (!OK_32PTR(addr_ucp))
444 		return (EINVAL);
445 	switch (ipic->ipic_addr_length) {
446 	case IP_ADDR_LEN: {
447 		/* Extract the destination address. */
448 		addr = *(ipaddr_t *)addr_ucp;
449 		/* Find the corresponding IRE. */
450 		ire = ire_cache_lookup(addr, zoneid, NULL, ipst);
451 		break;
452 	}
453 	case IPV6_ADDR_LEN: {
454 		/* Extract the destination address. */
455 		v6addr = *(in6_addr_t *)addr_ucp;
456 		/* Find the corresponding IRE. */
457 		ire = ire_cache_lookup_v6(&v6addr, zoneid, NULL, ipst);
458 		break;
459 	}
460 	default:
461 		return (EINVAL);
462 	}
463 
464 	if (ire == NULL)
465 		return (ENOENT);
466 	/*
467 	 * Update the round trip time estimate and/or the max frag size
468 	 * and/or the slow start threshold.
469 	 *
470 	 * We serialize multiple advises using ire_lock.
471 	 */
472 	mutex_enter(&ire->ire_lock);
473 	if (ipic->ipic_rtt) {
474 		/*
475 		 * If there is no old cached values, initialize them
476 		 * conservatively.  Set them to be (1.5 * new value).
477 		 */
478 		if (ire->ire_uinfo.iulp_rtt != 0) {
479 			ire->ire_uinfo.iulp_rtt = (ire->ire_uinfo.iulp_rtt +
480 			    ipic->ipic_rtt) >> 1;
481 		} else {
482 			ire->ire_uinfo.iulp_rtt = ipic->ipic_rtt +
483 			    (ipic->ipic_rtt >> 1);
484 		}
485 		if (ire->ire_uinfo.iulp_rtt_sd != 0) {
486 			ire->ire_uinfo.iulp_rtt_sd =
487 			    (ire->ire_uinfo.iulp_rtt_sd +
488 			    ipic->ipic_rtt_sd) >> 1;
489 		} else {
490 			ire->ire_uinfo.iulp_rtt_sd = ipic->ipic_rtt_sd +
491 			    (ipic->ipic_rtt_sd >> 1);
492 		}
493 	}
494 	if (ipic->ipic_max_frag)
495 		ire->ire_max_frag = MIN(ipic->ipic_max_frag, IP_MAXPACKET);
496 	if (ipic->ipic_ssthresh != 0) {
497 		if (ire->ire_uinfo.iulp_ssthresh != 0)
498 			ire->ire_uinfo.iulp_ssthresh =
499 			    (ipic->ipic_ssthresh +
500 			    ire->ire_uinfo.iulp_ssthresh) >> 1;
501 		else
502 			ire->ire_uinfo.iulp_ssthresh = ipic->ipic_ssthresh;
503 	}
504 	/*
505 	 * Don't need the ire_lock below this. ire_type does not change
506 	 * after initialization. ire_marks is protected by irb_lock.
507 	 */
508 	mutex_exit(&ire->ire_lock);
509 
510 	if (ipic->ipic_ire_marks != 0 && ire->ire_type == IRE_CACHE) {
511 		/*
512 		 * Only increment the temporary IRE count if the original
513 		 * IRE is not already marked temporary.
514 		 */
515 		irb = ire->ire_bucket;
516 		rw_enter(&irb->irb_lock, RW_WRITER);
517 		if ((ipic->ipic_ire_marks & IRE_MARK_TEMPORARY) &&
518 		    !(ire->ire_marks & IRE_MARK_TEMPORARY)) {
519 			irb->irb_tmp_ire_cnt++;
520 		}
521 		ire->ire_marks |= ipic->ipic_ire_marks;
522 		rw_exit(&irb->irb_lock);
523 	}
524 
525 	ire_refrele(ire);
526 	return (0);
527 }
528 
529 /*
530  * This function is associated with the IP_IOC_IRE_DELETE[_NO_REPLY]
531  * IOCTL[s].  The NO_REPLY form is used by TCP to delete a route IRE
532  * for a host that is not responding.  This will force an attempt to
533  * establish a new route, if available, and flush out the ARP entry so
534  * it will re-resolve.  Management processes may want to use the
535  * version that generates a reply.
536  *
537  * This function does not support IPv6 since Neighbor Unreachability Detection
538  * means that negative advise like this is useless.
539  */
540 /* ARGSUSED */
541 int
542 ip_ire_delete(queue_t *q, mblk_t *mp, cred_t *ioc_cr)
543 {
544 	uchar_t		*addr_ucp;
545 	ipaddr_t	addr;
546 	ire_t		*ire;
547 	ipid_t		*ipid;
548 	boolean_t	routing_sock_info = B_FALSE;	/* Sent info? */
549 	zoneid_t	zoneid;
550 	ire_t		*gire = NULL;
551 	ill_t		*ill;
552 	mblk_t		*arp_mp;
553 	ip_stack_t	*ipst;
554 
555 	ASSERT(q->q_next == NULL);
556 	zoneid = Q_TO_CONN(q)->conn_zoneid;
557 	ipst = CONNQ_TO_IPST(q);
558 
559 	/*
560 	 * Check privilege using the ioctl credential; if it is NULL
561 	 * then this is a kernel message and therefor privileged.
562 	 */
563 	if (ioc_cr != NULL && secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
564 		return (EPERM);
565 
566 	ipid = (ipid_t *)mp->b_rptr;
567 
568 	/* Only actions on IRE_CACHEs are acceptable at present. */
569 	if (ipid->ipid_ire_type != IRE_CACHE)
570 		return (EINVAL);
571 
572 	addr_ucp = mi_offset_param(mp, ipid->ipid_addr_offset,
573 	    ipid->ipid_addr_length);
574 	if (addr_ucp == NULL || !OK_32PTR(addr_ucp))
575 		return (EINVAL);
576 	switch (ipid->ipid_addr_length) {
577 	case IP_ADDR_LEN:
578 		/* addr_ucp points at IP addr */
579 		break;
580 	case sizeof (sin_t): {
581 		sin_t	*sin;
582 		/*
583 		 * got complete (sockaddr) address - increment addr_ucp to point
584 		 * at the ip_addr field.
585 		 */
586 		sin = (sin_t *)addr_ucp;
587 		addr_ucp = (uchar_t *)&sin->sin_addr.s_addr;
588 		break;
589 	}
590 	default:
591 		return (EINVAL);
592 	}
593 	/* Extract the destination address. */
594 	bcopy(addr_ucp, &addr, IP_ADDR_LEN);
595 
596 	/* Try to find the CACHED IRE. */
597 	ire = ire_cache_lookup(addr, zoneid, NULL, ipst);
598 
599 	/* Nail it. */
600 	if (ire) {
601 		/* Allow delete only on CACHE entries */
602 		if (ire->ire_type != IRE_CACHE) {
603 			ire_refrele(ire);
604 			return (EINVAL);
605 		}
606 
607 		/*
608 		 * Verify that the IRE has been around for a while.
609 		 * This is to protect against transport protocols
610 		 * that are too eager in sending delete messages.
611 		 */
612 		if (gethrestime_sec() <
613 		    ire->ire_create_time + ipst->ips_ip_ignore_delete_time) {
614 			ire_refrele(ire);
615 			return (EINVAL);
616 		}
617 		/*
618 		 * Now we have a potentially dead cache entry. We need
619 		 * to remove it.
620 		 * If this cache entry is generated from a
621 		 * default route (i.e., ire_cmask == 0),
622 		 * search the default list and mark it dead and some
623 		 * background process will try to activate it.
624 		 */
625 		if ((ire->ire_gateway_addr != 0) && (ire->ire_cmask == 0)) {
626 			/*
627 			 * Make sure that we pick a different
628 			 * IRE_DEFAULT next time.
629 			 */
630 			ire_t *gw_ire;
631 			irb_t *irb = NULL;
632 			uint_t match_flags;
633 
634 			match_flags = (MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE);
635 
636 			gire = ire_ftable_lookup(ire->ire_addr,
637 			    ire->ire_cmask, 0, 0,
638 			    ire->ire_ipif, NULL, zoneid, 0, NULL, match_flags,
639 			    ipst);
640 
641 			ip3dbg(("ire_ftable_lookup() returned gire %p\n",
642 			    (void *)gire));
643 
644 			if (gire != NULL) {
645 				irb = gire->ire_bucket;
646 
647 				/*
648 				 * We grab it as writer just to serialize
649 				 * multiple threads trying to bump up
650 				 * irb_rr_origin
651 				 */
652 				rw_enter(&irb->irb_lock, RW_WRITER);
653 				if ((gw_ire = irb->irb_rr_origin) == NULL) {
654 					rw_exit(&irb->irb_lock);
655 					goto done;
656 				}
657 
658 				DTRACE_PROBE1(ip__ire__del__origin,
659 				    (ire_t *), gw_ire);
660 
661 				/* Skip past the potentially bad gateway */
662 				if (ire->ire_gateway_addr ==
663 				    gw_ire->ire_gateway_addr) {
664 					ire_t *next = gw_ire->ire_next;
665 
666 					DTRACE_PROBE2(ip__ire__del,
667 					    (ire_t *), gw_ire, (irb_t *), irb);
668 					IRE_FIND_NEXT_ORIGIN(next);
669 					irb->irb_rr_origin = next;
670 				}
671 				rw_exit(&irb->irb_lock);
672 			}
673 		}
674 done:
675 		if (gire != NULL)
676 			IRE_REFRELE(gire);
677 		/* report the bad route to routing sockets */
678 		ip_rts_change(RTM_LOSING, ire->ire_addr, ire->ire_gateway_addr,
679 		    ire->ire_mask, ire->ire_src_addr, 0, 0, 0,
680 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_IFA), ipst);
681 		routing_sock_info = B_TRUE;
682 
683 		/*
684 		 * TCP is really telling us to start over completely, and it
685 		 * expects that we'll resend the ARP query.  Tell ARP to
686 		 * discard the entry, if this is a local destination.
687 		 */
688 		ill = ire->ire_stq->q_ptr;
689 		if (ire->ire_gateway_addr == 0 &&
690 		    (arp_mp = ill_ared_alloc(ill, addr)) != NULL) {
691 			putnext(ill->ill_rq, arp_mp);
692 		}
693 
694 		ire_delete(ire);
695 		ire_refrele(ire);
696 	}
697 	/*
698 	 * Also look for an IRE_HOST type redirect ire and
699 	 * remove it if present.
700 	 */
701 	ire = ire_route_lookup(addr, 0, 0, IRE_HOST, NULL, NULL,
702 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
703 
704 	/* Nail it. */
705 	if (ire != NULL) {
706 		if (ire->ire_flags & RTF_DYNAMIC) {
707 			if (!routing_sock_info) {
708 				ip_rts_change(RTM_LOSING, ire->ire_addr,
709 				    ire->ire_gateway_addr, ire->ire_mask,
710 				    ire->ire_src_addr, 0, 0, 0,
711 				    (RTA_DST | RTA_GATEWAY |
712 				    RTA_NETMASK | RTA_IFA),
713 				    ipst);
714 			}
715 			ire_delete(ire);
716 		}
717 		ire_refrele(ire);
718 	}
719 	return (0);
720 }
721 
722 /*
723  * Named Dispatch routine to produce a formatted report on all IREs.
724  * This report is accessed by using the ndd utility to "get" ND variable
725  * "ipv4_ire_status".
726  */
727 /* ARGSUSED */
728 int
729 ip_ire_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
730 {
731 	zoneid_t zoneid;
732 	ip_stack_t	*ipst;
733 
734 	if (CONN_Q(q))
735 		ipst = CONNQ_TO_IPST(q);
736 	else
737 		ipst = ILLQ_TO_IPST(q);
738 
739 	(void) mi_mpprintf(mp,
740 	    "IRE      " MI_COL_HDRPAD_STR
741 	/*   01234567[89ABCDEF] */
742 	    "rfq      " MI_COL_HDRPAD_STR
743 	/*   01234567[89ABCDEF] */
744 	    "stq      " MI_COL_HDRPAD_STR
745 	/*   01234567[89ABCDEF] */
746 	    " zone "
747 	/*   12345 */
748 	    "addr            mask            "
749 	/*   123.123.123.123 123.123.123.123 */
750 	    "src             gateway         mxfrg rtt   rtt_sd ssthresh ref "
751 	/*   123.123.123.123 123.123.123.123 12345 12345 123456 12345678 123 */
752 	    "rtomax tstamp_ok wscale_ok ecn_ok pmtud_ok sack sendpipe "
753 	/*   123456 123456789 123456789 123456 12345678 1234 12345678 */
754 	    "recvpipe in/out/forward type");
755 	/*   12345678 in/out/forward xxxxxxxxxx */
756 
757 	/*
758 	 * Because of the ndd constraint, at most we can have 64K buffer
759 	 * to put in all IRE info.  So to be more efficient, just
760 	 * allocate a 64K buffer here, assuming we need that large buffer.
761 	 * This should be OK as only root can do ndd /dev/ip.
762 	 */
763 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
764 		/* The following may work even if we cannot get a large buf. */
765 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
766 		return (0);
767 	}
768 
769 	zoneid = Q_TO_CONN(q)->conn_zoneid;
770 	if (zoneid == GLOBAL_ZONEID)
771 		zoneid = ALL_ZONES;
772 
773 	ire_walk_v4(ire_report_ftable, mp->b_cont, zoneid, ipst);
774 	ire_walk_v4(ire_report_ctable, mp->b_cont, zoneid, ipst);
775 
776 	return (0);
777 }
778 
779 
780 /* ire_walk routine invoked for ip_ire_report for each cached IRE. */
781 static void
782 ire_report_ctable(ire_t *ire, char *mp)
783 {
784 	char	buf1[16];
785 	char	buf2[16];
786 	char	buf3[16];
787 	char	buf4[16];
788 	uint_t	fo_pkt_count;
789 	uint_t	ib_pkt_count;
790 	int	ref;
791 	uint_t	print_len, buf_len;
792 
793 	if ((ire->ire_type & IRE_CACHETABLE) == 0)
794 		return;
795 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
796 	if (buf_len <= 0)
797 		return;
798 
799 	/* Number of active references of this ire */
800 	ref = ire->ire_refcnt;
801 	/* "inbound" to a non local address is a forward */
802 	ib_pkt_count = ire->ire_ib_pkt_count;
803 	fo_pkt_count = 0;
804 	if (!(ire->ire_type & (IRE_LOCAL|IRE_BROADCAST))) {
805 		fo_pkt_count = ib_pkt_count;
806 		ib_pkt_count = 0;
807 	}
808 	print_len =  snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
809 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR "%5d "
810 	    "%s %s %s %s %05d %05ld %06ld %08d %03d %06d %09d %09d %06d %08d "
811 	    "%04d %08d %08d %d/%d/%d %s\n",
812 	    (void *)ire, (void *)ire->ire_rfq, (void *)ire->ire_stq,
813 	    (int)ire->ire_zoneid,
814 	    ip_dot_addr(ire->ire_addr, buf1), ip_dot_addr(ire->ire_mask, buf2),
815 	    ip_dot_addr(ire->ire_src_addr, buf3),
816 	    ip_dot_addr(ire->ire_gateway_addr, buf4),
817 	    ire->ire_max_frag, ire->ire_uinfo.iulp_rtt,
818 	    ire->ire_uinfo.iulp_rtt_sd, ire->ire_uinfo.iulp_ssthresh, ref,
819 	    ire->ire_uinfo.iulp_rtomax,
820 	    (ire->ire_uinfo.iulp_tstamp_ok ? 1: 0),
821 	    (ire->ire_uinfo.iulp_wscale_ok ? 1: 0),
822 	    (ire->ire_uinfo.iulp_ecn_ok ? 1: 0),
823 	    (ire->ire_uinfo.iulp_pmtud_ok ? 1: 0),
824 	    ire->ire_uinfo.iulp_sack,
825 	    ire->ire_uinfo.iulp_spipe, ire->ire_uinfo.iulp_rpipe,
826 	    ib_pkt_count, ire->ire_ob_pkt_count, fo_pkt_count,
827 	    ip_nv_lookup(ire_nv_tbl, (int)ire->ire_type));
828 	if (print_len < buf_len) {
829 		((mblk_t *)mp)->b_wptr += print_len;
830 	} else {
831 		((mblk_t *)mp)->b_wptr += buf_len;
832 	}
833 }
834 
835 /*
836  * ip_ire_req is called by ip_wput when an IRE_DB_REQ_TYPE message is handed
837  * down from the Upper Level Protocol to request a copy of the IRE (to check
838  * its type or to extract information like round-trip time estimates or the
839  * MTU.)
840  * The address is assumed to be in the ire_addr field. If no IRE is found
841  * an IRE is returned with ire_type being zero.
842  * Note that the upper lavel protocol has to check for broadcast
843  * (IRE_BROADCAST) and multicast (CLASSD(addr)).
844  * If there is a b_cont the resulting IRE_DB_TYPE mblk is placed at the
845  * end of the returned message.
846  *
847  * TCP sends down a message of this type with a connection request packet
848  * chained on. UDP and ICMP send it down to verify that a route exists for
849  * the destination address when they get connected.
850  */
851 void
852 ip_ire_req(queue_t *q, mblk_t *mp)
853 {
854 	ire_t	*inire;
855 	ire_t	*ire;
856 	mblk_t	*mp1;
857 	ire_t	*sire = NULL;
858 	zoneid_t zoneid = Q_TO_CONN(q)->conn_zoneid;
859 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
860 
861 	ASSERT(q->q_next == NULL);
862 
863 	if ((mp->b_wptr - mp->b_rptr) < sizeof (ire_t) ||
864 	    !OK_32PTR(mp->b_rptr)) {
865 		freemsg(mp);
866 		return;
867 	}
868 	inire = (ire_t *)mp->b_rptr;
869 	/*
870 	 * Got it, now take our best shot at an IRE.
871 	 */
872 	if (inire->ire_ipversion == IPV6_VERSION) {
873 		ire = ire_route_lookup_v6(&inire->ire_addr_v6, 0, 0, 0,
874 		    NULL, &sire, zoneid, NULL,
875 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT), ipst);
876 	} else {
877 		ASSERT(inire->ire_ipversion == IPV4_VERSION);
878 		ire = ire_route_lookup(inire->ire_addr, 0, 0, 0,
879 		    NULL, &sire, zoneid, NULL,
880 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT), ipst);
881 	}
882 
883 	/*
884 	 * We prevent returning IRES with source address INADDR_ANY
885 	 * as these were temporarily created for sending packets
886 	 * from endpoints that have conn_unspec_src set.
887 	 */
888 	if (ire == NULL ||
889 	    (ire->ire_ipversion == IPV4_VERSION &&
890 	    ire->ire_src_addr == INADDR_ANY) ||
891 	    (ire->ire_ipversion == IPV6_VERSION &&
892 	    IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6))) {
893 		inire->ire_type = 0;
894 	} else {
895 		bcopy(ire, inire, sizeof (ire_t));
896 		/* Copy the route metrics from the parent. */
897 		if (sire != NULL) {
898 			bcopy(&(sire->ire_uinfo), &(inire->ire_uinfo),
899 			    sizeof (iulp_t));
900 		}
901 
902 		/*
903 		 * As we don't lookup global policy here, we may not
904 		 * pass the right size if per-socket policy is not
905 		 * present. For these cases, path mtu discovery will
906 		 * do the right thing.
907 		 */
908 		inire->ire_ipsec_overhead = conn_ipsec_length(Q_TO_CONN(q));
909 
910 		/* Pass the latest setting of the ip_path_mtu_discovery */
911 		inire->ire_frag_flag |=
912 		    (ipst->ips_ip_path_mtu_discovery) ? IPH_DF : 0;
913 	}
914 	if (ire != NULL)
915 		ire_refrele(ire);
916 	if (sire != NULL)
917 		ire_refrele(sire);
918 	mp->b_wptr = &mp->b_rptr[sizeof (ire_t)];
919 	mp->b_datap->db_type = IRE_DB_TYPE;
920 
921 	/* Put the IRE_DB_TYPE mblk last in the chain */
922 	mp1 = mp->b_cont;
923 	if (mp1 != NULL) {
924 		mp->b_cont = NULL;
925 		linkb(mp1, mp);
926 		mp = mp1;
927 	}
928 	qreply(q, mp);
929 }
930 
931 /*
932  * Send a packet using the specified IRE.
933  * If ire_src_addr_v6 is all zero then discard the IRE after
934  * the packet has been sent.
935  */
936 static void
937 ire_send(queue_t *q, mblk_t *pkt, ire_t *ire)
938 {
939 	mblk_t *ipsec_mp;
940 	boolean_t is_secure;
941 	uint_t ifindex;
942 	ill_t	*ill;
943 	zoneid_t zoneid = ire->ire_zoneid;
944 	ip_stack_t	*ipst = ire->ire_ipst;
945 
946 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
947 	ASSERT(!(ire->ire_type & IRE_LOCAL)); /* Has different ire_zoneid */
948 	ipsec_mp = pkt;
949 	is_secure = (pkt->b_datap->db_type == M_CTL);
950 	if (is_secure) {
951 		ipsec_out_t *io;
952 
953 		pkt = pkt->b_cont;
954 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
955 		if (io->ipsec_out_type == IPSEC_OUT)
956 			zoneid = io->ipsec_out_zoneid;
957 	}
958 
959 	/* If the packet originated externally then */
960 	if (pkt->b_prev) {
961 		ire_refrele(ire);
962 		/*
963 		 * Extract the ifindex from b_prev (set in ip_rput_noire).
964 		 * Look up interface to see if it still exists (it could have
965 		 * been unplumbed by the time the reply came back from ARP)
966 		 */
967 		ifindex = (uint_t)(uintptr_t)pkt->b_prev;
968 		ill = ill_lookup_on_ifindex(ifindex, B_FALSE,
969 		    NULL, NULL, NULL, NULL, ipst);
970 		if (ill == NULL) {
971 			pkt->b_prev = NULL;
972 			pkt->b_next = NULL;
973 			freemsg(ipsec_mp);
974 			return;
975 		}
976 		q = ill->ill_rq;
977 		pkt->b_prev = NULL;
978 		/*
979 		 * This packet has not gone through IPSEC processing
980 		 * and hence we should not have any IPSEC message
981 		 * prepended.
982 		 */
983 		ASSERT(ipsec_mp == pkt);
984 		put(q, pkt);
985 		ill_refrele(ill);
986 	} else if (pkt->b_next) {
987 		/* Packets from multicast router */
988 		pkt->b_next = NULL;
989 		/*
990 		 * We never get the IPSEC_OUT while forwarding the
991 		 * packet for multicast router.
992 		 */
993 		ASSERT(ipsec_mp == pkt);
994 		ip_rput_forward(ire, (ipha_t *)pkt->b_rptr, ipsec_mp, NULL);
995 		ire_refrele(ire);
996 	} else {
997 		/* Locally originated packets */
998 		boolean_t is_inaddr_any;
999 		ipha_t *ipha = (ipha_t *)pkt->b_rptr;
1000 
1001 		/*
1002 		 * We need to do an ire_delete below for which
1003 		 * we need to make sure that the IRE will be
1004 		 * around even after calling ip_wput_ire -
1005 		 * which does ire_refrele. Otherwise somebody
1006 		 * could potentially delete this ire and hence
1007 		 * free this ire and we will be calling ire_delete
1008 		 * on a freed ire below.
1009 		 */
1010 		is_inaddr_any = (ire->ire_src_addr == INADDR_ANY);
1011 		if (is_inaddr_any) {
1012 			IRE_REFHOLD(ire);
1013 		}
1014 		/*
1015 		 * If we were resolving a router we can not use the
1016 		 * routers IRE for sending the packet (since it would
1017 		 * violate the uniqness of the IP idents) thus we
1018 		 * make another pass through ip_wput to create the IRE_CACHE
1019 		 * for the destination.
1020 		 * When IRE_MARK_NOADD is set, ire_add() is not called.
1021 		 * Thus ip_wput() will never find a ire and result in an
1022 		 * infinite loop. Thus we check whether IRE_MARK_NOADD is
1023 		 * is set. This also implies that IRE_MARK_NOADD can only be
1024 		 * used to send packets to directly connected hosts.
1025 		 */
1026 		if (ipha->ipha_dst != ire->ire_addr &&
1027 		    !(ire->ire_marks & IRE_MARK_NOADD)) {
1028 			ire_refrele(ire);	/* Held in ire_add */
1029 			if (CONN_Q(q)) {
1030 				(void) ip_output(Q_TO_CONN(q), ipsec_mp, q,
1031 				    IRE_SEND);
1032 			} else {
1033 				(void) ip_output((void *)(uintptr_t)zoneid,
1034 				    ipsec_mp, q, IRE_SEND);
1035 			}
1036 		} else {
1037 			if (is_secure) {
1038 				ipsec_out_t *oi;
1039 				ipha_t *ipha;
1040 
1041 				oi = (ipsec_out_t *)ipsec_mp->b_rptr;
1042 				ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
1043 				if (oi->ipsec_out_proc_begin) {
1044 					/*
1045 					 * This is the case where
1046 					 * ip_wput_ipsec_out could not find
1047 					 * the IRE and recreated a new one.
1048 					 * As ip_wput_ipsec_out does ire
1049 					 * lookups, ire_refrele for the extra
1050 					 * bump in ire_add.
1051 					 */
1052 					ire_refrele(ire);
1053 					ip_wput_ipsec_out(q, ipsec_mp, ipha,
1054 					    NULL, NULL);
1055 				} else {
1056 					/*
1057 					 * IRE_REFRELE will be done in
1058 					 * ip_wput_ire.
1059 					 */
1060 					ip_wput_ire(q, ipsec_mp, ire, NULL,
1061 					    IRE_SEND, zoneid);
1062 				}
1063 			} else {
1064 				/*
1065 				 * IRE_REFRELE will be done in ip_wput_ire.
1066 				 */
1067 				ip_wput_ire(q, ipsec_mp, ire, NULL,
1068 				    IRE_SEND, zoneid);
1069 			}
1070 		}
1071 		/*
1072 		 * Special code to support sending a single packet with
1073 		 * conn_unspec_src using an IRE which has no source address.
1074 		 * The IRE is deleted here after sending the packet to avoid
1075 		 * having other code trip on it. But before we delete the
1076 		 * ire, somebody could have looked up this ire.
1077 		 * We prevent returning/using this IRE by the upper layers
1078 		 * by making checks to NULL source address in other places
1079 		 * like e.g ip_ire_append, ip_ire_req and ip_bind_connected.
1080 		 * Though, this does not completely prevent other threads
1081 		 * from using this ire, this should not cause any problems.
1082 		 *
1083 		 * NOTE : We use is_inaddr_any instead of using ire_src_addr
1084 		 * because for the normal case i.e !is_inaddr_any, ire_refrele
1085 		 * above could have potentially freed the ire.
1086 		 */
1087 		if (is_inaddr_any) {
1088 			/*
1089 			 * If this IRE has been deleted by another thread, then
1090 			 * ire_bucket won't be NULL, but ire_ptpn will be NULL.
1091 			 * Thus, ire_delete will do nothing.  This check
1092 			 * guards against calling ire_delete when the IRE was
1093 			 * never inserted in the table, which is handled by
1094 			 * ire_delete as dropping another reference.
1095 			 */
1096 			if (ire->ire_bucket != NULL) {
1097 				ip1dbg(("ire_send: delete IRE\n"));
1098 				ire_delete(ire);
1099 			}
1100 			ire_refrele(ire);	/* Held above */
1101 		}
1102 	}
1103 }
1104 
1105 /*
1106  * Send a packet using the specified IRE.
1107  * If ire_src_addr_v6 is all zero then discard the IRE after
1108  * the packet has been sent.
1109  */
1110 static void
1111 ire_send_v6(queue_t *q, mblk_t *pkt, ire_t *ire)
1112 {
1113 	mblk_t *ipsec_mp;
1114 	boolean_t secure;
1115 	uint_t ifindex;
1116 	zoneid_t zoneid = ire->ire_zoneid;
1117 	ip_stack_t	*ipst = ire->ire_ipst;
1118 
1119 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
1120 	ASSERT(!(ire->ire_type & IRE_LOCAL)); /* Has different ire_zoneid */
1121 	if (pkt->b_datap->db_type == M_CTL) {
1122 		ipsec_out_t *io;
1123 
1124 		ipsec_mp = pkt;
1125 		pkt = pkt->b_cont;
1126 		secure = B_TRUE;
1127 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
1128 		if (io->ipsec_out_type == IPSEC_OUT)
1129 			zoneid = io->ipsec_out_zoneid;
1130 	} else {
1131 		ipsec_mp = pkt;
1132 		secure = B_FALSE;
1133 	}
1134 
1135 	/* If the packet originated externally then */
1136 	if (pkt->b_prev) {
1137 		ill_t	*ill;
1138 		/*
1139 		 * Extract the ifindex from b_prev (set in ip_rput_data_v6).
1140 		 * Look up interface to see if it still exists (it could have
1141 		 * been unplumbed by the time the reply came back from the
1142 		 * resolver).
1143 		 */
1144 		ifindex = (uint_t)(uintptr_t)pkt->b_prev;
1145 		ill = ill_lookup_on_ifindex(ifindex, B_TRUE,
1146 		    NULL, NULL, NULL, NULL, ipst);
1147 		if (ill == NULL) {
1148 			pkt->b_prev = NULL;
1149 			pkt->b_next = NULL;
1150 			freemsg(ipsec_mp);
1151 			ire_refrele(ire);	/* Held in ire_add */
1152 			return;
1153 		}
1154 		q = ill->ill_rq;
1155 		pkt->b_prev = NULL;
1156 		/*
1157 		 * This packet has not gone through IPSEC processing
1158 		 * and hence we should not have any IPSEC message
1159 		 * prepended.
1160 		 */
1161 		ASSERT(ipsec_mp == pkt);
1162 		put(q, pkt);
1163 		ill_refrele(ill);
1164 	} else if (pkt->b_next) {
1165 		/* Packets from multicast router */
1166 		pkt->b_next = NULL;
1167 		/*
1168 		 * We never get the IPSEC_OUT while forwarding the
1169 		 * packet for multicast router.
1170 		 */
1171 		ASSERT(ipsec_mp == pkt);
1172 		/*
1173 		 * XXX TODO IPv6.
1174 		 */
1175 		freemsg(pkt);
1176 #ifdef XXX
1177 		ip_rput_forward(ire, (ipha_t *)pkt->b_rptr, pkt, NULL);
1178 #endif
1179 	} else {
1180 		if (secure) {
1181 			ipsec_out_t *oi;
1182 			ip6_t *ip6h;
1183 
1184 			oi = (ipsec_out_t *)ipsec_mp->b_rptr;
1185 			ip6h = (ip6_t *)ipsec_mp->b_cont->b_rptr;
1186 			if (oi->ipsec_out_proc_begin) {
1187 				/*
1188 				 * This is the case where
1189 				 * ip_wput_ipsec_out could not find
1190 				 * the IRE and recreated a new one.
1191 				 */
1192 				ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h,
1193 				    NULL, NULL);
1194 			} else {
1195 				if (CONN_Q(q)) {
1196 					(void) ip_output_v6(Q_TO_CONN(q),
1197 					    ipsec_mp, q, IRE_SEND);
1198 				} else {
1199 					(void) ip_output_v6(
1200 					    (void *)(uintptr_t)zoneid,
1201 					    ipsec_mp, q, IRE_SEND);
1202 				}
1203 			}
1204 		} else {
1205 			/*
1206 			 * Send packets through ip_output_v6 so that any
1207 			 * ip6_info header can be processed again.
1208 			 */
1209 			if (CONN_Q(q)) {
1210 				(void) ip_output_v6(Q_TO_CONN(q), ipsec_mp, q,
1211 				    IRE_SEND);
1212 			} else {
1213 				(void) ip_output_v6((void *)(uintptr_t)zoneid,
1214 				    ipsec_mp, q, IRE_SEND);
1215 			}
1216 		}
1217 		/*
1218 		 * Special code to support sending a single packet with
1219 		 * conn_unspec_src using an IRE which has no source address.
1220 		 * The IRE is deleted here after sending the packet to avoid
1221 		 * having other code trip on it. But before we delete the
1222 		 * ire, somebody could have looked up this ire.
1223 		 * We prevent returning/using this IRE by the upper layers
1224 		 * by making checks to NULL source address in other places
1225 		 * like e.g ip_ire_append_v6, ip_ire_req and
1226 		 * ip_bind_connected_v6. Though, this does not completely
1227 		 * prevent other threads from using this ire, this should
1228 		 * not cause any problems.
1229 		 */
1230 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_src_addr_v6)) {
1231 			ip1dbg(("ire_send_v6: delete IRE\n"));
1232 			ire_delete(ire);
1233 		}
1234 	}
1235 	ire_refrele(ire);	/* Held in ire_add */
1236 }
1237 
1238 /*
1239  * Make sure that IRE bucket does not get too long.
1240  * This can cause lock up because ire_cache_lookup()
1241  * may take "forever" to finish.
1242  *
1243  * We just remove cnt IREs each time.  This means that
1244  * the bucket length will stay approximately constant,
1245  * depending on cnt.  This should be enough to defend
1246  * against DoS attack based on creating temporary IREs
1247  * (for forwarding and non-TCP traffic).
1248  *
1249  * Note that new IRE is normally added at the tail of the
1250  * bucket.  This means that we are removing the "oldest"
1251  * temporary IRE added.  Only if there are IREs with
1252  * the same ire_addr, do we not add it at the tail.  Refer
1253  * to ire_add_v*().  It should be OK for our purpose.
1254  *
1255  * For non-temporary cached IREs, we make sure that they
1256  * have not been used for some time (defined below), they
1257  * are non-local destinations, and there is no one using
1258  * them at the moment (refcnt == 1).
1259  *
1260  * The above means that the IRE bucket length may become
1261  * very long, consisting of mostly non-temporary IREs.
1262  * This can happen when the hash function does a bad job
1263  * so that most TCP connections cluster to a specific bucket.
1264  * This "hopefully" should never happen.  It can also
1265  * happen if most TCP connections have very long lives.
1266  * Even with the minimal hash table size of 256, there
1267  * has to be a lot of such connections to make the bucket
1268  * length unreasonably long.  This should probably not
1269  * happen either.  The third can when this can happen is
1270  * when the machine is under attack, such as SYN flooding.
1271  * TCP should already have the proper mechanism to protect
1272  * that.  So we should be safe.
1273  *
1274  * This function is called by ire_add_then_send() after
1275  * a new IRE is added and the packet is sent.
1276  *
1277  * The idle cutoff interval is set to 60s.  It can be
1278  * changed using /etc/system.
1279  */
1280 uint32_t ire_idle_cutoff_interval = 60000;
1281 
1282 static void
1283 ire_cache_cleanup(irb_t *irb, uint32_t threshold, int cnt)
1284 {
1285 	ire_t *ire;
1286 	int tmp_cnt = cnt;
1287 	clock_t cut_off = drv_usectohz(ire_idle_cutoff_interval * 1000);
1288 
1289 	/*
1290 	 * irb is NULL if the IRE is not added to the hash.  This
1291 	 * happens when IRE_MARK_NOADD is set in ire_add_then_send().
1292 	 */
1293 	if (irb == NULL)
1294 		return;
1295 
1296 	IRB_REFHOLD(irb);
1297 	if (irb->irb_tmp_ire_cnt > threshold) {
1298 		for (ire = irb->irb_ire; ire != NULL && tmp_cnt > 0;
1299 		    ire = ire->ire_next) {
1300 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
1301 				continue;
1302 			if (ire->ire_marks & IRE_MARK_TEMPORARY) {
1303 				ASSERT(ire->ire_type == IRE_CACHE);
1304 				ire_delete(ire);
1305 				tmp_cnt--;
1306 			}
1307 		}
1308 	}
1309 	if (irb->irb_ire_cnt - irb->irb_tmp_ire_cnt > threshold) {
1310 		for (ire = irb->irb_ire; ire != NULL && cnt > 0;
1311 		    ire = ire->ire_next) {
1312 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
1313 				continue;
1314 			if (ire->ire_ipversion == IPV4_VERSION) {
1315 				if (ire->ire_gateway_addr == 0)
1316 					continue;
1317 			} else {
1318 				if (IN6_IS_ADDR_UNSPECIFIED(
1319 				    &ire->ire_gateway_addr_v6))
1320 					continue;
1321 			}
1322 			if ((ire->ire_type == IRE_CACHE) &&
1323 			    (lbolt - ire->ire_last_used_time > cut_off) &&
1324 			    (ire->ire_refcnt == 1)) {
1325 				ire_delete(ire);
1326 				cnt--;
1327 			}
1328 		}
1329 	}
1330 	IRB_REFRELE(irb);
1331 }
1332 
1333 /*
1334  * ire_add_then_send is called when a new IRE has been created in order to
1335  * route an outgoing packet.  Typically, it is called from ip_wput when
1336  * a response comes back down from a resolver.  We add the IRE, and then
1337  * possibly run the packet through ip_wput or ip_rput, as appropriate.
1338  * However, we do not add the newly created IRE in the cache when
1339  * IRE_MARK_NOADD is set in the IRE. IRE_MARK_NOADD is set at
1340  * ip_newroute_ipif(). The ires with IRE_MARK_NOADD are ire_refrele'd by
1341  * ip_wput_ire() and get deleted.
1342  * Multirouting support: the packet is silently discarded when the new IRE
1343  * holds the RTF_MULTIRT flag, but is not the first IRE to be added with the
1344  * RTF_MULTIRT flag for the same destination address.
1345  * In this case, we just want to register this additional ire without
1346  * sending the packet, as it has already been replicated through
1347  * existing multirt routes in ip_wput().
1348  */
1349 void
1350 ire_add_then_send(queue_t *q, ire_t *ire, mblk_t *mp)
1351 {
1352 	irb_t *irb;
1353 	boolean_t drop = B_FALSE;
1354 	/* LINTED : set but not used in function */
1355 	boolean_t mctl_present;
1356 	mblk_t *first_mp = NULL;
1357 	mblk_t *save_mp = NULL;
1358 	ire_t *dst_ire;
1359 	ipha_t *ipha;
1360 	ip6_t *ip6h;
1361 	ip_stack_t	*ipst = ire->ire_ipst;
1362 
1363 	if (mp != NULL) {
1364 		/*
1365 		 * We first have to retrieve the destination address carried
1366 		 * by the packet.
1367 		 * We can't rely on ire as it can be related to a gateway.
1368 		 * The destination address will help in determining if
1369 		 * other RTF_MULTIRT ires are already registered.
1370 		 *
1371 		 * We first need to know where we are going : v4 or V6.
1372 		 * the ire version is enough, as there is no risk that
1373 		 * we resolve an IPv6 address with an IPv4 ire
1374 		 * or vice versa.
1375 		 */
1376 		if (ire->ire_ipversion == IPV4_VERSION) {
1377 			EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1378 			ipha = (ipha_t *)mp->b_rptr;
1379 			save_mp = mp;
1380 			mp = first_mp;
1381 
1382 			dst_ire = ire_cache_lookup(ipha->ipha_dst,
1383 			    ire->ire_zoneid, MBLK_GETLABEL(mp), ipst);
1384 		} else {
1385 			ASSERT(ire->ire_ipversion == IPV6_VERSION);
1386 			/*
1387 			 * Get a pointer to the beginning of the IPv6 header.
1388 			 * Ignore leading IPsec control mblks.
1389 			 */
1390 			first_mp = mp;
1391 			if (mp->b_datap->db_type == M_CTL) {
1392 				mp = mp->b_cont;
1393 			}
1394 			ip6h = (ip6_t *)mp->b_rptr;
1395 			save_mp = mp;
1396 			mp = first_mp;
1397 			dst_ire = ire_cache_lookup_v6(&ip6h->ip6_dst,
1398 			    ire->ire_zoneid, MBLK_GETLABEL(mp), ipst);
1399 		}
1400 		if (dst_ire != NULL) {
1401 			if (dst_ire->ire_flags & RTF_MULTIRT) {
1402 				/*
1403 				 * At least one resolved multirt route
1404 				 * already exists for the destination,
1405 				 * don't sent this packet: either drop it
1406 				 * or complete the pending resolution,
1407 				 * depending on the ire.
1408 				 */
1409 				drop = B_TRUE;
1410 			}
1411 			ip1dbg(("ire_add_then_send: dst_ire %p "
1412 			    "[dst %08x, gw %08x], drop %d\n",
1413 			    (void *)dst_ire,
1414 			    (dst_ire->ire_ipversion == IPV4_VERSION) ? \
1415 			    ntohl(dst_ire->ire_addr) : \
1416 			    ntohl(V4_PART_OF_V6(dst_ire->ire_addr_v6)),
1417 			    (dst_ire->ire_ipversion == IPV4_VERSION) ? \
1418 			    ntohl(dst_ire->ire_gateway_addr) : \
1419 			    ntohl(V4_PART_OF_V6(
1420 			    dst_ire->ire_gateway_addr_v6)),
1421 			    drop));
1422 			ire_refrele(dst_ire);
1423 		}
1424 	}
1425 
1426 	if (!(ire->ire_marks & IRE_MARK_NOADD)) {
1427 		/* Regular packets with cache bound ires are here. */
1428 		(void) ire_add(&ire, NULL, NULL, NULL, B_FALSE);
1429 
1430 		if (ire == NULL) {
1431 			mp->b_prev = NULL;
1432 			mp->b_next = NULL;
1433 			MULTIRT_DEBUG_UNTAG(mp);
1434 			freemsg(mp);
1435 			return;
1436 		}
1437 		if (mp == NULL) {
1438 			ire_refrele(ire);	/* Held in ire_add_v4/v6 */
1439 			return;
1440 		}
1441 	}
1442 	if (drop) {
1443 		/*
1444 		 * If we're adding an RTF_MULTIRT ire, the resolution
1445 		 * is over: we just drop the packet.
1446 		 */
1447 		if (ire->ire_flags & RTF_MULTIRT) {
1448 			if (save_mp) {
1449 				save_mp->b_prev = NULL;
1450 				save_mp->b_next = NULL;
1451 			}
1452 			MULTIRT_DEBUG_UNTAG(mp);
1453 			freemsg(mp);
1454 		} else {
1455 			/*
1456 			 * Otherwise, we're adding the ire to a gateway
1457 			 * for a multirt route.
1458 			 * Invoke ip_newroute() to complete the resolution
1459 			 * of the route. We will then come back here and
1460 			 * finally drop this packet in the above code.
1461 			 */
1462 			if (ire->ire_ipversion == IPV4_VERSION) {
1463 				/*
1464 				 * TODO: in order for CGTP to work in non-global
1465 				 * zones, ip_newroute() must create the IRE
1466 				 * cache in the zone indicated by
1467 				 * ire->ire_zoneid.
1468 				 */
1469 				ip_newroute(q, mp, ipha->ipha_dst,
1470 				    (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
1471 				    ire->ire_zoneid, ipst);
1472 			} else {
1473 				ASSERT(ire->ire_ipversion == IPV6_VERSION);
1474 				ip_newroute_v6(q, mp, &ip6h->ip6_dst, NULL,
1475 				    NULL, ire->ire_zoneid, ipst);
1476 			}
1477 		}
1478 
1479 		ire_refrele(ire); /* As done by ire_send(). */
1480 		return;
1481 	}
1482 	/*
1483 	 * Need to remember ire_bucket here as ire_send*() may delete
1484 	 * the ire so we cannot reference it after that.
1485 	 */
1486 	irb = ire->ire_bucket;
1487 	if (ire->ire_ipversion == IPV6_VERSION) {
1488 		ire_send_v6(q, mp, ire);
1489 		/*
1490 		 * Clean up more than 1 IRE so that the clean up does not
1491 		 * need to be done every time when a new IRE is added and
1492 		 * the threshold is reached.
1493 		 */
1494 		ire_cache_cleanup(irb, ip6_ire_max_bucket_cnt, 2);
1495 	} else {
1496 		ire_send(q, mp, ire);
1497 		ire_cache_cleanup(irb, ip_ire_max_bucket_cnt, 2);
1498 	}
1499 }
1500 
1501 /*
1502  * Initialize the ire that is specific to IPv4 part and call
1503  * ire_init_common to finish it.
1504  */
1505 ire_t *
1506 ire_init(ire_t *ire, uchar_t *addr, uchar_t *mask, uchar_t *src_addr,
1507     uchar_t *gateway, uint_t *max_fragp, nce_t *src_nce, queue_t *rfq,
1508     queue_t *stq, ushort_t type, ipif_t *ipif, ipaddr_t cmask, uint32_t phandle,
1509     uint32_t ihandle, uint32_t flags, const iulp_t *ulp_info, tsol_gc_t *gc,
1510     tsol_gcgrp_t *gcgrp, ip_stack_t *ipst)
1511 {
1512 	/*
1513 	 * Reject IRE security attribute creation/initialization
1514 	 * if system is not running in Trusted mode.
1515 	 */
1516 	if ((gc != NULL || gcgrp != NULL) && !is_system_labeled())
1517 		return (NULL);
1518 
1519 
1520 	BUMP_IRE_STATS(ipst->ips_ire_stats_v4, ire_stats_alloced);
1521 
1522 	if (addr != NULL)
1523 		bcopy(addr, &ire->ire_addr, IP_ADDR_LEN);
1524 	if (src_addr != NULL)
1525 		bcopy(src_addr, &ire->ire_src_addr, IP_ADDR_LEN);
1526 	if (mask != NULL) {
1527 		bcopy(mask, &ire->ire_mask, IP_ADDR_LEN);
1528 		ire->ire_masklen = ip_mask_to_plen(ire->ire_mask);
1529 	}
1530 	if (gateway != NULL) {
1531 		bcopy(gateway, &ire->ire_gateway_addr, IP_ADDR_LEN);
1532 	}
1533 
1534 	if (type == IRE_CACHE)
1535 		ire->ire_cmask = cmask;
1536 
1537 	/* ire_init_common will free the mblks upon encountering any failure */
1538 	if (!ire_init_common(ire, max_fragp, src_nce, rfq, stq, type, ipif,
1539 	    phandle, ihandle, flags, IPV4_VERSION, ulp_info, gc, gcgrp, ipst))
1540 		return (NULL);
1541 
1542 	return (ire);
1543 }
1544 
1545 /*
1546  * Similar to ire_create except that it is called only when
1547  * we want to allocate ire as an mblk e.g. we have an external
1548  * resolver ARP.
1549  */
1550 ire_t *
1551 ire_create_mp(uchar_t *addr, uchar_t *mask, uchar_t *src_addr, uchar_t *gateway,
1552     uint_t max_frag, nce_t *src_nce, queue_t *rfq, queue_t *stq, ushort_t type,
1553     ipif_t *ipif, ipaddr_t cmask, uint32_t phandle, uint32_t ihandle,
1554     uint32_t flags, const iulp_t *ulp_info, tsol_gc_t *gc, tsol_gcgrp_t *gcgrp,
1555     ip_stack_t *ipst)
1556 {
1557 	ire_t	*ire, *buf;
1558 	ire_t	*ret_ire;
1559 	mblk_t	*mp;
1560 	size_t	bufsize;
1561 	frtn_t	*frtnp;
1562 	ill_t	*ill;
1563 
1564 	bufsize = sizeof (ire_t) + sizeof (frtn_t);
1565 	buf = kmem_alloc(bufsize, KM_NOSLEEP);
1566 	if (buf == NULL) {
1567 		ip1dbg(("ire_create_mp: alloc failed\n"));
1568 		return (NULL);
1569 	}
1570 	frtnp = (frtn_t *)(buf + 1);
1571 	frtnp->free_arg = (caddr_t)buf;
1572 	frtnp->free_func = ire_freemblk;
1573 
1574 	/*
1575 	 * Allocate the new IRE. The ire created will hold a ref on
1576 	 * an nce_t after ire_nce_init, and this ref must either be
1577 	 * (a)  transferred to the ire_cache entry created when ire_add_v4
1578 	 *	is called after successful arp resolution, or,
1579 	 * (b)  released, when arp resolution fails
1580 	 * Case (b) is handled in ire_freemblk() which will be called
1581 	 * when mp is freed as a result of failed arp.
1582 	 */
1583 	mp = esballoc((unsigned char *)buf, bufsize, BPRI_MED, frtnp);
1584 	if (mp == NULL) {
1585 		ip1dbg(("ire_create_mp: alloc failed\n"));
1586 		kmem_free(buf, bufsize);
1587 		return (NULL);
1588 	}
1589 	ire = (ire_t *)mp->b_rptr;
1590 	mp->b_wptr = (uchar_t *)&ire[1];
1591 
1592 	/* Start clean. */
1593 	*ire = ire_null;
1594 	ire->ire_mp = mp;
1595 	mp->b_datap->db_type = IRE_DB_TYPE;
1596 	ire->ire_marks |= IRE_MARK_UNCACHED;
1597 
1598 	ret_ire = ire_init(ire, addr, mask, src_addr, gateway, NULL, src_nce,
1599 	    rfq, stq, type, ipif, cmask, phandle, ihandle, flags, ulp_info, gc,
1600 	    gcgrp, ipst);
1601 
1602 	ill = (ill_t *)(stq->q_ptr);
1603 	if (ret_ire == NULL) {
1604 		/* ire_freemblk needs these set */
1605 		ire->ire_stq_ifindex = ill->ill_phyint->phyint_ifindex;
1606 		ire->ire_ipst = ipst;
1607 		freeb(ire->ire_mp);
1608 		return (NULL);
1609 	}
1610 	ret_ire->ire_stq_ifindex = ill->ill_phyint->phyint_ifindex;
1611 	ASSERT(ret_ire == ire);
1612 	/*
1613 	 * ire_max_frag is normally zero here and is atomically set
1614 	 * under the irebucket lock in ire_add_v[46] except for the
1615 	 * case of IRE_MARK_NOADD. In that event the the ire_max_frag
1616 	 * is non-zero here.
1617 	 */
1618 	ire->ire_max_frag = max_frag;
1619 	return (ire);
1620 }
1621 
1622 /*
1623  * ire_create is called to allocate and initialize a new IRE.
1624  *
1625  * NOTE : This is called as writer sometimes though not required
1626  * by this function.
1627  */
1628 ire_t *
1629 ire_create(uchar_t *addr, uchar_t *mask, uchar_t *src_addr, uchar_t *gateway,
1630     uint_t *max_fragp, nce_t *src_nce, queue_t *rfq, queue_t *stq,
1631     ushort_t type, ipif_t *ipif, ipaddr_t cmask, uint32_t phandle,
1632     uint32_t ihandle, uint32_t flags, const iulp_t *ulp_info, tsol_gc_t *gc,
1633     tsol_gcgrp_t *gcgrp, ip_stack_t *ipst)
1634 {
1635 	ire_t	*ire;
1636 	ire_t	*ret_ire;
1637 
1638 	ire = kmem_cache_alloc(ire_cache, KM_NOSLEEP);
1639 	if (ire == NULL) {
1640 		ip1dbg(("ire_create: alloc failed\n"));
1641 		return (NULL);
1642 	}
1643 	*ire = ire_null;
1644 
1645 	ret_ire = ire_init(ire, addr, mask, src_addr, gateway, max_fragp,
1646 	    src_nce, rfq, stq, type, ipif, cmask, phandle, ihandle, flags,
1647 	    ulp_info, gc, gcgrp, ipst);
1648 
1649 	if (ret_ire == NULL) {
1650 		kmem_cache_free(ire_cache, ire);
1651 		return (NULL);
1652 	}
1653 	ASSERT(ret_ire == ire);
1654 	return (ire);
1655 }
1656 
1657 
1658 /*
1659  * Common to IPv4 and IPv6
1660  */
1661 boolean_t
1662 ire_init_common(ire_t *ire, uint_t *max_fragp, nce_t *src_nce, queue_t *rfq,
1663     queue_t *stq, ushort_t type, ipif_t *ipif, uint32_t phandle,
1664     uint32_t ihandle, uint32_t flags, uchar_t ipversion, const iulp_t *ulp_info,
1665     tsol_gc_t *gc, tsol_gcgrp_t *gcgrp, ip_stack_t *ipst)
1666 {
1667 	ire->ire_max_fragp = max_fragp;
1668 	ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ? IPH_DF : 0;
1669 
1670 #ifdef DEBUG
1671 	if (ipif != NULL) {
1672 		if (ipif->ipif_isv6)
1673 			ASSERT(ipversion == IPV6_VERSION);
1674 		else
1675 			ASSERT(ipversion == IPV4_VERSION);
1676 	}
1677 #endif /* DEBUG */
1678 
1679 	/*
1680 	 * Create/initialize IRE security attribute only in Trusted mode;
1681 	 * if the passed in gc/gcgrp is non-NULL, we expect that the caller
1682 	 * has held a reference to it and will release it when this routine
1683 	 * returns a failure, otherwise we own the reference.  We do this
1684 	 * prior to initializing the rest IRE fields.
1685 	 *
1686 	 * Don't allocate ire_gw_secattr for the resolver case to prevent
1687 	 * memory leak (in case of external resolution failure). We'll
1688 	 * allocate it after a successful external resolution, in ire_add().
1689 	 * Note that ire->ire_mp != NULL here means this ire is headed
1690 	 * to an external resolver.
1691 	 */
1692 	if (is_system_labeled()) {
1693 		if ((type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST |
1694 		    IRE_INTERFACE)) != 0) {
1695 			/* release references on behalf of caller */
1696 			if (gc != NULL)
1697 				GC_REFRELE(gc);
1698 			if (gcgrp != NULL)
1699 				GCGRP_REFRELE(gcgrp);
1700 		} else if ((ire->ire_mp == NULL) &&
1701 		    tsol_ire_init_gwattr(ire, ipversion, gc, gcgrp) != 0) {
1702 			return (B_FALSE);
1703 		}
1704 	}
1705 
1706 	ire->ire_stq = stq;
1707 	ire->ire_rfq = rfq;
1708 	ire->ire_type = type;
1709 	ire->ire_flags = RTF_UP | flags;
1710 	ire->ire_ident = TICK_TO_MSEC(lbolt);
1711 	bcopy(ulp_info, &ire->ire_uinfo, sizeof (iulp_t));
1712 
1713 	ire->ire_tire_mark = ire->ire_ob_pkt_count + ire->ire_ib_pkt_count;
1714 	ire->ire_last_used_time = lbolt;
1715 	ire->ire_create_time = (uint32_t)gethrestime_sec();
1716 
1717 	/*
1718 	 * If this IRE is an IRE_CACHE, inherit the handles from the
1719 	 * parent IREs. For others in the forwarding table, assign appropriate
1720 	 * new ones.
1721 	 *
1722 	 * The mutex protecting ire_handle is because ire_create is not always
1723 	 * called as a writer.
1724 	 */
1725 	if (ire->ire_type & IRE_OFFSUBNET) {
1726 		mutex_enter(&ipst->ips_ire_handle_lock);
1727 		ire->ire_phandle = (uint32_t)ipst->ips_ire_handle++;
1728 		mutex_exit(&ipst->ips_ire_handle_lock);
1729 	} else if (ire->ire_type & IRE_INTERFACE) {
1730 		mutex_enter(&ipst->ips_ire_handle_lock);
1731 		ire->ire_ihandle = (uint32_t)ipst->ips_ire_handle++;
1732 		mutex_exit(&ipst->ips_ire_handle_lock);
1733 	} else if (ire->ire_type == IRE_CACHE) {
1734 		ire->ire_phandle = phandle;
1735 		ire->ire_ihandle = ihandle;
1736 	}
1737 	ire->ire_ipif = ipif;
1738 	if (ipif != NULL) {
1739 		ire->ire_ipif_seqid = ipif->ipif_seqid;
1740 		ire->ire_zoneid = ipif->ipif_zoneid;
1741 	} else {
1742 		ire->ire_zoneid = GLOBAL_ZONEID;
1743 	}
1744 	ire->ire_ipversion = ipversion;
1745 	mutex_init(&ire->ire_lock, NULL, MUTEX_DEFAULT, NULL);
1746 	if (ipversion == IPV4_VERSION) {
1747 		/*
1748 		 * IPv6 initializes the ire_nce in ire_add_v6, which expects
1749 		 * to find the ire_nce to be null when it is called.
1750 		 */
1751 		if (ire_nce_init(ire, src_nce) != 0) {
1752 			/* some failure occurred. propagate error back */
1753 			return (B_FALSE);
1754 		}
1755 	}
1756 	ire->ire_refcnt = 1;
1757 	ire->ire_ipst = ipst;	/* No netstack_hold */
1758 	ire->ire_trace_disable = B_FALSE;
1759 
1760 	return (B_TRUE);
1761 }
1762 
1763 /*
1764  * This routine is called repeatedly by ipif_up to create broadcast IREs.
1765  * It is passed a pointer to a slot in an IRE pointer array into which to
1766  * place the pointer to the new IRE, if indeed we create one.  If the
1767  * IRE corresponding to the address passed in would be a duplicate of an
1768  * existing one, we don't create the new one.  irep is incremented before
1769  * return only if we do create a new IRE.  (Always called as writer.)
1770  *
1771  * Note that with the "match_flags" parameter, we can match on either
1772  * a particular logical interface (MATCH_IRE_IPIF) or for all logical
1773  * interfaces for a given physical interface (MATCH_IRE_ILL).  Currently,
1774  * we only create broadcast ire's on a per physical interface basis. If
1775  * someone is going to be mucking with logical interfaces, it is important
1776  * to call "ipif_check_bcast_ires()" to make sure that any change to a
1777  * logical interface will not cause critical broadcast IRE's to be deleted.
1778  */
1779 ire_t **
1780 ire_check_and_create_bcast(ipif_t *ipif, ipaddr_t  addr, ire_t **irep,
1781     int match_flags)
1782 {
1783 	ire_t *ire;
1784 	uint64_t check_flags = IPIF_DEPRECATED | IPIF_NOLOCAL | IPIF_ANYCAST;
1785 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
1786 
1787 	/*
1788 	 * No broadcast IREs for the LOOPBACK interface
1789 	 * or others such as point to point and IPIF_NOXMIT.
1790 	 */
1791 	if (!(ipif->ipif_flags & IPIF_BROADCAST) ||
1792 	    (ipif->ipif_flags & IPIF_NOXMIT))
1793 		return (irep);
1794 
1795 	/* If this would be a duplicate, don't bother. */
1796 	if ((ire = ire_ctable_lookup(addr, 0, IRE_BROADCAST, ipif,
1797 	    ipif->ipif_zoneid, NULL, match_flags, ipst)) != NULL) {
1798 		/*
1799 		 * We look for non-deprecated (and non-anycast, non-nolocal)
1800 		 * ipifs as the best choice. ipifs with check_flags matching
1801 		 * (deprecated, etc) are used only if non-deprecated ipifs
1802 		 * are not available. if the existing ire's ipif is deprecated
1803 		 * and the new ipif is non-deprecated, switch to the new ipif
1804 		 */
1805 		if ((!(ire->ire_ipif->ipif_flags & check_flags)) ||
1806 		    (ipif->ipif_flags & check_flags)) {
1807 			ire_refrele(ire);
1808 			return (irep);
1809 		}
1810 		/*
1811 		 * Bcast ires exist in pairs. Both have to be deleted,
1812 		 * Since we are exclusive we can make the above assertion.
1813 		 * The 1st has to be refrele'd since it was ctable_lookup'd.
1814 		 */
1815 		ASSERT(IAM_WRITER_IPIF(ipif));
1816 		ASSERT(ire->ire_next->ire_addr == ire->ire_addr);
1817 		ire_delete(ire->ire_next);
1818 		ire_delete(ire);
1819 		ire_refrele(ire);
1820 	}
1821 
1822 	irep = ire_create_bcast(ipif, addr, irep);
1823 
1824 	return (irep);
1825 }
1826 
1827 uint_t ip_loopback_mtu = IP_LOOPBACK_MTU;
1828 
1829 /*
1830  * This routine is called from ipif_check_bcast_ires and ire_check_bcast.
1831  * It leaves all the verifying and deleting to those routines. So it always
1832  * creates 2 bcast ires and chains them into the ire array passed in.
1833  */
1834 ire_t **
1835 ire_create_bcast(ipif_t *ipif, ipaddr_t  addr, ire_t **irep)
1836 {
1837 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
1838 
1839 	*irep++ = ire_create(
1840 	    (uchar_t *)&addr,			/* dest addr */
1841 	    (uchar_t *)&ip_g_all_ones,		/* mask */
1842 	    (uchar_t *)&ipif->ipif_src_addr,	/* source addr */
1843 	    NULL,				/* no gateway */
1844 	    &ipif->ipif_mtu,			/* max frag */
1845 	    NULL,				/* no src nce */
1846 	    ipif->ipif_rq,			/* recv-from queue */
1847 	    ipif->ipif_wq,			/* send-to queue */
1848 	    IRE_BROADCAST,
1849 	    ipif,
1850 	    0,
1851 	    0,
1852 	    0,
1853 	    0,
1854 	    &ire_uinfo_null,
1855 	    NULL,
1856 	    NULL,
1857 	    ipst);
1858 
1859 	*irep++ = ire_create(
1860 	    (uchar_t *)&addr,			/* dest address */
1861 	    (uchar_t *)&ip_g_all_ones,		/* mask */
1862 	    (uchar_t *)&ipif->ipif_src_addr,	/* source address */
1863 	    NULL,				/* no gateway */
1864 	    &ip_loopback_mtu,			/* max frag size */
1865 	    NULL,				/* no src_nce */
1866 	    ipif->ipif_rq,			/* recv-from queue */
1867 	    NULL,				/* no send-to queue */
1868 	    IRE_BROADCAST,			/* Needed for fanout in wput */
1869 	    ipif,
1870 	    0,
1871 	    0,
1872 	    0,
1873 	    0,
1874 	    &ire_uinfo_null,
1875 	    NULL,
1876 	    NULL,
1877 	    ipst);
1878 
1879 	return (irep);
1880 }
1881 
1882 /*
1883  * ire_walk routine to delete or update any IRE_CACHE that might contain
1884  * stale information.
1885  * The flags state which entries to delete or update.
1886  * Garbage collection is done separately using kmem alloc callbacks to
1887  * ip_trash_ire_reclaim.
1888  * Used for both IPv4 and IPv6. However, IPv6 only uses FLUSH_MTU_TIME
1889  * since other stale information is cleaned up using NUD.
1890  */
1891 void
1892 ire_expire(ire_t *ire, char *arg)
1893 {
1894 	ire_expire_arg_t	*ieap = (ire_expire_arg_t *)(uintptr_t)arg;
1895 	ill_t			*stq_ill;
1896 	int			flush_flags = ieap->iea_flush_flag;
1897 	ip_stack_t		*ipst = ieap->iea_ipst;
1898 
1899 	if ((flush_flags & FLUSH_REDIRECT_TIME) &&
1900 	    (ire->ire_flags & RTF_DYNAMIC)) {
1901 		/* Make sure we delete the corresponding IRE_CACHE */
1902 		ip1dbg(("ire_expire: all redirects\n"));
1903 		ip_rts_rtmsg(RTM_DELETE, ire, 0, ipst);
1904 		ire_delete(ire);
1905 		atomic_dec_32(&ipst->ips_ip_redirect_cnt);
1906 		return;
1907 	}
1908 	if (ire->ire_type != IRE_CACHE)
1909 		return;
1910 
1911 	if (flush_flags & FLUSH_ARP_TIME) {
1912 		/*
1913 		 * Remove all IRE_CACHE.
1914 		 * Verify that create time is more than
1915 		 * ip_ire_arp_interval milliseconds ago.
1916 		 */
1917 		if (NCE_EXPIRED(ire->ire_nce, ipst)) {
1918 			ire_delete(ire);
1919 			return;
1920 		}
1921 	}
1922 
1923 	if (ipst->ips_ip_path_mtu_discovery && (flush_flags & FLUSH_MTU_TIME) &&
1924 	    (ire->ire_ipif != NULL)) {
1925 		/* Increase pmtu if it is less than the interface mtu */
1926 		mutex_enter(&ire->ire_lock);
1927 		/*
1928 		 * If the ipif is a vni (whose mtu is 0, since it's virtual)
1929 		 * get the mtu from the sending interfaces' ipif
1930 		 */
1931 		if (IS_VNI(ire->ire_ipif->ipif_ill)) {
1932 			stq_ill = ire->ire_stq->q_ptr;
1933 			ire->ire_max_frag = MIN(stq_ill->ill_ipif->ipif_mtu,
1934 			    IP_MAXPACKET);
1935 		} else {
1936 			ire->ire_max_frag = MIN(ire->ire_ipif->ipif_mtu,
1937 			    IP_MAXPACKET);
1938 		}
1939 		ire->ire_frag_flag |= IPH_DF;
1940 		mutex_exit(&ire->ire_lock);
1941 	}
1942 }
1943 
1944 /*
1945  * Return any local address.  We use this to target ourselves
1946  * when the src address was specified as 'default'.
1947  * Preference for IRE_LOCAL entries.
1948  */
1949 ire_t *
1950 ire_lookup_local(zoneid_t zoneid, ip_stack_t *ipst)
1951 {
1952 	ire_t	*ire;
1953 	irb_t	*irb;
1954 	ire_t	*maybe = NULL;
1955 	int i;
1956 
1957 	for (i = 0; i < ipst->ips_ip_cache_table_size;  i++) {
1958 		irb = &ipst->ips_ip_cache_table[i];
1959 		if (irb->irb_ire == NULL)
1960 			continue;
1961 		rw_enter(&irb->irb_lock, RW_READER);
1962 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
1963 			if ((ire->ire_marks & IRE_MARK_CONDEMNED) ||
1964 			    (ire->ire_zoneid != zoneid &&
1965 			    ire->ire_zoneid != ALL_ZONES))
1966 				continue;
1967 			switch (ire->ire_type) {
1968 			case IRE_LOOPBACK:
1969 				if (maybe == NULL) {
1970 					IRE_REFHOLD(ire);
1971 					maybe = ire;
1972 				}
1973 				break;
1974 			case IRE_LOCAL:
1975 				if (maybe != NULL) {
1976 					ire_refrele(maybe);
1977 				}
1978 				IRE_REFHOLD(ire);
1979 				rw_exit(&irb->irb_lock);
1980 				return (ire);
1981 			}
1982 		}
1983 		rw_exit(&irb->irb_lock);
1984 	}
1985 	return (maybe);
1986 }
1987 
1988 /*
1989  * If the specified IRE is associated with a particular ILL, return
1990  * that ILL pointer (May be called as writer.).
1991  *
1992  * NOTE : This is not a generic function that can be used always.
1993  * This function always returns the ill of the outgoing packets
1994  * if this ire is used.
1995  */
1996 ill_t *
1997 ire_to_ill(const ire_t *ire)
1998 {
1999 	ill_t *ill = NULL;
2000 
2001 	/*
2002 	 * 1) For an IRE_CACHE, ire_ipif is the one where it obtained
2003 	 *    the source address from. ire_stq is the one where the
2004 	 *    packets will be sent out on. We return that here.
2005 	 *
2006 	 * 2) IRE_BROADCAST normally has a loopback and a non-loopback
2007 	 *    copy and they always exist next to each other with loopback
2008 	 *    copy being the first one. If we are called on the non-loopback
2009 	 *    copy, return the one pointed by ire_stq. If it was called on
2010 	 *    a loopback copy, we still return the one pointed by the next
2011 	 *    ire's ire_stq pointer i.e the one pointed by the non-loopback
2012 	 *    copy. We don't want use ire_ipif as it might represent the
2013 	 *    source address (if we borrow source addresses for
2014 	 *    IRE_BROADCASTS in the future).
2015 	 *    However if an interface is currently coming up, the above
2016 	 *    condition may not hold during that period since the ires
2017 	 *    are added one at a time. Thus one of the pair could have been
2018 	 *    added and the other not yet added.
2019 	 * 3) For many other IREs (e.g., IRE_LOCAL), ire_rfq indicates the ill.
2020 	 * 4) For all others return the ones pointed by ire_ipif->ipif_ill.
2021 	 *    That handles IRE_LOOPBACK.
2022 	 */
2023 
2024 	if (ire->ire_type == IRE_CACHE) {
2025 		ill = (ill_t *)ire->ire_stq->q_ptr;
2026 	} else if (ire->ire_type == IRE_BROADCAST) {
2027 		if (ire->ire_stq != NULL) {
2028 			ill = (ill_t *)ire->ire_stq->q_ptr;
2029 		} else {
2030 			ire_t  *ire_next;
2031 
2032 			ire_next = ire->ire_next;
2033 			if (ire_next != NULL &&
2034 			    ire_next->ire_type == IRE_BROADCAST &&
2035 			    ire_next->ire_addr == ire->ire_addr &&
2036 			    ire_next->ire_ipif == ire->ire_ipif) {
2037 				ill = (ill_t *)ire_next->ire_stq->q_ptr;
2038 			}
2039 		}
2040 	} else if (ire->ire_rfq != NULL) {
2041 		ill = ire->ire_rfq->q_ptr;
2042 	} else if (ire->ire_ipif != NULL) {
2043 		ill = ire->ire_ipif->ipif_ill;
2044 	}
2045 	return (ill);
2046 }
2047 
2048 /* Arrange to call the specified function for every IRE in the world. */
2049 void
2050 ire_walk(pfv_t func, void *arg, ip_stack_t *ipst)
2051 {
2052 	ire_walk_ipvers(func, arg, 0, ALL_ZONES, ipst);
2053 }
2054 
2055 void
2056 ire_walk_v4(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
2057 {
2058 	ire_walk_ipvers(func, arg, IPV4_VERSION, zoneid, ipst);
2059 }
2060 
2061 void
2062 ire_walk_v6(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
2063 {
2064 	ire_walk_ipvers(func, arg, IPV6_VERSION, zoneid, ipst);
2065 }
2066 
2067 /*
2068  * Walk a particular version. version == 0 means both v4 and v6.
2069  */
2070 static void
2071 ire_walk_ipvers(pfv_t func, void *arg, uchar_t vers, zoneid_t zoneid,
2072     ip_stack_t *ipst)
2073 {
2074 	if (vers != IPV6_VERSION) {
2075 		/*
2076 		 * ip_forwarding_table variable doesn't matter for IPv4 since
2077 		 * ire_walk_ill_tables uses ips_ip_ftable for IPv4.
2078 		 */
2079 		ire_walk_ill_tables(0, 0, func, arg, IP_MASK_TABLE_SIZE,
2080 		    0, NULL,
2081 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
2082 		    NULL, zoneid, ipst);
2083 	}
2084 	if (vers != IPV4_VERSION) {
2085 		ire_walk_ill_tables(0, 0, func, arg, IP6_MASK_TABLE_SIZE,
2086 		    ipst->ips_ip6_ftable_hash_size,
2087 		    ipst->ips_ip_forwarding_table_v6,
2088 		    ipst->ips_ip6_cache_table_size,
2089 		    ipst->ips_ip_cache_table_v6, NULL, zoneid, ipst);
2090 	}
2091 }
2092 
2093 /*
2094  * Arrange to call the specified
2095  * function for every IRE that matches the ill.
2096  */
2097 void
2098 ire_walk_ill(uint_t match_flags, uint_t ire_type, pfv_t func, void *arg,
2099     ill_t *ill)
2100 {
2101 	ire_walk_ill_ipvers(match_flags, ire_type, func, arg, 0, ill);
2102 }
2103 
2104 void
2105 ire_walk_ill_v4(uint_t match_flags, uint_t ire_type, pfv_t func, void *arg,
2106     ill_t *ill)
2107 {
2108 	ire_walk_ill_ipvers(match_flags, ire_type, func, arg, IPV4_VERSION,
2109 	    ill);
2110 }
2111 
2112 void
2113 ire_walk_ill_v6(uint_t match_flags, uint_t ire_type, pfv_t func, void *arg,
2114     ill_t *ill)
2115 {
2116 	ire_walk_ill_ipvers(match_flags, ire_type, func, arg, IPV6_VERSION,
2117 	    ill);
2118 }
2119 
2120 /*
2121  * Walk a particular ill and version. version == 0 means both v4 and v6.
2122  */
2123 static void
2124 ire_walk_ill_ipvers(uint_t match_flags, uint_t ire_type, pfv_t func,
2125     void *arg, uchar_t vers, ill_t *ill)
2126 {
2127 	ip_stack_t	*ipst = ill->ill_ipst;
2128 
2129 	if (vers != IPV6_VERSION) {
2130 		ire_walk_ill_tables(match_flags, ire_type, func, arg,
2131 		    IP_MASK_TABLE_SIZE, 0,
2132 		    NULL, ipst->ips_ip_cache_table_size,
2133 		    ipst->ips_ip_cache_table, ill, ALL_ZONES, ipst);
2134 	}
2135 	if (vers != IPV4_VERSION) {
2136 		ire_walk_ill_tables(match_flags, ire_type, func, arg,
2137 		    IP6_MASK_TABLE_SIZE, ipst->ips_ip6_ftable_hash_size,
2138 		    ipst->ips_ip_forwarding_table_v6,
2139 		    ipst->ips_ip6_cache_table_size,
2140 		    ipst->ips_ip_cache_table_v6, ill, ALL_ZONES, ipst);
2141 	}
2142 }
2143 
2144 boolean_t
2145 ire_walk_ill_match(uint_t match_flags, uint_t ire_type, ire_t *ire,
2146     ill_t *ill, zoneid_t zoneid, ip_stack_t *ipst)
2147 {
2148 	ill_t *ire_stq_ill = NULL;
2149 	ill_t *ire_ipif_ill = NULL;
2150 	ill_group_t *ire_ill_group = NULL;
2151 
2152 	ASSERT(match_flags != 0 || zoneid != ALL_ZONES);
2153 	/*
2154 	 * MATCH_IRE_ILL/MATCH_IRE_ILL_GROUP : We match both on ill
2155 	 *    pointed by ire_stq and ire_ipif. Only in the case of
2156 	 *    IRE_CACHEs can ire_stq and ire_ipif be pointing to
2157 	 *    different ills. But we want to keep this function generic
2158 	 *    enough for future use. So, we always try to match on both.
2159 	 *    The only caller of this function ire_walk_ill_tables, will
2160 	 *    call "func" after we return from this function. We expect
2161 	 *    "func" to do the right filtering of ires in this case.
2162 	 *
2163 	 * NOTE : In the case of MATCH_IRE_ILL_GROUP, groups
2164 	 * pointed by ire_stq and ire_ipif should always be the same.
2165 	 * So, we just match on only one of them.
2166 	 */
2167 	if (match_flags & (MATCH_IRE_ILL|MATCH_IRE_ILL_GROUP)) {
2168 		if (ire->ire_stq != NULL)
2169 			ire_stq_ill = (ill_t *)ire->ire_stq->q_ptr;
2170 		if (ire->ire_ipif != NULL)
2171 			ire_ipif_ill = ire->ire_ipif->ipif_ill;
2172 		if (ire_stq_ill != NULL)
2173 			ire_ill_group = ire_stq_ill->ill_group;
2174 		if ((ire_ill_group == NULL) && (ire_ipif_ill != NULL))
2175 			ire_ill_group = ire_ipif_ill->ill_group;
2176 	}
2177 
2178 	if (zoneid != ALL_ZONES) {
2179 		/*
2180 		 * We're walking the IREs for a specific zone. The only relevant
2181 		 * IREs are:
2182 		 * - all IREs with a matching ire_zoneid
2183 		 * - all IRE_OFFSUBNETs as they're shared across all zones
2184 		 * - IRE_INTERFACE IREs for interfaces with a usable source addr
2185 		 *   with a matching zone
2186 		 * - IRE_DEFAULTs with a gateway reachable from the zone
2187 		 * We should really match on IRE_OFFSUBNETs and IRE_DEFAULTs
2188 		 * using the same rule; but the above rules are consistent with
2189 		 * the behavior of ire_ftable_lookup[_v6]() so that all the
2190 		 * routes that can be matched during lookup are also matched
2191 		 * here.
2192 		 */
2193 		if (zoneid != ire->ire_zoneid && ire->ire_zoneid != ALL_ZONES) {
2194 			/*
2195 			 * Note, IRE_INTERFACE can have the stq as NULL. For
2196 			 * example, if the default multicast route is tied to
2197 			 * the loopback address.
2198 			 */
2199 			if ((ire->ire_type & IRE_INTERFACE) &&
2200 			    (ire->ire_stq != NULL)) {
2201 				ire_stq_ill = (ill_t *)ire->ire_stq->q_ptr;
2202 				if (ire->ire_ipversion == IPV4_VERSION) {
2203 					if (!ipif_usesrc_avail(ire_stq_ill,
2204 					    zoneid))
2205 						/* No usable src addr in zone */
2206 						return (B_FALSE);
2207 				} else if (ire_stq_ill->ill_usesrc_ifindex
2208 				    != 0) {
2209 					/*
2210 					 * For IPv6 use ipif_select_source_v6()
2211 					 * so the right scope selection is done
2212 					 */
2213 					ipif_t *src_ipif;
2214 					src_ipif =
2215 					    ipif_select_source_v6(ire_stq_ill,
2216 					    &ire->ire_addr_v6, RESTRICT_TO_NONE,
2217 					    IPV6_PREFER_SRC_DEFAULT,
2218 					    zoneid);
2219 					if (src_ipif != NULL) {
2220 						ipif_refrele(src_ipif);
2221 					} else {
2222 						return (B_FALSE);
2223 					}
2224 				} else {
2225 					return (B_FALSE);
2226 				}
2227 
2228 			} else if (!(ire->ire_type & IRE_OFFSUBNET)) {
2229 				return (B_FALSE);
2230 			}
2231 		}
2232 
2233 		/*
2234 		 * Match all default routes from the global zone, irrespective
2235 		 * of reachability. For a non-global zone only match those
2236 		 * where ire_gateway_addr has a IRE_INTERFACE for the zoneid.
2237 		 */
2238 		if (ire->ire_type == IRE_DEFAULT && zoneid != GLOBAL_ZONEID) {
2239 			int ire_match_flags = 0;
2240 			in6_addr_t gw_addr_v6;
2241 			ire_t *rire;
2242 
2243 			ire_match_flags |= MATCH_IRE_TYPE;
2244 			if (ire->ire_ipif != NULL) {
2245 				ire_match_flags |= MATCH_IRE_ILL_GROUP;
2246 			}
2247 			if (ire->ire_ipversion == IPV4_VERSION) {
2248 				rire = ire_route_lookup(ire->ire_gateway_addr,
2249 				    0, 0, IRE_INTERFACE, ire->ire_ipif, NULL,
2250 				    zoneid, NULL, ire_match_flags, ipst);
2251 			} else {
2252 				ASSERT(ire->ire_ipversion == IPV6_VERSION);
2253 				mutex_enter(&ire->ire_lock);
2254 				gw_addr_v6 = ire->ire_gateway_addr_v6;
2255 				mutex_exit(&ire->ire_lock);
2256 				rire = ire_route_lookup_v6(&gw_addr_v6,
2257 				    NULL, NULL, IRE_INTERFACE, ire->ire_ipif,
2258 				    NULL, zoneid, NULL, ire_match_flags, ipst);
2259 			}
2260 			if (rire == NULL) {
2261 				return (B_FALSE);
2262 			}
2263 			ire_refrele(rire);
2264 		}
2265 	}
2266 
2267 	if (((!(match_flags & MATCH_IRE_TYPE)) ||
2268 	    (ire->ire_type & ire_type)) &&
2269 	    ((!(match_flags & MATCH_IRE_ILL)) ||
2270 	    (ire_stq_ill == ill || ire_ipif_ill == ill)) &&
2271 	    ((!(match_flags & MATCH_IRE_ILL_GROUP)) ||
2272 	    (ire_stq_ill == ill) || (ire_ipif_ill == ill) ||
2273 	    (ire_ill_group != NULL &&
2274 	    ire_ill_group == ill->ill_group))) {
2275 		return (B_TRUE);
2276 	}
2277 	return (B_FALSE);
2278 }
2279 
2280 int
2281 rtfunc(struct radix_node *rn, void *arg)
2282 {
2283 	struct rtfuncarg *rtf = arg;
2284 	struct rt_entry *rt;
2285 	irb_t *irb;
2286 	ire_t *ire;
2287 	boolean_t ret;
2288 
2289 	rt = (struct rt_entry *)rn;
2290 	ASSERT(rt != NULL);
2291 	irb = &rt->rt_irb;
2292 	for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
2293 		if ((rtf->rt_match_flags != 0) ||
2294 		    (rtf->rt_zoneid != ALL_ZONES)) {
2295 			ret = ire_walk_ill_match(rtf->rt_match_flags,
2296 			    rtf->rt_ire_type, ire,
2297 			    rtf->rt_ill, rtf->rt_zoneid, rtf->rt_ipst);
2298 		} else
2299 			ret = B_TRUE;
2300 		if (ret)
2301 			(*rtf->rt_func)(ire, rtf->rt_arg);
2302 	}
2303 	return (0);
2304 }
2305 
2306 /*
2307  * Walk the ftable and the ctable entries that match the ill.
2308  */
2309 void
2310 ire_walk_ill_tables(uint_t match_flags, uint_t ire_type, pfv_t func,
2311     void *arg, size_t ftbl_sz, size_t htbl_sz, irb_t **ipftbl,
2312     size_t ctbl_sz, irb_t *ipctbl, ill_t *ill, zoneid_t zoneid,
2313     ip_stack_t *ipst)
2314 {
2315 	irb_t	*irb_ptr;
2316 	irb_t	*irb;
2317 	ire_t	*ire;
2318 	int i, j;
2319 	boolean_t ret;
2320 	struct rtfuncarg rtfarg;
2321 
2322 	ASSERT((!(match_flags & (MATCH_IRE_ILL |
2323 	    MATCH_IRE_ILL_GROUP))) || (ill != NULL));
2324 	ASSERT(!(match_flags & MATCH_IRE_TYPE) || (ire_type != 0));
2325 	/*
2326 	 * Optimize by not looking at the forwarding table if there
2327 	 * is a MATCH_IRE_TYPE specified with no IRE_FORWARDTABLE
2328 	 * specified in ire_type.
2329 	 */
2330 	if (!(match_flags & MATCH_IRE_TYPE) ||
2331 	    ((ire_type & IRE_FORWARDTABLE) != 0)) {
2332 		/* knobs such that routine is called only for v6 case */
2333 		if (ipftbl == ipst->ips_ip_forwarding_table_v6) {
2334 			for (i = (ftbl_sz - 1);  i >= 0; i--) {
2335 				if ((irb_ptr = ipftbl[i]) == NULL)
2336 					continue;
2337 				for (j = 0; j < htbl_sz; j++) {
2338 					irb = &irb_ptr[j];
2339 					if (irb->irb_ire == NULL)
2340 						continue;
2341 
2342 					IRB_REFHOLD(irb);
2343 					for (ire = irb->irb_ire; ire != NULL;
2344 					    ire = ire->ire_next) {
2345 						if (match_flags == 0 &&
2346 						    zoneid == ALL_ZONES) {
2347 							ret = B_TRUE;
2348 						} else {
2349 							ret =
2350 							    ire_walk_ill_match(
2351 							    match_flags,
2352 							    ire_type, ire, ill,
2353 							    zoneid, ipst);
2354 						}
2355 						if (ret)
2356 							(*func)(ire, arg);
2357 					}
2358 					IRB_REFRELE(irb);
2359 				}
2360 			}
2361 		} else {
2362 			(void) memset(&rtfarg, 0, sizeof (rtfarg));
2363 			rtfarg.rt_func = func;
2364 			rtfarg.rt_arg = arg;
2365 			if (match_flags != 0) {
2366 				rtfarg.rt_match_flags = match_flags;
2367 			}
2368 			rtfarg.rt_ire_type = ire_type;
2369 			rtfarg.rt_ill = ill;
2370 			rtfarg.rt_zoneid = zoneid;
2371 			rtfarg.rt_ipst = ipst;	/* No netstack_hold */
2372 			(void) ipst->ips_ip_ftable->rnh_walktree_mt(
2373 			    ipst->ips_ip_ftable,
2374 			    rtfunc, &rtfarg, irb_refhold_rn, irb_refrele_rn);
2375 		}
2376 	}
2377 
2378 	/*
2379 	 * Optimize by not looking at the cache table if there
2380 	 * is a MATCH_IRE_TYPE specified with no IRE_CACHETABLE
2381 	 * specified in ire_type.
2382 	 */
2383 	if (!(match_flags & MATCH_IRE_TYPE) ||
2384 	    ((ire_type & IRE_CACHETABLE) != 0)) {
2385 		for (i = 0; i < ctbl_sz;  i++) {
2386 			irb = &ipctbl[i];
2387 			if (irb->irb_ire == NULL)
2388 				continue;
2389 			IRB_REFHOLD(irb);
2390 			for (ire = irb->irb_ire; ire != NULL;
2391 			    ire = ire->ire_next) {
2392 				if (match_flags == 0 && zoneid == ALL_ZONES) {
2393 					ret = B_TRUE;
2394 				} else {
2395 					ret = ire_walk_ill_match(
2396 					    match_flags, ire_type,
2397 					    ire, ill, zoneid, ipst);
2398 				}
2399 				if (ret)
2400 					(*func)(ire, arg);
2401 			}
2402 			IRB_REFRELE(irb);
2403 		}
2404 	}
2405 }
2406 
2407 /*
2408  * This function takes a mask and returns
2409  * number of bits set in the mask. If no
2410  * bit is set it returns 0.
2411  * Assumes a contiguous mask.
2412  */
2413 int
2414 ip_mask_to_plen(ipaddr_t mask)
2415 {
2416 	return (mask == 0 ? 0 : IP_ABITS - (ffs(ntohl(mask)) -1));
2417 }
2418 
2419 /*
2420  * Convert length for a mask to the mask.
2421  */
2422 ipaddr_t
2423 ip_plen_to_mask(uint_t masklen)
2424 {
2425 	return (htonl(IP_HOST_MASK << (IP_ABITS - masklen)));
2426 }
2427 
2428 void
2429 ire_atomic_end(irb_t *irb_ptr, ire_t *ire)
2430 {
2431 	ill_t	*ill_list[NUM_ILLS];
2432 	ip_stack_t	*ipst = ire->ire_ipst;
2433 
2434 	ill_list[0] = ire->ire_stq != NULL ? ire->ire_stq->q_ptr : NULL;
2435 	ill_list[1] = ire->ire_ipif != NULL ? ire->ire_ipif->ipif_ill : NULL;
2436 	ill_unlock_ills(ill_list, NUM_ILLS);
2437 	rw_exit(&irb_ptr->irb_lock);
2438 	rw_exit(&ipst->ips_ill_g_usesrc_lock);
2439 }
2440 
2441 /*
2442  * ire_add_v[46] atomically make sure that the ipif or ill associated
2443  * with the new ire being added is stable and not IPIF_CHANGING or ILL_CHANGING
2444  * before adding the ire to the table. This ensures that we don't create
2445  * new IRE_CACHEs with stale values for parameters that are passed to
2446  * ire_create such as ire_max_frag. Note that ire_create() is passed a pointer
2447  * to the ipif_mtu, and not the value. The actual value is derived from the
2448  * parent ire or ipif under the bucket lock.
2449  */
2450 int
2451 ire_atomic_start(irb_t *irb_ptr, ire_t *ire, queue_t *q, mblk_t *mp,
2452     ipsq_func_t func)
2453 {
2454 	ill_t	*stq_ill;
2455 	ill_t	*ipif_ill;
2456 	ill_t	*ill_list[NUM_ILLS];
2457 	int	cnt = NUM_ILLS;
2458 	int	error = 0;
2459 	ill_t	*ill = NULL;
2460 	ip_stack_t	*ipst = ire->ire_ipst;
2461 
2462 	ill_list[0] = stq_ill = ire->ire_stq !=
2463 	    NULL ? ire->ire_stq->q_ptr : NULL;
2464 	ill_list[1] = ipif_ill = ire->ire_ipif !=
2465 	    NULL ? ire->ire_ipif->ipif_ill : NULL;
2466 
2467 	ASSERT((q != NULL && mp != NULL && func != NULL) ||
2468 	    (q == NULL && mp == NULL && func == NULL));
2469 	rw_enter(&ipst->ips_ill_g_usesrc_lock, RW_READER);
2470 	GRAB_CONN_LOCK(q);
2471 	rw_enter(&irb_ptr->irb_lock, RW_WRITER);
2472 	ill_lock_ills(ill_list, cnt);
2473 
2474 	/*
2475 	 * While the IRE is in the process of being added, a user may have
2476 	 * invoked the ifconfig usesrc option on the stq_ill to make it a
2477 	 * usesrc client ILL. Check for this possibility here, if it is true
2478 	 * then we fail adding the IRE_CACHE. Another check is to make sure
2479 	 * that an ipif_ill of an IRE_CACHE being added is not part of a usesrc
2480 	 * group. The ill_g_usesrc_lock is released in ire_atomic_end
2481 	 */
2482 	if ((ire->ire_type & IRE_CACHE) &&
2483 	    (ire->ire_marks & IRE_MARK_USESRC_CHECK)) {
2484 		if (stq_ill->ill_usesrc_ifindex != 0) {
2485 			ASSERT(stq_ill->ill_usesrc_grp_next != NULL);
2486 			if ((ipif_ill->ill_phyint->phyint_ifindex !=
2487 			    stq_ill->ill_usesrc_ifindex) ||
2488 			    (ipif_ill->ill_usesrc_grp_next == NULL) ||
2489 			    (ipif_ill->ill_usesrc_ifindex != 0)) {
2490 				error = EINVAL;
2491 				goto done;
2492 			}
2493 		} else if (ipif_ill->ill_usesrc_grp_next != NULL) {
2494 			error = EINVAL;
2495 			goto done;
2496 		}
2497 	}
2498 
2499 	/*
2500 	 * IPMP flag settings happen without taking the exclusive route
2501 	 * in ip_sioctl_flags. So we need to make an atomic check here
2502 	 * for FAILED/OFFLINE/INACTIVE flags or if it has hit the
2503 	 * FAILBACK=no case.
2504 	 */
2505 	if ((stq_ill != NULL) && !IAM_WRITER_ILL(stq_ill)) {
2506 		if (stq_ill->ill_state_flags & ILL_CHANGING) {
2507 			ill = stq_ill;
2508 			error = EAGAIN;
2509 		} else if ((stq_ill->ill_phyint->phyint_flags & PHYI_OFFLINE) ||
2510 		    (ill_is_probeonly(stq_ill) &&
2511 		    !(ire->ire_marks & IRE_MARK_HIDDEN))) {
2512 			error = EINVAL;
2513 		}
2514 		goto done;
2515 	}
2516 
2517 	/*
2518 	 * We don't check for OFFLINE/FAILED in this case because
2519 	 * the source address selection logic (ipif_select_source)
2520 	 * may still select a source address from such an ill. The
2521 	 * assumption is that these addresses will be moved by in.mpathd
2522 	 * soon. (i.e. this is a race). However link local addresses
2523 	 * will not move and hence ipif_select_source_v6 tries to avoid
2524 	 * FAILED ills. Please see ipif_select_source_v6 for more info
2525 	 */
2526 	if ((ipif_ill != NULL) && !IAM_WRITER_ILL(ipif_ill) &&
2527 	    (ipif_ill->ill_state_flags & ILL_CHANGING)) {
2528 		ill = ipif_ill;
2529 		error = EAGAIN;
2530 		goto done;
2531 	}
2532 
2533 	if ((ire->ire_ipif != NULL) && !IAM_WRITER_IPIF(ire->ire_ipif) &&
2534 	    (ire->ire_ipif->ipif_state_flags & IPIF_CHANGING)) {
2535 		ill = ire->ire_ipif->ipif_ill;
2536 		ASSERT(ill != NULL);
2537 		error = EAGAIN;
2538 		goto done;
2539 	}
2540 
2541 done:
2542 	if (error == EAGAIN && ILL_CAN_WAIT(ill, q)) {
2543 		ipsq_t *ipsq = ill->ill_phyint->phyint_ipsq;
2544 		mutex_enter(&ipsq->ipsq_lock);
2545 		ire_atomic_end(irb_ptr, ire);
2546 		ipsq_enq(ipsq, q, mp, func, NEW_OP, ill);
2547 		mutex_exit(&ipsq->ipsq_lock);
2548 		error = EINPROGRESS;
2549 	} else if (error != 0) {
2550 		ire_atomic_end(irb_ptr, ire);
2551 	}
2552 
2553 	RELEASE_CONN_LOCK(q);
2554 	return (error);
2555 }
2556 
2557 /*
2558  * Add a fully initialized IRE to an appropriate table based on
2559  * ire_type.
2560  *
2561  * allow_unresolved == B_FALSE indicates a legacy code-path call
2562  * that has prohibited the addition of incomplete ire's. If this
2563  * parameter is set, and we find an nce that is in a state other
2564  * than ND_REACHABLE, we fail the add. Note that nce_state could be
2565  * something other than ND_REACHABLE if the nce had just expired and
2566  * the ire_create preceding the ire_add added a new ND_INITIAL nce.
2567  */
2568 int
2569 ire_add(ire_t **irep, queue_t *q, mblk_t *mp, ipsq_func_t func,
2570     boolean_t allow_unresolved)
2571 {
2572 	ire_t	*ire1;
2573 	ill_t	*stq_ill = NULL;
2574 	ill_t	*ill;
2575 	ipif_t	*ipif = NULL;
2576 	ill_walk_context_t ctx;
2577 	ire_t	*ire = *irep;
2578 	int	error;
2579 	boolean_t ire_is_mblk = B_FALSE;
2580 	tsol_gcgrp_t *gcgrp = NULL;
2581 	tsol_gcgrp_addr_t ga;
2582 	ip_stack_t	*ipst = ire->ire_ipst;
2583 
2584 	/* get ready for the day when original ire is not created as mblk */
2585 	if (ire->ire_mp != NULL) {
2586 		ire_is_mblk = B_TRUE;
2587 		/* Copy the ire to a kmem_alloc'ed area */
2588 		ire1 = kmem_cache_alloc(ire_cache, KM_NOSLEEP);
2589 		if (ire1 == NULL) {
2590 			ip1dbg(("ire_add: alloc failed\n"));
2591 			ire_delete(ire);
2592 			*irep = NULL;
2593 			return (ENOMEM);
2594 		}
2595 		ire->ire_marks &= ~IRE_MARK_UNCACHED;
2596 		*ire1 = *ire;
2597 		ire1->ire_mp = NULL;
2598 		ire1->ire_stq_ifindex = 0;
2599 		freeb(ire->ire_mp);
2600 		ire = ire1;
2601 	}
2602 	if (ire->ire_stq != NULL)
2603 		stq_ill = (ill_t *)ire->ire_stq->q_ptr;
2604 
2605 	if (ire->ire_type == IRE_CACHE) {
2606 		/*
2607 		 * If this interface is FAILED, or INACTIVE or has hit
2608 		 * the FAILBACK=no case, we create IRE_CACHES marked
2609 		 * HIDDEN for some special cases e.g. bind to
2610 		 * IPIF_NOFAILOVER address etc. So, if this interface
2611 		 * is FAILED/INACTIVE/hit FAILBACK=no case, and we are
2612 		 * not creating hidden ires, we should not allow that.
2613 		 * This happens because the state of the interface
2614 		 * changed while we were waiting in ARP. If this is the
2615 		 * daemon sending probes, the next probe will create
2616 		 * HIDDEN ires and we will create an ire then. This
2617 		 * cannot happen with NDP currently because IRE is
2618 		 * never queued in NDP. But it can happen in the
2619 		 * future when we have external resolvers with IPv6.
2620 		 * If the interface gets marked with OFFLINE while we
2621 		 * are waiting in ARP, don't add the ire.
2622 		 */
2623 		if ((stq_ill->ill_phyint->phyint_flags & PHYI_OFFLINE) ||
2624 		    (ill_is_probeonly(stq_ill) &&
2625 		    !(ire->ire_marks & IRE_MARK_HIDDEN))) {
2626 			/*
2627 			 * We don't know whether it is a valid ipif or not.
2628 			 * unless we do the check below. So, set it to NULL.
2629 			 */
2630 			ire->ire_ipif = NULL;
2631 			ire_delete(ire);
2632 			*irep = NULL;
2633 			return (EINVAL);
2634 		}
2635 	}
2636 
2637 	if (stq_ill != NULL && ire->ire_type == IRE_CACHE &&
2638 	    stq_ill->ill_net_type == IRE_IF_RESOLVER) {
2639 		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
2640 		ill = ILL_START_WALK_ALL(&ctx, ipst);
2641 		for (; ill != NULL; ill = ill_next(&ctx, ill)) {
2642 			mutex_enter(&ill->ill_lock);
2643 			if (ill->ill_state_flags & ILL_CONDEMNED) {
2644 				mutex_exit(&ill->ill_lock);
2645 				continue;
2646 			}
2647 			/*
2648 			 * We need to make sure that the ipif is a valid one
2649 			 * before adding the IRE_CACHE. This happens only
2650 			 * with IRE_CACHE when there is an external resolver.
2651 			 *
2652 			 * We can unplumb a logical interface while the
2653 			 * packet is waiting in ARP with the IRE. Then,
2654 			 * later on when we feed the IRE back, the ipif
2655 			 * has to be re-checked. This can't happen with
2656 			 * NDP currently, as we never queue the IRE with
2657 			 * the packet. We always try to recreate the IRE
2658 			 * when the resolution is completed. But, we do
2659 			 * it for IPv6 also here so that in future if
2660 			 * we have external resolvers, it will work without
2661 			 * any change.
2662 			 */
2663 			ipif = ipif_lookup_seqid(ill, ire->ire_ipif_seqid);
2664 			if (ipif != NULL) {
2665 				ipif_refhold_locked(ipif);
2666 				mutex_exit(&ill->ill_lock);
2667 				break;
2668 			}
2669 			mutex_exit(&ill->ill_lock);
2670 		}
2671 		rw_exit(&ipst->ips_ill_g_lock);
2672 		if (ipif == NULL ||
2673 		    (ipif->ipif_isv6 &&
2674 		    !IN6_ARE_ADDR_EQUAL(&ire->ire_src_addr_v6,
2675 		    &ipif->ipif_v6src_addr)) ||
2676 		    (!ipif->ipif_isv6 &&
2677 		    ire->ire_src_addr != ipif->ipif_src_addr) ||
2678 		    ire->ire_zoneid != ipif->ipif_zoneid) {
2679 
2680 			if (ipif != NULL)
2681 				ipif_refrele(ipif);
2682 			ire->ire_ipif = NULL;
2683 			ire_delete(ire);
2684 			*irep = NULL;
2685 			return (EINVAL);
2686 		}
2687 
2688 
2689 		ASSERT(ill != NULL);
2690 		/*
2691 		 * If this group was dismantled while this packets was
2692 		 * queued in ARP, don't add it here.
2693 		 */
2694 		if (ire->ire_ipif->ipif_ill->ill_group != ill->ill_group) {
2695 			/* We don't want ire_inactive bump stats for this */
2696 			ipif_refrele(ipif);
2697 			ire->ire_ipif = NULL;
2698 			ire_delete(ire);
2699 			*irep = NULL;
2700 			return (EINVAL);
2701 		}
2702 
2703 		/*
2704 		 * Since we didn't attach label security attributes to the
2705 		 * ire for the resolver case, we need to add it now. (only
2706 		 * for v4 resolver and v6 xresolv case).
2707 		 */
2708 		if (is_system_labeled() && ire_is_mblk) {
2709 			if (ire->ire_ipversion == IPV4_VERSION) {
2710 				ga.ga_af = AF_INET;
2711 				IN6_IPADDR_TO_V4MAPPED(ire->ire_gateway_addr !=
2712 				    INADDR_ANY ? ire->ire_gateway_addr :
2713 				    ire->ire_addr, &ga.ga_addr);
2714 			} else {
2715 				ga.ga_af = AF_INET6;
2716 				ga.ga_addr = IN6_IS_ADDR_UNSPECIFIED(
2717 				    &ire->ire_gateway_addr_v6) ?
2718 				    ire->ire_addr_v6 :
2719 				    ire->ire_gateway_addr_v6;
2720 			}
2721 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
2722 			error = tsol_ire_init_gwattr(ire, ire->ire_ipversion,
2723 			    NULL, gcgrp);
2724 			if (error != 0) {
2725 				if (gcgrp != NULL) {
2726 					GCGRP_REFRELE(gcgrp);
2727 					gcgrp = NULL;
2728 				}
2729 				ipif_refrele(ipif);
2730 				ire->ire_ipif = NULL;
2731 				ire_delete(ire);
2732 				*irep = NULL;
2733 				return (error);
2734 			}
2735 		}
2736 	}
2737 
2738 	/*
2739 	 * In case ire was changed
2740 	 */
2741 	*irep = ire;
2742 	if (ire->ire_ipversion == IPV6_VERSION)
2743 		error = ire_add_v6(irep, q, mp, func);
2744 	else
2745 		error = ire_add_v4(irep, q, mp, func, allow_unresolved);
2746 	if (ipif != NULL)
2747 		ipif_refrele(ipif);
2748 	return (error);
2749 }
2750 
2751 /*
2752  * Add an initialized IRE to an appropriate table based on ire_type.
2753  *
2754  * The forward table contains IRE_PREFIX/IRE_HOST and
2755  * IRE_IF_RESOLVER/IRE_IF_NORESOLVER and IRE_DEFAULT.
2756  *
2757  * The cache table contains IRE_BROADCAST/IRE_LOCAL/IRE_LOOPBACK
2758  * and IRE_CACHE.
2759  *
2760  * NOTE : This function is called as writer though not required
2761  * by this function.
2762  */
2763 static int
2764 ire_add_v4(ire_t **ire_p, queue_t *q, mblk_t *mp, ipsq_func_t func,
2765     boolean_t allow_unresolved)
2766 {
2767 	ire_t	*ire1;
2768 	irb_t	*irb_ptr;
2769 	ire_t	**irep;
2770 	int	flags;
2771 	ire_t	*pire = NULL;
2772 	ill_t	*stq_ill;
2773 	ire_t	*ire = *ire_p;
2774 	int	error;
2775 	boolean_t need_refrele = B_FALSE;
2776 	nce_t	*nce;
2777 	ip_stack_t	*ipst = ire->ire_ipst;
2778 
2779 	if (ire->ire_ipif != NULL)
2780 		ASSERT(!MUTEX_HELD(&ire->ire_ipif->ipif_ill->ill_lock));
2781 	if (ire->ire_stq != NULL)
2782 		ASSERT(!MUTEX_HELD(
2783 		    &((ill_t *)(ire->ire_stq->q_ptr))->ill_lock));
2784 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
2785 	ASSERT(ire->ire_mp == NULL); /* Calls should go through ire_add */
2786 
2787 	/* Find the appropriate list head. */
2788 	switch (ire->ire_type) {
2789 	case IRE_HOST:
2790 		ire->ire_mask = IP_HOST_MASK;
2791 		ire->ire_masklen = IP_ABITS;
2792 		if ((ire->ire_flags & RTF_SETSRC) == 0)
2793 			ire->ire_src_addr = 0;
2794 		break;
2795 	case IRE_CACHE:
2796 	case IRE_BROADCAST:
2797 	case IRE_LOCAL:
2798 	case IRE_LOOPBACK:
2799 		ire->ire_mask = IP_HOST_MASK;
2800 		ire->ire_masklen = IP_ABITS;
2801 		break;
2802 	case IRE_PREFIX:
2803 		if ((ire->ire_flags & RTF_SETSRC) == 0)
2804 			ire->ire_src_addr = 0;
2805 		break;
2806 	case IRE_DEFAULT:
2807 		if ((ire->ire_flags & RTF_SETSRC) == 0)
2808 			ire->ire_src_addr = 0;
2809 		break;
2810 	case IRE_IF_RESOLVER:
2811 	case IRE_IF_NORESOLVER:
2812 		break;
2813 	default:
2814 		ip0dbg(("ire_add_v4: ire %p has unrecognized IRE type (%d)\n",
2815 		    (void *)ire, ire->ire_type));
2816 		ire_delete(ire);
2817 		*ire_p = NULL;
2818 		return (EINVAL);
2819 	}
2820 
2821 	/* Make sure the address is properly masked. */
2822 	ire->ire_addr &= ire->ire_mask;
2823 
2824 	/*
2825 	 * ip_newroute/ip_newroute_multi are unable to prevent the deletion
2826 	 * of the interface route while adding an IRE_CACHE for an on-link
2827 	 * destination in the IRE_IF_RESOLVER case, since the ire has to
2828 	 * go to ARP and return. We can't do a REFHOLD on the
2829 	 * associated interface ire for fear of ARP freeing the message.
2830 	 * Here we look up the interface ire in the forwarding table and
2831 	 * make sure that the interface route has not been deleted.
2832 	 */
2833 	if (ire->ire_type == IRE_CACHE && ire->ire_gateway_addr == 0 &&
2834 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_net_type == IRE_IF_RESOLVER) {
2835 
2836 		ASSERT(ire->ire_max_fragp == NULL);
2837 		if (CLASSD(ire->ire_addr) && !(ire->ire_flags & RTF_SETSRC)) {
2838 			/*
2839 			 * The ihandle that we used in ip_newroute_multi
2840 			 * comes from the interface route corresponding
2841 			 * to ire_ipif. Lookup here to see if it exists
2842 			 * still.
2843 			 * If the ire has a source address assigned using
2844 			 * RTF_SETSRC, ire_ipif is the logical interface holding
2845 			 * this source address, so we can't use it to check for
2846 			 * the existence of the interface route. Instead we rely
2847 			 * on the brute force ihandle search in
2848 			 * ire_ihandle_lookup_onlink() below.
2849 			 */
2850 			pire = ipif_to_ire(ire->ire_ipif);
2851 			if (pire == NULL) {
2852 				ire_delete(ire);
2853 				*ire_p = NULL;
2854 				return (EINVAL);
2855 			} else if (pire->ire_ihandle != ire->ire_ihandle) {
2856 				ire_refrele(pire);
2857 				ire_delete(ire);
2858 				*ire_p = NULL;
2859 				return (EINVAL);
2860 			}
2861 		} else {
2862 			pire = ire_ihandle_lookup_onlink(ire);
2863 			if (pire == NULL) {
2864 				ire_delete(ire);
2865 				*ire_p = NULL;
2866 				return (EINVAL);
2867 			}
2868 		}
2869 		/* Prevent pire from getting deleted */
2870 		IRB_REFHOLD(pire->ire_bucket);
2871 		/* Has it been removed already ? */
2872 		if (pire->ire_marks & IRE_MARK_CONDEMNED) {
2873 			IRB_REFRELE(pire->ire_bucket);
2874 			ire_refrele(pire);
2875 			ire_delete(ire);
2876 			*ire_p = NULL;
2877 			return (EINVAL);
2878 		}
2879 	} else {
2880 		ASSERT(ire->ire_max_fragp != NULL);
2881 	}
2882 	flags = (MATCH_IRE_MASK | MATCH_IRE_TYPE | MATCH_IRE_GW);
2883 
2884 	if (ire->ire_ipif != NULL) {
2885 		/*
2886 		 * We use MATCH_IRE_IPIF while adding IRE_CACHES only
2887 		 * for historic reasons and to maintain symmetry with
2888 		 * IPv6 code path. Historically this was used by
2889 		 * multicast code to create multiple IRE_CACHES on
2890 		 * a single ill with different ipifs. This was used
2891 		 * so that multicast packets leaving the node had the
2892 		 * right source address. This is no longer needed as
2893 		 * ip_wput initializes the address correctly.
2894 		 */
2895 		flags |= MATCH_IRE_IPIF;
2896 		/*
2897 		 * If we are creating hidden ires, make sure we search on
2898 		 * this ill (MATCH_IRE_ILL) and a hidden ire,
2899 		 * while we are searching for duplicates below. Otherwise we
2900 		 * could potentially find an IRE on some other interface
2901 		 * and it may not be a IRE marked with IRE_MARK_HIDDEN. We
2902 		 * shouldn't do this as this will lead to an infinite loop
2903 		 * (if we get to ip_wput again) eventually we need an hidden
2904 		 * ire for this packet to go out. MATCH_IRE_ILL is explicitly
2905 		 * done below.
2906 		 */
2907 		if (ire->ire_type == IRE_CACHE &&
2908 		    (ire->ire_marks & IRE_MARK_HIDDEN))
2909 			flags |= (MATCH_IRE_MARK_HIDDEN);
2910 	}
2911 	if ((ire->ire_type & IRE_CACHETABLE) == 0) {
2912 		irb_ptr = ire_get_bucket(ire);
2913 		need_refrele = B_TRUE;
2914 		if (irb_ptr == NULL) {
2915 			/*
2916 			 * This assumes that the ire has not added
2917 			 * a reference to the ipif.
2918 			 */
2919 			ire->ire_ipif = NULL;
2920 			ire_delete(ire);
2921 			if (pire != NULL) {
2922 				IRB_REFRELE(pire->ire_bucket);
2923 				ire_refrele(pire);
2924 			}
2925 			*ire_p = NULL;
2926 			return (EINVAL);
2927 		}
2928 	} else {
2929 		irb_ptr = &(ipst->ips_ip_cache_table[IRE_ADDR_HASH(
2930 		    ire->ire_addr, ipst->ips_ip_cache_table_size)]);
2931 	}
2932 
2933 	/*
2934 	 * Start the atomic add of the ire. Grab the ill locks,
2935 	 * ill_g_usesrc_lock and the bucket lock. Check for condemned
2936 	 *
2937 	 * If ipif or ill is changing ire_atomic_start() may queue the
2938 	 * request and return EINPROGRESS.
2939 	 * To avoid lock order problems, get the ndp4->ndp_g_lock.
2940 	 */
2941 	mutex_enter(&ipst->ips_ndp4->ndp_g_lock);
2942 	error = ire_atomic_start(irb_ptr, ire, q, mp, func);
2943 	if (error != 0) {
2944 		mutex_exit(&ipst->ips_ndp4->ndp_g_lock);
2945 		/*
2946 		 * We don't know whether it is a valid ipif or not.
2947 		 * So, set it to NULL. This assumes that the ire has not added
2948 		 * a reference to the ipif.
2949 		 */
2950 		ire->ire_ipif = NULL;
2951 		ire_delete(ire);
2952 		if (pire != NULL) {
2953 			IRB_REFRELE(pire->ire_bucket);
2954 			ire_refrele(pire);
2955 		}
2956 		*ire_p = NULL;
2957 		if (need_refrele)
2958 			IRB_REFRELE(irb_ptr);
2959 		return (error);
2960 	}
2961 	/*
2962 	 * To avoid creating ires having stale values for the ire_max_frag
2963 	 * we get the latest value atomically here. For more details
2964 	 * see the block comment in ip_sioctl_mtu and in DL_NOTE_SDU_CHANGE
2965 	 * in ip_rput_dlpi_writer
2966 	 */
2967 	if (ire->ire_max_fragp == NULL) {
2968 		if (CLASSD(ire->ire_addr))
2969 			ire->ire_max_frag = ire->ire_ipif->ipif_mtu;
2970 		else
2971 			ire->ire_max_frag = pire->ire_max_frag;
2972 	} else {
2973 		uint_t	max_frag;
2974 
2975 		max_frag = *ire->ire_max_fragp;
2976 		ire->ire_max_fragp = NULL;
2977 		ire->ire_max_frag = max_frag;
2978 	}
2979 	/*
2980 	 * Atomically check for duplicate and insert in the table.
2981 	 */
2982 	for (ire1 = irb_ptr->irb_ire; ire1 != NULL; ire1 = ire1->ire_next) {
2983 		if (ire1->ire_marks & IRE_MARK_CONDEMNED)
2984 			continue;
2985 		if (ire->ire_ipif != NULL) {
2986 			/*
2987 			 * We do MATCH_IRE_ILL implicitly here for IREs
2988 			 * with a non-null ire_ipif, including IRE_CACHEs.
2989 			 * As ire_ipif and ire_stq could point to two
2990 			 * different ills, we can't pass just ire_ipif to
2991 			 * ire_match_args and get a match on both ills.
2992 			 * This is just needed for duplicate checks here and
2993 			 * so we don't add an extra argument to
2994 			 * ire_match_args for this. Do it locally.
2995 			 *
2996 			 * NOTE : Currently there is no part of the code
2997 			 * that asks for both MATH_IRE_IPIF and MATCH_IRE_ILL
2998 			 * match for IRE_CACHEs. Thus we don't want to
2999 			 * extend the arguments to ire_match_args.
3000 			 */
3001 			if (ire1->ire_stq != ire->ire_stq)
3002 				continue;
3003 			/*
3004 			 * Multiroute IRE_CACHEs for a given destination can
3005 			 * have the same ire_ipif, typically if their source
3006 			 * address is forced using RTF_SETSRC, and the same
3007 			 * send-to queue. We differentiate them using the parent
3008 			 * handle.
3009 			 */
3010 			if (ire->ire_type == IRE_CACHE &&
3011 			    (ire1->ire_flags & RTF_MULTIRT) &&
3012 			    (ire->ire_flags & RTF_MULTIRT) &&
3013 			    (ire1->ire_phandle != ire->ire_phandle))
3014 				continue;
3015 		}
3016 		if (ire1->ire_zoneid != ire->ire_zoneid)
3017 			continue;
3018 		if (ire_match_args(ire1, ire->ire_addr, ire->ire_mask,
3019 		    ire->ire_gateway_addr, ire->ire_type, ire->ire_ipif,
3020 		    ire->ire_zoneid, 0, NULL, flags)) {
3021 			/*
3022 			 * Return the old ire after doing a REFHOLD.
3023 			 * As most of the callers continue to use the IRE
3024 			 * after adding, we return a held ire. This will
3025 			 * avoid a lookup in the caller again. If the callers
3026 			 * don't want to use it, they need to do a REFRELE.
3027 			 */
3028 			ip1dbg(("found dup ire existing %p new %p",
3029 			    (void *)ire1, (void *)ire));
3030 			IRE_REFHOLD(ire1);
3031 			ire_atomic_end(irb_ptr, ire);
3032 			mutex_exit(&ipst->ips_ndp4->ndp_g_lock);
3033 			ire_delete(ire);
3034 			if (pire != NULL) {
3035 				/*
3036 				 * Assert that it is not removed from the
3037 				 * list yet.
3038 				 */
3039 				ASSERT(pire->ire_ptpn != NULL);
3040 				IRB_REFRELE(pire->ire_bucket);
3041 				ire_refrele(pire);
3042 			}
3043 			*ire_p = ire1;
3044 			if (need_refrele)
3045 				IRB_REFRELE(irb_ptr);
3046 			return (0);
3047 		}
3048 	}
3049 	if (ire->ire_type & IRE_CACHE) {
3050 		ASSERT(ire->ire_stq != NULL);
3051 		nce = ndp_lookup_v4(ire_to_ill(ire),
3052 		    ((ire->ire_gateway_addr != INADDR_ANY) ?
3053 		    &ire->ire_gateway_addr : &ire->ire_addr),
3054 		    B_TRUE);
3055 		if (nce != NULL)
3056 			mutex_enter(&nce->nce_lock);
3057 		/*
3058 		 * if the nce is NCE_F_CONDEMNED, or if it is not ND_REACHABLE
3059 		 * and the caller has prohibited the addition of incomplete
3060 		 * ire's, we fail the add. Note that nce_state could be
3061 		 * something other than ND_REACHABLE if the nce had
3062 		 * just expired and the ire_create preceding the
3063 		 * ire_add added a new ND_INITIAL nce.
3064 		 */
3065 		if ((nce == NULL) ||
3066 		    (nce->nce_flags & NCE_F_CONDEMNED) ||
3067 		    (!allow_unresolved &&
3068 		    (nce->nce_state != ND_REACHABLE))) {
3069 			if (nce != NULL) {
3070 				DTRACE_PROBE1(ire__bad__nce, nce_t *, nce);
3071 				mutex_exit(&nce->nce_lock);
3072 			}
3073 			ire_atomic_end(irb_ptr, ire);
3074 			mutex_exit(&ipst->ips_ndp4->ndp_g_lock);
3075 			if (nce != NULL)
3076 				NCE_REFRELE(nce);
3077 			DTRACE_PROBE1(ire__no__nce, ire_t *, ire);
3078 			ire_delete(ire);
3079 			if (pire != NULL) {
3080 				IRB_REFRELE(pire->ire_bucket);
3081 				ire_refrele(pire);
3082 			}
3083 			*ire_p = NULL;
3084 			if (need_refrele)
3085 				IRB_REFRELE(irb_ptr);
3086 			return (EINVAL);
3087 		} else {
3088 			ire->ire_nce = nce;
3089 			mutex_exit(&nce->nce_lock);
3090 			/*
3091 			 * We are associating this nce to the ire, so
3092 			 * change the nce ref taken in ndp_lookup_v4() from
3093 			 * NCE_REFHOLD to NCE_REFHOLD_NOTR
3094 			 */
3095 			NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
3096 		}
3097 	}
3098 	/*
3099 	 * Make it easy for ip_wput_ire() to hit multiple broadcast ires by
3100 	 * grouping identical addresses together on the hash chain. We also
3101 	 * don't want to send multiple copies out if there are two ills part
3102 	 * of the same group. Thus we group the ires with same addr and same
3103 	 * ill group together so that ip_wput_ire can easily skip all the
3104 	 * ires with same addr and same group after sending the first copy.
3105 	 * We do this only for IRE_BROADCASTs as ip_wput_ire is currently
3106 	 * interested in such groupings only for broadcasts.
3107 	 *
3108 	 * NOTE : If the interfaces are brought up first and then grouped,
3109 	 * illgrp_insert will handle it. We come here when the interfaces
3110 	 * are already in group and we are bringing them UP.
3111 	 *
3112 	 * Find the first entry that matches ire_addr. *irep will be null
3113 	 * if no match.
3114 	 *
3115 	 * Note: the loopback and non-loopback broadcast entries for an
3116 	 * interface MUST be added before any MULTIRT entries.
3117 	 */
3118 	irep = (ire_t **)irb_ptr;
3119 	while ((ire1 = *irep) != NULL && ire->ire_addr != ire1->ire_addr)
3120 		irep = &ire1->ire_next;
3121 	if (ire->ire_type == IRE_BROADCAST && *irep != NULL) {
3122 		/*
3123 		 * We found some ire (i.e *irep) with a matching addr. We
3124 		 * want to group ires with same addr and same ill group
3125 		 * together.
3126 		 *
3127 		 * First get to the entry that matches our address and
3128 		 * ill group i.e stop as soon as we find the first ire
3129 		 * matching the ill group and address. If there is only
3130 		 * an address match, we should walk and look for some
3131 		 * group match. These are some of the possible scenarios :
3132 		 *
3133 		 * 1) There are no groups at all i.e all ire's ill_group
3134 		 *    are NULL. In that case we will essentially group
3135 		 *    all the ires with the same addr together. Same as
3136 		 *    the "else" block of this "if".
3137 		 *
3138 		 * 2) There are some groups and this ire's ill_group is
3139 		 *    NULL. In this case, we will first find the group
3140 		 *    that matches the address and a NULL group. Then
3141 		 *    we will insert the ire at the end of that group.
3142 		 *
3143 		 * 3) There are some groups and this ires's ill_group is
3144 		 *    non-NULL. In this case we will first find the group
3145 		 *    that matches the address and the ill_group. Then
3146 		 *    we will insert the ire at the end of that group.
3147 		 */
3148 		for (;;) {
3149 			ire1 = *irep;
3150 			if ((ire1->ire_next == NULL) ||
3151 			    (ire1->ire_next->ire_addr != ire->ire_addr) ||
3152 			    (ire1->ire_type != IRE_BROADCAST) ||
3153 			    (ire1->ire_flags & RTF_MULTIRT) ||
3154 			    (ire1->ire_ipif->ipif_ill->ill_group ==
3155 			    ire->ire_ipif->ipif_ill->ill_group))
3156 				break;
3157 			irep = &ire1->ire_next;
3158 		}
3159 		ASSERT(*irep != NULL);
3160 		/*
3161 		 * The ire will be added before *irep, so
3162 		 * if irep is a MULTIRT ire, just break to
3163 		 * ire insertion code.
3164 		 */
3165 		if (((*irep)->ire_flags & RTF_MULTIRT) != 0)
3166 			goto insert_ire;
3167 
3168 		irep = &((*irep)->ire_next);
3169 
3170 		/*
3171 		 * Either we have hit the end of the list or the address
3172 		 * did not match or the group *matched*. If we found
3173 		 * a match on the group, skip to the end of the group.
3174 		 */
3175 		while (*irep != NULL) {
3176 			ire1 = *irep;
3177 			if ((ire1->ire_addr != ire->ire_addr) ||
3178 			    (ire1->ire_type != IRE_BROADCAST) ||
3179 			    (ire1->ire_ipif->ipif_ill->ill_group !=
3180 			    ire->ire_ipif->ipif_ill->ill_group))
3181 				break;
3182 			if (ire1->ire_ipif->ipif_ill->ill_group == NULL &&
3183 			    ire1->ire_ipif == ire->ire_ipif) {
3184 				irep = &ire1->ire_next;
3185 				break;
3186 			}
3187 			irep = &ire1->ire_next;
3188 		}
3189 	} else if (*irep != NULL) {
3190 		/*
3191 		 * Find the last ire which matches ire_addr.
3192 		 * Needed to do tail insertion among entries with the same
3193 		 * ire_addr.
3194 		 */
3195 		while (ire->ire_addr == ire1->ire_addr) {
3196 			irep = &ire1->ire_next;
3197 			ire1 = *irep;
3198 			if (ire1 == NULL)
3199 				break;
3200 		}
3201 	}
3202 
3203 insert_ire:
3204 	/* Insert at *irep */
3205 	ire1 = *irep;
3206 	if (ire1 != NULL)
3207 		ire1->ire_ptpn = &ire->ire_next;
3208 	ire->ire_next = ire1;
3209 	/* Link the new one in. */
3210 	ire->ire_ptpn = irep;
3211 
3212 	/*
3213 	 * ire_walk routines de-reference ire_next without holding
3214 	 * a lock. Before we point to the new ire, we want to make
3215 	 * sure the store that sets the ire_next of the new ire
3216 	 * reaches global visibility, so that ire_walk routines
3217 	 * don't see a truncated list of ires i.e if the ire_next
3218 	 * of the new ire gets set after we do "*irep = ire" due
3219 	 * to re-ordering, the ire_walk thread will see a NULL
3220 	 * once it accesses the ire_next of the new ire.
3221 	 * membar_producer() makes sure that the following store
3222 	 * happens *after* all of the above stores.
3223 	 */
3224 	membar_producer();
3225 	*irep = ire;
3226 	ire->ire_bucket = irb_ptr;
3227 	/*
3228 	 * We return a bumped up IRE above. Keep it symmetrical
3229 	 * so that the callers will always have to release. This
3230 	 * helps the callers of this function because they continue
3231 	 * to use the IRE after adding and hence they don't have to
3232 	 * lookup again after we return the IRE.
3233 	 *
3234 	 * NOTE : We don't have to use atomics as this is appearing
3235 	 * in the list for the first time and no one else can bump
3236 	 * up the reference count on this yet.
3237 	 */
3238 	IRE_REFHOLD_LOCKED(ire);
3239 	BUMP_IRE_STATS(ipst->ips_ire_stats_v4, ire_stats_inserted);
3240 
3241 	irb_ptr->irb_ire_cnt++;
3242 	if (irb_ptr->irb_marks & IRB_MARK_FTABLE)
3243 		irb_ptr->irb_nire++;
3244 
3245 	if (ire->ire_marks & IRE_MARK_TEMPORARY)
3246 		irb_ptr->irb_tmp_ire_cnt++;
3247 
3248 	if (ire->ire_ipif != NULL) {
3249 		ire->ire_ipif->ipif_ire_cnt++;
3250 		if (ire->ire_stq != NULL) {
3251 			stq_ill = (ill_t *)ire->ire_stq->q_ptr;
3252 			stq_ill->ill_ire_cnt++;
3253 		}
3254 	} else {
3255 		ASSERT(ire->ire_stq == NULL);
3256 	}
3257 
3258 	ire_atomic_end(irb_ptr, ire);
3259 	mutex_exit(&ipst->ips_ndp4->ndp_g_lock);
3260 
3261 	if (pire != NULL) {
3262 		/* Assert that it is not removed from the list yet */
3263 		ASSERT(pire->ire_ptpn != NULL);
3264 		IRB_REFRELE(pire->ire_bucket);
3265 		ire_refrele(pire);
3266 	}
3267 
3268 	if (ire->ire_type != IRE_CACHE) {
3269 		/*
3270 		 * For ire's with host mask see if there is an entry
3271 		 * in the cache. If there is one flush the whole cache as
3272 		 * there might be multiple entries due to RTF_MULTIRT (CGTP).
3273 		 * If no entry is found than there is no need to flush the
3274 		 * cache.
3275 		 */
3276 		if (ire->ire_mask == IP_HOST_MASK) {
3277 			ire_t *lire;
3278 			lire = ire_ctable_lookup(ire->ire_addr, NULL, IRE_CACHE,
3279 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3280 			if (lire != NULL) {
3281 				ire_refrele(lire);
3282 				ire_flush_cache_v4(ire, IRE_FLUSH_ADD);
3283 			}
3284 		} else {
3285 			ire_flush_cache_v4(ire, IRE_FLUSH_ADD);
3286 		}
3287 	}
3288 	/*
3289 	 * We had to delay the fast path probe until the ire is inserted
3290 	 * in the list. Otherwise the fast path ack won't find the ire in
3291 	 * the table.
3292 	 */
3293 	if (ire->ire_type == IRE_CACHE ||
3294 	    (ire->ire_type == IRE_BROADCAST && ire->ire_stq != NULL)) {
3295 		ASSERT(ire->ire_nce != NULL);
3296 		if (ire->ire_nce->nce_state == ND_REACHABLE)
3297 			nce_fastpath(ire->ire_nce);
3298 	}
3299 	if (ire->ire_ipif != NULL)
3300 		ASSERT(!MUTEX_HELD(&ire->ire_ipif->ipif_ill->ill_lock));
3301 	*ire_p = ire;
3302 	if (need_refrele) {
3303 		IRB_REFRELE(irb_ptr);
3304 	}
3305 	return (0);
3306 }
3307 
3308 /*
3309  * IRB_REFRELE is the only caller of the function. ire_unlink calls to
3310  * do the final cleanup for this ire.
3311  */
3312 void
3313 ire_cleanup(ire_t *ire)
3314 {
3315 	ire_t *ire_next;
3316 	ip_stack_t *ipst = ire->ire_ipst;
3317 
3318 	ASSERT(ire != NULL);
3319 
3320 	while (ire != NULL) {
3321 		ire_next = ire->ire_next;
3322 		if (ire->ire_ipversion == IPV4_VERSION) {
3323 			ire_delete_v4(ire);
3324 			BUMP_IRE_STATS(ipst->ips_ire_stats_v4,
3325 			    ire_stats_deleted);
3326 		} else {
3327 			ASSERT(ire->ire_ipversion == IPV6_VERSION);
3328 			ire_delete_v6(ire);
3329 			BUMP_IRE_STATS(ipst->ips_ire_stats_v6,
3330 			    ire_stats_deleted);
3331 		}
3332 		/*
3333 		 * Now it's really out of the list. Before doing the
3334 		 * REFRELE, set ire_next to NULL as ire_inactive asserts
3335 		 * so.
3336 		 */
3337 		ire->ire_next = NULL;
3338 		IRE_REFRELE_NOTR(ire);
3339 		ire = ire_next;
3340 	}
3341 }
3342 
3343 /*
3344  * IRB_REFRELE is the only caller of the function. It calls to unlink
3345  * all the CONDEMNED ires from this bucket.
3346  */
3347 ire_t *
3348 ire_unlink(irb_t *irb)
3349 {
3350 	ire_t *ire;
3351 	ire_t *ire1;
3352 	ire_t **ptpn;
3353 	ire_t *ire_list = NULL;
3354 
3355 	ASSERT(RW_WRITE_HELD(&irb->irb_lock));
3356 	ASSERT(((irb->irb_marks & IRB_MARK_FTABLE) && irb->irb_refcnt == 1) ||
3357 	    (irb->irb_refcnt == 0));
3358 	ASSERT(irb->irb_marks & IRB_MARK_CONDEMNED);
3359 	ASSERT(irb->irb_ire != NULL);
3360 
3361 	for (ire = irb->irb_ire; ire != NULL; ire = ire1) {
3362 		ip_stack_t	*ipst = ire->ire_ipst;
3363 
3364 		ire1 = ire->ire_next;
3365 		if (ire->ire_marks & IRE_MARK_CONDEMNED) {
3366 			ptpn = ire->ire_ptpn;
3367 			ire1 = ire->ire_next;
3368 			if (ire1)
3369 				ire1->ire_ptpn = ptpn;
3370 			*ptpn = ire1;
3371 			ire->ire_ptpn = NULL;
3372 			ire->ire_next = NULL;
3373 			if (ire->ire_type == IRE_DEFAULT) {
3374 				/*
3375 				 * IRE is out of the list. We need to adjust
3376 				 * the accounting before the caller drops
3377 				 * the lock.
3378 				 */
3379 				if (ire->ire_ipversion == IPV6_VERSION) {
3380 					ASSERT(ipst->
3381 					    ips_ipv6_ire_default_count !=
3382 					    0);
3383 					ipst->ips_ipv6_ire_default_count--;
3384 				}
3385 			}
3386 			/*
3387 			 * We need to call ire_delete_v4 or ire_delete_v6
3388 			 * to clean up the cache or the redirects pointing at
3389 			 * the default gateway. We need to drop the lock
3390 			 * as ire_flush_cache/ire_delete_host_redircts require
3391 			 * so. But we can't drop the lock, as ire_unlink needs
3392 			 * to atomically remove the ires from the list.
3393 			 * So, create a temporary list of CONDEMNED ires
3394 			 * for doing ire_delete_v4/ire_delete_v6 operations
3395 			 * later on.
3396 			 */
3397 			ire->ire_next = ire_list;
3398 			ire_list = ire;
3399 		}
3400 	}
3401 	irb->irb_marks &= ~IRB_MARK_CONDEMNED;
3402 	return (ire_list);
3403 }
3404 
3405 /*
3406  * Delete all the cache entries with this 'addr'.  When IP gets a gratuitous
3407  * ARP message on any of its interface queue, it scans the nce table and
3408  * deletes and calls ndp_delete() for the appropriate nce. This action
3409  * also deletes all the neighbor/ire cache entries for that address.
3410  * This function is called from ip_arp_news in ip.c and also for
3411  * ARP ioctl processing in ip_if.c. ip_ire_clookup_and_delete returns
3412  * true if it finds a nce entry which is used by ip_arp_news to determine if
3413  * it needs to do an ire_walk_v4. The return value is also  used for the
3414  * same purpose by ARP IOCTL processing * in ip_if.c when deleting
3415  * ARP entries. For SIOC*IFARP ioctls in addition to the address,
3416  * ip_if->ipif_ill also needs to be matched.
3417  */
3418 boolean_t
3419 ip_ire_clookup_and_delete(ipaddr_t addr, ipif_t *ipif, ip_stack_t *ipst)
3420 {
3421 	ill_t	*ill;
3422 	nce_t	*nce;
3423 
3424 	ill = (ipif ? ipif->ipif_ill : NULL);
3425 
3426 	if (ill != NULL) {
3427 		/*
3428 		 * clean up the nce (and any relevant ire's) that matches
3429 		 * on addr and ill.
3430 		 */
3431 		nce = ndp_lookup_v4(ill, &addr, B_FALSE);
3432 		if (nce != NULL) {
3433 			ndp_delete(nce);
3434 			return (B_TRUE);
3435 		}
3436 	} else {
3437 		/*
3438 		 * ill is wildcard. clean up all nce's and
3439 		 * ire's that match on addr
3440 		 */
3441 		nce_clookup_t cl;
3442 
3443 		cl.ncecl_addr = addr;
3444 		cl.ncecl_found = B_FALSE;
3445 
3446 		ndp_walk_common(ipst->ips_ndp4, NULL,
3447 		    (pfi_t)ip_nce_clookup_and_delete, (uchar_t *)&cl, B_TRUE);
3448 
3449 		/*
3450 		 *  ncecl_found would be set by ip_nce_clookup_and_delete if
3451 		 *  we found a matching nce.
3452 		 */
3453 		return (cl.ncecl_found);
3454 	}
3455 	return (B_FALSE);
3456 
3457 }
3458 
3459 /* Delete the supplied nce if its nce_addr matches the supplied address */
3460 static void
3461 ip_nce_clookup_and_delete(nce_t *nce, void *arg)
3462 {
3463 	nce_clookup_t *cl = (nce_clookup_t *)arg;
3464 	ipaddr_t nce_addr;
3465 
3466 	IN6_V4MAPPED_TO_IPADDR(&nce->nce_addr, nce_addr);
3467 	if (nce_addr == cl->ncecl_addr) {
3468 		cl->ncecl_found = B_TRUE;
3469 		/* clean up the nce (and any relevant ire's) */
3470 		ndp_delete(nce);
3471 	}
3472 }
3473 
3474 /*
3475  * Clean up the radix node for this ire. Must be called by IRB_REFRELE
3476  * when there are no ire's left in the bucket. Returns TRUE if the bucket
3477  * is deleted and freed.
3478  */
3479 boolean_t
3480 irb_inactive(irb_t *irb)
3481 {
3482 	struct rt_entry *rt;
3483 	struct radix_node *rn;
3484 	ip_stack_t *ipst = irb->irb_ipst;
3485 
3486 	ASSERT(irb->irb_ipst != NULL);
3487 
3488 	rt = IRB2RT(irb);
3489 	rn = (struct radix_node *)rt;
3490 
3491 	/* first remove it from the radix tree. */
3492 	RADIX_NODE_HEAD_WLOCK(ipst->ips_ip_ftable);
3493 	rw_enter(&irb->irb_lock, RW_WRITER);
3494 	if (irb->irb_refcnt == 1 && irb->irb_nire == 0) {
3495 		rn = ipst->ips_ip_ftable->rnh_deladdr(rn->rn_key, rn->rn_mask,
3496 		    ipst->ips_ip_ftable);
3497 		DTRACE_PROBE1(irb__free, rt_t *,  rt);
3498 		ASSERT((void *)rn == (void *)rt);
3499 		Free(rt, rt_entry_cache);
3500 		/* irb_lock is freed */
3501 		RADIX_NODE_HEAD_UNLOCK(ipst->ips_ip_ftable);
3502 		return (B_TRUE);
3503 	}
3504 	rw_exit(&irb->irb_lock);
3505 	RADIX_NODE_HEAD_UNLOCK(ipst->ips_ip_ftable);
3506 	return (B_FALSE);
3507 }
3508 
3509 /*
3510  * Delete the specified IRE.
3511  */
3512 void
3513 ire_delete(ire_t *ire)
3514 {
3515 	ire_t	*ire1;
3516 	ire_t	**ptpn;
3517 	irb_t *irb;
3518 	ip_stack_t	*ipst = ire->ire_ipst;
3519 
3520 	if ((irb = ire->ire_bucket) == NULL) {
3521 		/*
3522 		 * It was never inserted in the list. Should call REFRELE
3523 		 * to free this IRE.
3524 		 */
3525 		IRE_REFRELE_NOTR(ire);
3526 		return;
3527 	}
3528 
3529 	rw_enter(&irb->irb_lock, RW_WRITER);
3530 
3531 	if (irb->irb_rr_origin == ire) {
3532 		irb->irb_rr_origin = NULL;
3533 	}
3534 
3535 	/*
3536 	 * In case of V4 we might still be waiting for fastpath ack.
3537 	 */
3538 	if (ire->ire_ipversion == IPV4_VERSION &&
3539 	    (ire->ire_type == IRE_CACHE ||
3540 	    (ire->ire_type == IRE_BROADCAST && ire->ire_stq != NULL))) {
3541 		ASSERT(ire->ire_nce != NULL);
3542 		nce_fastpath_list_delete(ire->ire_nce);
3543 	}
3544 
3545 	if (ire->ire_ptpn == NULL) {
3546 		/*
3547 		 * Some other thread has removed us from the list.
3548 		 * It should have done the REFRELE for us.
3549 		 */
3550 		rw_exit(&irb->irb_lock);
3551 		return;
3552 	}
3553 
3554 	if (irb->irb_refcnt != 0) {
3555 		/*
3556 		 * The last thread to leave this bucket will
3557 		 * delete this ire.
3558 		 */
3559 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
3560 			irb->irb_ire_cnt--;
3561 			if (ire->ire_marks & IRE_MARK_TEMPORARY)
3562 				irb->irb_tmp_ire_cnt--;
3563 			ire->ire_marks |= IRE_MARK_CONDEMNED;
3564 		}
3565 		irb->irb_marks |= IRB_MARK_CONDEMNED;
3566 		rw_exit(&irb->irb_lock);
3567 		return;
3568 	}
3569 
3570 	/*
3571 	 * Normally to delete an ire, we walk the bucket. While we
3572 	 * walk the bucket, we normally bump up irb_refcnt and hence
3573 	 * we return from above where we mark CONDEMNED and the ire
3574 	 * gets deleted from ire_unlink. This case is where somebody
3575 	 * knows the ire e.g by doing a lookup, and wants to delete the
3576 	 * IRE. irb_refcnt would be 0 in this case if nobody is walking
3577 	 * the bucket.
3578 	 */
3579 	ptpn = ire->ire_ptpn;
3580 	ire1 = ire->ire_next;
3581 	if (ire1 != NULL)
3582 		ire1->ire_ptpn = ptpn;
3583 	ASSERT(ptpn != NULL);
3584 	*ptpn = ire1;
3585 	ire->ire_ptpn = NULL;
3586 	ire->ire_next = NULL;
3587 	if (ire->ire_ipversion == IPV6_VERSION) {
3588 		BUMP_IRE_STATS(ipst->ips_ire_stats_v6, ire_stats_deleted);
3589 	} else {
3590 		BUMP_IRE_STATS(ipst->ips_ire_stats_v4, ire_stats_deleted);
3591 	}
3592 	/*
3593 	 * ip_wput/ip_wput_v6 checks this flag to see whether
3594 	 * it should still use the cached ire or not.
3595 	 */
3596 	ire->ire_marks |= IRE_MARK_CONDEMNED;
3597 	if (ire->ire_type == IRE_DEFAULT) {
3598 		/*
3599 		 * IRE is out of the list. We need to adjust the
3600 		 * accounting before we drop the lock.
3601 		 */
3602 		if (ire->ire_ipversion == IPV6_VERSION) {
3603 			ASSERT(ipst->ips_ipv6_ire_default_count != 0);
3604 			ipst->ips_ipv6_ire_default_count--;
3605 		}
3606 	}
3607 	irb->irb_ire_cnt--;
3608 
3609 	if (ire->ire_marks & IRE_MARK_TEMPORARY)
3610 		irb->irb_tmp_ire_cnt--;
3611 	rw_exit(&irb->irb_lock);
3612 
3613 	if (ire->ire_ipversion == IPV6_VERSION) {
3614 		ire_delete_v6(ire);
3615 	} else {
3616 		ire_delete_v4(ire);
3617 	}
3618 	/*
3619 	 * We removed it from the list. Decrement the
3620 	 * reference count.
3621 	 */
3622 	IRE_REFRELE_NOTR(ire);
3623 }
3624 
3625 /*
3626  * Delete the specified IRE.
3627  * All calls should use ire_delete().
3628  * Sometimes called as writer though not required by this function.
3629  *
3630  * NOTE : This function is called only if the ire was added
3631  * in the list.
3632  */
3633 static void
3634 ire_delete_v4(ire_t *ire)
3635 {
3636 	ip_stack_t	*ipst = ire->ire_ipst;
3637 
3638 	ASSERT(ire->ire_refcnt >= 1);
3639 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
3640 
3641 	if (ire->ire_type != IRE_CACHE)
3642 		ire_flush_cache_v4(ire, IRE_FLUSH_DELETE);
3643 	if (ire->ire_type == IRE_DEFAULT) {
3644 		/*
3645 		 * when a default gateway is going away
3646 		 * delete all the host redirects pointing at that
3647 		 * gateway.
3648 		 */
3649 		ire_delete_host_redirects(ire->ire_gateway_addr, ipst);
3650 	}
3651 }
3652 
3653 /*
3654  * IRE_REFRELE/ire_refrele are the only caller of the function. It calls
3655  * to free the ire when the reference count goes to zero.
3656  */
3657 void
3658 ire_inactive(ire_t *ire)
3659 {
3660 	nce_t	*nce;
3661 	ill_t	*ill = NULL;
3662 	ill_t	*stq_ill = NULL;
3663 	ipif_t	*ipif;
3664 	boolean_t	need_wakeup = B_FALSE;
3665 	irb_t 	*irb;
3666 	ip_stack_t	*ipst = ire->ire_ipst;
3667 
3668 	ASSERT(ire->ire_refcnt == 0);
3669 	ASSERT(ire->ire_ptpn == NULL);
3670 	ASSERT(ire->ire_next == NULL);
3671 
3672 	if (ire->ire_gw_secattr != NULL) {
3673 		ire_gw_secattr_free(ire->ire_gw_secattr);
3674 		ire->ire_gw_secattr = NULL;
3675 	}
3676 
3677 	if (ire->ire_mp != NULL) {
3678 		ASSERT(ire->ire_bucket == NULL);
3679 		mutex_destroy(&ire->ire_lock);
3680 		BUMP_IRE_STATS(ipst->ips_ire_stats_v4, ire_stats_freed);
3681 		if (ire->ire_nce != NULL)
3682 			NCE_REFRELE_NOTR(ire->ire_nce);
3683 		freeb(ire->ire_mp);
3684 		return;
3685 	}
3686 
3687 	if ((nce = ire->ire_nce) != NULL) {
3688 		NCE_REFRELE_NOTR(nce);
3689 		ire->ire_nce = NULL;
3690 	}
3691 
3692 	if (ire->ire_ipif == NULL)
3693 		goto end;
3694 
3695 	ipif = ire->ire_ipif;
3696 	ill = ipif->ipif_ill;
3697 
3698 	if (ire->ire_bucket == NULL) {
3699 		/* The ire was never inserted in the table. */
3700 		goto end;
3701 	}
3702 
3703 	/*
3704 	 * ipif_ire_cnt on this ipif goes down by 1. If the ire_stq is
3705 	 * non-null ill_ire_count also goes down by 1.
3706 	 *
3707 	 * The ipif that is associated with an ire is ire->ire_ipif and
3708 	 * hence when the ire->ire_ipif->ipif_ire_cnt drops to zero we call
3709 	 * ipif_ill_refrele_tail. Usually stq_ill is null or the same as
3710 	 * ire->ire_ipif->ipif_ill. So nothing more needs to be done. Only
3711 	 * in the case of IRE_CACHES when IPMP is used, stq_ill can be
3712 	 * different. If this is different from ire->ire_ipif->ipif_ill and
3713 	 * if the ill_ire_cnt on the stq_ill also has dropped to zero, we call
3714 	 * ipif_ill_refrele_tail on the stq_ill.
3715 	 */
3716 
3717 	if (ire->ire_stq != NULL)
3718 		stq_ill = (ill_t *)ire->ire_stq->q_ptr;
3719 
3720 	if (stq_ill == NULL || stq_ill == ill) {
3721 		/* Optimize the most common case */
3722 		mutex_enter(&ill->ill_lock);
3723 		ASSERT(ipif->ipif_ire_cnt != 0);
3724 		ipif->ipif_ire_cnt--;
3725 		if (ipif->ipif_ire_cnt == 0)
3726 			need_wakeup = B_TRUE;
3727 		if (stq_ill != NULL) {
3728 			ASSERT(stq_ill->ill_ire_cnt != 0);
3729 			stq_ill->ill_ire_cnt--;
3730 			if (stq_ill->ill_ire_cnt == 0)
3731 				need_wakeup = B_TRUE;
3732 		}
3733 		if (need_wakeup) {
3734 			/* Drops the ill lock */
3735 			ipif_ill_refrele_tail(ill);
3736 		} else {
3737 			mutex_exit(&ill->ill_lock);
3738 		}
3739 	} else {
3740 		/*
3741 		 * We can't grab all the ill locks at the same time.
3742 		 * It can lead to recursive lock enter in the call to
3743 		 * ipif_ill_refrele_tail and later. Instead do it 1 at
3744 		 * a time.
3745 		 */
3746 		mutex_enter(&ill->ill_lock);
3747 		ASSERT(ipif->ipif_ire_cnt != 0);
3748 		ipif->ipif_ire_cnt--;
3749 		if (ipif->ipif_ire_cnt == 0) {
3750 			/* Drops the lock */
3751 			ipif_ill_refrele_tail(ill);
3752 		} else {
3753 			mutex_exit(&ill->ill_lock);
3754 		}
3755 		if (stq_ill != NULL) {
3756 			mutex_enter(&stq_ill->ill_lock);
3757 			ASSERT(stq_ill->ill_ire_cnt != 0);
3758 			stq_ill->ill_ire_cnt--;
3759 			if (stq_ill->ill_ire_cnt == 0)  {
3760 				/* Drops the ill lock */
3761 				ipif_ill_refrele_tail(stq_ill);
3762 			} else {
3763 				mutex_exit(&stq_ill->ill_lock);
3764 			}
3765 		}
3766 	}
3767 end:
3768 	/* This should be true for both V4 and V6 */
3769 
3770 	if ((ire->ire_type & IRE_FORWARDTABLE) &&
3771 	    (ire->ire_ipversion == IPV4_VERSION) &&
3772 	    ((irb = ire->ire_bucket) != NULL)) {
3773 		rw_enter(&irb->irb_lock, RW_WRITER);
3774 		irb->irb_nire--;
3775 		/*
3776 		 * Instead of examining the conditions for freeing
3777 		 * the radix node here, we do it by calling
3778 		 * IRB_REFRELE which is a single point in the code
3779 		 * that embeds that logic. Bump up the refcnt to
3780 		 * be able to call IRB_REFRELE
3781 		 */
3782 		IRB_REFHOLD_LOCKED(irb);
3783 		rw_exit(&irb->irb_lock);
3784 		IRB_REFRELE(irb);
3785 	}
3786 	ire->ire_ipif = NULL;
3787 
3788 #ifdef DEBUG
3789 	ire_trace_cleanup(ire);
3790 #endif
3791 	mutex_destroy(&ire->ire_lock);
3792 	if (ire->ire_ipversion == IPV6_VERSION) {
3793 		BUMP_IRE_STATS(ipst->ips_ire_stats_v6, ire_stats_freed);
3794 	} else {
3795 		BUMP_IRE_STATS(ipst->ips_ire_stats_v4, ire_stats_freed);
3796 	}
3797 	ASSERT(ire->ire_mp == NULL);
3798 	/* Has been allocated out of the cache */
3799 	kmem_cache_free(ire_cache, ire);
3800 }
3801 
3802 /*
3803  * ire_walk routine to delete all IRE_CACHE/IRE_HOST types redirect
3804  * entries that have a given gateway address.
3805  */
3806 void
3807 ire_delete_cache_gw(ire_t *ire, char *cp)
3808 {
3809 	ipaddr_t	gw_addr;
3810 
3811 	if (!(ire->ire_type & IRE_CACHE) &&
3812 	    !(ire->ire_flags & RTF_DYNAMIC))
3813 		return;
3814 
3815 	bcopy(cp, &gw_addr, sizeof (gw_addr));
3816 	if (ire->ire_gateway_addr == gw_addr) {
3817 		ip1dbg(("ire_delete_cache_gw: deleted 0x%x type %d to 0x%x\n",
3818 		    (int)ntohl(ire->ire_addr), ire->ire_type,
3819 		    (int)ntohl(ire->ire_gateway_addr)));
3820 		ire_delete(ire);
3821 	}
3822 }
3823 
3824 /*
3825  * Remove all IRE_CACHE entries that match the ire specified.
3826  *
3827  * The flag argument indicates if the flush request is due to addition
3828  * of new route (IRE_FLUSH_ADD) or deletion of old route (IRE_FLUSH_DELETE).
3829  *
3830  * This routine takes only the IREs from the forwarding table and flushes
3831  * the corresponding entries from the cache table.
3832  *
3833  * When flushing due to the deletion of an old route, it
3834  * just checks the cache handles (ire_phandle and ire_ihandle) and
3835  * deletes the ones that match.
3836  *
3837  * When flushing due to the creation of a new route, it checks
3838  * if a cache entry's address matches the one in the IRE and
3839  * that the cache entry's parent has a less specific mask than the
3840  * one in IRE. The destination of such a cache entry could be the
3841  * gateway for other cache entries, so we need to flush those as
3842  * well by looking for gateway addresses matching the IRE's address.
3843  */
3844 void
3845 ire_flush_cache_v4(ire_t *ire, int flag)
3846 {
3847 	int i;
3848 	ire_t *cire;
3849 	irb_t *irb;
3850 	ip_stack_t	*ipst = ire->ire_ipst;
3851 
3852 	if (ire->ire_type & IRE_CACHE)
3853 		return;
3854 
3855 	/*
3856 	 * If a default is just created, there is no point
3857 	 * in going through the cache, as there will not be any
3858 	 * cached ires.
3859 	 */
3860 	if (ire->ire_type == IRE_DEFAULT && flag == IRE_FLUSH_ADD)
3861 		return;
3862 	if (flag == IRE_FLUSH_ADD) {
3863 		/*
3864 		 * This selective flush is due to the addition of
3865 		 * new IRE.
3866 		 */
3867 		for (i = 0; i < ipst->ips_ip_cache_table_size; i++) {
3868 			irb = &ipst->ips_ip_cache_table[i];
3869 			if ((cire = irb->irb_ire) == NULL)
3870 				continue;
3871 			IRB_REFHOLD(irb);
3872 			for (cire = irb->irb_ire; cire != NULL;
3873 			    cire = cire->ire_next) {
3874 				if (cire->ire_type != IRE_CACHE)
3875 					continue;
3876 				/*
3877 				 * If 'cire' belongs to the same subnet
3878 				 * as the new ire being added, and 'cire'
3879 				 * is derived from a prefix that is less
3880 				 * specific than the new ire being added,
3881 				 * we need to flush 'cire'; for instance,
3882 				 * when a new interface comes up.
3883 				 */
3884 				if (((cire->ire_addr & ire->ire_mask) ==
3885 				    (ire->ire_addr & ire->ire_mask)) &&
3886 				    (ip_mask_to_plen(cire->ire_cmask) <=
3887 				    ire->ire_masklen)) {
3888 					ire_delete(cire);
3889 					continue;
3890 				}
3891 				/*
3892 				 * This is the case when the ire_gateway_addr
3893 				 * of 'cire' belongs to the same subnet as
3894 				 * the new ire being added.
3895 				 * Flushing such ires is sometimes required to
3896 				 * avoid misrouting: say we have a machine with
3897 				 * two interfaces (I1 and I2), a default router
3898 				 * R on the I1 subnet, and a host route to an
3899 				 * off-link destination D with a gateway G on
3900 				 * the I2 subnet.
3901 				 * Under normal operation, we will have an
3902 				 * on-link cache entry for G and an off-link
3903 				 * cache entry for D with G as ire_gateway_addr,
3904 				 * traffic to D will reach its destination
3905 				 * through gateway G.
3906 				 * If the administrator does 'ifconfig I2 down',
3907 				 * the cache entries for D and G will be
3908 				 * flushed. However, G will now be resolved as
3909 				 * an off-link destination using R (the default
3910 				 * router) as gateway. Then D will also be
3911 				 * resolved as an off-link destination using G
3912 				 * as gateway - this behavior is due to
3913 				 * compatibility reasons, see comment in
3914 				 * ire_ihandle_lookup_offlink(). Traffic to D
3915 				 * will go to the router R and probably won't
3916 				 * reach the destination.
3917 				 * The administrator then does 'ifconfig I2 up'.
3918 				 * Since G is on the I2 subnet, this routine
3919 				 * will flush its cache entry. It must also
3920 				 * flush the cache entry for D, otherwise
3921 				 * traffic will stay misrouted until the IRE
3922 				 * times out.
3923 				 */
3924 				if ((cire->ire_gateway_addr & ire->ire_mask) ==
3925 				    (ire->ire_addr & ire->ire_mask)) {
3926 					ire_delete(cire);
3927 					continue;
3928 				}
3929 			}
3930 			IRB_REFRELE(irb);
3931 		}
3932 	} else {
3933 		/*
3934 		 * delete the cache entries based on
3935 		 * handle in the IRE as this IRE is
3936 		 * being deleted/changed.
3937 		 */
3938 		for (i = 0; i < ipst->ips_ip_cache_table_size; i++) {
3939 			irb = &ipst->ips_ip_cache_table[i];
3940 			if ((cire = irb->irb_ire) == NULL)
3941 				continue;
3942 			IRB_REFHOLD(irb);
3943 			for (cire = irb->irb_ire; cire != NULL;
3944 			    cire = cire->ire_next) {
3945 				if (cire->ire_type != IRE_CACHE)
3946 					continue;
3947 				if ((cire->ire_phandle == 0 ||
3948 				    cire->ire_phandle != ire->ire_phandle) &&
3949 				    (cire->ire_ihandle == 0 ||
3950 				    cire->ire_ihandle != ire->ire_ihandle))
3951 					continue;
3952 				ire_delete(cire);
3953 			}
3954 			IRB_REFRELE(irb);
3955 		}
3956 	}
3957 }
3958 
3959 /*
3960  * Matches the arguments passed with the values in the ire.
3961  *
3962  * Note: for match types that match using "ipif" passed in, ipif
3963  * must be checked for non-NULL before calling this routine.
3964  */
3965 boolean_t
3966 ire_match_args(ire_t *ire, ipaddr_t addr, ipaddr_t mask, ipaddr_t gateway,
3967     int type, const ipif_t *ipif, zoneid_t zoneid, uint32_t ihandle,
3968     const ts_label_t *tsl, int match_flags)
3969 {
3970 	ill_t *ire_ill = NULL, *dst_ill;
3971 	ill_t *ipif_ill = NULL;
3972 	ill_group_t *ire_ill_group = NULL;
3973 	ill_group_t *ipif_ill_group = NULL;
3974 
3975 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
3976 	ASSERT((ire->ire_addr & ~ire->ire_mask) == 0);
3977 	ASSERT((!(match_flags & (MATCH_IRE_ILL|MATCH_IRE_ILL_GROUP))) ||
3978 	    (ipif != NULL && !ipif->ipif_isv6));
3979 
3980 	/*
3981 	 * HIDDEN cache entries have to be looked up specifically with
3982 	 * MATCH_IRE_MARK_HIDDEN. MATCH_IRE_MARK_HIDDEN is usually set
3983 	 * when the interface is FAILED or INACTIVE. In that case,
3984 	 * any IRE_CACHES that exists should be marked with
3985 	 * IRE_MARK_HIDDEN. So, we don't really need to match below
3986 	 * for IRE_MARK_HIDDEN. But we do so for consistency.
3987 	 */
3988 	if (!(match_flags & MATCH_IRE_MARK_HIDDEN) &&
3989 	    (ire->ire_marks & IRE_MARK_HIDDEN))
3990 		return (B_FALSE);
3991 
3992 	/*
3993 	 * MATCH_IRE_MARK_PRIVATE_ADDR is set when IP_NEXTHOP option
3994 	 * is used. In that case the routing table is bypassed and the
3995 	 * packets are sent directly to the specified nexthop. The
3996 	 * IRE_CACHE entry representing this route should be marked
3997 	 * with IRE_MARK_PRIVATE_ADDR.
3998 	 */
3999 
4000 	if (!(match_flags & MATCH_IRE_MARK_PRIVATE_ADDR) &&
4001 	    (ire->ire_marks & IRE_MARK_PRIVATE_ADDR))
4002 		return (B_FALSE);
4003 
4004 	if (zoneid != ALL_ZONES && zoneid != ire->ire_zoneid &&
4005 	    ire->ire_zoneid != ALL_ZONES) {
4006 		/*
4007 		 * If MATCH_IRE_ZONEONLY has been set and the supplied zoneid is
4008 		 * valid and does not match that of ire_zoneid, a failure to
4009 		 * match is reported at this point. Otherwise, since some IREs
4010 		 * that are available in the global zone can be used in local
4011 		 * zones, additional checks need to be performed:
4012 		 *
4013 		 *	IRE_BROADCAST, IRE_CACHE and IRE_LOOPBACK
4014 		 *	entries should never be matched in this situation.
4015 		 *
4016 		 *	IRE entries that have an interface associated with them
4017 		 *	should in general not match unless they are an IRE_LOCAL
4018 		 *	or in the case when MATCH_IRE_DEFAULT has been set in
4019 		 *	the caller.  In the case of the former, checking of the
4020 		 *	other fields supplied should take place.
4021 		 *
4022 		 *	In the case where MATCH_IRE_DEFAULT has been set,
4023 		 *	all of the ipif's associated with the IRE's ill are
4024 		 *	checked to see if there is a matching zoneid.  If any
4025 		 *	one ipif has a matching zoneid, this IRE is a
4026 		 *	potential candidate so checking of the other fields
4027 		 *	takes place.
4028 		 *
4029 		 *	In the case where the IRE_INTERFACE has a usable source
4030 		 *	address (indicated by ill_usesrc_ifindex) in the
4031 		 *	correct zone then it's permitted to return this IRE
4032 		 */
4033 		if (match_flags & MATCH_IRE_ZONEONLY)
4034 			return (B_FALSE);
4035 		if (ire->ire_type & (IRE_BROADCAST | IRE_CACHE | IRE_LOOPBACK))
4036 			return (B_FALSE);
4037 		/*
4038 		 * Note, IRE_INTERFACE can have the stq as NULL. For
4039 		 * example, if the default multicast route is tied to
4040 		 * the loopback address.
4041 		 */
4042 		if ((ire->ire_type & IRE_INTERFACE) &&
4043 		    (ire->ire_stq != NULL)) {
4044 			dst_ill = (ill_t *)ire->ire_stq->q_ptr;
4045 			/*
4046 			 * If there is a usable source address in the
4047 			 * zone, then it's ok to return an
4048 			 * IRE_INTERFACE
4049 			 */
4050 			if (ipif_usesrc_avail(dst_ill, zoneid)) {
4051 				ip3dbg(("ire_match_args: dst_ill %p match %d\n",
4052 				    (void *)dst_ill,
4053 				    (ire->ire_addr == (addr & mask))));
4054 			} else {
4055 				ip3dbg(("ire_match_args: src_ipif NULL"
4056 				    " dst_ill %p\n", (void *)dst_ill));
4057 				return (B_FALSE);
4058 			}
4059 		}
4060 		if (ire->ire_ipif != NULL && ire->ire_type != IRE_LOCAL &&
4061 		    !(ire->ire_type & IRE_INTERFACE)) {
4062 			ipif_t	*tipif;
4063 
4064 			if ((match_flags & MATCH_IRE_DEFAULT) == 0) {
4065 				return (B_FALSE);
4066 			}
4067 			mutex_enter(&ire->ire_ipif->ipif_ill->ill_lock);
4068 			for (tipif = ire->ire_ipif->ipif_ill->ill_ipif;
4069 			    tipif != NULL; tipif = tipif->ipif_next) {
4070 				if (IPIF_CAN_LOOKUP(tipif) &&
4071 				    (tipif->ipif_flags & IPIF_UP) &&
4072 				    (tipif->ipif_zoneid == zoneid ||
4073 				    tipif->ipif_zoneid == ALL_ZONES))
4074 					break;
4075 			}
4076 			mutex_exit(&ire->ire_ipif->ipif_ill->ill_lock);
4077 			if (tipif == NULL) {
4078 				return (B_FALSE);
4079 			}
4080 		}
4081 	}
4082 
4083 	/*
4084 	 * For IRE_CACHES, MATCH_IRE_ILL/ILL_GROUP really means that
4085 	 * somebody wants to send out on a particular interface which
4086 	 * is given by ire_stq and hence use ire_stq to derive the ill
4087 	 * value. ire_ipif for IRE_CACHES is just the means of getting
4088 	 * a source address i.e ire_src_addr = ire->ire_ipif->ipif_src_addr.
4089 	 * ire_to_ill does the right thing for this.
4090 	 */
4091 	if (match_flags & (MATCH_IRE_ILL|MATCH_IRE_ILL_GROUP)) {
4092 		ire_ill = ire_to_ill(ire);
4093 		if (ire_ill != NULL)
4094 			ire_ill_group = ire_ill->ill_group;
4095 		ipif_ill = ipif->ipif_ill;
4096 		ipif_ill_group = ipif_ill->ill_group;
4097 	}
4098 
4099 	if ((ire->ire_addr == (addr & mask)) &&
4100 	    ((!(match_flags & MATCH_IRE_GW)) ||
4101 	    (ire->ire_gateway_addr == gateway)) &&
4102 	    ((!(match_flags & MATCH_IRE_TYPE)) ||
4103 	    (ire->ire_type & type)) &&
4104 	    ((!(match_flags & MATCH_IRE_SRC)) ||
4105 	    (ire->ire_src_addr == ipif->ipif_src_addr)) &&
4106 	    ((!(match_flags & MATCH_IRE_IPIF)) ||
4107 	    (ire->ire_ipif == ipif)) &&
4108 	    ((!(match_flags & MATCH_IRE_MARK_HIDDEN)) ||
4109 	    (ire->ire_type != IRE_CACHE ||
4110 	    ire->ire_marks & IRE_MARK_HIDDEN)) &&
4111 	    ((!(match_flags & MATCH_IRE_MARK_PRIVATE_ADDR)) ||
4112 	    (ire->ire_type != IRE_CACHE ||
4113 	    ire->ire_marks & IRE_MARK_PRIVATE_ADDR)) &&
4114 	    ((!(match_flags & MATCH_IRE_ILL)) ||
4115 	    (ire_ill == ipif_ill)) &&
4116 	    ((!(match_flags & MATCH_IRE_IHANDLE)) ||
4117 	    (ire->ire_ihandle == ihandle)) &&
4118 	    ((!(match_flags & MATCH_IRE_MASK)) ||
4119 	    (ire->ire_mask == mask)) &&
4120 	    ((!(match_flags & MATCH_IRE_ILL_GROUP)) ||
4121 	    (ire_ill == ipif_ill) ||
4122 	    (ire_ill_group != NULL &&
4123 	    ire_ill_group == ipif_ill_group)) &&
4124 	    ((!(match_flags & MATCH_IRE_SECATTR)) ||
4125 	    (!is_system_labeled()) ||
4126 	    (tsol_ire_match_gwattr(ire, tsl) == 0))) {
4127 		/* We found the matched IRE */
4128 		return (B_TRUE);
4129 	}
4130 	return (B_FALSE);
4131 }
4132 
4133 
4134 /*
4135  * Lookup for a route in all the tables
4136  */
4137 ire_t *
4138 ire_route_lookup(ipaddr_t addr, ipaddr_t mask, ipaddr_t gateway,
4139     int type, const ipif_t *ipif, ire_t **pire, zoneid_t zoneid,
4140     const ts_label_t *tsl, int flags, ip_stack_t *ipst)
4141 {
4142 	ire_t *ire = NULL;
4143 
4144 	/*
4145 	 * ire_match_args() will dereference ipif MATCH_IRE_SRC or
4146 	 * MATCH_IRE_ILL is set.
4147 	 */
4148 	if ((flags & (MATCH_IRE_SRC | MATCH_IRE_ILL | MATCH_IRE_ILL_GROUP)) &&
4149 	    (ipif == NULL))
4150 		return (NULL);
4151 
4152 	/*
4153 	 * might be asking for a cache lookup,
4154 	 * This is not best way to lookup cache,
4155 	 * user should call ire_cache_lookup directly.
4156 	 *
4157 	 * If MATCH_IRE_TYPE was set, first lookup in the cache table and then
4158 	 * in the forwarding table, if the applicable type flags were set.
4159 	 */
4160 	if ((flags & MATCH_IRE_TYPE) == 0 || (type & IRE_CACHETABLE) != 0) {
4161 		ire = ire_ctable_lookup(addr, gateway, type, ipif, zoneid,
4162 		    tsl, flags, ipst);
4163 		if (ire != NULL)
4164 			return (ire);
4165 	}
4166 	if ((flags & MATCH_IRE_TYPE) == 0 || (type & IRE_FORWARDTABLE) != 0) {
4167 		ire = ire_ftable_lookup(addr, mask, gateway, type, ipif, pire,
4168 		    zoneid, 0, tsl, flags, ipst);
4169 	}
4170 	return (ire);
4171 }
4172 
4173 
4174 /*
4175  * Delete the IRE cache for the gateway and all IRE caches whose
4176  * ire_gateway_addr points to this gateway, and allow them to
4177  * be created on demand by ip_newroute.
4178  */
4179 void
4180 ire_clookup_delete_cache_gw(ipaddr_t addr, zoneid_t zoneid, ip_stack_t *ipst)
4181 {
4182 	irb_t *irb;
4183 	ire_t *ire;
4184 
4185 	irb = &ipst->ips_ip_cache_table[IRE_ADDR_HASH(addr,
4186 	    ipst->ips_ip_cache_table_size)];
4187 	IRB_REFHOLD(irb);
4188 	for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
4189 		if (ire->ire_marks & IRE_MARK_CONDEMNED)
4190 			continue;
4191 
4192 		ASSERT(ire->ire_mask == IP_HOST_MASK);
4193 		if (ire_match_args(ire, addr, ire->ire_mask, 0, IRE_CACHE,
4194 		    NULL, zoneid, 0, NULL, MATCH_IRE_TYPE)) {
4195 			ire_delete(ire);
4196 		}
4197 	}
4198 	IRB_REFRELE(irb);
4199 
4200 	ire_walk_v4(ire_delete_cache_gw, &addr, zoneid, ipst);
4201 }
4202 
4203 /*
4204  * Looks up cache table for a route.
4205  * specific lookup can be indicated by
4206  * passing the MATCH_* flags and the
4207  * necessary parameters.
4208  */
4209 ire_t *
4210 ire_ctable_lookup(ipaddr_t addr, ipaddr_t gateway, int type, const ipif_t *ipif,
4211     zoneid_t zoneid, const ts_label_t *tsl, int flags, ip_stack_t *ipst)
4212 {
4213 	irb_t *irb_ptr;
4214 	ire_t *ire;
4215 
4216 	/*
4217 	 * ire_match_args() will dereference ipif MATCH_IRE_SRC or
4218 	 * MATCH_IRE_ILL is set.
4219 	 */
4220 	if ((flags & (MATCH_IRE_SRC | MATCH_IRE_ILL | MATCH_IRE_ILL_GROUP)) &&
4221 	    (ipif == NULL))
4222 		return (NULL);
4223 
4224 	irb_ptr = &ipst->ips_ip_cache_table[IRE_ADDR_HASH(addr,
4225 	    ipst->ips_ip_cache_table_size)];
4226 	rw_enter(&irb_ptr->irb_lock, RW_READER);
4227 	for (ire = irb_ptr->irb_ire; ire != NULL; ire = ire->ire_next) {
4228 		if (ire->ire_marks & IRE_MARK_CONDEMNED)
4229 			continue;
4230 		ASSERT(ire->ire_mask == IP_HOST_MASK);
4231 		if (ire_match_args(ire, addr, ire->ire_mask, gateway, type,
4232 		    ipif, zoneid, 0, tsl, flags)) {
4233 			IRE_REFHOLD(ire);
4234 			rw_exit(&irb_ptr->irb_lock);
4235 			return (ire);
4236 		}
4237 	}
4238 	rw_exit(&irb_ptr->irb_lock);
4239 	return (NULL);
4240 }
4241 
4242 /*
4243  * Check whether the IRE_LOCAL and the IRE potentially used to transmit
4244  * (could be an IRE_CACHE, IRE_BROADCAST, or IRE_INTERFACE) are part of
4245  * the same ill group.
4246  */
4247 boolean_t
4248 ire_local_same_ill_group(ire_t *ire_local, ire_t *xmit_ire)
4249 {
4250 	ill_t		*recv_ill, *xmit_ill;
4251 	ill_group_t	*recv_group, *xmit_group;
4252 
4253 	ASSERT(ire_local->ire_type & (IRE_LOCAL|IRE_LOOPBACK));
4254 	ASSERT(xmit_ire->ire_type & (IRE_CACHETABLE|IRE_INTERFACE));
4255 
4256 	recv_ill = ire_to_ill(ire_local);
4257 	xmit_ill = ire_to_ill(xmit_ire);
4258 
4259 	ASSERT(recv_ill != NULL);
4260 	ASSERT(xmit_ill != NULL);
4261 
4262 	if (recv_ill == xmit_ill)
4263 		return (B_TRUE);
4264 
4265 	recv_group = recv_ill->ill_group;
4266 	xmit_group = xmit_ill->ill_group;
4267 
4268 	if (recv_group != NULL && recv_group == xmit_group)
4269 		return (B_TRUE);
4270 
4271 	return (B_FALSE);
4272 }
4273 
4274 /*
4275  * Check if the IRE_LOCAL uses the same ill (group) as another route would use.
4276  * If there is no alternate route, or the alternate is a REJECT or BLACKHOLE,
4277  * then we don't allow this IRE_LOCAL to be used.
4278  */
4279 boolean_t
4280 ire_local_ok_across_zones(ire_t *ire_local, zoneid_t zoneid, void *addr,
4281     const ts_label_t *tsl, ip_stack_t *ipst)
4282 {
4283 	ire_t		*alt_ire;
4284 	boolean_t	rval;
4285 
4286 	if (ire_local->ire_ipversion == IPV4_VERSION) {
4287 		alt_ire = ire_ftable_lookup(*((ipaddr_t *)addr), 0, 0, 0, NULL,
4288 		    NULL, zoneid, 0, tsl,
4289 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4290 		    MATCH_IRE_RJ_BHOLE, ipst);
4291 	} else {
4292 		alt_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
4293 		    0, NULL, NULL, zoneid, 0, tsl,
4294 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4295 		    MATCH_IRE_RJ_BHOLE, ipst);
4296 	}
4297 
4298 	if (alt_ire == NULL)
4299 		return (B_FALSE);
4300 
4301 	if (alt_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4302 		ire_refrele(alt_ire);
4303 		return (B_FALSE);
4304 	}
4305 	rval = ire_local_same_ill_group(ire_local, alt_ire);
4306 
4307 	ire_refrele(alt_ire);
4308 	return (rval);
4309 }
4310 
4311 /*
4312  * Lookup cache. Don't return IRE_MARK_HIDDEN entries. Callers
4313  * should use ire_ctable_lookup with MATCH_IRE_MARK_HIDDEN to get
4314  * to the hidden ones.
4315  *
4316  * In general the zoneid has to match (where ALL_ZONES match all of them).
4317  * But for IRE_LOCAL we also need to handle the case where L2 should
4318  * conceptually loop back the packet. This is necessary since neither
4319  * Ethernet drivers nor Ethernet hardware loops back packets sent to their
4320  * own MAC address. This loopback is needed when the normal
4321  * routes (ignoring IREs with different zoneids) would send out the packet on
4322  * the same ill (or ill group) as the ill with which this IRE_LOCAL is
4323  * associated.
4324  *
4325  * Earlier versions of this code always matched an IRE_LOCAL independently of
4326  * the zoneid. We preserve that earlier behavior when
4327  * ip_restrict_interzone_loopback is turned off.
4328  */
4329 ire_t *
4330 ire_cache_lookup(ipaddr_t addr, zoneid_t zoneid, const ts_label_t *tsl,
4331     ip_stack_t *ipst)
4332 {
4333 	irb_t *irb_ptr;
4334 	ire_t *ire;
4335 
4336 	irb_ptr = &ipst->ips_ip_cache_table[IRE_ADDR_HASH(addr,
4337 	    ipst->ips_ip_cache_table_size)];
4338 	rw_enter(&irb_ptr->irb_lock, RW_READER);
4339 	for (ire = irb_ptr->irb_ire; ire != NULL; ire = ire->ire_next) {
4340 		if (ire->ire_marks & (IRE_MARK_CONDEMNED |
4341 		    IRE_MARK_HIDDEN | IRE_MARK_PRIVATE_ADDR)) {
4342 			continue;
4343 		}
4344 		if (ire->ire_addr == addr) {
4345 			/*
4346 			 * Finally, check if the security policy has any
4347 			 * restriction on using this route for the specified
4348 			 * message.
4349 			 */
4350 			if (tsl != NULL &&
4351 			    ire->ire_gw_secattr != NULL &&
4352 			    tsol_ire_match_gwattr(ire, tsl) != 0) {
4353 				continue;
4354 			}
4355 
4356 			if (zoneid == ALL_ZONES || ire->ire_zoneid == zoneid ||
4357 			    ire->ire_zoneid == ALL_ZONES) {
4358 				IRE_REFHOLD(ire);
4359 				rw_exit(&irb_ptr->irb_lock);
4360 				return (ire);
4361 			}
4362 
4363 			if (ire->ire_type == IRE_LOCAL) {
4364 				if (ipst->ips_ip_restrict_interzone_loopback &&
4365 				    !ire_local_ok_across_zones(ire, zoneid,
4366 				    &addr, tsl, ipst))
4367 					continue;
4368 
4369 				IRE_REFHOLD(ire);
4370 				rw_exit(&irb_ptr->irb_lock);
4371 				return (ire);
4372 			}
4373 		}
4374 	}
4375 	rw_exit(&irb_ptr->irb_lock);
4376 	return (NULL);
4377 }
4378 
4379 /*
4380  * Locate the interface ire that is tied to the cache ire 'cire' via
4381  * cire->ire_ihandle.
4382  *
4383  * We are trying to create the cache ire for an offlink destn based
4384  * on the cache ire of the gateway in 'cire'. 'pire' is the prefix ire
4385  * as found by ip_newroute(). We are called from ip_newroute() in
4386  * the IRE_CACHE case.
4387  */
4388 ire_t *
4389 ire_ihandle_lookup_offlink(ire_t *cire, ire_t *pire)
4390 {
4391 	ire_t	*ire;
4392 	int	match_flags;
4393 	ipaddr_t gw_addr;
4394 	ipif_t	*gw_ipif;
4395 	ip_stack_t	*ipst = cire->ire_ipst;
4396 
4397 	ASSERT(cire != NULL && pire != NULL);
4398 
4399 	/*
4400 	 * We don't need to specify the zoneid to ire_ftable_lookup() below
4401 	 * because the ihandle refers to an ipif which can be in only one zone.
4402 	 */
4403 	match_flags =  MATCH_IRE_TYPE | MATCH_IRE_IHANDLE | MATCH_IRE_MASK;
4404 	/*
4405 	 * ip_newroute calls ire_ftable_lookup with MATCH_IRE_ILL only
4406 	 * for on-link hosts. We should never be here for onlink.
4407 	 * Thus, use MATCH_IRE_ILL_GROUP.
4408 	 */
4409 	if (pire->ire_ipif != NULL)
4410 		match_flags |= MATCH_IRE_ILL_GROUP;
4411 	/*
4412 	 * We know that the mask of the interface ire equals cire->ire_cmask.
4413 	 * (When ip_newroute() created 'cire' for the gateway it set its
4414 	 * cmask from the interface ire's mask)
4415 	 */
4416 	ire = ire_ftable_lookup(cire->ire_addr, cire->ire_cmask, 0,
4417 	    IRE_INTERFACE, pire->ire_ipif, NULL, ALL_ZONES, cire->ire_ihandle,
4418 	    NULL, match_flags, ipst);
4419 	if (ire != NULL)
4420 		return (ire);
4421 	/*
4422 	 * If we didn't find an interface ire above, we can't declare failure.
4423 	 * For backwards compatibility, we need to support prefix routes
4424 	 * pointing to next hop gateways that are not on-link.
4425 	 *
4426 	 * Assume we are trying to ping some offlink destn, and we have the
4427 	 * routing table below.
4428 	 *
4429 	 * Eg.	default	- gw1		<--- pire	(line 1)
4430 	 *	gw1	- gw2				(line 2)
4431 	 *	gw2	- hme0				(line 3)
4432 	 *
4433 	 * If we already have a cache ire for gw1 in 'cire', the
4434 	 * ire_ftable_lookup above would have failed, since there is no
4435 	 * interface ire to reach gw1. We will fallthru below.
4436 	 *
4437 	 * Here we duplicate the steps that ire_ftable_lookup() did in
4438 	 * getting 'cire' from 'pire', in the MATCH_IRE_RECURSIVE case.
4439 	 * The differences are the following
4440 	 * i.   We want the interface ire only, so we call ire_ftable_lookup()
4441 	 *	instead of ire_route_lookup()
4442 	 * ii.  We look for only prefix routes in the 1st call below.
4443 	 * ii.  We want to match on the ihandle in the 2nd call below.
4444 	 */
4445 	match_flags =  MATCH_IRE_TYPE;
4446 	if (pire->ire_ipif != NULL)
4447 		match_flags |= MATCH_IRE_ILL_GROUP;
4448 	ire = ire_ftable_lookup(pire->ire_gateway_addr, 0, 0, IRE_OFFSUBNET,
4449 	    pire->ire_ipif, NULL, ALL_ZONES, 0, NULL, match_flags, ipst);
4450 	if (ire == NULL)
4451 		return (NULL);
4452 	/*
4453 	 * At this point 'ire' corresponds to the entry shown in line 2.
4454 	 * gw_addr is 'gw2' in the example above.
4455 	 */
4456 	gw_addr = ire->ire_gateway_addr;
4457 	gw_ipif = ire->ire_ipif;
4458 	ire_refrele(ire);
4459 
4460 	match_flags |= MATCH_IRE_IHANDLE;
4461 	ire = ire_ftable_lookup(gw_addr, 0, 0, IRE_INTERFACE,
4462 	    gw_ipif, NULL, ALL_ZONES, cire->ire_ihandle, NULL, match_flags,
4463 	    ipst);
4464 	return (ire);
4465 }
4466 
4467 /*
4468  * Return the IRE_LOOPBACK, IRE_IF_RESOLVER or IRE_IF_NORESOLVER
4469  * ire associated with the specified ipif.
4470  *
4471  * This might occasionally be called when IPIF_UP is not set since
4472  * the IP_MULTICAST_IF as well as creating interface routes
4473  * allows specifying a down ipif (ipif_lookup* match ipifs that are down).
4474  *
4475  * Note that if IPIF_NOLOCAL, IPIF_NOXMIT, or IPIF_DEPRECATED is set on
4476  * the ipif, this routine might return NULL.
4477  */
4478 ire_t *
4479 ipif_to_ire(const ipif_t *ipif)
4480 {
4481 	ire_t	*ire;
4482 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
4483 
4484 	ASSERT(!ipif->ipif_isv6);
4485 	if (ipif->ipif_ire_type == IRE_LOOPBACK) {
4486 		ire = ire_ctable_lookup(ipif->ipif_lcl_addr, 0, IRE_LOOPBACK,
4487 		    ipif, ALL_ZONES, NULL, (MATCH_IRE_TYPE | MATCH_IRE_IPIF),
4488 		    ipst);
4489 	} else if (ipif->ipif_flags & IPIF_POINTOPOINT) {
4490 		/* In this case we need to lookup destination address. */
4491 		ire = ire_ftable_lookup(ipif->ipif_pp_dst_addr, IP_HOST_MASK, 0,
4492 		    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0, NULL,
4493 		    (MATCH_IRE_TYPE | MATCH_IRE_IPIF | MATCH_IRE_MASK), ipst);
4494 	} else {
4495 		ire = ire_ftable_lookup(ipif->ipif_subnet,
4496 		    ipif->ipif_net_mask, 0, IRE_INTERFACE, ipif, NULL,
4497 		    ALL_ZONES, 0, NULL, (MATCH_IRE_TYPE | MATCH_IRE_IPIF |
4498 		    MATCH_IRE_MASK), ipst);
4499 	}
4500 	return (ire);
4501 }
4502 
4503 /*
4504  * ire_walk function.
4505  * Count the number of IRE_CACHE entries in different categories.
4506  */
4507 void
4508 ire_cache_count(ire_t *ire, char *arg)
4509 {
4510 	ire_cache_count_t *icc = (ire_cache_count_t *)arg;
4511 
4512 	if (ire->ire_type != IRE_CACHE)
4513 		return;
4514 
4515 	icc->icc_total++;
4516 
4517 	if (ire->ire_ipversion == IPV6_VERSION) {
4518 		mutex_enter(&ire->ire_lock);
4519 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6)) {
4520 			mutex_exit(&ire->ire_lock);
4521 			icc->icc_onlink++;
4522 			return;
4523 		}
4524 		mutex_exit(&ire->ire_lock);
4525 	} else {
4526 		if (ire->ire_gateway_addr == 0) {
4527 			icc->icc_onlink++;
4528 			return;
4529 		}
4530 	}
4531 
4532 	ASSERT(ire->ire_ipif != NULL);
4533 	if (ire->ire_max_frag < ire->ire_ipif->ipif_mtu)
4534 		icc->icc_pmtu++;
4535 	else if (ire->ire_tire_mark != ire->ire_ob_pkt_count +
4536 	    ire->ire_ib_pkt_count)
4537 		icc->icc_offlink++;
4538 	else
4539 		icc->icc_unused++;
4540 }
4541 
4542 /*
4543  * ire_walk function called by ip_trash_ire_reclaim().
4544  * Free a fraction of the IRE_CACHE cache entries. The fractions are
4545  * different for different categories of IRE_CACHE entries.
4546  * A fraction of zero means to not free any in that category.
4547  * Use the hash bucket id plus lbolt as a random number. Thus if the fraction
4548  * is N then every Nth hash bucket chain will be freed.
4549  */
4550 void
4551 ire_cache_reclaim(ire_t *ire, char *arg)
4552 {
4553 	ire_cache_reclaim_t *icr = (ire_cache_reclaim_t *)arg;
4554 	uint_t rand;
4555 	ip_stack_t	*ipst = icr->icr_ipst;
4556 
4557 	if (ire->ire_type != IRE_CACHE)
4558 		return;
4559 
4560 	if (ire->ire_ipversion == IPV6_VERSION) {
4561 		rand = (uint_t)lbolt +
4562 		    IRE_ADDR_HASH_V6(ire->ire_addr_v6,
4563 		    ipst->ips_ip6_cache_table_size);
4564 		mutex_enter(&ire->ire_lock);
4565 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6)) {
4566 			mutex_exit(&ire->ire_lock);
4567 			if (icr->icr_onlink != 0 &&
4568 			    (rand/icr->icr_onlink)*icr->icr_onlink == rand) {
4569 				ire_delete(ire);
4570 				return;
4571 			}
4572 			goto done;
4573 		}
4574 		mutex_exit(&ire->ire_lock);
4575 	} else {
4576 		rand = (uint_t)lbolt +
4577 		    IRE_ADDR_HASH(ire->ire_addr, ipst->ips_ip_cache_table_size);
4578 		if (ire->ire_gateway_addr == 0) {
4579 			if (icr->icr_onlink != 0 &&
4580 			    (rand/icr->icr_onlink)*icr->icr_onlink == rand) {
4581 				ire_delete(ire);
4582 				return;
4583 			}
4584 			goto done;
4585 		}
4586 	}
4587 	/* Not onlink IRE */
4588 	ASSERT(ire->ire_ipif != NULL);
4589 	if (ire->ire_max_frag < ire->ire_ipif->ipif_mtu) {
4590 		/* Use ptmu fraction */
4591 		if (icr->icr_pmtu != 0 &&
4592 		    (rand/icr->icr_pmtu)*icr->icr_pmtu == rand) {
4593 			ire_delete(ire);
4594 			return;
4595 		}
4596 	} else if (ire->ire_tire_mark != ire->ire_ob_pkt_count +
4597 	    ire->ire_ib_pkt_count) {
4598 		/* Use offlink fraction */
4599 		if (icr->icr_offlink != 0 &&
4600 		    (rand/icr->icr_offlink)*icr->icr_offlink == rand) {
4601 			ire_delete(ire);
4602 			return;
4603 		}
4604 	} else {
4605 		/* Use unused fraction */
4606 		if (icr->icr_unused != 0 &&
4607 		    (rand/icr->icr_unused)*icr->icr_unused == rand) {
4608 			ire_delete(ire);
4609 			return;
4610 		}
4611 	}
4612 done:
4613 	/*
4614 	 * Update tire_mark so that those that haven't been used since this
4615 	 * reclaim will be considered unused next time we reclaim.
4616 	 */
4617 	ire->ire_tire_mark = ire->ire_ob_pkt_count + ire->ire_ib_pkt_count;
4618 }
4619 
4620 static void
4621 power2_roundup(uint32_t *value)
4622 {
4623 	int i;
4624 
4625 	for (i = 1; i < 31; i++) {
4626 		if (*value <= (1 << i))
4627 			break;
4628 	}
4629 	*value = (1 << i);
4630 }
4631 
4632 /* Global init for all zones */
4633 void
4634 ip_ire_g_init()
4635 {
4636 	/*
4637 	 * Create ire caches, ire_reclaim()
4638 	 * will give IRE_CACHE back to system when needed.
4639 	 * This needs to be done here before anything else, since
4640 	 * ire_add() expects the cache to be created.
4641 	 */
4642 	ire_cache = kmem_cache_create("ire_cache",
4643 	    sizeof (ire_t), 0, ip_ire_constructor,
4644 	    ip_ire_destructor, ip_trash_ire_reclaim, NULL, NULL, 0);
4645 
4646 	rt_entry_cache = kmem_cache_create("rt_entry",
4647 	    sizeof (struct rt_entry), 0, NULL, NULL, NULL, NULL, NULL, 0);
4648 
4649 	/*
4650 	 * Have radix code setup kmem caches etc.
4651 	 */
4652 	rn_init();
4653 }
4654 
4655 void
4656 ip_ire_init(ip_stack_t *ipst)
4657 {
4658 	int i;
4659 	uint32_t mem_cnt;
4660 	uint32_t cpu_cnt;
4661 	uint32_t min_cnt;
4662 	pgcnt_t mem_avail;
4663 
4664 	/*
4665 	 * ip_ire_max_bucket_cnt is sized below based on the memory
4666 	 * size and the cpu speed of the machine. This is upper
4667 	 * bounded by the compile time value of ip_ire_max_bucket_cnt
4668 	 * and is lower bounded by the compile time value of
4669 	 * ip_ire_min_bucket_cnt.  Similar logic applies to
4670 	 * ip6_ire_max_bucket_cnt.
4671 	 *
4672 	 * We calculate this for each IP Instances in order to use
4673 	 * the kmem_avail and ip_ire_{min,max}_bucket_cnt that are
4674 	 * in effect when the zone is booted.
4675 	 */
4676 	mem_avail = kmem_avail();
4677 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
4678 	    ip_cache_table_size / sizeof (ire_t);
4679 	cpu_cnt = CPU->cpu_type_info.pi_clock >> ip_ire_cpu_ratio;
4680 
4681 	min_cnt = MIN(cpu_cnt, mem_cnt);
4682 	if (min_cnt < ip_ire_min_bucket_cnt)
4683 		min_cnt = ip_ire_min_bucket_cnt;
4684 	if (ip_ire_max_bucket_cnt > min_cnt) {
4685 		ip_ire_max_bucket_cnt = min_cnt;
4686 	}
4687 
4688 	mem_cnt = (mem_avail >> ip_ire_mem_ratio) /
4689 	    ip6_cache_table_size / sizeof (ire_t);
4690 	min_cnt = MIN(cpu_cnt, mem_cnt);
4691 	if (min_cnt < ip6_ire_min_bucket_cnt)
4692 		min_cnt = ip6_ire_min_bucket_cnt;
4693 	if (ip6_ire_max_bucket_cnt > min_cnt) {
4694 		ip6_ire_max_bucket_cnt = min_cnt;
4695 	}
4696 
4697 	mutex_init(&ipst->ips_ire_ft_init_lock, NULL, MUTEX_DEFAULT, 0);
4698 	mutex_init(&ipst->ips_ire_handle_lock, NULL, MUTEX_DEFAULT, NULL);
4699 
4700 	(void) rn_inithead((void **)&ipst->ips_ip_ftable, 32);
4701 
4702 
4703 	/* Calculate the IPv4 cache table size. */
4704 	ipst->ips_ip_cache_table_size = MAX(ip_cache_table_size,
4705 	    ((mem_avail >> ip_ire_mem_ratio) / sizeof (ire_t) /
4706 	    ip_ire_max_bucket_cnt));
4707 	if (ipst->ips_ip_cache_table_size > ip_max_cache_table_size)
4708 		ipst->ips_ip_cache_table_size = ip_max_cache_table_size;
4709 	/*
4710 	 * Make sure that the table size is always a power of 2.  The
4711 	 * hash macro IRE_ADDR_HASH() depends on that.
4712 	 */
4713 	power2_roundup(&ipst->ips_ip_cache_table_size);
4714 
4715 	ipst->ips_ip_cache_table = kmem_zalloc(ipst->ips_ip_cache_table_size *
4716 	    sizeof (irb_t), KM_SLEEP);
4717 
4718 	for (i = 0; i < ipst->ips_ip_cache_table_size; i++) {
4719 		rw_init(&ipst->ips_ip_cache_table[i].irb_lock, NULL,
4720 		    RW_DEFAULT, NULL);
4721 	}
4722 
4723 	/* Calculate the IPv6 cache table size. */
4724 	ipst->ips_ip6_cache_table_size = MAX(ip6_cache_table_size,
4725 	    ((mem_avail >> ip_ire_mem_ratio) / sizeof (ire_t) /
4726 	    ip6_ire_max_bucket_cnt));
4727 	if (ipst->ips_ip6_cache_table_size > ip6_max_cache_table_size)
4728 		ipst->ips_ip6_cache_table_size = ip6_max_cache_table_size;
4729 	/*
4730 	 * Make sure that the table size is always a power of 2.  The
4731 	 * hash macro IRE_ADDR_HASH_V6() depends on that.
4732 	 */
4733 	power2_roundup(&ipst->ips_ip6_cache_table_size);
4734 
4735 	ipst->ips_ip_cache_table_v6 = kmem_zalloc(
4736 	    ipst->ips_ip6_cache_table_size * sizeof (irb_t), KM_SLEEP);
4737 
4738 	for (i = 0; i < ipst->ips_ip6_cache_table_size; i++) {
4739 		rw_init(&ipst->ips_ip_cache_table_v6[i].irb_lock, NULL,
4740 		    RW_DEFAULT, NULL);
4741 	}
4742 
4743 	/*
4744 	 * Make sure that the forwarding table size is a power of 2.
4745 	 * The IRE*_ADDR_HASH() macroes depend on that.
4746 	 */
4747 	ipst->ips_ip6_ftable_hash_size = ip6_ftable_hash_size;
4748 	power2_roundup(&ipst->ips_ip6_ftable_hash_size);
4749 
4750 	ipst->ips_ire_handle = 1;
4751 }
4752 
4753 void
4754 ip_ire_g_fini(void)
4755 {
4756 	kmem_cache_destroy(ire_cache);
4757 	kmem_cache_destroy(rt_entry_cache);
4758 
4759 	rn_fini();
4760 }
4761 
4762 void
4763 ip_ire_fini(ip_stack_t *ipst)
4764 {
4765 	int i;
4766 
4767 	/*
4768 	 * Delete all IREs - assumes that the ill/ipifs have
4769 	 * been removed so what remains are just the ftable and IRE_CACHE.
4770 	 */
4771 	ire_walk(ire_delete, NULL, ipst);
4772 
4773 	rn_freehead(ipst->ips_ip_ftable);
4774 	ipst->ips_ip_ftable = NULL;
4775 
4776 	mutex_destroy(&ipst->ips_ire_ft_init_lock);
4777 	mutex_destroy(&ipst->ips_ire_handle_lock);
4778 
4779 	for (i = 0; i < ipst->ips_ip_cache_table_size; i++) {
4780 		ASSERT(ipst->ips_ip_cache_table[i].irb_ire == NULL);
4781 		rw_destroy(&ipst->ips_ip_cache_table[i].irb_lock);
4782 	}
4783 	kmem_free(ipst->ips_ip_cache_table,
4784 	    ipst->ips_ip_cache_table_size * sizeof (irb_t));
4785 	ipst->ips_ip_cache_table = NULL;
4786 
4787 	for (i = 0; i < ipst->ips_ip6_cache_table_size; i++) {
4788 		ASSERT(ipst->ips_ip_cache_table_v6[i].irb_ire == NULL);
4789 		rw_destroy(&ipst->ips_ip_cache_table_v6[i].irb_lock);
4790 	}
4791 	kmem_free(ipst->ips_ip_cache_table_v6,
4792 	    ipst->ips_ip6_cache_table_size * sizeof (irb_t));
4793 	ipst->ips_ip_cache_table_v6 = NULL;
4794 
4795 	for (i = 0; i < IP6_MASK_TABLE_SIZE; i++) {
4796 		irb_t *ptr;
4797 		int j;
4798 
4799 		if ((ptr = ipst->ips_ip_forwarding_table_v6[i]) == NULL)
4800 			continue;
4801 
4802 		for (j = 0; j < ipst->ips_ip6_ftable_hash_size; j++) {
4803 			ASSERT(ptr[j].irb_ire == NULL);
4804 			rw_destroy(&ptr[j].irb_lock);
4805 		}
4806 		mi_free(ptr);
4807 		ipst->ips_ip_forwarding_table_v6[i] = NULL;
4808 	}
4809 }
4810 
4811 /*
4812  * Check if another multirt route resolution is needed.
4813  * B_TRUE is returned is there remain a resolvable route,
4814  * or if no route for that dst is resolved yet.
4815  * B_FALSE is returned if all routes for that dst are resolved
4816  * or if the remaining unresolved routes are actually not
4817  * resolvable.
4818  * This only works in the global zone.
4819  */
4820 boolean_t
4821 ire_multirt_need_resolve(ipaddr_t dst, const ts_label_t *tsl, ip_stack_t *ipst)
4822 {
4823 	ire_t	*first_fire;
4824 	ire_t	*first_cire;
4825 	ire_t	*fire;
4826 	ire_t	*cire;
4827 	irb_t	*firb;
4828 	irb_t	*cirb;
4829 	int	unres_cnt = 0;
4830 	boolean_t resolvable = B_FALSE;
4831 
4832 	/* Retrieve the first IRE_HOST that matches the destination */
4833 	first_fire = ire_ftable_lookup(dst, IP_HOST_MASK, 0, IRE_HOST, NULL,
4834 	    NULL, ALL_ZONES, 0, tsl,
4835 	    MATCH_IRE_MASK | MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
4836 
4837 	/* No route at all */
4838 	if (first_fire == NULL) {
4839 		return (B_TRUE);
4840 	}
4841 
4842 	firb = first_fire->ire_bucket;
4843 	ASSERT(firb != NULL);
4844 
4845 	/* Retrieve the first IRE_CACHE ire for that destination. */
4846 	first_cire = ire_cache_lookup(dst, GLOBAL_ZONEID, tsl, ipst);
4847 
4848 	/* No resolved route. */
4849 	if (first_cire == NULL) {
4850 		ire_refrele(first_fire);
4851 		return (B_TRUE);
4852 	}
4853 
4854 	/*
4855 	 * At least one route is resolved. Here we look through the forward
4856 	 * and cache tables, to compare the number of declared routes
4857 	 * with the number of resolved routes. The search for a resolvable
4858 	 * route is performed only if at least one route remains
4859 	 * unresolved.
4860 	 */
4861 	cirb = first_cire->ire_bucket;
4862 	ASSERT(cirb != NULL);
4863 
4864 	/* Count the number of routes to that dest that are declared. */
4865 	IRB_REFHOLD(firb);
4866 	for (fire = first_fire; fire != NULL; fire = fire->ire_next) {
4867 		if (!(fire->ire_flags & RTF_MULTIRT))
4868 			continue;
4869 		if (fire->ire_addr != dst)
4870 			continue;
4871 		unres_cnt++;
4872 	}
4873 	IRB_REFRELE(firb);
4874 
4875 	/* Then subtract the number of routes to that dst that are resolved */
4876 	IRB_REFHOLD(cirb);
4877 	for (cire = first_cire; cire != NULL; cire = cire->ire_next) {
4878 		if (!(cire->ire_flags & RTF_MULTIRT))
4879 			continue;
4880 		if (cire->ire_addr != dst)
4881 			continue;
4882 		if (cire->ire_marks & (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
4883 			continue;
4884 		unres_cnt--;
4885 	}
4886 	IRB_REFRELE(cirb);
4887 
4888 	/* At least one route is unresolved; search for a resolvable route. */
4889 	if (unres_cnt > 0)
4890 		resolvable = ire_multirt_lookup(&first_cire, &first_fire,
4891 		    MULTIRT_USESTAMP | MULTIRT_CACHEGW, tsl, ipst);
4892 
4893 	if (first_fire != NULL)
4894 		ire_refrele(first_fire);
4895 
4896 	if (first_cire != NULL)
4897 		ire_refrele(first_cire);
4898 
4899 	return (resolvable);
4900 }
4901 
4902 
4903 /*
4904  * Explore a forward_table bucket, starting from fire_arg.
4905  * fire_arg MUST be an IRE_HOST entry.
4906  *
4907  * Return B_TRUE and update *ire_arg and *fire_arg
4908  * if at least one resolvable route is found. *ire_arg
4909  * is the IRE entry for *fire_arg's gateway.
4910  *
4911  * Return B_FALSE otherwise (all routes are resolved or
4912  * the remaining unresolved routes are all unresolvable).
4913  *
4914  * The IRE selection relies on a priority mechanism
4915  * driven by the flags passed in by the caller.
4916  * The caller, such as ip_newroute_ipif(), can get the most
4917  * relevant ire at each stage of a multiple route resolution.
4918  *
4919  * The rules are:
4920  *
4921  * - if MULTIRT_CACHEGW is specified in flags, IRE_CACHETABLE
4922  *   ires are preferred for the gateway. This gives the highest
4923  *   priority to routes that can be resolved without using
4924  *   a resolver.
4925  *
4926  * - if MULTIRT_CACHEGW is not specified, or if MULTIRT_CACHEGW
4927  *   is specified but no IRE_CACHETABLE ire entry for the gateway
4928  *   is found, the following rules apply.
4929  *
4930  * - if MULTIRT_USESTAMP is specified in flags, IRE_INTERFACE
4931  *   ires for the gateway, that have not been tried since
4932  *   a configurable amount of time, are preferred.
4933  *   This applies when a resolver must be invoked for
4934  *   a missing route, but we don't want to use the resolver
4935  *   upon each packet emission. If no such resolver is found,
4936  *   B_FALSE is returned.
4937  *   The MULTIRT_USESTAMP flag can be combined with
4938  *   MULTIRT_CACHEGW.
4939  *
4940  * - if MULTIRT_USESTAMP is not specified in flags, the first
4941  *   unresolved but resolvable route is selected.
4942  *
4943  * - Otherwise, there is no resolvalble route, and
4944  *   B_FALSE is returned.
4945  *
4946  * At last, MULTIRT_SETSTAMP can be specified in flags to
4947  * request the timestamp of unresolvable routes to
4948  * be refreshed. This prevents the useless exploration
4949  * of those routes for a while, when MULTIRT_USESTAMP is used.
4950  *
4951  * This only works in the global zone.
4952  */
4953 boolean_t
4954 ire_multirt_lookup(ire_t **ire_arg, ire_t **fire_arg, uint32_t flags,
4955     const ts_label_t *tsl, ip_stack_t *ipst)
4956 {
4957 	clock_t	delta;
4958 	ire_t	*best_fire = NULL;
4959 	ire_t	*best_cire = NULL;
4960 	ire_t	*first_fire;
4961 	ire_t	*first_cire;
4962 	ire_t	*fire;
4963 	ire_t	*cire;
4964 	irb_t	*firb = NULL;
4965 	irb_t	*cirb = NULL;
4966 	ire_t	*gw_ire;
4967 	boolean_t	already_resolved;
4968 	boolean_t	res;
4969 	ipaddr_t	dst;
4970 	ipaddr_t	gw;
4971 
4972 	ip2dbg(("ire_multirt_lookup: *ire_arg %p, *fire_arg %p, flags %04x\n",
4973 	    (void *)*ire_arg, (void *)*fire_arg, flags));
4974 
4975 	ASSERT(ire_arg != NULL);
4976 	ASSERT(fire_arg != NULL);
4977 
4978 	/* Not an IRE_HOST ire; give up. */
4979 	if ((*fire_arg == NULL) || ((*fire_arg)->ire_type != IRE_HOST)) {
4980 		return (B_FALSE);
4981 	}
4982 
4983 	/* This is the first IRE_HOST ire for that destination. */
4984 	first_fire = *fire_arg;
4985 	firb = first_fire->ire_bucket;
4986 	ASSERT(firb != NULL);
4987 
4988 	dst = first_fire->ire_addr;
4989 
4990 	ip2dbg(("ire_multirt_lookup: dst %08x\n", ntohl(dst)));
4991 
4992 	/*
4993 	 * Retrieve the first IRE_CACHE ire for that destination;
4994 	 * if we don't find one, no route for that dest is
4995 	 * resolved yet.
4996 	 */
4997 	first_cire = ire_cache_lookup(dst, GLOBAL_ZONEID, tsl, ipst);
4998 	if (first_cire != NULL) {
4999 		cirb = first_cire->ire_bucket;
5000 	}
5001 
5002 	ip2dbg(("ire_multirt_lookup: first_cire %p\n", (void *)first_cire));
5003 
5004 	/*
5005 	 * Search for a resolvable route, giving the top priority
5006 	 * to routes that can be resolved without any call to the resolver.
5007 	 */
5008 	IRB_REFHOLD(firb);
5009 
5010 	if (!CLASSD(dst)) {
5011 		/*
5012 		 * For all multiroute IRE_HOST ires for that destination,
5013 		 * check if the route via the IRE_HOST's gateway is
5014 		 * resolved yet.
5015 		 */
5016 		for (fire = first_fire; fire != NULL; fire = fire->ire_next) {
5017 
5018 			if (!(fire->ire_flags & RTF_MULTIRT))
5019 				continue;
5020 			if (fire->ire_addr != dst)
5021 				continue;
5022 
5023 			if (fire->ire_gw_secattr != NULL &&
5024 			    tsol_ire_match_gwattr(fire, tsl) != 0) {
5025 				continue;
5026 			}
5027 
5028 			gw = fire->ire_gateway_addr;
5029 
5030 			ip2dbg(("ire_multirt_lookup: fire %p, "
5031 			    "ire_addr %08x, ire_gateway_addr %08x\n",
5032 			    (void *)fire, ntohl(fire->ire_addr), ntohl(gw)));
5033 
5034 			already_resolved = B_FALSE;
5035 
5036 			if (first_cire != NULL) {
5037 				ASSERT(cirb != NULL);
5038 
5039 				IRB_REFHOLD(cirb);
5040 				/*
5041 				 * For all IRE_CACHE ires for that
5042 				 * destination.
5043 				 */
5044 				for (cire = first_cire;
5045 				    cire != NULL;
5046 				    cire = cire->ire_next) {
5047 
5048 					if (!(cire->ire_flags & RTF_MULTIRT))
5049 						continue;
5050 					if (cire->ire_addr != dst)
5051 						continue;
5052 					if (cire->ire_marks &
5053 					    (IRE_MARK_CONDEMNED |
5054 					    IRE_MARK_HIDDEN))
5055 						continue;
5056 
5057 					if (cire->ire_gw_secattr != NULL &&
5058 					    tsol_ire_match_gwattr(cire,
5059 					    tsl) != 0) {
5060 						continue;
5061 					}
5062 
5063 					/*
5064 					 * Check if the IRE_CACHE's gateway
5065 					 * matches the IRE_HOST's gateway.
5066 					 */
5067 					if (cire->ire_gateway_addr == gw) {
5068 						already_resolved = B_TRUE;
5069 						break;
5070 					}
5071 				}
5072 				IRB_REFRELE(cirb);
5073 			}
5074 
5075 			/*
5076 			 * This route is already resolved;
5077 			 * proceed with next one.
5078 			 */
5079 			if (already_resolved) {
5080 				ip2dbg(("ire_multirt_lookup: found cire %p, "
5081 				    "already resolved\n", (void *)cire));
5082 				continue;
5083 			}
5084 
5085 			/*
5086 			 * The route is unresolved; is it actually
5087 			 * resolvable, i.e. is there a cache or a resolver
5088 			 * for the gateway?
5089 			 */
5090 			gw_ire = ire_route_lookup(gw, 0, 0, 0, NULL, NULL,
5091 			    ALL_ZONES, tsl,
5092 			    MATCH_IRE_RECURSIVE | MATCH_IRE_SECATTR, ipst);
5093 
5094 			ip2dbg(("ire_multirt_lookup: looked up gw_ire %p\n",
5095 			    (void *)gw_ire));
5096 
5097 			/*
5098 			 * If gw_ire is typed IRE_CACHETABLE,
5099 			 * this route can be resolved without any call to the
5100 			 * resolver. If the MULTIRT_CACHEGW flag is set,
5101 			 * give the top priority to this ire and exit the
5102 			 * loop.
5103 			 * This is typically the case when an ARP reply
5104 			 * is processed through ip_wput_nondata().
5105 			 */
5106 			if ((flags & MULTIRT_CACHEGW) &&
5107 			    (gw_ire != NULL) &&
5108 			    (gw_ire->ire_type & IRE_CACHETABLE)) {
5109 				ASSERT(gw_ire->ire_nce == NULL ||
5110 				    gw_ire->ire_nce->nce_state == ND_REACHABLE);
5111 				/*
5112 				 * Release the resolver associated to the
5113 				 * previous candidate best ire, if any.
5114 				 */
5115 				if (best_cire != NULL) {
5116 					ire_refrele(best_cire);
5117 					ASSERT(best_fire != NULL);
5118 				}
5119 
5120 				best_fire = fire;
5121 				best_cire = gw_ire;
5122 
5123 				ip2dbg(("ire_multirt_lookup: found top prio "
5124 				    "best_fire %p, best_cire %p\n",
5125 				    (void *)best_fire, (void *)best_cire));
5126 				break;
5127 			}
5128 
5129 			/*
5130 			 * Compute the time elapsed since our preceding
5131 			 * attempt to  resolve that route.
5132 			 * If the MULTIRT_USESTAMP flag is set, we take that
5133 			 * route into account only if this time interval
5134 			 * exceeds ip_multirt_resolution_interval;
5135 			 * this prevents us from attempting to resolve a
5136 			 * broken route upon each sending of a packet.
5137 			 */
5138 			delta = lbolt - fire->ire_last_used_time;
5139 			delta = TICK_TO_MSEC(delta);
5140 
5141 			res = (boolean_t)((delta >
5142 			    ipst->ips_ip_multirt_resolution_interval) ||
5143 			    (!(flags & MULTIRT_USESTAMP)));
5144 
5145 			ip2dbg(("ire_multirt_lookup: fire %p, delta %lu, "
5146 			    "res %d\n",
5147 			    (void *)fire, delta, res));
5148 
5149 			if (res) {
5150 				/*
5151 				 * We are here if MULTIRT_USESTAMP flag is set
5152 				 * and the resolver for fire's gateway
5153 				 * has not been tried since
5154 				 * ip_multirt_resolution_interval, or if
5155 				 * MULTIRT_USESTAMP is not set but gw_ire did
5156 				 * not fill the conditions for MULTIRT_CACHEGW,
5157 				 * or if neither MULTIRT_USESTAMP nor
5158 				 * MULTIRT_CACHEGW are set.
5159 				 */
5160 				if (gw_ire != NULL) {
5161 					if (best_fire == NULL) {
5162 						ASSERT(best_cire == NULL);
5163 
5164 						best_fire = fire;
5165 						best_cire = gw_ire;
5166 
5167 						ip2dbg(("ire_multirt_lookup:"
5168 						    "found candidate "
5169 						    "best_fire %p, "
5170 						    "best_cire %p\n",
5171 						    (void *)best_fire,
5172 						    (void *)best_cire));
5173 
5174 						/*
5175 						 * If MULTIRT_CACHEGW is not
5176 						 * set, we ignore the top
5177 						 * priority ires that can
5178 						 * be resolved without any
5179 						 * call to the resolver;
5180 						 * In that case, there is
5181 						 * actually no need
5182 						 * to continue the loop.
5183 						 */
5184 						if (!(flags &
5185 						    MULTIRT_CACHEGW)) {
5186 							break;
5187 						}
5188 						continue;
5189 					}
5190 				} else {
5191 					/*
5192 					 * No resolver for the gateway: the
5193 					 * route is not resolvable.
5194 					 * If the MULTIRT_SETSTAMP flag is
5195 					 * set, we stamp the IRE_HOST ire,
5196 					 * so we will not select it again
5197 					 * during this resolution interval.
5198 					 */
5199 					if (flags & MULTIRT_SETSTAMP)
5200 						fire->ire_last_used_time =
5201 						    lbolt;
5202 				}
5203 			}
5204 
5205 			if (gw_ire != NULL)
5206 				ire_refrele(gw_ire);
5207 		}
5208 	} else { /* CLASSD(dst) */
5209 
5210 		for (fire = first_fire;
5211 		    fire != NULL;
5212 		    fire = fire->ire_next) {
5213 
5214 			if (!(fire->ire_flags & RTF_MULTIRT))
5215 				continue;
5216 			if (fire->ire_addr != dst)
5217 				continue;
5218 
5219 			if (fire->ire_gw_secattr != NULL &&
5220 			    tsol_ire_match_gwattr(fire, tsl) != 0) {
5221 				continue;
5222 			}
5223 
5224 			already_resolved = B_FALSE;
5225 
5226 			gw = fire->ire_gateway_addr;
5227 
5228 			gw_ire = ire_ftable_lookup(gw, 0, 0, IRE_INTERFACE,
5229 			    NULL, NULL, ALL_ZONES, 0, tsl,
5230 			    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE |
5231 			    MATCH_IRE_SECATTR, ipst);
5232 
5233 			/* No resolver for the gateway; we skip this ire. */
5234 			if (gw_ire == NULL) {
5235 				continue;
5236 			}
5237 			ASSERT(gw_ire->ire_nce == NULL ||
5238 			    gw_ire->ire_nce->nce_state == ND_REACHABLE);
5239 
5240 			if (first_cire != NULL) {
5241 
5242 				IRB_REFHOLD(cirb);
5243 				/*
5244 				 * For all IRE_CACHE ires for that
5245 				 * destination.
5246 				 */
5247 				for (cire = first_cire;
5248 				    cire != NULL;
5249 				    cire = cire->ire_next) {
5250 
5251 					if (!(cire->ire_flags & RTF_MULTIRT))
5252 						continue;
5253 					if (cire->ire_addr != dst)
5254 						continue;
5255 					if (cire->ire_marks &
5256 					    (IRE_MARK_CONDEMNED |
5257 					    IRE_MARK_HIDDEN))
5258 						continue;
5259 
5260 					if (cire->ire_gw_secattr != NULL &&
5261 					    tsol_ire_match_gwattr(cire,
5262 					    tsl) != 0) {
5263 						continue;
5264 					}
5265 
5266 					/*
5267 					 * Cache entries are linked to the
5268 					 * parent routes using the parent handle
5269 					 * (ire_phandle). If no cache entry has
5270 					 * the same handle as fire, fire is
5271 					 * still unresolved.
5272 					 */
5273 					ASSERT(cire->ire_phandle != 0);
5274 					if (cire->ire_phandle ==
5275 					    fire->ire_phandle) {
5276 						already_resolved = B_TRUE;
5277 						break;
5278 					}
5279 				}
5280 				IRB_REFRELE(cirb);
5281 			}
5282 
5283 			/*
5284 			 * This route is already resolved; proceed with
5285 			 * next one.
5286 			 */
5287 			if (already_resolved) {
5288 				ire_refrele(gw_ire);
5289 				continue;
5290 			}
5291 
5292 			/*
5293 			 * Compute the time elapsed since our preceding
5294 			 * attempt to resolve that route.
5295 			 * If the MULTIRT_USESTAMP flag is set, we take
5296 			 * that route into account only if this time
5297 			 * interval exceeds ip_multirt_resolution_interval;
5298 			 * this prevents us from attempting to resolve a
5299 			 * broken route upon each sending of a packet.
5300 			 */
5301 			delta = lbolt - fire->ire_last_used_time;
5302 			delta = TICK_TO_MSEC(delta);
5303 
5304 			res = (boolean_t)((delta >
5305 			    ipst->ips_ip_multirt_resolution_interval) ||
5306 			    (!(flags & MULTIRT_USESTAMP)));
5307 
5308 			ip3dbg(("ire_multirt_lookup: fire %p, delta %lx, "
5309 			    "flags %04x, res %d\n",
5310 			    (void *)fire, delta, flags, res));
5311 
5312 			if (res) {
5313 				if (best_cire != NULL) {
5314 					/*
5315 					 * Release the resolver associated
5316 					 * to the preceding candidate best
5317 					 * ire, if any.
5318 					 */
5319 					ire_refrele(best_cire);
5320 					ASSERT(best_fire != NULL);
5321 				}
5322 				best_fire = fire;
5323 				best_cire = gw_ire;
5324 				continue;
5325 			}
5326 
5327 			ire_refrele(gw_ire);
5328 		}
5329 	}
5330 
5331 	if (best_fire != NULL) {
5332 		IRE_REFHOLD(best_fire);
5333 	}
5334 	IRB_REFRELE(firb);
5335 
5336 	/* Release the first IRE_CACHE we initially looked up, if any. */
5337 	if (first_cire != NULL)
5338 		ire_refrele(first_cire);
5339 
5340 	/* Found a resolvable route. */
5341 	if (best_fire != NULL) {
5342 		ASSERT(best_cire != NULL);
5343 
5344 		if (*fire_arg != NULL)
5345 			ire_refrele(*fire_arg);
5346 		if (*ire_arg != NULL)
5347 			ire_refrele(*ire_arg);
5348 
5349 		/*
5350 		 * Update the passed-in arguments with the
5351 		 * resolvable multirt route we found.
5352 		 */
5353 		*fire_arg = best_fire;
5354 		*ire_arg = best_cire;
5355 
5356 		ip2dbg(("ire_multirt_lookup: returning B_TRUE, "
5357 		    "*fire_arg %p, *ire_arg %p\n",
5358 		    (void *)best_fire, (void *)best_cire));
5359 
5360 		return (B_TRUE);
5361 	}
5362 
5363 	ASSERT(best_cire == NULL);
5364 
5365 	ip2dbg(("ire_multirt_lookup: returning B_FALSE, *fire_arg %p, "
5366 	    "*ire_arg %p\n",
5367 	    (void *)*fire_arg, (void *)*ire_arg));
5368 
5369 	/* No resolvable route. */
5370 	return (B_FALSE);
5371 }
5372 
5373 /*
5374  * IRE iterator for inbound and loopback broadcast processing.
5375  * Given an IRE_BROADCAST ire, walk the ires with the same destination
5376  * address, but skip over the passed-in ire. Returns the next ire without
5377  * a hold - assumes that the caller holds a reference on the IRE bucket.
5378  */
5379 ire_t *
5380 ire_get_next_bcast_ire(ire_t *curr, ire_t *ire)
5381 {
5382 	ill_t *ill;
5383 
5384 	if (curr == NULL) {
5385 		for (curr = ire->ire_bucket->irb_ire; curr != NULL;
5386 		    curr = curr->ire_next) {
5387 			if (curr->ire_addr == ire->ire_addr)
5388 				break;
5389 		}
5390 	} else {
5391 		curr = curr->ire_next;
5392 	}
5393 	ill = ire_to_ill(ire);
5394 	for (; curr != NULL; curr = curr->ire_next) {
5395 		if (curr->ire_addr != ire->ire_addr) {
5396 			/*
5397 			 * All the IREs to a given destination are contiguous;
5398 			 * break out once the address doesn't match.
5399 			 */
5400 			break;
5401 		}
5402 		if (curr == ire) {
5403 			/* skip over the passed-in ire */
5404 			continue;
5405 		}
5406 		if ((curr->ire_stq != NULL && ire->ire_stq == NULL) ||
5407 		    (curr->ire_stq == NULL && ire->ire_stq != NULL)) {
5408 			/*
5409 			 * If the passed-in ire is loopback, skip over
5410 			 * non-loopback ires and vice versa.
5411 			 */
5412 			continue;
5413 		}
5414 		if (ire_to_ill(curr) != ill) {
5415 			/* skip over IREs going through a different interface */
5416 			continue;
5417 		}
5418 		if (curr->ire_marks & IRE_MARK_CONDEMNED) {
5419 			/* skip over deleted IREs */
5420 			continue;
5421 		}
5422 		return (curr);
5423 	}
5424 	return (NULL);
5425 }
5426 
5427 #ifdef DEBUG
5428 void
5429 ire_trace_ref(ire_t *ire)
5430 {
5431 	mutex_enter(&ire->ire_lock);
5432 	if (ire->ire_trace_disable) {
5433 		mutex_exit(&ire->ire_lock);
5434 		return;
5435 	}
5436 
5437 	if (th_trace_ref(ire, ire->ire_ipst)) {
5438 		mutex_exit(&ire->ire_lock);
5439 	} else {
5440 		ire->ire_trace_disable = B_TRUE;
5441 		mutex_exit(&ire->ire_lock);
5442 		ire_trace_cleanup(ire);
5443 	}
5444 }
5445 
5446 void
5447 ire_untrace_ref(ire_t *ire)
5448 {
5449 	mutex_enter(&ire->ire_lock);
5450 	if (!ire->ire_trace_disable)
5451 		th_trace_unref(ire);
5452 	mutex_exit(&ire->ire_lock);
5453 }
5454 
5455 static void
5456 ire_trace_cleanup(const ire_t *ire)
5457 {
5458 	th_trace_cleanup(ire, ire->ire_trace_disable);
5459 }
5460 #endif /* DEBUG */
5461 
5462 /*
5463  * Generate a message chain with an arp request to resolve the in_ire.
5464  * It is assumed that in_ire itself is currently in the ire cache table,
5465  * so we create a fake_ire filled with enough information about ire_addr etc.
5466  * to retrieve in_ire when the DL_UNITDATA response from the resolver
5467  * comes back. The fake_ire itself is created by calling esballoc with
5468  * the fr_rtnp (free routine) set to ire_freemblk. This routine will be
5469  * invoked when the mblk containing fake_ire is freed.
5470  */
5471 void
5472 ire_arpresolve(ire_t *in_ire, ill_t *dst_ill)
5473 {
5474 	areq_t		*areq;
5475 	ipaddr_t	*addrp;
5476 	mblk_t 		*ire_mp, *areq_mp;
5477 	ire_t 		*ire, *buf;
5478 	size_t		bufsize;
5479 	frtn_t		*frtnp;
5480 	ill_t		*ill;
5481 	ip_stack_t	*ipst = dst_ill->ill_ipst;
5482 
5483 	/*
5484 	 * Construct message chain for the resolver
5485 	 * of the form:
5486 	 *	ARP_REQ_MBLK-->IRE_MBLK
5487 	 *
5488 	 * NOTE : If the response does not
5489 	 * come back, ARP frees the packet. For this reason,
5490 	 * we can't REFHOLD the bucket of save_ire to prevent
5491 	 * deletions. We may not be able to REFRELE the bucket
5492 	 * if the response never comes back. Thus, before
5493 	 * adding the ire, ire_add_v4 will make sure that the
5494 	 * interface route does not get deleted. This is the
5495 	 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
5496 	 * where we can always prevent deletions because of
5497 	 * the synchronous nature of adding IRES i.e
5498 	 * ire_add_then_send is called after creating the IRE.
5499 	 */
5500 
5501 	/*
5502 	 * We use esballoc to allocate the second part(the ire_t size mblk)
5503 	 * of the message chain depicted above. THis mblk will be freed
5504 	 * by arp when there is a  timeout, and otherwise passed to IP
5505 	 * and IP will * free it after processing the ARP response.
5506 	 */
5507 
5508 	bufsize = sizeof (ire_t) + sizeof (frtn_t);
5509 	buf = kmem_alloc(bufsize, KM_NOSLEEP);
5510 	if (buf == NULL) {
5511 		ip1dbg(("ire_arpresolver:alloc buffer failed\n "));
5512 		return;
5513 	}
5514 	frtnp = (frtn_t *)(buf + 1);
5515 	frtnp->free_arg = (caddr_t)buf;
5516 	frtnp->free_func = ire_freemblk;
5517 
5518 	ire_mp = esballoc((unsigned char *)buf, bufsize, BPRI_MED, frtnp);
5519 
5520 	if (ire_mp == NULL) {
5521 		ip1dbg(("ire_arpresolve: esballoc failed\n"));
5522 		kmem_free(buf, bufsize);
5523 		return;
5524 	}
5525 	ASSERT(in_ire->ire_nce != NULL);
5526 	areq_mp = copyb(dst_ill->ill_resolver_mp);
5527 	if (areq_mp == NULL) {
5528 		kmem_free(buf, bufsize);
5529 		return;
5530 	}
5531 
5532 	ire_mp->b_datap->db_type = IRE_ARPRESOLVE_TYPE;
5533 	ire = (ire_t *)buf;
5534 	/*
5535 	 * keep enough info in the fake ire so that we can pull up
5536 	 * the incomplete ire (in_ire) after result comes back from
5537 	 * arp and make it complete.
5538 	 */
5539 	*ire = ire_null;
5540 	ire->ire_u = in_ire->ire_u;
5541 	ire->ire_ipif_seqid = in_ire->ire_ipif_seqid;
5542 	ire->ire_ipif = in_ire->ire_ipif;
5543 	ire->ire_stq = in_ire->ire_stq;
5544 	ill = ire_to_ill(ire);
5545 	ire->ire_stq_ifindex = ill->ill_phyint->phyint_ifindex;
5546 	ire->ire_zoneid = in_ire->ire_zoneid;
5547 	ire->ire_ipst = ipst;
5548 
5549 	/*
5550 	 * ire_freemblk will be called when ire_mp is freed, both for
5551 	 * successful and failed arp resolution. IRE_MARK_UNCACHED will be set
5552 	 * when the arp resolution failed.
5553 	 */
5554 	ire->ire_marks |= IRE_MARK_UNCACHED;
5555 	ire->ire_mp = ire_mp;
5556 	ire_mp->b_wptr = (uchar_t *)&ire[1];
5557 	ire_mp->b_cont = NULL;
5558 	linkb(areq_mp, ire_mp);
5559 
5560 	/*
5561 	 * Fill in the source and dest addrs for the resolver.
5562 	 * NOTE: this depends on memory layouts imposed by
5563 	 * ill_init().
5564 	 */
5565 	areq = (areq_t *)areq_mp->b_rptr;
5566 	addrp = (ipaddr_t *)((char *)areq + areq->areq_sender_addr_offset);
5567 	*addrp = ire->ire_src_addr;
5568 
5569 	addrp = (ipaddr_t *)((char *)areq + areq->areq_target_addr_offset);
5570 	if (ire->ire_gateway_addr != INADDR_ANY) {
5571 		*addrp = ire->ire_gateway_addr;
5572 	} else {
5573 		*addrp = ire->ire_addr;
5574 	}
5575 
5576 	/* Up to the resolver. */
5577 	if (canputnext(dst_ill->ill_rq)) {
5578 		putnext(dst_ill->ill_rq, areq_mp);
5579 	} else {
5580 		freemsg(areq_mp);
5581 	}
5582 }
5583 
5584 /*
5585  * Esballoc free function for AR_ENTRY_QUERY request to clean up any
5586  * unresolved ire_t and/or nce_t structures when ARP resolution fails.
5587  *
5588  * This function can be called by ARP via free routine for ire_mp or
5589  * by IPv4(both host and forwarding path) via ire_delete
5590  * in case ARP resolution fails.
5591  * NOTE: Since IP is MT, ARP can call into IP but not vice versa
5592  * (for IP to talk to ARP, it still has to send AR* messages).
5593  *
5594  * Note that the ARP/IP merge should replace the functioanlity by providing
5595  * direct function calls to clean up unresolved entries in ire/nce lists.
5596  */
5597 void
5598 ire_freemblk(ire_t *ire_mp)
5599 {
5600 	nce_t		*nce = NULL;
5601 	ill_t		*ill;
5602 	ip_stack_t	*ipst;
5603 
5604 	ASSERT(ire_mp != NULL);
5605 
5606 	if ((ire_mp->ire_addr == NULL) && (ire_mp->ire_gateway_addr == NULL)) {
5607 		ip1dbg(("ire_freemblk(0x%p) ire_addr is NULL\n",
5608 		    (void *)ire_mp));
5609 		goto cleanup;
5610 	}
5611 	if ((ire_mp->ire_marks & IRE_MARK_UNCACHED) == 0) {
5612 		goto cleanup; /* everything succeeded. just free and return */
5613 	}
5614 
5615 	/*
5616 	 * the arp information corresponding to this ire_mp was not
5617 	 * transferred to  a ire_cache entry. Need
5618 	 * to clean up incomplete ire's and nce, if necessary.
5619 	 */
5620 	ASSERT(ire_mp->ire_stq != NULL);
5621 	ASSERT(ire_mp->ire_stq_ifindex != 0);
5622 	ASSERT(ire_mp->ire_ipst != NULL);
5623 
5624 	ipst = ire_mp->ire_ipst;
5625 
5626 	/*
5627 	 * Get any nce's corresponding to this ire_mp. We first have to
5628 	 * make sure that the ill is still around.
5629 	 */
5630 	ill = ill_lookup_on_ifindex(ire_mp->ire_stq_ifindex,
5631 	    B_FALSE, NULL, NULL, NULL, NULL, ipst);
5632 	if (ill == NULL || (ire_mp->ire_stq != ill->ill_wq) ||
5633 	    (ill->ill_state_flags & ILL_CONDEMNED)) {
5634 		/*
5635 		 * ill went away. no nce to clean up.
5636 		 * Note that the ill_state_flags could be set to
5637 		 * ILL_CONDEMNED after this point, but if we know
5638 		 * that it is CONDEMNED now, we just bail out quickly.
5639 		 */
5640 		if (ill != NULL)
5641 			ill_refrele(ill);
5642 		goto cleanup;
5643 	}
5644 	nce = ndp_lookup_v4(ill,
5645 	    ((ire_mp->ire_gateway_addr != INADDR_ANY) ?
5646 	    &ire_mp->ire_gateway_addr : &ire_mp->ire_addr),
5647 	    B_FALSE);
5648 	ill_refrele(ill);
5649 
5650 	if ((nce != NULL) && (nce->nce_state != ND_REACHABLE)) {
5651 		/*
5652 		 * some incomplete nce was found.
5653 		 */
5654 		DTRACE_PROBE2(ire__freemblk__arp__resolv__fail,
5655 		    nce_t *, nce, ire_t *, ire_mp);
5656 		/*
5657 		 * Send the icmp_unreachable messages for the queued mblks in
5658 		 * ire->ire_nce->nce_qd_mp, since ARP resolution failed
5659 		 * for this ire
5660 		 */
5661 		arp_resolv_failed(nce);
5662 		/*
5663 		 * Delete the nce and clean up all ire's pointing at this nce
5664 		 * in the cachetable
5665 		 */
5666 		ndp_delete(nce);
5667 	}
5668 	if (nce != NULL)
5669 		NCE_REFRELE(nce); /* release the ref taken by ndp_lookup_v4 */
5670 
5671 cleanup:
5672 	/*
5673 	 * Get rid of the ire buffer
5674 	 * We call kmem_free here(instead of ire_delete()), since
5675 	 * this is the freeb's callback.
5676 	 */
5677 	kmem_free(ire_mp, sizeof (ire_t) + sizeof (frtn_t));
5678 }
5679 
5680 /*
5681  * find, or create if needed, a neighbor cache entry nce_t for IRE_CACHE and
5682  * non-loopback IRE_BROADCAST ire's.
5683  *
5684  * If a neighbor-cache entry has to be created (i.e., one does not already
5685  * exist in the nce list) the nce_res_mp and nce_state of the neighbor cache
5686  * entry are initialized in ndp_add_v4(). These values are picked from
5687  * the src_nce, if one is passed in. Otherwise (if src_nce == NULL) the
5688  * ire->ire_type and the outgoing interface (ire_to_ill(ire)) values
5689  * determine the {nce_state, nce_res_mp} of the nce_t created. All
5690  * IRE_BROADCAST entries have nce_state = ND_REACHABLE, and the nce_res_mp
5691  * is set to the ill_bcast_mp of the outgoing inerface. For unicast ire
5692  * entries,
5693  *   - if the outgoing interface is of type IRE_IF_RESOLVER, a newly created
5694  *     nce_t will have a null nce_res_mp, and will be in the ND_INITIAL state.
5695  *   - if the outgoing interface is a IRE_IF_NORESOLVER interface, no link
5696  *     layer resolution is necessary, so that the nce_t will be in the
5697  *     ND_REACHABLE state and the nce_res_mp will have a copy of the
5698  *     ill_resolver_mp of the outgoing interface.
5699  *
5700  * The link layer information needed for broadcast addresses, and for
5701  * packets sent on IRE_IF_NORESOLVER interfaces is a constant mapping that
5702  * never needs re-verification for the lifetime of the nce_t. These are
5703  * therefore marked NCE_F_PERMANENT, and never allowed to expire via
5704  * NCE_EXPIRED.
5705  *
5706  * IRE_CACHE ire's contain the information for  the nexthop (ire_gateway_addr)
5707  * in the case of indirect routes, and for the dst itself (ire_addr) in the
5708  * case of direct routes, with the nce_res_mp containing a template
5709  * DL_UNITDATA request.
5710  *
5711  * The actual association of the ire_nce to the nce created here is
5712  * typically done in ire_add_v4 for IRE_CACHE entries. Exceptions
5713  * to this rule are SO_DONTROUTE ire's (IRE_MARK_NO_ADD), for which
5714  * the ire_nce assignment is done in ire_add_then_send.
5715  */
5716 int
5717 ire_nce_init(ire_t *ire, nce_t *src_nce)
5718 {
5719 	in_addr_t	addr4;
5720 	int		err;
5721 	nce_t		*nce = NULL;
5722 	ill_t		*ire_ill;
5723 	uint16_t	nce_flags = 0;
5724 	ip_stack_t	*ipst;
5725 
5726 	if (ire->ire_stq == NULL)
5727 		return (0); /* no need to create nce for local/loopback */
5728 
5729 	switch (ire->ire_type) {
5730 	case IRE_CACHE:
5731 		if (ire->ire_gateway_addr != INADDR_ANY)
5732 			addr4 = ire->ire_gateway_addr; /* 'G' route */
5733 		else
5734 			addr4 = ire->ire_addr; /* direct route */
5735 		break;
5736 	case IRE_BROADCAST:
5737 		addr4 = ire->ire_addr;
5738 		nce_flags |= (NCE_F_PERMANENT|NCE_F_BCAST);
5739 		break;
5740 	default:
5741 		return (0);
5742 	}
5743 
5744 	/*
5745 	 * ire_ipif is picked based on RTF_SETSRC, usesrc etc.
5746 	 * rules in ire_forward_src_ipif. We want the dlureq_mp
5747 	 * for the outgoing interface, which we get from the ire_stq.
5748 	 */
5749 	ire_ill = ire_to_ill(ire);
5750 	ipst = ire_ill->ill_ipst;
5751 
5752 	/*
5753 	 * IRE_IF_NORESOLVER entries never need re-verification and
5754 	 * do not expire, so we mark them as NCE_F_PERMANENT.
5755 	 */
5756 	if (ire_ill->ill_net_type == IRE_IF_NORESOLVER)
5757 		nce_flags |= NCE_F_PERMANENT;
5758 
5759 retry_nce:
5760 	err = ndp_lookup_then_add_v4(ire_ill, &addr4, nce_flags,
5761 	    &nce, src_nce);
5762 
5763 	if (err == EEXIST && NCE_EXPIRED(nce, ipst)) {
5764 		/*
5765 		 * We looked up an expired nce.
5766 		 * Go back and try to create one again.
5767 		 */
5768 		ndp_delete(nce);
5769 		NCE_REFRELE(nce);
5770 		nce = NULL;
5771 		goto retry_nce;
5772 	}
5773 
5774 	ip1dbg(("ire 0x%p addr 0x%lx type 0x%x; found nce 0x%p err %d\n",
5775 	    (void *)ire, (ulong_t)addr4, ire->ire_type, (void *)nce, err));
5776 
5777 	switch (err) {
5778 	case 0:
5779 	case EEXIST:
5780 		/*
5781 		 * return a pointer to a newly created or existing nce_t;
5782 		 * note that the ire-nce mapping is many-one, i.e.,
5783 		 * multiple ire's could point to the same nce_t.
5784 		 */
5785 		break;
5786 	default:
5787 		DTRACE_PROBE2(nce__init__fail, ill_t *, ire_ill, int, err);
5788 		return (EINVAL);
5789 	}
5790 	if (ire->ire_type == IRE_BROADCAST) {
5791 		/*
5792 		 * Two bcast ires are created for each interface;
5793 		 * 1. loopback copy (which does not  have an
5794 		 *    ire_stq, and therefore has no ire_nce), and,
5795 		 * 2. the non-loopback copy, which has the nce_res_mp
5796 		 *    initialized to a copy of the ill_bcast_mp, and
5797 		 *    is marked as ND_REACHABLE at this point.
5798 		 *    This nce does not undergo any further state changes,
5799 		 *    and exists as long as the interface is plumbed.
5800 		 * Note: we do the ire_nce assignment here for IRE_BROADCAST
5801 		 * because some functions like ill_mark_bcast() inline the
5802 		 * ire_add functionality.
5803 		 */
5804 		ire->ire_nce = nce;
5805 		/*
5806 		 * We are associating this nce to the ire,
5807 		 * so change the nce ref taken in
5808 		 * ndp_lookup_then_add_v4() from
5809 		 * NCE_REFHOLD to NCE_REFHOLD_NOTR
5810 		 */
5811 		NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
5812 	} else {
5813 		/*
5814 		 * We are not using this nce_t just yet so release
5815 		 * the ref taken in ndp_lookup_then_add_v4()
5816 		 */
5817 		NCE_REFRELE(nce);
5818 	}
5819 	return (0);
5820 }
5821