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