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