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