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