xref: /titanic_52/usr/src/uts/common/inet/ip/ip_ire.c (revision f841f6ad96ea6675d6c6b35c749eaac601799fdf)
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 	if (is_system_labeled()) {
1857 		if ((type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST |
1858 		    IRE_INTERFACE)) != 0) {
1859 			/* release references on behalf of caller */
1860 			if (gc != NULL)
1861 				GC_REFRELE(gc);
1862 			if (gcgrp != NULL)
1863 				GCGRP_REFRELE(gcgrp);
1864 		} else if (tsol_ire_init_gwattr(ire, ipversion,
1865 		    gc, gcgrp) != 0) {
1866 			/* free any caller-allocated mblks upon failure */
1867 			if (fp_mp != NULL)
1868 				freeb(fp_mp);
1869 			if (dlureq_mp != NULL)
1870 				freeb(dlureq_mp);
1871 			return (B_FALSE);
1872 		}
1873 	}
1874 
1875 	ire->ire_fp_mp = fp_mp;
1876 	ire->ire_dlureq_mp = dlureq_mp;
1877 	ire->ire_stq = stq;
1878 	ire->ire_rfq = rfq;
1879 	ire->ire_type = type;
1880 	ire->ire_flags = RTF_UP | flags;
1881 	ire->ire_ident = TICK_TO_MSEC(lbolt);
1882 	bcopy(ulp_info, &ire->ire_uinfo, sizeof (iulp_t));
1883 
1884 	ire->ire_tire_mark = ire->ire_ob_pkt_count + ire->ire_ib_pkt_count;
1885 	ire->ire_last_used_time = lbolt;
1886 	ire->ire_create_time = (uint32_t)gethrestime_sec();
1887 
1888 	/*
1889 	 * If this IRE is an IRE_CACHE, inherit the handles from the
1890 	 * parent IREs. For others in the forwarding table, assign appropriate
1891 	 * new ones.
1892 	 *
1893 	 * The mutex protecting ire_handle is because ire_create is not always
1894 	 * called as a writer.
1895 	 */
1896 	if (ire->ire_type & IRE_OFFSUBNET) {
1897 		mutex_enter(&ire_handle_lock);
1898 		ire->ire_phandle = (uint32_t)ire_handle++;
1899 		mutex_exit(&ire_handle_lock);
1900 	} else if (ire->ire_type & IRE_INTERFACE) {
1901 		mutex_enter(&ire_handle_lock);
1902 		ire->ire_ihandle = (uint32_t)ire_handle++;
1903 		mutex_exit(&ire_handle_lock);
1904 	} else if (ire->ire_type == IRE_CACHE) {
1905 		ire->ire_phandle = phandle;
1906 		ire->ire_ihandle = ihandle;
1907 	}
1908 	ire->ire_in_ill = in_ill;
1909 	ire->ire_ipif = ipif;
1910 	if (ipif != NULL) {
1911 		ire->ire_ipif_seqid = ipif->ipif_seqid;
1912 		ire->ire_zoneid = ipif->ipif_zoneid;
1913 	} else {
1914 		ire->ire_zoneid = GLOBAL_ZONEID;
1915 	}
1916 	ire->ire_ipversion = ipversion;
1917 	ire->ire_refcnt = 1;
1918 	mutex_init(&ire->ire_lock, NULL, MUTEX_DEFAULT, NULL);
1919 
1920 #ifdef IRE_DEBUG
1921 	bzero(ire->ire_trace, sizeof (th_trace_t *) * IP_TR_HASH_MAX);
1922 #endif
1923 
1924 	return (B_TRUE);
1925 }
1926 
1927 /*
1928  * This routine is called repeatedly by ipif_up to create broadcast IREs.
1929  * It is passed a pointer to a slot in an IRE pointer array into which to
1930  * place the pointer to the new IRE, if indeed we create one.  If the
1931  * IRE corresponding to the address passed in would be a duplicate of an
1932  * existing one, we don't create the new one.  irep is incremented before
1933  * return only if we do create a new IRE.  (Always called as writer.)
1934  *
1935  * Note that with the "match_flags" parameter, we can match on either
1936  * a particular logical interface (MATCH_IRE_IPIF) or for all logical
1937  * interfaces for a given physical interface (MATCH_IRE_ILL).  Currently,
1938  * we only create broadcast ire's on a per physical interface basis. If
1939  * someone is going to be mucking with logical interfaces, it is important
1940  * to call "ipif_check_bcast_ires()" to make sure that any change to a
1941  * logical interface will not cause critical broadcast IRE's to be deleted.
1942  */
1943 ire_t **
1944 ire_check_and_create_bcast(ipif_t *ipif, ipaddr_t  addr, ire_t **irep,
1945     int match_flags)
1946 {
1947 	ire_t *ire;
1948 	uint64_t check_flags = IPIF_DEPRECATED | IPIF_NOLOCAL | IPIF_ANYCAST;
1949 
1950 	/*
1951 	 * No broadcast IREs for the LOOPBACK interface
1952 	 * or others such as point to point and IPIF_NOXMIT.
1953 	 */
1954 	if (!(ipif->ipif_flags & IPIF_BROADCAST) ||
1955 	    (ipif->ipif_flags & IPIF_NOXMIT))
1956 		return (irep);
1957 
1958 	/* If this would be a duplicate, don't bother. */
1959 	if ((ire = ire_ctable_lookup(addr, 0, IRE_BROADCAST, ipif,
1960 	    ipif->ipif_zoneid, NULL, match_flags)) != NULL) {
1961 		/*
1962 		 * We look for non-deprecated (and non-anycast, non-nolocal)
1963 		 * ipifs as the best choice. ipifs with check_flags matching
1964 		 * (deprecated, etc) are used only if non-deprecated ipifs
1965 		 * are not available. if the existing ire's ipif is deprecated
1966 		 * and the new ipif is non-deprecated, switch to the new ipif
1967 		 */
1968 		if ((!(ire->ire_ipif->ipif_flags & check_flags)) ||
1969 		    (ipif->ipif_flags & check_flags)) {
1970 			ire_refrele(ire);
1971 			return (irep);
1972 		}
1973 		/*
1974 		 * Bcast ires exist in pairs. Both have to be deleted,
1975 		 * Since we are exclusive we can make the above assertion.
1976 		 * The 1st has to be refrele'd since it was ctable_lookup'd.
1977 		 */
1978 		ASSERT(IAM_WRITER_IPIF(ipif));
1979 		ASSERT(ire->ire_next->ire_addr == ire->ire_addr);
1980 		ire_delete(ire->ire_next);
1981 		ire_delete(ire);
1982 		ire_refrele(ire);
1983 	}
1984 
1985 	irep = ire_create_bcast(ipif, addr, irep);
1986 
1987 	return (irep);
1988 }
1989 
1990 uint_t ip_loopback_mtu = IP_LOOPBACK_MTU;
1991 
1992 /*
1993  * This routine is called from ipif_check_bcast_ires and ire_check_bcast.
1994  * It leaves all the verifying and deleting to those routines. So it always
1995  * creates 2 bcast ires and chains them into the ire array passed in.
1996  */
1997 ire_t **
1998 ire_create_bcast(ipif_t *ipif, ipaddr_t  addr, ire_t **irep)
1999 {
2000 	*irep++ = ire_create(
2001 	    (uchar_t *)&addr,			/* dest addr */
2002 	    (uchar_t *)&ip_g_all_ones,		/* mask */
2003 	    (uchar_t *)&ipif->ipif_src_addr,	/* source addr */
2004 	    NULL,				/* no gateway */
2005 	    NULL,				/* no in_src_addr */
2006 	    &ipif->ipif_mtu,			/* max frag */
2007 	    NULL,				/* fast path header */
2008 	    ipif->ipif_rq,			/* recv-from queue */
2009 	    ipif->ipif_wq,			/* send-to queue */
2010 	    IRE_BROADCAST,
2011 	    ipif->ipif_bcast_mp,		/* xmit header */
2012 	    ipif,
2013 	    NULL,
2014 	    0,
2015 	    0,
2016 	    0,
2017 	    0,
2018 	    &ire_uinfo_null,
2019 	    NULL,
2020 	    NULL);
2021 
2022 	*irep++ = ire_create(
2023 		(uchar_t *)&addr,		 /* dest address */
2024 		(uchar_t *)&ip_g_all_ones,	 /* mask */
2025 		(uchar_t *)&ipif->ipif_src_addr, /* source address */
2026 		NULL,				 /* no gateway */
2027 		NULL,				 /* no in_src_addr */
2028 		&ip_loopback_mtu,		 /* max frag size */
2029 		NULL,				 /* Fast Path header */
2030 		ipif->ipif_rq,			 /* recv-from queue */
2031 		NULL,				 /* no send-to queue */
2032 		IRE_BROADCAST,		/* Needed for fanout in wput */
2033 		NULL,
2034 		ipif,
2035 		NULL,
2036 		0,
2037 		0,
2038 		0,
2039 		0,
2040 		&ire_uinfo_null,
2041 		NULL,
2042 		NULL);
2043 
2044 	return (irep);
2045 }
2046 
2047 /*
2048  * ire_walk routine to delete or update any IRE_CACHE that might contain
2049  * stale information.
2050  * The flags state which entries to delete or update.
2051  * Garbage collection is done separately using kmem alloc callbacks to
2052  * ip_trash_ire_reclaim.
2053  * Used for both IPv4 and IPv6. However, IPv6 only uses FLUSH_MTU_TIME
2054  * since other stale information is cleaned up using NUD.
2055  */
2056 void
2057 ire_expire(ire_t *ire, char *arg)
2058 {
2059 	int flush_flags = (int)(uintptr_t)arg;
2060 	ill_t	*stq_ill;
2061 
2062 	if ((flush_flags & FLUSH_REDIRECT_TIME) &&
2063 	    ire->ire_type == IRE_HOST_REDIRECT) {
2064 		/* Make sure we delete the corresponding IRE_CACHE */
2065 		ip1dbg(("ire_expire: all redirects\n"));
2066 		ip_rts_rtmsg(RTM_DELETE, ire, 0);
2067 		ire_delete(ire);
2068 		return;
2069 	}
2070 	if (ire->ire_type != IRE_CACHE)
2071 		return;
2072 
2073 	if (flush_flags & FLUSH_ARP_TIME) {
2074 		/*
2075 		 * Remove all IRE_CACHE.
2076 		 * Verify that create time is more than
2077 		 * ip_ire_arp_interval milliseconds ago.
2078 		 */
2079 		if (((uint32_t)gethrestime_sec() - ire->ire_create_time) *
2080 		    MILLISEC > ip_ire_arp_interval) {
2081 			ip1dbg(("ire_expire: all IRE_CACHE\n"));
2082 			ire_delete(ire);
2083 			return;
2084 		}
2085 	}
2086 
2087 	if (ip_path_mtu_discovery && (flush_flags & FLUSH_MTU_TIME) &&
2088 	    (ire->ire_ipif != NULL)) {
2089 		/* Increase pmtu if it is less than the interface mtu */
2090 		mutex_enter(&ire->ire_lock);
2091 		/*
2092 		 * If the ipif is a vni (whose mtu is 0, since it's virtual)
2093 		 * get the mtu from the sending interfaces' ipif
2094 		 */
2095 		if (IS_VNI(ire->ire_ipif->ipif_ill)) {
2096 			stq_ill = ire->ire_stq->q_ptr;
2097 			ire->ire_max_frag = MIN(stq_ill->ill_ipif->ipif_mtu,
2098 			    IP_MAXPACKET);
2099 		} else {
2100 			ire->ire_max_frag = MIN(ire->ire_ipif->ipif_mtu,
2101 			    IP_MAXPACKET);
2102 		}
2103 		ire->ire_frag_flag |= IPH_DF;
2104 		mutex_exit(&ire->ire_lock);
2105 	}
2106 }
2107 
2108 /*
2109  * Do fast path probing if necessary.
2110  */
2111 static void
2112 ire_fastpath(ire_t *ire)
2113 {
2114 	ill_t	*ill;
2115 	int res;
2116 
2117 	if (ire->ire_fp_mp != NULL || ire->ire_dlureq_mp == NULL ||
2118 	    (ire->ire_stq == NULL)) {
2119 		/*
2120 		 * Already contains fastpath info or
2121 		 * doesn't have DL_UNITDATA_REQ header
2122 		 * or is a loopback broadcast ire i.e. no stq.
2123 		 */
2124 		return;
2125 	}
2126 	ill = ire_to_ill(ire);
2127 	if (ill == NULL)
2128 		return;
2129 	ire_fastpath_list_add(ill, ire);
2130 	res = ill_fastpath_probe(ill, ire->ire_dlureq_mp);
2131 	/*
2132 	 * EAGAIN is an indication of a transient error
2133 	 * i.e. allocation failure etc. leave the ire in the list it will
2134 	 * be updated when another probe happens for another ire if not
2135 	 * it will be taken out of the list when the ire is deleted.
2136 	 */
2137 	if (res != 0 && res != EAGAIN)
2138 		ire_fastpath_list_delete(ill, ire);
2139 }
2140 
2141 /*
2142  * Update all IRE's that are not in fastpath mode and
2143  * have an dlureq_mp that matches mp. mp->b_cont contains
2144  * the fastpath header.
2145  *
2146  * Returns TRUE if entry should be dequeued, or FALSE otherwise.
2147  */
2148 boolean_t
2149 ire_fastpath_update(ire_t *ire, void *arg)
2150 {
2151 	mblk_t 	*mp, *fp_mp;
2152 	uchar_t 	*up, *up2;
2153 	ptrdiff_t	cmplen;
2154 
2155 	ASSERT((ire->ire_type & (IRE_CACHE | IRE_BROADCAST |
2156 	    IRE_MIPRTUN)) != 0);
2157 
2158 	/*
2159 	 * Already contains fastpath info or doesn't have
2160 	 * DL_UNITDATA_REQ header.
2161 	 */
2162 	if (ire->ire_fp_mp != NULL || ire->ire_dlureq_mp == NULL)
2163 		return (B_TRUE);
2164 
2165 	ip2dbg(("ire_fastpath_update: trying\n"));
2166 	mp = (mblk_t *)arg;
2167 	up = mp->b_rptr;
2168 	cmplen = mp->b_wptr - up;
2169 	/* Serialize multiple fast path updates */
2170 	mutex_enter(&ire->ire_lock);
2171 	up2 = ire->ire_dlureq_mp->b_rptr;
2172 	ASSERT(cmplen >= 0);
2173 	if (ire->ire_dlureq_mp->b_wptr - up2 != cmplen ||
2174 	    bcmp(up, up2, cmplen) != 0) {
2175 		mutex_exit(&ire->ire_lock);
2176 		/*
2177 		 * Don't take the ire off the fastpath list yet,
2178 		 * since the response may come later.
2179 		 */
2180 		return (B_FALSE);
2181 	}
2182 	/* Matched - install mp as the ire_fp_mp */
2183 	ip1dbg(("ire_fastpath_update: match\n"));
2184 	fp_mp = dupb(mp->b_cont);
2185 	if (fp_mp) {
2186 		/*
2187 		 * We checked ire_fp_mp above. Check it again with the
2188 		 * lock. Update fp_mp only if it has not been done
2189 		 * already.
2190 		 */
2191 		if (ire->ire_fp_mp == NULL) {
2192 			/*
2193 			 * ire_ll_hdr_length is just an optimization to
2194 			 * store the length. It is used to return the
2195 			 * fast path header length to the upper layers.
2196 			 */
2197 			ire->ire_fp_mp = fp_mp;
2198 			ire->ire_ll_hdr_length =
2199 			    (uint_t)(fp_mp->b_wptr - fp_mp->b_rptr);
2200 		} else {
2201 			freeb(fp_mp);
2202 		}
2203 	}
2204 	mutex_exit(&ire->ire_lock);
2205 	return (B_TRUE);
2206 }
2207 
2208 /*
2209  * This function handles the DL_NOTE_FASTPATH_FLUSH notification from the
2210  * driver.
2211  */
2212 /* ARGSUSED */
2213 void
2214 ire_fastpath_flush(ire_t *ire, void *arg)
2215 {
2216 	ill_t	*ill;
2217 	int	res;
2218 
2219 	/* No fastpath info? */
2220 	if (ire->ire_fp_mp == NULL || ire->ire_dlureq_mp == NULL)
2221 		return;
2222 
2223 	/*
2224 	 * Just remove the IRE if it is for non-broadcast dest.  Then
2225 	 * we will create another one which will have the correct
2226 	 * fastpath info.
2227 	 */
2228 	switch (ire->ire_type) {
2229 	case IRE_CACHE:
2230 		ire_delete(ire);
2231 		break;
2232 	case IRE_MIPRTUN:
2233 	case IRE_BROADCAST:
2234 		/*
2235 		 * We can't delete the ire since it is difficult to
2236 		 * recreate these ire's without going through the
2237 		 * ipif down/up dance. The ire_fp_mp is protected by the
2238 		 * ire_lock in the case of IRE_MIPRTUN and IRE_BROADCAST.
2239 		 * All access to ire_fp_mp in the case of these 2 ire types
2240 		 * is protected by ire_lock.
2241 		 */
2242 		mutex_enter(&ire->ire_lock);
2243 		if (ire->ire_fp_mp != NULL) {
2244 			freeb(ire->ire_fp_mp);
2245 			ire->ire_fp_mp = NULL;
2246 			mutex_exit(&ire->ire_lock);
2247 			/*
2248 			 * No fastpath probe if there is no stq i.e.
2249 			 * i.e. the case of loopback broadcast ire.
2250 			 */
2251 			if (ire->ire_stq == NULL)
2252 				break;
2253 			ill = (ill_t *)((ire->ire_stq)->q_ptr);
2254 			ire_fastpath_list_add(ill, ire);
2255 			res = ill_fastpath_probe(ill, ire->ire_dlureq_mp);
2256 			/*
2257 			 * EAGAIN is an indication of a transient error
2258 			 * i.e. allocation failure etc. leave the ire in the
2259 			 * list it will be updated when another probe happens
2260 			 * for another ire if not it will be taken out of the
2261 			 * list when the ire is deleted.
2262 			 */
2263 			if (res != 0 && res != EAGAIN)
2264 				ire_fastpath_list_delete(ill, ire);
2265 		} else {
2266 			mutex_exit(&ire->ire_lock);
2267 		}
2268 		break;
2269 	default:
2270 		/* This should not happen! */
2271 		ip0dbg(("ire_fastpath_flush: Wrong ire type %s\n",
2272 		    ip_nv_lookup(ire_nv_tbl, (int)ire->ire_type)));
2273 		break;
2274 	}
2275 }
2276 
2277 /*
2278  * Drain the list of ire's waiting for fastpath response.
2279  */
2280 void
2281 ire_fastpath_list_dispatch(ill_t *ill, boolean_t (*func)(ire_t *, void *),
2282     void *arg)
2283 {
2284 	ire_t	 *next_ire;
2285 	ire_t	 *current_ire;
2286 	ire_t	 *first_ire;
2287 	ire_t	 *prev_ire = NULL;
2288 
2289 	ASSERT(ill != NULL);
2290 
2291 	mutex_enter(&ill->ill_lock);
2292 	first_ire = current_ire = (ire_t *)ill->ill_fastpath_list;
2293 	while (current_ire != (ire_t *)&ill->ill_fastpath_list) {
2294 		next_ire = current_ire->ire_fastpath;
2295 		/*
2296 		 * Take it off the list if we're flushing, or if the callback
2297 		 * routine tells us to do so.  Otherwise, leave the ire in the
2298 		 * fastpath list to handle any pending response from the lower
2299 		 * layer.  We can't drain the list when the callback routine
2300 		 * comparison failed, because the response is asynchronous in
2301 		 * nature, and may not arrive in the same order as the list
2302 		 * insertion.
2303 		 */
2304 		if (func == NULL || func(current_ire, arg)) {
2305 			current_ire->ire_fastpath = NULL;
2306 			if (current_ire == first_ire)
2307 				ill->ill_fastpath_list = first_ire = next_ire;
2308 			else
2309 				prev_ire->ire_fastpath = next_ire;
2310 		} else {
2311 			/* previous element that is still in the list */
2312 			prev_ire = current_ire;
2313 		}
2314 		current_ire = next_ire;
2315 	}
2316 	mutex_exit(&ill->ill_lock);
2317 }
2318 
2319 /*
2320  * Add ire to the ire fastpath list.
2321  */
2322 static void
2323 ire_fastpath_list_add(ill_t *ill, ire_t *ire)
2324 {
2325 	ASSERT(ill != NULL);
2326 	ASSERT(ire->ire_stq != NULL);
2327 
2328 	rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
2329 	mutex_enter(&ill->ill_lock);
2330 
2331 	/*
2332 	 * if ire has not been deleted and
2333 	 * is not already in the list add it.
2334 	 */
2335 	if (((ire->ire_marks & IRE_MARK_CONDEMNED) == 0) &&
2336 	    (ire->ire_fastpath == NULL)) {
2337 		ire->ire_fastpath = (ire_t *)ill->ill_fastpath_list;
2338 		ill->ill_fastpath_list = ire;
2339 	}
2340 
2341 	mutex_exit(&ill->ill_lock);
2342 	rw_exit(&ire->ire_bucket->irb_lock);
2343 }
2344 
2345 /*
2346  * remove ire from the ire fastpath list.
2347  */
2348 void
2349 ire_fastpath_list_delete(ill_t *ill, ire_t *ire)
2350 {
2351 	ire_t	*ire_ptr;
2352 
2353 	ASSERT(ire->ire_stq != NULL && ill != NULL);
2354 
2355 	mutex_enter(&ill->ill_lock);
2356 	if (ire->ire_fastpath == NULL)
2357 		goto done;
2358 
2359 	ASSERT(ill->ill_fastpath_list != &ill->ill_fastpath_list);
2360 
2361 	if (ill->ill_fastpath_list == ire) {
2362 		ill->ill_fastpath_list = ire->ire_fastpath;
2363 	} else {
2364 		ire_ptr = ill->ill_fastpath_list;
2365 		while (ire_ptr != (ire_t *)&ill->ill_fastpath_list) {
2366 			if (ire_ptr->ire_fastpath == ire) {
2367 				ire_ptr->ire_fastpath = ire->ire_fastpath;
2368 				break;
2369 			}
2370 			ire_ptr = ire_ptr->ire_fastpath;
2371 		}
2372 	}
2373 	ire->ire_fastpath = NULL;
2374 done:
2375 	mutex_exit(&ill->ill_lock);
2376 }
2377 
2378 
2379 /*
2380  * Find an IRE_INTERFACE for the multicast group.
2381  * Allows different routes for multicast addresses
2382  * in the unicast routing table (akin to 224.0.0.0 but could be more specific)
2383  * which point at different interfaces. This is used when IP_MULTICAST_IF
2384  * isn't specified (when sending) and when IP_ADD_MEMBERSHIP doesn't
2385  * specify the interface to join on.
2386  *
2387  * Supports IP_BOUND_IF by following the ipif/ill when recursing.
2388  */
2389 ire_t *
2390 ire_lookup_multi(ipaddr_t group, zoneid_t zoneid)
2391 {
2392 	ire_t	*ire;
2393 	ipif_t	*ipif = NULL;
2394 	int	match_flags = MATCH_IRE_TYPE;
2395 	ipaddr_t gw_addr;
2396 
2397 	ire = ire_ftable_lookup(group, 0, 0, 0, NULL, NULL, zoneid,
2398 	    0, NULL, MATCH_IRE_DEFAULT);
2399 
2400 	/* We search a resolvable ire in case of multirouting. */
2401 	if ((ire != NULL) && (ire->ire_flags & RTF_MULTIRT)) {
2402 		ire_t *cire = NULL;
2403 		/*
2404 		 * If the route is not resolvable, the looked up ire
2405 		 * may be changed here. In that case, ire_multirt_lookup()
2406 		 * IRE_REFRELE the original ire and change it.
2407 		 */
2408 		(void) ire_multirt_lookup(&cire, &ire, MULTIRT_CACHEGW, NULL);
2409 		if (cire != NULL)
2410 			ire_refrele(cire);
2411 	}
2412 	if (ire == NULL)
2413 		return (NULL);
2414 	/*
2415 	 * Make sure we follow ire_ipif.
2416 	 *
2417 	 * We need to determine the interface route through
2418 	 * which the gateway will be reached. We don't really
2419 	 * care which interface is picked if the interface is
2420 	 * part of a group.
2421 	 */
2422 	if (ire->ire_ipif != NULL) {
2423 		ipif = ire->ire_ipif;
2424 		match_flags |= MATCH_IRE_ILL_GROUP;
2425 	}
2426 
2427 	switch (ire->ire_type) {
2428 	case IRE_DEFAULT:
2429 	case IRE_PREFIX:
2430 	case IRE_HOST:
2431 		gw_addr = ire->ire_gateway_addr;
2432 		ire_refrele(ire);
2433 		ire = ire_ftable_lookup(gw_addr, 0, 0,
2434 		    IRE_INTERFACE, ipif, NULL, zoneid, 0,
2435 		    NULL, match_flags);
2436 		return (ire);
2437 	case IRE_IF_NORESOLVER:
2438 	case IRE_IF_RESOLVER:
2439 		return (ire);
2440 	default:
2441 		ire_refrele(ire);
2442 		return (NULL);
2443 	}
2444 }
2445 
2446 /*
2447  * Return any local address.  We use this to target ourselves
2448  * when the src address was specified as 'default'.
2449  * Preference for IRE_LOCAL entries.
2450  */
2451 ire_t *
2452 ire_lookup_local(zoneid_t zoneid)
2453 {
2454 	ire_t	*ire;
2455 	irb_t	*irb;
2456 	ire_t	*maybe = NULL;
2457 	int i;
2458 
2459 	for (i = 0; i < ip_cache_table_size;  i++) {
2460 		irb = &ip_cache_table[i];
2461 		if (irb->irb_ire == NULL)
2462 			continue;
2463 		rw_enter(&irb->irb_lock, RW_READER);
2464 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
2465 			if ((ire->ire_marks & IRE_MARK_CONDEMNED) ||
2466 			    (ire->ire_zoneid != zoneid &&
2467 			    ire->ire_zoneid != ALL_ZONES))
2468 				continue;
2469 			switch (ire->ire_type) {
2470 			case IRE_LOOPBACK:
2471 				if (maybe == NULL) {
2472 					IRE_REFHOLD(ire);
2473 					maybe = ire;
2474 				}
2475 				break;
2476 			case IRE_LOCAL:
2477 				if (maybe != NULL) {
2478 					ire_refrele(maybe);
2479 				}
2480 				IRE_REFHOLD(ire);
2481 				rw_exit(&irb->irb_lock);
2482 				return (ire);
2483 			}
2484 		}
2485 		rw_exit(&irb->irb_lock);
2486 	}
2487 	return (maybe);
2488 }
2489 
2490 /*
2491  * If the specified IRE is associated with a particular ILL, return
2492  * that ILL pointer (May be called as writer.).
2493  *
2494  * NOTE : This is not a generic function that can be used always.
2495  * This function always returns the ill of the outgoing packets
2496  * if this ire is used.
2497  */
2498 ill_t *
2499 ire_to_ill(const ire_t *ire)
2500 {
2501 	ill_t *ill = NULL;
2502 
2503 	/*
2504 	 * 1) For an IRE_CACHE, ire_ipif is the one where it obtained
2505 	 *    the source address from. ire_stq is the one where the
2506 	 *    packets will be sent out on. We return that here.
2507 	 *
2508 	 * 2) IRE_BROADCAST normally has a loopback and a non-loopback
2509 	 *    copy and they always exist next to each other with loopback
2510 	 *    copy being the first one. If we are called on the non-loopback
2511 	 *    copy, return the one pointed by ire_stq. If it was called on
2512 	 *    a loopback copy, we still return the one pointed by the next
2513 	 *    ire's ire_stq pointer i.e the one pointed by the non-loopback
2514 	 *    copy. We don't want use ire_ipif as it might represent the
2515 	 *    source address (if we borrow source addresses for
2516 	 *    IRE_BROADCASTS in the future).
2517 	 *    However if an interface is currently coming up, the above
2518 	 *    condition may not hold during that period since the ires
2519 	 *    are added one at a time. Thus one of the pair could have been
2520 	 *    added and the other not yet added.
2521 	 * 3) For all others return the ones pointed by ire_ipif->ipif_ill.
2522 	 */
2523 
2524 	if (ire->ire_type == IRE_CACHE) {
2525 		ill = (ill_t *)ire->ire_stq->q_ptr;
2526 	} else if (ire->ire_type == IRE_BROADCAST) {
2527 		if (ire->ire_stq != NULL) {
2528 			ill = (ill_t *)ire->ire_stq->q_ptr;
2529 		} else {
2530 			ire_t  *ire_next;
2531 
2532 			ire_next = ire->ire_next;
2533 			if (ire_next != NULL &&
2534 			    ire_next->ire_type == IRE_BROADCAST &&
2535 			    ire_next->ire_addr == ire->ire_addr &&
2536 			    ire_next->ire_ipif == ire->ire_ipif) {
2537 				ill = (ill_t *)ire_next->ire_stq->q_ptr;
2538 			}
2539 		}
2540 	} else if (ire->ire_ipif != NULL) {
2541 		ill = ire->ire_ipif->ipif_ill;
2542 	}
2543 	return (ill);
2544 }
2545 
2546 /* Arrange to call the specified function for every IRE in the world. */
2547 void
2548 ire_walk(pfv_t func, void *arg)
2549 {
2550 	ire_walk_ipvers(func, arg, 0, ALL_ZONES);
2551 }
2552 
2553 void
2554 ire_walk_v4(pfv_t func, void *arg, zoneid_t zoneid)
2555 {
2556 	ire_walk_ipvers(func, arg, IPV4_VERSION, zoneid);
2557 }
2558 
2559 void
2560 ire_walk_v6(pfv_t func, void *arg, zoneid_t zoneid)
2561 {
2562 	ire_walk_ipvers(func, arg, IPV6_VERSION, zoneid);
2563 }
2564 
2565 /*
2566  * Walk a particular version. version == 0 means both v4 and v6.
2567  */
2568 static void
2569 ire_walk_ipvers(pfv_t func, void *arg, uchar_t vers, zoneid_t zoneid)
2570 {
2571 	if (vers != IPV6_VERSION) {
2572 		ire_walk_ill_tables(0, 0, func, arg, IP_MASK_TABLE_SIZE,
2573 		    ip_ftable_hash_size, ip_forwarding_table,
2574 		    ip_cache_table_size, ip_cache_table, NULL, zoneid);
2575 	}
2576 	if (vers != IPV4_VERSION) {
2577 		ire_walk_ill_tables(0, 0, func, arg, IP6_MASK_TABLE_SIZE,
2578 		    ip6_ftable_hash_size, ip_forwarding_table_v6,
2579 		    ip6_cache_table_size, ip_cache_table_v6, NULL, zoneid);
2580 	}
2581 }
2582 
2583 /*
2584  * Arrange to call the specified
2585  * function for every IRE that matches the ill.
2586  */
2587 void
2588 ire_walk_ill(uint_t match_flags, uint_t ire_type, pfv_t func, void *arg,
2589     ill_t *ill)
2590 {
2591 	ire_walk_ill_ipvers(match_flags, ire_type, func, arg, 0, ill);
2592 }
2593 
2594 void
2595 ire_walk_ill_v4(uint_t match_flags, uint_t ire_type, pfv_t func, void *arg,
2596     ill_t *ill)
2597 {
2598 	ire_walk_ill_ipvers(match_flags, ire_type, func, arg, IPV4_VERSION,
2599 	    ill);
2600 }
2601 
2602 void
2603 ire_walk_ill_v6(uint_t match_flags, uint_t ire_type, pfv_t func, void *arg,
2604     ill_t *ill)
2605 {
2606 	ire_walk_ill_ipvers(match_flags, ire_type, func, arg, IPV6_VERSION,
2607 	    ill);
2608 }
2609 
2610 /*
2611  * Walk a particular ill and version. version == 0 means both v4 and v6.
2612  */
2613 static void
2614 ire_walk_ill_ipvers(uint_t match_flags, uint_t ire_type, pfv_t func,
2615     void *arg, uchar_t vers, ill_t *ill)
2616 {
2617 	if (vers != IPV6_VERSION) {
2618 		ire_walk_ill_tables(match_flags, ire_type, func, arg,
2619 		    IP_MASK_TABLE_SIZE, ip_ftable_hash_size,
2620 		    ip_forwarding_table, ip_cache_table_size,
2621 		    ip_cache_table, ill, ALL_ZONES);
2622 	}
2623 	if (vers != IPV4_VERSION) {
2624 		ire_walk_ill_tables(match_flags, ire_type, func, arg,
2625 		    IP6_MASK_TABLE_SIZE, ip6_ftable_hash_size,
2626 		    ip_forwarding_table_v6, ip6_cache_table_size,
2627 		    ip_cache_table_v6, ill, ALL_ZONES);
2628 	}
2629 }
2630 
2631 static boolean_t
2632 ire_walk_ill_match(uint_t match_flags, uint_t ire_type, ire_t *ire,
2633     ill_t *ill, zoneid_t zoneid)
2634 {
2635 	ill_t *ire_stq_ill = NULL;
2636 	ill_t *ire_ipif_ill = NULL;
2637 	ill_group_t *ire_ill_group = NULL;
2638 
2639 	ASSERT(match_flags != 0 || zoneid != ALL_ZONES);
2640 	/*
2641 	 * 1) MATCH_IRE_WQ : Used specifically to match on ire_stq.
2642 	 *    The fast path update uses this to make sure it does not
2643 	 *    update the fast path header of interface X with the fast
2644 	 *    path updates it recieved on interface Y.  It is similar
2645 	 *    in handling DL_NOTE_FASTPATH_FLUSH.
2646 	 *
2647 	 * 2) MATCH_IRE_ILL/MATCH_IRE_ILL_GROUP : We match both on ill
2648 	 *    pointed by ire_stq and ire_ipif. Only in the case of
2649 	 *    IRE_CACHEs can ire_stq and ire_ipif be pointing to
2650 	 *    different ills. But we want to keep this function generic
2651 	 *    enough for future use. So, we always try to match on both.
2652 	 *    The only caller of this function ire_walk_ill_tables, will
2653 	 *    call "func" after we return from this function. We expect
2654 	 *    "func" to do the right filtering of ires in this case.
2655 	 *
2656 	 * NOTE : In the case of MATCH_IRE_ILL_GROUP, groups
2657 	 * pointed by ire_stq and ire_ipif should always be the same.
2658 	 * So, we just match on only one of them.
2659 	 */
2660 	if (match_flags & (MATCH_IRE_ILL|MATCH_IRE_ILL_GROUP)) {
2661 		if (ire->ire_stq != NULL)
2662 			ire_stq_ill = (ill_t *)ire->ire_stq->q_ptr;
2663 		if (ire->ire_ipif != NULL)
2664 			ire_ipif_ill = ire->ire_ipif->ipif_ill;
2665 		if (ire_stq_ill != NULL)
2666 			ire_ill_group = ire_stq_ill->ill_group;
2667 		if ((ire_ill_group == NULL) && (ire_ipif_ill != NULL))
2668 			ire_ill_group = ire_ipif_ill->ill_group;
2669 	}
2670 
2671 	if (zoneid != ALL_ZONES) {
2672 		/*
2673 		 * We're walking the IREs for a specific zone. The only relevant
2674 		 * IREs are:
2675 		 * - all IREs with a matching ire_zoneid
2676 		 * - all IRE_OFFSUBNETs as they're shared across all zones
2677 		 * - IRE_INTERFACE IREs for interfaces with a usable source addr
2678 		 *   with a matching zone
2679 		 * - IRE_DEFAULTs with a gateway reachable from the zone
2680 		 * We should really match on IRE_OFFSUBNETs and IRE_DEFAULTs
2681 		 * using the same rule; but the above rules are consistent with
2682 		 * the behavior of ire_ftable_lookup[_v6]() so that all the
2683 		 * routes that can be matched during lookup are also matched
2684 		 * here.
2685 		 */
2686 		if (zoneid != ire->ire_zoneid && ire->ire_zoneid != ALL_ZONES) {
2687 			/*
2688 			 * Note, IRE_INTERFACE can have the stq as NULL. For
2689 			 * example, if the default multicast route is tied to
2690 			 * the loopback address.
2691 			 */
2692 			if ((ire->ire_type & IRE_INTERFACE) &&
2693 			    (ire->ire_stq != NULL)) {
2694 				ire_stq_ill = (ill_t *)ire->ire_stq->q_ptr;
2695 				if (ire->ire_ipversion == IPV4_VERSION) {
2696 					if (!ipif_usesrc_avail(ire_stq_ill,
2697 					    zoneid))
2698 						/* No usable src addr in zone */
2699 						return (B_FALSE);
2700 				} else if (ire_stq_ill->ill_usesrc_ifindex
2701 				    != 0) {
2702 					/*
2703 					 * For IPv6 use ipif_select_source_v6()
2704 					 * so the right scope selection is done
2705 					 */
2706 					ipif_t *src_ipif;
2707 					src_ipif =
2708 					    ipif_select_source_v6(ire_stq_ill,
2709 					    &ire->ire_addr_v6, RESTRICT_TO_NONE,
2710 					    IPV6_PREFER_SRC_DEFAULT,
2711 					    zoneid);
2712 					if (src_ipif != NULL) {
2713 						ipif_refrele(src_ipif);
2714 					} else {
2715 						return (B_FALSE);
2716 					}
2717 				} else {
2718 					return (B_FALSE);
2719 				}
2720 
2721 			} else if (!(ire->ire_type & IRE_OFFSUBNET)) {
2722 				return (B_FALSE);
2723 			}
2724 		}
2725 
2726 		/*
2727 		 * Match all default routes from the global zone, irrespective
2728 		 * of reachability.
2729 		 */
2730 		if (ire->ire_type == IRE_DEFAULT && zoneid != GLOBAL_ZONEID) {
2731 			int ire_match_flags = 0;
2732 			in6_addr_t gw_addr_v6;
2733 			ire_t *rire;
2734 
2735 			if (ire->ire_ipif != NULL) {
2736 				ire_match_flags |= MATCH_IRE_ILL_GROUP;
2737 			}
2738 			if (ire->ire_ipversion == IPV4_VERSION) {
2739 				rire = ire_route_lookup(ire->ire_gateway_addr,
2740 				    0, 0, 0, ire->ire_ipif, NULL, zoneid, NULL,
2741 				    ire_match_flags);
2742 			} else {
2743 				ASSERT(ire->ire_ipversion == IPV6_VERSION);
2744 				mutex_enter(&ire->ire_lock);
2745 				gw_addr_v6 = ire->ire_gateway_addr_v6;
2746 				mutex_exit(&ire->ire_lock);
2747 				rire = ire_route_lookup_v6(&gw_addr_v6,
2748 				    NULL, NULL, 0, ire->ire_ipif, NULL, zoneid,
2749 				    NULL, ire_match_flags);
2750 			}
2751 			if (rire == NULL) {
2752 				return (B_FALSE);
2753 			}
2754 			ire_refrele(rire);
2755 		}
2756 	}
2757 
2758 	if (((!(match_flags & MATCH_IRE_TYPE)) ||
2759 		(ire->ire_type & ire_type)) &&
2760 	    ((!(match_flags & MATCH_IRE_WQ)) ||
2761 		(ire->ire_stq == ill->ill_wq)) &&
2762 	    ((!(match_flags & MATCH_IRE_ILL)) ||
2763 		(ire_stq_ill == ill || ire_ipif_ill == ill)) &&
2764 	    ((!(match_flags & MATCH_IRE_ILL_GROUP)) ||
2765 		(ire_stq_ill == ill) || (ire_ipif_ill == ill) ||
2766 		(ire_ill_group != NULL &&
2767 		ire_ill_group == ill->ill_group))) {
2768 		return (B_TRUE);
2769 	}
2770 	return (B_FALSE);
2771 }
2772 
2773 /*
2774  * Walk the ftable and the ctable entries that match the ill.
2775  */
2776 static void
2777 ire_walk_ill_tables(uint_t match_flags, uint_t ire_type, pfv_t func,
2778     void *arg, size_t ftbl_sz, size_t htbl_sz, irb_t **ipftbl,
2779     size_t ctbl_sz, irb_t *ipctbl, ill_t *ill, zoneid_t zoneid)
2780 {
2781 	irb_t	*irb_ptr;
2782 	irb_t	*irb;
2783 	ire_t	*ire;
2784 	int i, j;
2785 	boolean_t ret;
2786 
2787 	ASSERT((!(match_flags & (MATCH_IRE_WQ | MATCH_IRE_ILL |
2788 	    MATCH_IRE_ILL_GROUP))) || (ill != NULL));
2789 	ASSERT(!(match_flags & MATCH_IRE_TYPE) || (ire_type != 0));
2790 	/*
2791 	 * Optimize by not looking at the forwarding table if there
2792 	 * is a MATCH_IRE_TYPE specified with no IRE_FORWARDTABLE
2793 	 * specified in ire_type.
2794 	 */
2795 	if (!(match_flags & MATCH_IRE_TYPE) ||
2796 	    ((ire_type & IRE_FORWARDTABLE) != 0)) {
2797 		for (i = (ftbl_sz - 1);  i >= 0; i--) {
2798 			if ((irb_ptr = ipftbl[i]) == NULL)
2799 				continue;
2800 			for (j = 0; j < htbl_sz; j++) {
2801 				irb = &irb_ptr[j];
2802 				if (irb->irb_ire == NULL)
2803 					continue;
2804 				IRB_REFHOLD(irb);
2805 				for (ire = irb->irb_ire; ire != NULL;
2806 				    ire = ire->ire_next) {
2807 					if (match_flags == 0 &&
2808 					    zoneid == ALL_ZONES) {
2809 						ret = B_TRUE;
2810 					} else {
2811 						ret = ire_walk_ill_match(
2812 						    match_flags, ire_type,
2813 						    ire, ill, zoneid);
2814 					}
2815 					if (ret)
2816 						(*func)(ire, arg);
2817 				}
2818 				IRB_REFRELE(irb);
2819 			}
2820 		}
2821 	}
2822 
2823 	/*
2824 	 * Optimize by not looking at the cache table if there
2825 	 * is a MATCH_IRE_TYPE specified with no IRE_CACHETABLE
2826 	 * specified in ire_type.
2827 	 */
2828 	if (!(match_flags & MATCH_IRE_TYPE) ||
2829 	    ((ire_type & IRE_CACHETABLE) != 0)) {
2830 		for (i = 0; i < ctbl_sz;  i++) {
2831 			irb = &ipctbl[i];
2832 			if (irb->irb_ire == NULL)
2833 				continue;
2834 			IRB_REFHOLD(irb);
2835 			for (ire = irb->irb_ire; ire != NULL;
2836 			    ire = ire->ire_next) {
2837 				if (match_flags == 0 && zoneid == ALL_ZONES) {
2838 					ret = B_TRUE;
2839 				} else {
2840 					ret = ire_walk_ill_match(
2841 					    match_flags, ire_type,
2842 					    ire, ill, zoneid);
2843 				}
2844 				if (ret)
2845 					(*func)(ire, arg);
2846 			}
2847 			IRB_REFRELE(irb);
2848 		}
2849 	}
2850 }
2851 
2852 /*
2853  * This routine walks through the ill chain to find if there is any
2854  * ire linked to the ill's interface based forwarding table
2855  * The arg could be ill or mp. This routine is called when a ill goes
2856  * down/deleted or the 'ipv4_ire_srcif_status' report is printed.
2857  */
2858 void
2859 ire_walk_srcif_table_v4(pfv_t func, void *arg)
2860 {
2861 	irb_t   *irb;
2862 	ire_t   *ire;
2863 	ill_t	*ill, *next_ill;
2864 	int	i;
2865 	int	total_count;
2866 	ill_walk_context_t ctx;
2867 
2868 	/*
2869 	 * Take care of ire's in other ill's per-interface forwarding
2870 	 * table. Check if any ire in any of the ill's ill_srcif_table
2871 	 * is pointing to this ill.
2872 	 */
2873 	mutex_enter(&ire_srcif_table_lock);
2874 	if (ire_srcif_table_count == 0) {
2875 		mutex_exit(&ire_srcif_table_lock);
2876 		return;
2877 	}
2878 	mutex_exit(&ire_srcif_table_lock);
2879 
2880 #ifdef DEBUG
2881 	/* Keep accounting of all interface based table ires */
2882 	total_count = 0;
2883 	rw_enter(&ill_g_lock, RW_READER);
2884 	ill = ILL_START_WALK_V4(&ctx);
2885 	while (ill != NULL) {
2886 		mutex_enter(&ill->ill_lock);
2887 		total_count += ill->ill_srcif_refcnt;
2888 		next_ill = ill_next(&ctx, ill);
2889 		mutex_exit(&ill->ill_lock);
2890 		ill = next_ill;
2891 	}
2892 	rw_exit(&ill_g_lock);
2893 
2894 	/* Hold lock here to make sure ire_srcif_table_count is stable */
2895 	mutex_enter(&ire_srcif_table_lock);
2896 	i = ire_srcif_table_count;
2897 	mutex_exit(&ire_srcif_table_lock);
2898 	ip1dbg(("ire_walk_srcif_v4: ire_srcif_table_count %d "
2899 	    "total ill_srcif_refcnt %d\n", i, total_count));
2900 #endif
2901 	rw_enter(&ill_g_lock, RW_READER);
2902 	ill = ILL_START_WALK_V4(&ctx);
2903 	while (ill != NULL) {
2904 		mutex_enter(&ill->ill_lock);
2905 		if ((ill->ill_srcif_refcnt == 0) || !ILL_CAN_LOOKUP(ill)) {
2906 			next_ill = ill_next(&ctx, ill);
2907 			mutex_exit(&ill->ill_lock);
2908 			ill = next_ill;
2909 			continue;
2910 		}
2911 		ill_refhold_locked(ill);
2912 		mutex_exit(&ill->ill_lock);
2913 		rw_exit(&ill_g_lock);
2914 		if (ill->ill_srcif_table != NULL) {
2915 			for (i = 0; i < IP_SRCIF_TABLE_SIZE; i++) {
2916 				irb = &(ill->ill_srcif_table[i]);
2917 				if (irb->irb_ire == NULL)
2918 					continue;
2919 				IRB_REFHOLD(irb);
2920 				for (ire = irb->irb_ire; ire != NULL;
2921 				    ire = ire->ire_next) {
2922 					(*func)(ire, arg);
2923 				}
2924 				IRB_REFRELE(irb);
2925 			}
2926 		}
2927 		rw_enter(&ill_g_lock, RW_READER);
2928 		next_ill = ill_next(&ctx, ill);
2929 		ill_refrele(ill);
2930 		ill = next_ill;
2931 	}
2932 	rw_exit(&ill_g_lock);
2933 }
2934 
2935 /*
2936  * This function takes a mask and returns
2937  * number of bits set in the mask. If no
2938  * bit is set it returns 0.
2939  * Assumes a contiguous mask.
2940  */
2941 int
2942 ip_mask_to_plen(ipaddr_t mask)
2943 {
2944 	return (mask == 0 ? 0 : IP_ABITS - (ffs(ntohl(mask)) -1));
2945 }
2946 
2947 /*
2948  * Convert length for a mask to the mask.
2949  */
2950 ipaddr_t
2951 ip_plen_to_mask(uint_t masklen)
2952 {
2953 	return (htonl(IP_HOST_MASK << (IP_ABITS - masklen)));
2954 }
2955 
2956 void
2957 ire_atomic_end(irb_t *irb_ptr, ire_t *ire)
2958 {
2959 	ill_t	*ill_list[NUM_ILLS];
2960 
2961 	ill_list[0] = ire->ire_stq != NULL ? ire->ire_stq->q_ptr : NULL;
2962 	ill_list[1] = ire->ire_ipif != NULL ? ire->ire_ipif->ipif_ill : NULL;
2963 	ill_list[2] = ire->ire_in_ill;
2964 	ill_unlock_ills(ill_list, NUM_ILLS);
2965 	rw_exit(&irb_ptr->irb_lock);
2966 	rw_exit(&ill_g_usesrc_lock);
2967 }
2968 
2969 /*
2970  * ire_add_v[46] atomically make sure that the ipif or ill associated
2971  * with the new ire being added is stable and not IPIF_CHANGING or ILL_CHANGING
2972  * before adding the ire to the table. This ensures that we don't create
2973  * new IRE_CACHEs with stale values for parameters that are passed to
2974  * ire_create such as ire_max_frag. Note that ire_create() is passed a pointer
2975  * to the ipif_mtu, and not the value. The actual value is derived from the
2976  * parent ire or ipif under the bucket lock.
2977  */
2978 int
2979 ire_atomic_start(irb_t *irb_ptr, ire_t *ire, queue_t *q, mblk_t *mp,
2980     ipsq_func_t func)
2981 {
2982 	ill_t	*stq_ill;
2983 	ill_t	*ipif_ill;
2984 	ill_t	*in_ill;
2985 	ill_t	*ill_list[NUM_ILLS];
2986 	int	cnt = NUM_ILLS;
2987 	int	error = 0;
2988 	ill_t	*ill = NULL;
2989 
2990 	ill_list[0] = stq_ill = ire->ire_stq !=
2991 		NULL ? ire->ire_stq->q_ptr : NULL;
2992 	ill_list[1] = ipif_ill = ire->ire_ipif !=
2993 		NULL ? ire->ire_ipif->ipif_ill : NULL;
2994 	ill_list[2] = in_ill = ire->ire_in_ill;
2995 
2996 	ASSERT((q != NULL && mp != NULL && func != NULL) ||
2997 	    (q == NULL && mp == NULL && func == NULL));
2998 	rw_enter(&ill_g_usesrc_lock, RW_READER);
2999 	GRAB_CONN_LOCK(q);
3000 	rw_enter(&irb_ptr->irb_lock, RW_WRITER);
3001 	ill_lock_ills(ill_list, cnt);
3002 
3003 	/*
3004 	 * While the IRE is in the process of being added, a user may have
3005 	 * invoked the ifconfig usesrc option on the stq_ill to make it a
3006 	 * usesrc client ILL. Check for this possibility here, if it is true
3007 	 * then we fail adding the IRE_CACHE. Another check is to make sure
3008 	 * that an ipif_ill of an IRE_CACHE being added is not part of a usesrc
3009 	 * group. The ill_g_usesrc_lock is released in ire_atomic_end
3010 	 */
3011 	if ((ire->ire_type & IRE_CACHE) &&
3012 	    (ire->ire_marks & IRE_MARK_USESRC_CHECK)) {
3013 		if (stq_ill->ill_usesrc_ifindex != 0) {
3014 			ASSERT(stq_ill->ill_usesrc_grp_next != NULL);
3015 			if ((ipif_ill->ill_phyint->phyint_ifindex !=
3016 			    stq_ill->ill_usesrc_ifindex) ||
3017 			    (ipif_ill->ill_usesrc_grp_next == NULL) ||
3018 			    (ipif_ill->ill_usesrc_ifindex != 0)) {
3019 				error = EINVAL;
3020 				goto done;
3021 			}
3022 		} else if (ipif_ill->ill_usesrc_grp_next != NULL) {
3023 			error = EINVAL;
3024 			goto done;
3025 		}
3026 	}
3027 
3028 	/*
3029 	 * IPMP flag settings happen without taking the exclusive route
3030 	 * in ip_sioctl_flags. So we need to make an atomic check here
3031 	 * for FAILED/OFFLINE/INACTIVE flags or if it has hit the
3032 	 * FAILBACK=no case.
3033 	 */
3034 	if ((stq_ill != NULL) && !IAM_WRITER_ILL(stq_ill)) {
3035 		if (stq_ill->ill_state_flags & ILL_CHANGING) {
3036 			ill = stq_ill;
3037 			error = EAGAIN;
3038 		} else if ((stq_ill->ill_phyint->phyint_flags & PHYI_OFFLINE) ||
3039 		    (ill_is_probeonly(stq_ill) &&
3040 		    !(ire->ire_marks & IRE_MARK_HIDDEN))) {
3041 			error = EINVAL;
3042 		}
3043 		goto done;
3044 	}
3045 
3046 	/*
3047 	 * We don't check for OFFLINE/FAILED in this case because
3048 	 * the source address selection logic (ipif_select_source)
3049 	 * may still select a source address from such an ill. The
3050 	 * assumption is that these addresses will be moved by in.mpathd
3051 	 * soon. (i.e. this is a race). However link local addresses
3052 	 * will not move and hence ipif_select_source_v6 tries to avoid
3053 	 * FAILED ills. Please see ipif_select_source_v6 for more info
3054 	 */
3055 	if ((ipif_ill != NULL) && !IAM_WRITER_ILL(ipif_ill) &&
3056 	    (ipif_ill->ill_state_flags & ILL_CHANGING)) {
3057 		ill = ipif_ill;
3058 		error = EAGAIN;
3059 		goto done;
3060 	}
3061 
3062 	if ((in_ill != NULL) && !IAM_WRITER_ILL(in_ill) &&
3063 	    (in_ill->ill_state_flags & ILL_CHANGING)) {
3064 		ill = in_ill;
3065 		error = EAGAIN;
3066 		goto done;
3067 	}
3068 
3069 	if ((ire->ire_ipif != NULL) && !IAM_WRITER_IPIF(ire->ire_ipif) &&
3070 	    (ire->ire_ipif->ipif_state_flags & IPIF_CHANGING)) {
3071 		ill = ire->ire_ipif->ipif_ill;
3072 		ASSERT(ill != NULL);
3073 		error = EAGAIN;
3074 		goto done;
3075 	}
3076 
3077 done:
3078 	if (error == EAGAIN && ILL_CAN_WAIT(ill, q)) {
3079 		ipsq_t *ipsq = ill->ill_phyint->phyint_ipsq;
3080 		mutex_enter(&ipsq->ipsq_lock);
3081 		ire_atomic_end(irb_ptr, ire);
3082 		ipsq_enq(ipsq, q, mp, func, NEW_OP, ill);
3083 		mutex_exit(&ipsq->ipsq_lock);
3084 		error = EINPROGRESS;
3085 	} else if (error != 0) {
3086 		ire_atomic_end(irb_ptr, ire);
3087 	}
3088 
3089 	RELEASE_CONN_LOCK(q);
3090 	return (error);
3091 }
3092 
3093 /*
3094  * Add a fully initialized IRE to an appropriate table based on
3095  * ire_type.
3096  */
3097 int
3098 ire_add(ire_t **irep, queue_t *q, mblk_t *mp, ipsq_func_t func)
3099 {
3100 	ire_t	*ire1;
3101 	ill_t	*stq_ill = NULL;
3102 	ill_t	*ill;
3103 	ipif_t	*ipif = NULL;
3104 	ill_walk_context_t ctx;
3105 	ire_t	*ire = *irep;
3106 	int	error;
3107 
3108 	ASSERT(ire->ire_type != IRE_MIPRTUN);
3109 
3110 	/* get ready for the day when original ire is not created as mblk */
3111 	if (ire->ire_mp != NULL) {
3112 		/* Copy the ire to a kmem_alloc'ed area */
3113 		ire1 = kmem_cache_alloc(ire_cache, KM_NOSLEEP);
3114 		if (ire1 == NULL) {
3115 			ip1dbg(("ire_add: alloc failed\n"));
3116 			ire_delete(ire);
3117 			*irep = NULL;
3118 			return (ENOMEM);
3119 		}
3120 		*ire1 = *ire;
3121 		ire1->ire_mp = NULL;
3122 		freeb(ire->ire_mp);
3123 		ire = ire1;
3124 	}
3125 	if (ire->ire_stq != NULL)
3126 		stq_ill = (ill_t *)ire->ire_stq->q_ptr;
3127 
3128 	if (ire->ire_type == IRE_CACHE) {
3129 		/*
3130 		 * If this interface is FAILED, or INACTIVE or has hit
3131 		 * the FAILBACK=no case, we create IRE_CACHES marked
3132 		 * HIDDEN for some special cases e.g. bind to
3133 		 * IPIF_NOFAILOVER address etc. So, if this interface
3134 		 * is FAILED/INACTIVE/hit FAILBACK=no case, and we are
3135 		 * not creating hidden ires, we should not allow that.
3136 		 * This happens because the state of the interface
3137 		 * changed while we were waiting in ARP. If this is the
3138 		 * daemon sending probes, the next probe will create
3139 		 * HIDDEN ires and we will create an ire then. This
3140 		 * cannot happen with NDP currently because IRE is
3141 		 * never queued in NDP. But it can happen in the
3142 		 * future when we have external resolvers with IPv6.
3143 		 * If the interface gets marked with OFFLINE while we
3144 		 * are waiting in ARP, don't add the ire.
3145 		 */
3146 		if ((stq_ill->ill_phyint->phyint_flags & PHYI_OFFLINE) ||
3147 		    (ill_is_probeonly(stq_ill) &&
3148 		    !(ire->ire_marks & IRE_MARK_HIDDEN))) {
3149 			/*
3150 			 * We don't know whether it is a valid ipif or not.
3151 			 * unless we do the check below. So, set it to NULL.
3152 			 */
3153 			ire->ire_ipif = NULL;
3154 			ire_delete(ire);
3155 			*irep = NULL;
3156 			return (EINVAL);
3157 		}
3158 	}
3159 
3160 	if (stq_ill != NULL && ire->ire_type == IRE_CACHE &&
3161 	    stq_ill->ill_net_type == IRE_IF_RESOLVER) {
3162 		rw_enter(&ill_g_lock, RW_READER);
3163 		ill = ILL_START_WALK_ALL(&ctx);
3164 		for (; ill != NULL; ill = ill_next(&ctx, ill)) {
3165 			mutex_enter(&ill->ill_lock);
3166 			if (ill->ill_state_flags & ILL_CONDEMNED) {
3167 				mutex_exit(&ill->ill_lock);
3168 				continue;
3169 			}
3170 			/*
3171 			 * We need to make sure that the ipif is a valid one
3172 			 * before adding the IRE_CACHE. This happens only
3173 			 * with IRE_CACHE when there is an external resolver.
3174 			 *
3175 			 * We can unplumb a logical interface while the
3176 			 * packet is waiting in ARP with the IRE. Then,
3177 			 * later on when we feed the IRE back, the ipif
3178 			 * has to be re-checked. This can't happen with
3179 			 * NDP currently, as we never queue the IRE with
3180 			 * the packet. We always try to recreate the IRE
3181 			 * when the resolution is completed. But, we do
3182 			 * it for IPv6 also here so that in future if
3183 			 * we have external resolvers, it will work without
3184 			 * any change.
3185 			 */
3186 			ipif = ipif_lookup_seqid(ill, ire->ire_ipif_seqid);
3187 			if (ipif != NULL) {
3188 				ipif_refhold_locked(ipif);
3189 				mutex_exit(&ill->ill_lock);
3190 				break;
3191 			}
3192 			mutex_exit(&ill->ill_lock);
3193 		}
3194 		rw_exit(&ill_g_lock);
3195 		if (ipif == NULL ||
3196 		    (ipif->ipif_isv6 &&
3197 		    !IN6_ARE_ADDR_EQUAL(&ire->ire_src_addr_v6,
3198 		    &ipif->ipif_v6src_addr)) ||
3199 		    (!ipif->ipif_isv6 &&
3200 		    ire->ire_src_addr != ipif->ipif_src_addr) ||
3201 		    ire->ire_zoneid != ipif->ipif_zoneid) {
3202 
3203 			if (ipif != NULL)
3204 				ipif_refrele(ipif);
3205 			ire->ire_ipif = NULL;
3206 			ire_delete(ire);
3207 			*irep = NULL;
3208 			return (EINVAL);
3209 		}
3210 
3211 
3212 		ASSERT(ill != NULL);
3213 		/*
3214 		 * If this group was dismantled while this packets was
3215 		 * queued in ARP, don't add it here.
3216 		 */
3217 		if (ire->ire_ipif->ipif_ill->ill_group != ill->ill_group) {
3218 			/* We don't want ire_inactive bump stats for this */
3219 			ipif_refrele(ipif);
3220 			ire->ire_ipif = NULL;
3221 			ire_delete(ire);
3222 			*irep = NULL;
3223 			return (EINVAL);
3224 		}
3225 	}
3226 
3227 	/*
3228 	 * In case ire was changed
3229 	 */
3230 	*irep = ire;
3231 	if (ire->ire_ipversion == IPV6_VERSION) {
3232 		error = ire_add_v6(irep, q, mp, func);
3233 	} else {
3234 		if (ire->ire_in_ill == NULL)
3235 			error = ire_add_v4(irep, q, mp, func);
3236 		else
3237 			error = ire_add_srcif_v4(irep, q, mp, func);
3238 	}
3239 	if (ipif != NULL)
3240 		ipif_refrele(ipif);
3241 	return (error);
3242 }
3243 
3244 /*
3245  * Add a fully initialized IRE to an appropriate
3246  * table based on ire_type.
3247  *
3248  * The forward table contains IRE_PREFIX/IRE_HOST/IRE_HOST_REDIRECT
3249  * IRE_IF_RESOLVER/IRE_IF_NORESOLVER and IRE_DEFAULT.
3250  *
3251  * The cache table contains IRE_BROADCAST/IRE_LOCAL/IRE_LOOPBACK
3252  * and IRE_CACHE.
3253  *
3254  * NOTE : This function is called as writer though not required
3255  * by this function.
3256  */
3257 static int
3258 ire_add_v4(ire_t **ire_p, queue_t *q, mblk_t *mp, ipsq_func_t func)
3259 {
3260 	ire_t	*ire1;
3261 	int	mask_table_index;
3262 	irb_t	*irb_ptr;
3263 	ire_t	**irep;
3264 	int	flags;
3265 	ire_t	*pire = NULL;
3266 	ill_t	*stq_ill;
3267 	ire_t	*ire = *ire_p;
3268 	int	error;
3269 
3270 	if (ire->ire_ipif != NULL)
3271 		ASSERT(!MUTEX_HELD(&ire->ire_ipif->ipif_ill->ill_lock));
3272 	if (ire->ire_stq != NULL)
3273 		ASSERT(!MUTEX_HELD(
3274 		    &((ill_t *)(ire->ire_stq->q_ptr))->ill_lock));
3275 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
3276 	ASSERT(ire->ire_mp == NULL); /* Calls should go through ire_add */
3277 	ASSERT(ire->ire_in_ill == NULL); /* No srcif entries */
3278 
3279 	/* Find the appropriate list head. */
3280 	switch (ire->ire_type) {
3281 	case IRE_HOST:
3282 		ire->ire_mask = IP_HOST_MASK;
3283 		ire->ire_masklen = IP_ABITS;
3284 		if ((ire->ire_flags & RTF_SETSRC) == 0)
3285 			ire->ire_src_addr = 0;
3286 		break;
3287 	case IRE_HOST_REDIRECT:
3288 		ire->ire_mask = IP_HOST_MASK;
3289 		ire->ire_masklen = IP_ABITS;
3290 		ire->ire_src_addr = 0;
3291 		break;
3292 	case IRE_CACHE:
3293 	case IRE_BROADCAST:
3294 	case IRE_LOCAL:
3295 	case IRE_LOOPBACK:
3296 		ire->ire_mask = IP_HOST_MASK;
3297 		ire->ire_masklen = IP_ABITS;
3298 		break;
3299 	case IRE_PREFIX:
3300 		if ((ire->ire_flags & RTF_SETSRC) == 0)
3301 			ire->ire_src_addr = 0;
3302 		break;
3303 	case IRE_DEFAULT:
3304 		if ((ire->ire_flags & RTF_SETSRC) == 0)
3305 			ire->ire_src_addr = 0;
3306 		break;
3307 	case IRE_IF_RESOLVER:
3308 	case IRE_IF_NORESOLVER:
3309 		break;
3310 	default:
3311 		printf("ire_add_v4: ire %p has unrecognized IRE type (%d)\n",
3312 		    (void *)ire, ire->ire_type);
3313 		ire_delete(ire);
3314 		*ire_p = NULL;
3315 		return (EINVAL);
3316 	}
3317 
3318 	/* Make sure the address is properly masked. */
3319 	ire->ire_addr &= ire->ire_mask;
3320 
3321 	if ((ire->ire_type & IRE_CACHETABLE) == 0) {
3322 		/* IRE goes into Forward Table */
3323 		mask_table_index = ire->ire_masklen;
3324 		if ((ip_forwarding_table[mask_table_index]) == NULL) {
3325 			irb_t *ptr;
3326 			int i;
3327 
3328 			ptr = (irb_t *)mi_zalloc((ip_ftable_hash_size *
3329 			    sizeof (irb_t)));
3330 			if (ptr == NULL) {
3331 				ire_delete(ire);
3332 				*ire_p = NULL;
3333 				return (ENOMEM);
3334 			}
3335 			for (i = 0; i < ip_ftable_hash_size; i++) {
3336 				rw_init(&ptr[i].irb_lock, NULL,
3337 				    RW_DEFAULT, NULL);
3338 			}
3339 			mutex_enter(&ire_ft_init_lock);
3340 			if (ip_forwarding_table[mask_table_index] == NULL) {
3341 				ip_forwarding_table[mask_table_index] = ptr;
3342 				mutex_exit(&ire_ft_init_lock);
3343 			} else {
3344 				/*
3345 				 * Some other thread won the race in
3346 				 * initializing the forwarding table at the
3347 				 * same index.
3348 				 */
3349 				mutex_exit(&ire_ft_init_lock);
3350 				for (i = 0; i < ip_ftable_hash_size; i++) {
3351 					rw_destroy(&ptr[i].irb_lock);
3352 				}
3353 				mi_free(ptr);
3354 			}
3355 		}
3356 		irb_ptr = &(ip_forwarding_table[mask_table_index][
3357 		    IRE_ADDR_HASH(ire->ire_addr, ip_ftable_hash_size)]);
3358 	} else {
3359 		irb_ptr = &(ip_cache_table[IRE_ADDR_HASH(ire->ire_addr,
3360 		    ip_cache_table_size)]);
3361 	}
3362 	/*
3363 	 * ip_newroute/ip_newroute_multi are unable to prevent the deletion
3364 	 * of the interface route while adding an IRE_CACHE for an on-link
3365 	 * destination in the IRE_IF_RESOLVER case, since the ire has to
3366 	 * go to ARP and return. We can't do a REFHOLD on the
3367 	 * associated interface ire for fear of ARP freeing the message.
3368 	 * Here we look up the interface ire in the forwarding table and
3369 	 * make sure that the interface route has not been deleted.
3370 	 */
3371 	if (ire->ire_type == IRE_CACHE && ire->ire_gateway_addr == 0 &&
3372 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_net_type == IRE_IF_RESOLVER) {
3373 		ASSERT(ire->ire_max_fragp == NULL);
3374 		if (CLASSD(ire->ire_addr) && !(ire->ire_flags & RTF_SETSRC)) {
3375 			/*
3376 			 * The ihandle that we used in ip_newroute_multi
3377 			 * comes from the interface route corresponding
3378 			 * to ire_ipif. Lookup here to see if it exists
3379 			 * still.
3380 			 * If the ire has a source address assigned using
3381 			 * RTF_SETSRC, ire_ipif is the logical interface holding
3382 			 * this source address, so we can't use it to check for
3383 			 * the existence of the interface route. Instead we rely
3384 			 * on the brute force ihandle search in
3385 			 * ire_ihandle_lookup_onlink() below.
3386 			 */
3387 			pire = ipif_to_ire(ire->ire_ipif);
3388 			if (pire == NULL) {
3389 				ire_delete(ire);
3390 				*ire_p = NULL;
3391 				return (EINVAL);
3392 			} else if (pire->ire_ihandle != ire->ire_ihandle) {
3393 				ire_refrele(pire);
3394 				ire_delete(ire);
3395 				*ire_p = NULL;
3396 				return (EINVAL);
3397 			}
3398 		} else {
3399 			pire = ire_ihandle_lookup_onlink(ire);
3400 			if (pire == NULL) {
3401 				ire_delete(ire);
3402 				*ire_p = NULL;
3403 				return (EINVAL);
3404 			}
3405 		}
3406 		/* Prevent pire from getting deleted */
3407 		IRB_REFHOLD(pire->ire_bucket);
3408 		/* Has it been removed already ? */
3409 		if (pire->ire_marks & IRE_MARK_CONDEMNED) {
3410 			IRB_REFRELE(pire->ire_bucket);
3411 			ire_refrele(pire);
3412 			ire_delete(ire);
3413 			*ire_p = NULL;
3414 			return (EINVAL);
3415 		}
3416 	} else {
3417 		ASSERT(ire->ire_max_fragp != NULL);
3418 	}
3419 	flags = (MATCH_IRE_MASK | MATCH_IRE_TYPE | MATCH_IRE_GW);
3420 
3421 	if (ire->ire_ipif != NULL) {
3422 		/*
3423 		 * We use MATCH_IRE_IPIF while adding IRE_CACHES only
3424 		 * for historic reasons and to maintain symmetry with
3425 		 * IPv6 code path. Historically this was used by
3426 		 * multicast code to create multiple IRE_CACHES on
3427 		 * a single ill with different ipifs. This was used
3428 		 * so that multicast packets leaving the node had the
3429 		 * right source address. This is no longer needed as
3430 		 * ip_wput initializes the address correctly.
3431 		 */
3432 		flags |= MATCH_IRE_IPIF;
3433 		/*
3434 		 * If we are creating hidden ires, make sure we search on
3435 		 * this ill (MATCH_IRE_ILL) and a hidden ire,
3436 		 * while we are searching for duplicates below. Otherwise we
3437 		 * could potentially find an IRE on some other interface
3438 		 * and it may not be a IRE marked with IRE_MARK_HIDDEN. We
3439 		 * shouldn't do this as this will lead to an infinite loop
3440 		 * (if we get to ip_wput again) eventually we need an hidden
3441 		 * ire for this packet to go out. MATCH_IRE_ILL is explicitly
3442 		 * done below.
3443 		 */
3444 		if (ire->ire_type == IRE_CACHE &&
3445 		    (ire->ire_marks & IRE_MARK_HIDDEN))
3446 			flags |= (MATCH_IRE_MARK_HIDDEN);
3447 	}
3448 
3449 	/*
3450 	 * Start the atomic add of the ire. Grab the ill locks,
3451 	 * ill_g_usesrc_lock and the bucket lock. Check for condemned
3452 	 *
3453 	 * If ipif or ill is changing ire_atomic_start() may queue the
3454 	 * request and return EINPROGRESS.
3455 	 */
3456 	error = ire_atomic_start(irb_ptr, ire, q, mp, func);
3457 	if (error != 0) {
3458 		/*
3459 		 * We don't know whether it is a valid ipif or not.
3460 		 * So, set it to NULL. This assumes that the ire has not added
3461 		 * a reference to the ipif.
3462 		 */
3463 		ire->ire_ipif = NULL;
3464 		ire_delete(ire);
3465 		if (pire != NULL) {
3466 			IRB_REFRELE(pire->ire_bucket);
3467 			ire_refrele(pire);
3468 		}
3469 		*ire_p = NULL;
3470 		return (error);
3471 	}
3472 	/*
3473 	 * To avoid creating ires having stale values for the ire_max_frag
3474 	 * we get the latest value atomically here. For more details
3475 	 * see the block comment in ip_sioctl_mtu and in DL_NOTE_SDU_CHANGE
3476 	 * in ip_rput_dlpi_writer
3477 	 */
3478 	if (ire->ire_max_fragp == NULL) {
3479 		if (CLASSD(ire->ire_addr))
3480 			ire->ire_max_frag = ire->ire_ipif->ipif_mtu;
3481 		else
3482 			ire->ire_max_frag = pire->ire_max_frag;
3483 	} else {
3484 		uint_t	max_frag;
3485 
3486 		max_frag = *ire->ire_max_fragp;
3487 		ire->ire_max_fragp = NULL;
3488 		ire->ire_max_frag = max_frag;
3489 	}
3490 	/*
3491 	 * Atomically check for duplicate and insert in the table.
3492 	 */
3493 	for (ire1 = irb_ptr->irb_ire; ire1 != NULL; ire1 = ire1->ire_next) {
3494 		if (ire1->ire_marks & IRE_MARK_CONDEMNED)
3495 			continue;
3496 		if (ire->ire_ipif != NULL) {
3497 			/*
3498 			 * We do MATCH_IRE_ILL implicitly here for IREs
3499 			 * with a non-null ire_ipif, including IRE_CACHEs.
3500 			 * As ire_ipif and ire_stq could point to two
3501 			 * different ills, we can't pass just ire_ipif to
3502 			 * ire_match_args and get a match on both ills.
3503 			 * This is just needed for duplicate checks here and
3504 			 * so we don't add an extra argument to
3505 			 * ire_match_args for this. Do it locally.
3506 			 *
3507 			 * NOTE : Currently there is no part of the code
3508 			 * that asks for both MATH_IRE_IPIF and MATCH_IRE_ILL
3509 			 * match for IRE_CACHEs. Thus we don't want to
3510 			 * extend the arguments to ire_match_args.
3511 			 */
3512 			if (ire1->ire_stq != ire->ire_stq)
3513 				continue;
3514 			/*
3515 			 * Multiroute IRE_CACHEs for a given destination can
3516 			 * have the same ire_ipif, typically if their source
3517 			 * address is forced using RTF_SETSRC, and the same
3518 			 * send-to queue. We differentiate them using the parent
3519 			 * handle.
3520 			 */
3521 			if (ire->ire_type == IRE_CACHE &&
3522 			    (ire1->ire_flags & RTF_MULTIRT) &&
3523 			    (ire->ire_flags & RTF_MULTIRT) &&
3524 			    (ire1->ire_phandle != ire->ire_phandle))
3525 				continue;
3526 		}
3527 		if (ire1->ire_zoneid != ire->ire_zoneid)
3528 			continue;
3529 		if (ire_match_args(ire1, ire->ire_addr, ire->ire_mask,
3530 		    ire->ire_gateway_addr, ire->ire_type, ire->ire_ipif,
3531 		    ire->ire_zoneid, 0, NULL, flags)) {
3532 			/*
3533 			 * Return the old ire after doing a REFHOLD.
3534 			 * As most of the callers continue to use the IRE
3535 			 * after adding, we return a held ire. This will
3536 			 * avoid a lookup in the caller again. If the callers
3537 			 * don't want to use it, they need to do a REFRELE.
3538 			 */
3539 			ip1dbg(("found dup ire existing %p new %p",
3540 			    (void *)ire1, (void *)ire));
3541 			IRE_REFHOLD(ire1);
3542 			ire_atomic_end(irb_ptr, ire);
3543 			ire_delete(ire);
3544 			if (pire != NULL) {
3545 				/*
3546 				 * Assert that it is not removed from the
3547 				 * list yet.
3548 				 */
3549 				ASSERT(pire->ire_ptpn != NULL);
3550 				IRB_REFRELE(pire->ire_bucket);
3551 				ire_refrele(pire);
3552 			}
3553 			*ire_p = ire1;
3554 			return (0);
3555 		}
3556 	}
3557 
3558 	/*
3559 	 * Make it easy for ip_wput_ire() to hit multiple broadcast ires by
3560 	 * grouping identical addresses together on the hash chain. We also
3561 	 * don't want to send multiple copies out if there are two ills part
3562 	 * of the same group. Thus we group the ires with same addr and same
3563 	 * ill group together so that ip_wput_ire can easily skip all the
3564 	 * ires with same addr and same group after sending the first copy.
3565 	 * We do this only for IRE_BROADCASTs as ip_wput_ire is currently
3566 	 * interested in such groupings only for broadcasts.
3567 	 *
3568 	 * NOTE : If the interfaces are brought up first and then grouped,
3569 	 * illgrp_insert will handle it. We come here when the interfaces
3570 	 * are already in group and we are bringing them UP.
3571 	 *
3572 	 * Find the first entry that matches ire_addr. *irep will be null
3573 	 * if no match.
3574 	 */
3575 	irep = (ire_t **)irb_ptr;
3576 	while ((ire1 = *irep) != NULL && ire->ire_addr != ire1->ire_addr)
3577 		irep = &ire1->ire_next;
3578 	if (ire->ire_type == IRE_BROADCAST && *irep != NULL) {
3579 		/*
3580 		 * We found some ire (i.e *irep) with a matching addr. We
3581 		 * want to group ires with same addr and same ill group
3582 		 * together.
3583 		 *
3584 		 * First get to the entry that matches our address and
3585 		 * ill group i.e stop as soon as we find the first ire
3586 		 * matching the ill group and address. If there is only
3587 		 * an address match, we should walk and look for some
3588 		 * group match. These are some of the possible scenarios :
3589 		 *
3590 		 * 1) There are no groups at all i.e all ire's ill_group
3591 		 *    are NULL. In that case we will essentially group
3592 		 *    all the ires with the same addr together. Same as
3593 		 *    the "else" block of this "if".
3594 		 *
3595 		 * 2) There are some groups and this ire's ill_group is
3596 		 *    NULL. In this case, we will first find the group
3597 		 *    that matches the address and a NULL group. Then
3598 		 *    we will insert the ire at the end of that group.
3599 		 *
3600 		 * 3) There are some groups and this ires's ill_group is
3601 		 *    non-NULL. In this case we will first find the group
3602 		 *    that matches the address and the ill_group. Then
3603 		 *    we will insert the ire at the end of that group.
3604 		 */
3605 		/* LINTED : constant in conditional context */
3606 		while (1) {
3607 			ire1 = *irep;
3608 			if ((ire1->ire_next == NULL) ||
3609 			    (ire1->ire_next->ire_addr != ire->ire_addr) ||
3610 			    (ire1->ire_type != IRE_BROADCAST) ||
3611 			    (ire1->ire_ipif->ipif_ill->ill_group ==
3612 			    ire->ire_ipif->ipif_ill->ill_group))
3613 				break;
3614 			irep = &ire1->ire_next;
3615 		}
3616 		ASSERT(*irep != NULL);
3617 		irep = &((*irep)->ire_next);
3618 
3619 		/*
3620 		 * Either we have hit the end of the list or the address
3621 		 * did not match or the group *matched*. If we found
3622 		 * a match on the group, skip to the end of the group.
3623 		 */
3624 		while (*irep != NULL) {
3625 			ire1 = *irep;
3626 			if ((ire1->ire_addr != ire->ire_addr) ||
3627 			    (ire1->ire_type != IRE_BROADCAST) ||
3628 			    (ire1->ire_ipif->ipif_ill->ill_group !=
3629 			    ire->ire_ipif->ipif_ill->ill_group))
3630 				break;
3631 			if (ire1->ire_ipif->ipif_ill->ill_group == NULL &&
3632 			    ire1->ire_ipif == ire->ire_ipif) {
3633 				irep = &ire1->ire_next;
3634 				break;
3635 			}
3636 			irep = &ire1->ire_next;
3637 		}
3638 	} else if (*irep != NULL) {
3639 		/*
3640 		 * Find the last ire which matches ire_addr.
3641 		 * Needed to do tail insertion among entries with the same
3642 		 * ire_addr.
3643 		 */
3644 		while (ire->ire_addr == ire1->ire_addr) {
3645 			irep = &ire1->ire_next;
3646 			ire1 = *irep;
3647 			if (ire1 == NULL)
3648 				break;
3649 		}
3650 	}
3651 
3652 	if (ire->ire_type == IRE_DEFAULT) {
3653 		/*
3654 		 * We keep a count of default gateways which is used when
3655 		 * assigning them as routes.
3656 		 */
3657 		ip_ire_default_count++;
3658 		ASSERT(ip_ire_default_count != 0); /* Wraparound */
3659 	}
3660 	/* Insert at *irep */
3661 	ire1 = *irep;
3662 	if (ire1 != NULL)
3663 		ire1->ire_ptpn = &ire->ire_next;
3664 	ire->ire_next = ire1;
3665 	/* Link the new one in. */
3666 	ire->ire_ptpn = irep;
3667 
3668 	/*
3669 	 * ire_walk routines de-reference ire_next without holding
3670 	 * a lock. Before we point to the new ire, we want to make
3671 	 * sure the store that sets the ire_next of the new ire
3672 	 * reaches global visibility, so that ire_walk routines
3673 	 * don't see a truncated list of ires i.e if the ire_next
3674 	 * of the new ire gets set after we do "*irep = ire" due
3675 	 * to re-ordering, the ire_walk thread will see a NULL
3676 	 * once it accesses the ire_next of the new ire.
3677 	 * membar_producer() makes sure that the following store
3678 	 * happens *after* all of the above stores.
3679 	 */
3680 	membar_producer();
3681 	*irep = ire;
3682 	ire->ire_bucket = irb_ptr;
3683 	/*
3684 	 * We return a bumped up IRE above. Keep it symmetrical
3685 	 * so that the callers will always have to release. This
3686 	 * helps the callers of this function because they continue
3687 	 * to use the IRE after adding and hence they don't have to
3688 	 * lookup again after we return the IRE.
3689 	 *
3690 	 * NOTE : We don't have to use atomics as this is appearing
3691 	 * in the list for the first time and no one else can bump
3692 	 * up the reference count on this yet.
3693 	 */
3694 	IRE_REFHOLD_LOCKED(ire);
3695 	BUMP_IRE_STATS(ire_stats_v4, ire_stats_inserted);
3696 	irb_ptr->irb_ire_cnt++;
3697 	if (ire->ire_marks & IRE_MARK_TEMPORARY)
3698 		irb_ptr->irb_tmp_ire_cnt++;
3699 
3700 	if (ire->ire_ipif != NULL) {
3701 		ire->ire_ipif->ipif_ire_cnt++;
3702 		if (ire->ire_stq != NULL) {
3703 			stq_ill = (ill_t *)ire->ire_stq->q_ptr;
3704 			stq_ill->ill_ire_cnt++;
3705 		}
3706 	} else {
3707 		ASSERT(ire->ire_stq == NULL);
3708 	}
3709 
3710 	ire_atomic_end(irb_ptr, ire);
3711 
3712 	if (pire != NULL) {
3713 		/* Assert that it is not removed from the list yet */
3714 		ASSERT(pire->ire_ptpn != NULL);
3715 		IRB_REFRELE(pire->ire_bucket);
3716 		ire_refrele(pire);
3717 	}
3718 
3719 	if (ire->ire_type != IRE_CACHE) {
3720 		/*
3721 		 * For ire's with with host mask see if there is an entry
3722 		 * in the cache. If there is one flush the whole cache as
3723 		 * there might be multiple entries due to RTF_MULTIRT (CGTP).
3724 		 * If no entry is found than there is no need to flush the
3725 		 * cache.
3726 		 */
3727 		if (ire->ire_mask == IP_HOST_MASK) {
3728 			ire_t *lire;
3729 			lire = ire_ctable_lookup(ire->ire_addr, NULL, IRE_CACHE,
3730 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE);
3731 			if (lire != NULL) {
3732 				ire_refrele(lire);
3733 				ire_flush_cache_v4(ire, IRE_FLUSH_ADD);
3734 			}
3735 		} else {
3736 			ire_flush_cache_v4(ire, IRE_FLUSH_ADD);
3737 		}
3738 	}
3739 	/*
3740 	 * We had to delay the fast path probe until the ire is inserted
3741 	 * in the list. Otherwise the fast path ack won't find the ire in
3742 	 * the table.
3743 	 */
3744 	if (ire->ire_type == IRE_CACHE || ire->ire_type == IRE_BROADCAST)
3745 		ire_fastpath(ire);
3746 	if (ire->ire_ipif != NULL)
3747 		ASSERT(!MUTEX_HELD(&ire->ire_ipif->ipif_ill->ill_lock));
3748 	*ire_p = ire;
3749 	return (0);
3750 }
3751 
3752 /*
3753  * Search for all HOST REDIRECT routes that are
3754  * pointing at the specified gateway and
3755  * delete them. This routine is called only
3756  * when a default gateway is going away.
3757  */
3758 static void
3759 ire_delete_host_redirects(ipaddr_t gateway)
3760 {
3761 	irb_t *irb_ptr;
3762 	irb_t *irb;
3763 	ire_t *ire;
3764 	int i;
3765 
3766 	/* get the hash table for HOST routes */
3767 	irb_ptr = ip_forwarding_table[(IP_MASK_TABLE_SIZE - 1)];
3768 	if (irb_ptr == NULL)
3769 		return;
3770 	for (i = 0; (i < ip_ftable_hash_size); i++) {
3771 		irb = &irb_ptr[i];
3772 		IRB_REFHOLD(irb);
3773 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
3774 			if (ire->ire_type != IRE_HOST_REDIRECT)
3775 				continue;
3776 			if (ire->ire_gateway_addr == gateway) {
3777 				ire_delete(ire);
3778 			}
3779 		}
3780 		IRB_REFRELE(irb);
3781 	}
3782 }
3783 
3784 /*
3785  * IRB_REFRELE is the only caller of the function. ire_unlink calls to
3786  * do the final cleanup for this ire.
3787  */
3788 void
3789 ire_cleanup(ire_t *ire)
3790 {
3791 	ire_t *ire_next;
3792 
3793 	ASSERT(ire != NULL);
3794 
3795 	while (ire != NULL) {
3796 		ire_next = ire->ire_next;
3797 		if (ire->ire_ipversion == IPV4_VERSION) {
3798 			ire_delete_v4(ire);
3799 			BUMP_IRE_STATS(ire_stats_v4, ire_stats_deleted);
3800 		} else {
3801 			ASSERT(ire->ire_ipversion == IPV6_VERSION);
3802 			ire_delete_v6(ire);
3803 			BUMP_IRE_STATS(ire_stats_v6, ire_stats_deleted);
3804 		}
3805 		/*
3806 		 * Now it's really out of the list. Before doing the
3807 		 * REFRELE, set ire_next to NULL as ire_inactive asserts
3808 		 * so.
3809 		 */
3810 		ire->ire_next = NULL;
3811 		IRE_REFRELE_NOTR(ire);
3812 		ire = ire_next;
3813 	}
3814 }
3815 
3816 /*
3817  * IRB_REFRELE is the only caller of the function. It calls to unlink
3818  * all the CONDEMNED ires from this bucket.
3819  */
3820 ire_t *
3821 ire_unlink(irb_t *irb)
3822 {
3823 	ire_t *ire;
3824 	ire_t *ire1;
3825 	ire_t **ptpn;
3826 	ire_t *ire_list = NULL;
3827 
3828 	ASSERT(RW_WRITE_HELD(&irb->irb_lock));
3829 	ASSERT(irb->irb_refcnt == 0);
3830 	ASSERT(irb->irb_marks & IRE_MARK_CONDEMNED);
3831 	ASSERT(irb->irb_ire != NULL);
3832 
3833 	for (ire = irb->irb_ire; ire != NULL; ire = ire1) {
3834 		ire1 = ire->ire_next;
3835 		if (ire->ire_marks & IRE_MARK_CONDEMNED) {
3836 			ptpn = ire->ire_ptpn;
3837 			ire1 = ire->ire_next;
3838 			if (ire1)
3839 				ire1->ire_ptpn = ptpn;
3840 			*ptpn = ire1;
3841 			ire->ire_ptpn = NULL;
3842 			ire->ire_next = NULL;
3843 			if (ire->ire_type == IRE_DEFAULT) {
3844 				/*
3845 				 * IRE is out of the list. We need to adjust
3846 				 * the accounting before the caller drops
3847 				 * the lock.
3848 				 */
3849 				if (ire->ire_ipversion == IPV6_VERSION) {
3850 					ASSERT(ipv6_ire_default_count != 0);
3851 					ipv6_ire_default_count--;
3852 				} else {
3853 					ASSERT(ip_ire_default_count != 0);
3854 					ip_ire_default_count--;
3855 				}
3856 			}
3857 			/*
3858 			 * We need to call ire_delete_v4 or ire_delete_v6
3859 			 * to clean up the cache or the redirects pointing at
3860 			 * the default gateway. We need to drop the lock
3861 			 * as ire_flush_cache/ire_delete_host_redircts require
3862 			 * so. But we can't drop the lock, as ire_unlink needs
3863 			 * to atomically remove the ires from the list.
3864 			 * So, create a temporary list of CONDEMNED ires
3865 			 * for doing ire_delete_v4/ire_delete_v6 operations
3866 			 * later on.
3867 			 */
3868 			ire->ire_next = ire_list;
3869 			ire_list = ire;
3870 		}
3871 	}
3872 	ASSERT(irb->irb_refcnt == 0);
3873 	irb->irb_marks &= ~IRE_MARK_CONDEMNED;
3874 	ASSERT(ire_list != NULL);
3875 	return (ire_list);
3876 }
3877 
3878 /*
3879  * Delete all the cache entries with this 'addr'.  When IP gets a gratuitous
3880  * ARP message on any of its interface queue, it scans the cache table and
3881  * deletes all the cache entries for that address. This function is called
3882  * from ip_arp_news in ip.c and  also for ARP ioctl processing in ip_if.c.
3883  * ip_ire_clookup_and_delete returns true if it finds at least one cache entry
3884  * which is used by ip_arp_news to determine if it needs to do an ire_walk_v4.
3885  * The return value is also  used for the same purpose by ARP IOCTL processing
3886  * in ip_if.c when deleting ARP entries. For SIOC*IFARP ioctls in addition to
3887  * the address, ip_if->ipif_ill also needs to be matched.
3888  */
3889 boolean_t
3890 ip_ire_clookup_and_delete(ipaddr_t addr, ipif_t *ipif)
3891 {
3892 	irb_t		*irb;
3893 	ire_t		*cire;
3894 	ill_t		*ill;
3895 	boolean_t	found = B_FALSE, loop_end = B_FALSE;
3896 
3897 	irb = &ip_cache_table[IRE_ADDR_HASH(addr, ip_cache_table_size)];
3898 	IRB_REFHOLD(irb);
3899 	for (cire = irb->irb_ire; cire != NULL; cire = cire->ire_next) {
3900 		if (cire->ire_marks & IRE_MARK_CONDEMNED)
3901 			continue;
3902 		if (cire->ire_addr == addr) {
3903 
3904 			/* This signifies start of an address match */
3905 			if (!loop_end)
3906 				loop_end = B_TRUE;
3907 
3908 			/* We are interested only in IRE_CACHEs */
3909 			if (cire->ire_type == IRE_CACHE) {
3910 				/* If we want a match with the ILL */
3911 				if (ipif != NULL &&
3912 				    ((ill = ire_to_ill(cire)) == NULL ||
3913 				    ill != ipif->ipif_ill)) {
3914 					continue;
3915 				}
3916 				if (!found)
3917 					found = B_TRUE;
3918 				ire_delete(cire);
3919 			}
3920 		/* End of the match */
3921 		} else if (loop_end)
3922 			break;
3923 	}
3924 	IRB_REFRELE(irb);
3925 
3926 	return (found);
3927 
3928 }
3929 
3930 /*
3931  * Delete the specified IRE.
3932  */
3933 void
3934 ire_delete(ire_t *ire)
3935 {
3936 	ire_t	*ire1;
3937 	ire_t	**ptpn;
3938 	irb_t *irb;
3939 
3940 	/*
3941 	 * It was never inserted in the list. Should call REFRELE
3942 	 * to free this IRE.
3943 	 */
3944 	if ((irb = ire->ire_bucket) == NULL) {
3945 		IRE_REFRELE_NOTR(ire);
3946 		return;
3947 	}
3948 
3949 	rw_enter(&irb->irb_lock, RW_WRITER);
3950 
3951 	/*
3952 	 * In case of V4 we might still be waiting for fastpath ack.
3953 	 */
3954 	if (ire->ire_nce == NULL && ire->ire_stq != NULL) {
3955 		ill_t *ill;
3956 
3957 		ill = ire_to_ill(ire);
3958 		if (ill != NULL)
3959 			ire_fastpath_list_delete(ill, ire);
3960 	}
3961 
3962 	if (ire->ire_ptpn == NULL) {
3963 		/*
3964 		 * Some other thread has removed us from the list.
3965 		 * It should have done the REFRELE for us.
3966 		 */
3967 		rw_exit(&irb->irb_lock);
3968 		return;
3969 	}
3970 
3971 	if (irb->irb_refcnt != 0) {
3972 		/*
3973 		 * The last thread to leave this bucket will
3974 		 * delete this ire.
3975 		 */
3976 		if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
3977 			irb->irb_ire_cnt--;
3978 			if (ire->ire_marks & IRE_MARK_TEMPORARY)
3979 				irb->irb_tmp_ire_cnt--;
3980 			ire->ire_marks |= IRE_MARK_CONDEMNED;
3981 		}
3982 		irb->irb_marks |= IRE_MARK_CONDEMNED;
3983 		rw_exit(&irb->irb_lock);
3984 		return;
3985 	}
3986 
3987 	/*
3988 	 * Normally to delete an ire, we walk the bucket. While we
3989 	 * walk the bucket, we normally bump up irb_refcnt and hence
3990 	 * we return from above where we mark CONDEMNED and the ire
3991 	 * gets deleted from ire_unlink. This case is where somebody
3992 	 * knows the ire e.g by doing a lookup, and wants to delete the
3993 	 * IRE. irb_refcnt would be 0 in this case if nobody is walking
3994 	 * the bucket.
3995 	 */
3996 	ptpn = ire->ire_ptpn;
3997 	ire1 = ire->ire_next;
3998 	if (ire1 != NULL)
3999 		ire1->ire_ptpn = ptpn;
4000 	ASSERT(ptpn != NULL);
4001 	*ptpn = ire1;
4002 	ire->ire_ptpn = NULL;
4003 	ire->ire_next = NULL;
4004 	if (ire->ire_ipversion == IPV6_VERSION) {
4005 		BUMP_IRE_STATS(ire_stats_v6, ire_stats_deleted);
4006 	} else {
4007 		BUMP_IRE_STATS(ire_stats_v4, ire_stats_deleted);
4008 	}
4009 	/*
4010 	 * ip_wput/ip_wput_v6 checks this flag to see whether
4011 	 * it should still use the cached ire or not.
4012 	 */
4013 	ire->ire_marks |= IRE_MARK_CONDEMNED;
4014 	if (ire->ire_type == IRE_DEFAULT) {
4015 		/*
4016 		 * IRE is out of the list. We need to adjust the
4017 		 * accounting before we drop the lock.
4018 		 */
4019 		if (ire->ire_ipversion == IPV6_VERSION) {
4020 			ASSERT(ipv6_ire_default_count != 0);
4021 			ipv6_ire_default_count--;
4022 		} else {
4023 			ASSERT(ip_ire_default_count != 0);
4024 			ip_ire_default_count--;
4025 		}
4026 	}
4027 	irb->irb_ire_cnt--;
4028 	if (ire->ire_marks & IRE_MARK_TEMPORARY)
4029 		irb->irb_tmp_ire_cnt--;
4030 	rw_exit(&irb->irb_lock);
4031 
4032 	if (ire->ire_ipversion == IPV6_VERSION) {
4033 		ire_delete_v6(ire);
4034 	} else {
4035 		ire_delete_v4(ire);
4036 	}
4037 	/*
4038 	 * We removed it from the list. Decrement the
4039 	 * reference count.
4040 	 */
4041 	IRE_REFRELE_NOTR(ire);
4042 }
4043 
4044 /*
4045  * Delete the specified IRE.
4046  * All calls should use ire_delete().
4047  * Sometimes called as writer though not required by this function.
4048  *
4049  * NOTE : This function is called only if the ire was added
4050  * in the list.
4051  */
4052 static void
4053 ire_delete_v4(ire_t *ire)
4054 {
4055 	ASSERT(ire->ire_refcnt >= 1);
4056 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
4057 
4058 	if (ire->ire_type != IRE_CACHE)
4059 		ire_flush_cache_v4(ire, IRE_FLUSH_DELETE);
4060 	if (ire->ire_type == IRE_DEFAULT) {
4061 		/*
4062 		 * when a default gateway is going away
4063 		 * delete all the host redirects pointing at that
4064 		 * gateway.
4065 		 */
4066 		ire_delete_host_redirects(ire->ire_gateway_addr);
4067 	}
4068 }
4069 
4070 /*
4071  * IRE_REFRELE/ire_refrele are the only caller of the function. It calls
4072  * to free the ire when the reference count goes to zero.
4073  */
4074 void
4075 ire_inactive(ire_t *ire)
4076 {
4077 	mblk_t *mp;
4078 	nce_t	*nce;
4079 	ill_t	*ill = NULL;
4080 	ill_t	*stq_ill = NULL;
4081 	ill_t	*in_ill = NULL;
4082 	ipif_t	*ipif;
4083 	boolean_t	need_wakeup = B_FALSE;
4084 
4085 	ASSERT(ire->ire_refcnt == 0);
4086 	ASSERT(ire->ire_ptpn == NULL);
4087 	ASSERT(ire->ire_next == NULL);
4088 
4089 	if ((nce = ire->ire_nce) != NULL) {
4090 		/* Only IPv6 IRE_CACHE type has an nce */
4091 		ASSERT(ire->ire_type == IRE_CACHE);
4092 		ASSERT(ire->ire_ipversion == IPV6_VERSION);
4093 		NCE_REFRELE_NOTR(nce);
4094 		ire->ire_nce = NULL;
4095 	}
4096 	if (ire->ire_ipif == NULL)
4097 		goto end;
4098 
4099 	ipif = ire->ire_ipif;
4100 	ill = ipif->ipif_ill;
4101 
4102 	if (ire->ire_bucket == NULL) {
4103 		/* The ire was never inserted in the table. */
4104 		goto end;
4105 	}
4106 
4107 	/*
4108 	 * ipif_ire_cnt on this ipif goes down by 1. If the ire_stq is
4109 	 * non-null ill_ire_count also goes down by 1. If the in_ill is
4110 	 * non-null either ill_mrtun_refcnt or ill_srcif_refcnt goes down by 1.
4111 	 *
4112 	 * The ipif that is associated with an ire is ire->ire_ipif and
4113 	 * hence when the ire->ire_ipif->ipif_ire_cnt drops to zero we call
4114 	 * ipif_ill_refrele_tail. Usually stq_ill is null or the same as
4115 	 * ire->ire_ipif->ipif_ill. So nothing more needs to be done. Only
4116 	 * in the case of IRE_CACHES when IPMP is used, stq_ill can be
4117 	 * different. If this is different from ire->ire_ipif->ipif_ill and
4118 	 * if the ill_ire_cnt on the stq_ill also has dropped to zero, we call
4119 	 * ipif_ill_refrele_tail on the stq_ill. If mobile ip is in use
4120 	 * in_ill could be non-null. If it is a reverse tunnel related ire
4121 	 * ill_mrtun_refcnt is non-zero. If it is forward tunnel related ire
4122 	 * ill_srcif_refcnt is non-null.
4123 	 */
4124 
4125 	if (ire->ire_stq != NULL)
4126 		stq_ill = (ill_t *)ire->ire_stq->q_ptr;
4127 	if (ire->ire_in_ill != NULL)
4128 		in_ill = ire->ire_in_ill;
4129 
4130 	if ((stq_ill == NULL || stq_ill == ill) && (in_ill == NULL)) {
4131 		/* Optimize the most common case */
4132 		mutex_enter(&ill->ill_lock);
4133 		ASSERT(ipif->ipif_ire_cnt != 0);
4134 		ipif->ipif_ire_cnt--;
4135 		if (ipif->ipif_ire_cnt == 0)
4136 			need_wakeup = B_TRUE;
4137 		if (stq_ill != NULL) {
4138 			ASSERT(stq_ill->ill_ire_cnt != 0);
4139 			stq_ill->ill_ire_cnt--;
4140 			if (stq_ill->ill_ire_cnt == 0)
4141 				need_wakeup = B_TRUE;
4142 		}
4143 		if (need_wakeup) {
4144 			/* Drops the ill lock */
4145 			ipif_ill_refrele_tail(ill);
4146 		} else {
4147 			mutex_exit(&ill->ill_lock);
4148 		}
4149 	} else {
4150 		/*
4151 		 * We can't grab all the ill locks at the same time.
4152 		 * It can lead to recursive lock enter in the call to
4153 		 * ipif_ill_refrele_tail and later. Instead do it 1 at
4154 		 * a time.
4155 		 */
4156 		mutex_enter(&ill->ill_lock);
4157 		ASSERT(ipif->ipif_ire_cnt != 0);
4158 		ipif->ipif_ire_cnt--;
4159 		if (ipif->ipif_ire_cnt == 0) {
4160 			/* Drops the lock */
4161 			ipif_ill_refrele_tail(ill);
4162 		} else {
4163 			mutex_exit(&ill->ill_lock);
4164 		}
4165 		if (stq_ill != NULL) {
4166 			mutex_enter(&stq_ill->ill_lock);
4167 			ASSERT(stq_ill->ill_ire_cnt != 0);
4168 			stq_ill->ill_ire_cnt--;
4169 			if (stq_ill->ill_ire_cnt == 0)  {
4170 				/* Drops the ill lock */
4171 				ipif_ill_refrele_tail(stq_ill);
4172 			} else {
4173 				mutex_exit(&stq_ill->ill_lock);
4174 			}
4175 		}
4176 		if (in_ill != NULL) {
4177 			mutex_enter(&in_ill->ill_lock);
4178 			if (ire->ire_type == IRE_MIPRTUN) {
4179 				/*
4180 				 * Mobile IP reverse tunnel ire.
4181 				 * Decrement table count and the
4182 				 * ill reference count. This signifies
4183 				 * mipagent is deleting reverse tunnel
4184 				 * route for a particular mobile node.
4185 				 */
4186 				mutex_enter(&ire_mrtun_lock);
4187 				ire_mrtun_count--;
4188 				mutex_exit(&ire_mrtun_lock);
4189 				ASSERT(in_ill->ill_mrtun_refcnt != 0);
4190 				in_ill->ill_mrtun_refcnt--;
4191 				if (in_ill->ill_mrtun_refcnt == 0) {
4192 					/* Drops the ill lock */
4193 					ipif_ill_refrele_tail(in_ill);
4194 				} else {
4195 					mutex_exit(&in_ill->ill_lock);
4196 				}
4197 			} else {
4198 				mutex_enter(&ire_srcif_table_lock);
4199 				ire_srcif_table_count--;
4200 				mutex_exit(&ire_srcif_table_lock);
4201 				ASSERT(in_ill->ill_srcif_refcnt != 0);
4202 				in_ill->ill_srcif_refcnt--;
4203 				if (in_ill->ill_srcif_refcnt == 0) {
4204 					/* Drops the ill lock */
4205 					ipif_ill_refrele_tail(in_ill);
4206 				} else {
4207 					mutex_exit(&in_ill->ill_lock);
4208 				}
4209 			}
4210 		}
4211 	}
4212 end:
4213 	/* This should be true for both V4 and V6 */
4214 	ASSERT(ire->ire_fastpath == NULL);
4215 
4216 
4217 	ire->ire_ipif = NULL;
4218 
4219 	/* Free the xmit header, and the IRE itself. */
4220 	if ((mp = ire->ire_dlureq_mp) != NULL) {
4221 		freeb(mp);
4222 		ire->ire_dlureq_mp = NULL;
4223 	}
4224 
4225 	if ((mp = ire->ire_fp_mp) != NULL) {
4226 		freeb(mp);
4227 		ire->ire_fp_mp = NULL;
4228 	}
4229 
4230 	if (ire->ire_in_ill != NULL) {
4231 		ire->ire_in_ill = NULL;
4232 	}
4233 
4234 	if (ire->ire_gw_secattr != NULL) {
4235 		ire_gw_secattr_free(ire->ire_gw_secattr);
4236 		ire->ire_gw_secattr = NULL;
4237 	}
4238 #ifdef IRE_DEBUG
4239 	ire_trace_inactive(ire);
4240 #endif
4241 	mutex_destroy(&ire->ire_lock);
4242 	if (ire->ire_ipversion == IPV6_VERSION) {
4243 		BUMP_IRE_STATS(ire_stats_v6, ire_stats_freed);
4244 	} else {
4245 		BUMP_IRE_STATS(ire_stats_v4, ire_stats_freed);
4246 	}
4247 	if (ire->ire_mp != NULL) {
4248 		/* Still in an mblk */
4249 		freeb(ire->ire_mp);
4250 	} else {
4251 		/* Has been allocated out of the cache */
4252 		kmem_cache_free(ire_cache, ire);
4253 	}
4254 }
4255 
4256 /*
4257  * ire_walk routine to delete all IRE_CACHE/IRE_HOST_REDIRECT entries
4258  * that have a given gateway address.
4259  */
4260 void
4261 ire_delete_cache_gw(ire_t *ire, char *cp)
4262 {
4263 	ipaddr_t	gw_addr;
4264 
4265 	if (!(ire->ire_type & (IRE_CACHE|IRE_HOST_REDIRECT)))
4266 		return;
4267 
4268 	bcopy(cp, &gw_addr, sizeof (gw_addr));
4269 	if (ire->ire_gateway_addr == gw_addr) {
4270 		ip1dbg(("ire_delete_cache_gw: deleted 0x%x type %d to 0x%x\n",
4271 			(int)ntohl(ire->ire_addr), ire->ire_type,
4272 			(int)ntohl(ire->ire_gateway_addr)));
4273 		ire_delete(ire);
4274 	}
4275 }
4276 
4277 /*
4278  * Remove all IRE_CACHE entries that match the ire specified.
4279  *
4280  * The flag argument indicates if the flush request is due to addition
4281  * of new route (IRE_FLUSH_ADD) or deletion of old route (IRE_FLUSH_DELETE).
4282  *
4283  * This routine takes only the IREs from the forwarding table and flushes
4284  * the corresponding entries from the cache table.
4285  *
4286  * When flushing due to the deletion of an old route, it
4287  * just checks the cache handles (ire_phandle and ire_ihandle) and
4288  * deletes the ones that match.
4289  *
4290  * When flushing due to the creation of a new route, it checks
4291  * if a cache entry's address matches the one in the IRE and
4292  * that the cache entry's parent has a less specific mask than the
4293  * one in IRE. The destination of such a cache entry could be the
4294  * gateway for other cache entries, so we need to flush those as
4295  * well by looking for gateway addresses matching the IRE's address.
4296  */
4297 void
4298 ire_flush_cache_v4(ire_t *ire, int flag)
4299 {
4300 	int i;
4301 	ire_t *cire;
4302 	irb_t *irb;
4303 
4304 	if (ire->ire_type & IRE_CACHE)
4305 	    return;
4306 
4307 	/*
4308 	 * If a default is just created, there is no point
4309 	 * in going through the cache, as there will not be any
4310 	 * cached ires.
4311 	 */
4312 	if (ire->ire_type == IRE_DEFAULT && flag == IRE_FLUSH_ADD)
4313 		return;
4314 	if (flag == IRE_FLUSH_ADD) {
4315 		/*
4316 		 * This selective flush is due to the addition of
4317 		 * new IRE.
4318 		 */
4319 		for (i = 0; i < ip_cache_table_size; i++) {
4320 			irb = &ip_cache_table[i];
4321 			if ((cire = irb->irb_ire) == NULL)
4322 				continue;
4323 			IRB_REFHOLD(irb);
4324 			for (cire = irb->irb_ire; cire != NULL;
4325 			    cire = cire->ire_next) {
4326 				if (cire->ire_type != IRE_CACHE)
4327 					continue;
4328 				/*
4329 				 * If 'cire' belongs to the same subnet
4330 				 * as the new ire being added, and 'cire'
4331 				 * is derived from a prefix that is less
4332 				 * specific than the new ire being added,
4333 				 * we need to flush 'cire'; for instance,
4334 				 * when a new interface comes up.
4335 				 */
4336 				if (((cire->ire_addr & ire->ire_mask) ==
4337 				    (ire->ire_addr & ire->ire_mask)) &&
4338 				    (ip_mask_to_plen(cire->ire_cmask) <=
4339 				    ire->ire_masklen)) {
4340 					ire_delete(cire);
4341 					continue;
4342 				}
4343 				/*
4344 				 * This is the case when the ire_gateway_addr
4345 				 * of 'cire' belongs to the same subnet as
4346 				 * the new ire being added.
4347 				 * Flushing such ires is sometimes required to
4348 				 * avoid misrouting: say we have a machine with
4349 				 * two interfaces (I1 and I2), a default router
4350 				 * R on the I1 subnet, and a host route to an
4351 				 * off-link destination D with a gateway G on
4352 				 * the I2 subnet.
4353 				 * Under normal operation, we will have an
4354 				 * on-link cache entry for G and an off-link
4355 				 * cache entry for D with G as ire_gateway_addr,
4356 				 * traffic to D will reach its destination
4357 				 * through gateway G.
4358 				 * If the administrator does 'ifconfig I2 down',
4359 				 * the cache entries for D and G will be
4360 				 * flushed. However, G will now be resolved as
4361 				 * an off-link destination using R (the default
4362 				 * router) as gateway. Then D will also be
4363 				 * resolved as an off-link destination using G
4364 				 * as gateway - this behavior is due to
4365 				 * compatibility reasons, see comment in
4366 				 * ire_ihandle_lookup_offlink(). Traffic to D
4367 				 * will go to the router R and probably won't
4368 				 * reach the destination.
4369 				 * The administrator then does 'ifconfig I2 up'.
4370 				 * Since G is on the I2 subnet, this routine
4371 				 * will flush its cache entry. It must also
4372 				 * flush the cache entry for D, otherwise
4373 				 * traffic will stay misrouted until the IRE
4374 				 * times out.
4375 				 */
4376 				if ((cire->ire_gateway_addr & ire->ire_mask) ==
4377 				    (ire->ire_addr & ire->ire_mask)) {
4378 					ire_delete(cire);
4379 					continue;
4380 				}
4381 			}
4382 			IRB_REFRELE(irb);
4383 		}
4384 	} else {
4385 		/*
4386 		 * delete the cache entries based on
4387 		 * handle in the IRE as this IRE is
4388 		 * being deleted/changed.
4389 		 */
4390 		for (i = 0; i < ip_cache_table_size; i++) {
4391 			irb = &ip_cache_table[i];
4392 			if ((cire = irb->irb_ire) == NULL)
4393 				continue;
4394 			IRB_REFHOLD(irb);
4395 			for (cire = irb->irb_ire; cire != NULL;
4396 			    cire = cire->ire_next) {
4397 				if (cire->ire_type != IRE_CACHE)
4398 					continue;
4399 				if ((cire->ire_phandle == 0 ||
4400 				    cire->ire_phandle != ire->ire_phandle) &&
4401 				    (cire->ire_ihandle == 0 ||
4402 				    cire->ire_ihandle != ire->ire_ihandle))
4403 					continue;
4404 				ire_delete(cire);
4405 			}
4406 			IRB_REFRELE(irb);
4407 		}
4408 	}
4409 }
4410 
4411 /*
4412  * Matches the arguments passed with the values in the ire.
4413  *
4414  * Note: for match types that match using "ipif" passed in, ipif
4415  * must be checked for non-NULL before calling this routine.
4416  */
4417 static boolean_t
4418 ire_match_args(ire_t *ire, ipaddr_t addr, ipaddr_t mask, ipaddr_t gateway,
4419     int type, const ipif_t *ipif, zoneid_t zoneid, uint32_t ihandle,
4420     const ts_label_t *tsl, int match_flags)
4421 {
4422 	ill_t *ire_ill = NULL, *dst_ill;
4423 	ill_t *ipif_ill = NULL;
4424 	ill_group_t *ire_ill_group = NULL;
4425 	ill_group_t *ipif_ill_group = NULL;
4426 
4427 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
4428 	ASSERT((ire->ire_addr & ~ire->ire_mask) == 0);
4429 	ASSERT((!(match_flags & (MATCH_IRE_ILL|MATCH_IRE_ILL_GROUP))) ||
4430 	    (ipif != NULL && !ipif->ipif_isv6));
4431 	ASSERT(!(match_flags & MATCH_IRE_WQ));
4432 
4433 	/*
4434 	 * HIDDEN cache entries have to be looked up specifically with
4435 	 * MATCH_IRE_MARK_HIDDEN. MATCH_IRE_MARK_HIDDEN is usually set
4436 	 * when the interface is FAILED or INACTIVE. In that case,
4437 	 * any IRE_CACHES that exists should be marked with
4438 	 * IRE_MARK_HIDDEN. So, we don't really need to match below
4439 	 * for IRE_MARK_HIDDEN. But we do so for consistency.
4440 	 */
4441 	if (!(match_flags & MATCH_IRE_MARK_HIDDEN) &&
4442 	    (ire->ire_marks & IRE_MARK_HIDDEN))
4443 		return (B_FALSE);
4444 
4445 	/*
4446 	 * MATCH_IRE_MARK_PRIVATE_ADDR is set when IP_NEXTHOP option
4447 	 * is used. In that case the routing table is bypassed and the
4448 	 * packets are sent directly to the specified nexthop. The
4449 	 * IRE_CACHE entry representing this route should be marked
4450 	 * with IRE_MARK_PRIVATE_ADDR.
4451 	 */
4452 
4453 	if (!(match_flags & MATCH_IRE_MARK_PRIVATE_ADDR) &&
4454 	    (ire->ire_marks & IRE_MARK_PRIVATE_ADDR))
4455 		return (B_FALSE);
4456 
4457 	if (zoneid != ALL_ZONES && zoneid != ire->ire_zoneid &&
4458 	    ire->ire_zoneid != ALL_ZONES) {
4459 		/*
4460 		 * If MATCH_IRE_ZONEONLY has been set and the supplied zoneid is
4461 		 * valid and does not match that of ire_zoneid, a failure to
4462 		 * match is reported at this point. Otherwise, since some IREs
4463 		 * that are available in the global zone can be used in local
4464 		 * zones, additional checks need to be performed:
4465 		 *
4466 		 *	IRE_BROADCAST, IRE_CACHE and IRE_LOOPBACK
4467 		 *	entries should never be matched in this situation.
4468 		 *
4469 		 *	IRE entries that have an interface associated with them
4470 		 *	should in general not match unless they are an IRE_LOCAL
4471 		 *	or in the case when MATCH_IRE_DEFAULT has been set in
4472 		 *	the caller.  In the case of the former, checking of the
4473 		 *	other fields supplied should take place.
4474 		 *
4475 		 *	In the case where MATCH_IRE_DEFAULT has been set,
4476 		 *	all of the ipif's associated with the IRE's ill are
4477 		 *	checked to see if there is a matching zoneid.  If any
4478 		 *	one ipif has a matching zoneid, this IRE is a
4479 		 *	potential candidate so checking of the other fields
4480 		 *	takes place.
4481 		 *
4482 		 *	In the case where the IRE_INTERFACE has a usable source
4483 		 *	address (indicated by ill_usesrc_ifindex) in the
4484 		 *	correct zone then it's permitted to return this IRE
4485 		 */
4486 		if (match_flags & MATCH_IRE_ZONEONLY)
4487 			return (B_FALSE);
4488 		if (ire->ire_type & (IRE_BROADCAST | IRE_CACHE | IRE_LOOPBACK))
4489 			return (B_FALSE);
4490 		/*
4491 		 * Note, IRE_INTERFACE can have the stq as NULL. For
4492 		 * example, if the default multicast route is tied to
4493 		 * the loopback address.
4494 		 */
4495 		if ((ire->ire_type & IRE_INTERFACE) &&
4496 		    (ire->ire_stq != NULL)) {
4497 			dst_ill = (ill_t *)ire->ire_stq->q_ptr;
4498 			/*
4499 			 * If there is a usable source address in the
4500 			 * zone, then it's ok to return an
4501 			 * IRE_INTERFACE
4502 			 */
4503 			if (ipif_usesrc_avail(dst_ill, zoneid)) {
4504 				ip3dbg(("ire_match_args: dst_ill %p match %d\n",
4505 				    (void *)dst_ill,
4506 				    (ire->ire_addr == (addr & mask))));
4507 			} else {
4508 				ip3dbg(("ire_match_args: src_ipif NULL"
4509 				    " dst_ill %p\n", (void *)dst_ill));
4510 				return (B_FALSE);
4511 			}
4512 		}
4513 		if (ire->ire_ipif != NULL && ire->ire_type != IRE_LOCAL &&
4514 		    !(ire->ire_type & IRE_INTERFACE)) {
4515 			ipif_t	*tipif;
4516 
4517 			if ((match_flags & MATCH_IRE_DEFAULT) == 0) {
4518 				return (B_FALSE);
4519 			}
4520 			mutex_enter(&ire->ire_ipif->ipif_ill->ill_lock);
4521 			for (tipif = ire->ire_ipif->ipif_ill->ill_ipif;
4522 			    tipif != NULL; tipif = tipif->ipif_next) {
4523 				if (IPIF_CAN_LOOKUP(tipif) &&
4524 				    (tipif->ipif_flags & IPIF_UP) &&
4525 				    (tipif->ipif_zoneid == zoneid ||
4526 				    tipif->ipif_zoneid == ALL_ZONES))
4527 					break;
4528 			}
4529 			mutex_exit(&ire->ire_ipif->ipif_ill->ill_lock);
4530 			if (tipif == NULL) {
4531 				return (B_FALSE);
4532 			}
4533 		}
4534 	}
4535 
4536 	/*
4537 	 * For IRE_CACHES, MATCH_IRE_ILL/ILL_GROUP really means that
4538 	 * somebody wants to send out on a particular interface which
4539 	 * is given by ire_stq and hence use ire_stq to derive the ill
4540 	 * value. ire_ipif for IRE_CACHES is just the means of getting
4541 	 * a source address i.e ire_src_addr = ire->ire_ipif->ipif_src_addr.
4542 	 * ire_to_ill does the right thing for this.
4543 	 */
4544 	if (match_flags & (MATCH_IRE_ILL|MATCH_IRE_ILL_GROUP)) {
4545 		ire_ill = ire_to_ill(ire);
4546 		if (ire_ill != NULL)
4547 			ire_ill_group = ire_ill->ill_group;
4548 		ipif_ill = ipif->ipif_ill;
4549 		ipif_ill_group = ipif_ill->ill_group;
4550 	}
4551 
4552 	if ((ire->ire_addr == (addr & mask)) &&
4553 	    ((!(match_flags & MATCH_IRE_GW)) ||
4554 		(ire->ire_gateway_addr == gateway)) &&
4555 	    ((!(match_flags & MATCH_IRE_TYPE)) ||
4556 		(ire->ire_type & type)) &&
4557 	    ((!(match_flags & MATCH_IRE_SRC)) ||
4558 		(ire->ire_src_addr == ipif->ipif_src_addr)) &&
4559 	    ((!(match_flags & MATCH_IRE_IPIF)) ||
4560 		(ire->ire_ipif == ipif)) &&
4561 	    ((!(match_flags & MATCH_IRE_MARK_HIDDEN)) ||
4562 		(ire->ire_type != IRE_CACHE ||
4563 		ire->ire_marks & IRE_MARK_HIDDEN)) &&
4564 	    ((!(match_flags & MATCH_IRE_MARK_PRIVATE_ADDR)) ||
4565 		(ire->ire_type != IRE_CACHE ||
4566 		ire->ire_marks & IRE_MARK_PRIVATE_ADDR)) &&
4567 	    ((!(match_flags & MATCH_IRE_ILL)) ||
4568 		(ire_ill == ipif_ill)) &&
4569 	    ((!(match_flags & MATCH_IRE_IHANDLE)) ||
4570 		(ire->ire_ihandle == ihandle)) &&
4571 	    ((!(match_flags & MATCH_IRE_ILL_GROUP)) ||
4572 		(ire_ill == ipif_ill) ||
4573 		(ire_ill_group != NULL &&
4574 		ire_ill_group == ipif_ill_group)) &&
4575 	    ((!(match_flags & MATCH_IRE_SECATTR)) ||
4576 		(!is_system_labeled()) ||
4577 		(tsol_ire_match_gwattr(ire, tsl) == 0))) {
4578 		/* We found the matched IRE */
4579 		return (B_TRUE);
4580 	}
4581 	return (B_FALSE);
4582 }
4583 
4584 
4585 /*
4586  * Lookup for a route in all the tables
4587  */
4588 ire_t *
4589 ire_route_lookup(ipaddr_t addr, ipaddr_t mask, ipaddr_t gateway,
4590     int type, const ipif_t *ipif, ire_t **pire, zoneid_t zoneid,
4591     const ts_label_t *tsl, int flags)
4592 {
4593 	ire_t *ire = NULL;
4594 
4595 	/*
4596 	 * ire_match_args() will dereference ipif MATCH_IRE_SRC or
4597 	 * MATCH_IRE_ILL is set.
4598 	 */
4599 	if ((flags & (MATCH_IRE_SRC | MATCH_IRE_ILL | MATCH_IRE_ILL_GROUP)) &&
4600 	    (ipif == NULL))
4601 		return (NULL);
4602 
4603 	/*
4604 	 * might be asking for a cache lookup,
4605 	 * This is not best way to lookup cache,
4606 	 * user should call ire_cache_lookup directly.
4607 	 *
4608 	 * If MATCH_IRE_TYPE was set, first lookup in the cache table and then
4609 	 * in the forwarding table, if the applicable type flags were set.
4610 	 */
4611 	if ((flags & MATCH_IRE_TYPE) == 0 || (type & IRE_CACHETABLE) != 0) {
4612 		ire = ire_ctable_lookup(addr, gateway, type, ipif, zoneid,
4613 		    tsl, flags);
4614 		if (ire != NULL)
4615 			return (ire);
4616 	}
4617 	if ((flags & MATCH_IRE_TYPE) == 0 || (type & IRE_FORWARDTABLE) != 0) {
4618 		ire = ire_ftable_lookup(addr, mask, gateway, type, ipif, pire,
4619 		    zoneid, 0, tsl, flags);
4620 	}
4621 	return (ire);
4622 }
4623 
4624 /*
4625  * Lookup a route in forwarding table.
4626  * specific lookup is indicated by passing the
4627  * required parameters and indicating the
4628  * match required in flag field.
4629  *
4630  * Looking for default route can be done in three ways
4631  * 1) pass mask as 0 and set MATCH_IRE_MASK in flags field
4632  *    along with other matches.
4633  * 2) pass type as IRE_DEFAULT and set MATCH_IRE_TYPE in flags
4634  *    field along with other matches.
4635  * 3) if the destination and mask are passed as zeros.
4636  *
4637  * A request to return a default route if no route
4638  * is found, can be specified by setting MATCH_IRE_DEFAULT
4639  * in flags.
4640  *
4641  * It does not support recursion more than one level. It
4642  * will do recursive lookup only when the lookup maps to
4643  * a prefix or default route and MATCH_IRE_RECURSIVE flag is passed.
4644  *
4645  * If the routing table is setup to allow more than one level
4646  * of recursion, the cleaning up cache table will not work resulting
4647  * in invalid routing.
4648  *
4649  * Supports IP_BOUND_IF by following the ipif/ill when recursing.
4650  *
4651  * NOTE : When this function returns NULL, pire has already been released.
4652  *	  pire is valid only when this function successfully returns an
4653  *	  ire.
4654  */
4655 ire_t *
4656 ire_ftable_lookup(ipaddr_t addr, ipaddr_t mask, ipaddr_t gateway,
4657     int type, const ipif_t *ipif, ire_t **pire, zoneid_t zoneid,
4658     uint32_t ihandle, const ts_label_t *tsl, int flags)
4659 {
4660 	irb_t *irb_ptr;
4661 	ire_t *ire = NULL;
4662 	int i;
4663 	ipaddr_t gw_addr;
4664 
4665 	ASSERT(ipif == NULL || !ipif->ipif_isv6);
4666 	ASSERT(!(flags & MATCH_IRE_WQ));
4667 
4668 	/*
4669 	 * When we return NULL from this function, we should make
4670 	 * sure that *pire is NULL so that the callers will not
4671 	 * wrongly REFRELE the pire.
4672 	 */
4673 	if (pire != NULL)
4674 		*pire = NULL;
4675 	/*
4676 	 * ire_match_args() will dereference ipif MATCH_IRE_SRC or
4677 	 * MATCH_IRE_ILL is set.
4678 	 */
4679 	if ((flags & (MATCH_IRE_SRC | MATCH_IRE_ILL | MATCH_IRE_ILL_GROUP)) &&
4680 	    (ipif == NULL))
4681 		return (NULL);
4682 
4683 	/*
4684 	 * If the mask is known, the lookup
4685 	 * is simple, if the mask is not known
4686 	 * we need to search.
4687 	 */
4688 	if (flags & MATCH_IRE_MASK) {
4689 		uint_t masklen;
4690 
4691 		masklen = ip_mask_to_plen(mask);
4692 		if (ip_forwarding_table[masklen] == NULL)
4693 			return (NULL);
4694 		irb_ptr = &(ip_forwarding_table[masklen][
4695 		    IRE_ADDR_HASH(addr & mask, ip_ftable_hash_size)]);
4696 		rw_enter(&irb_ptr->irb_lock, RW_READER);
4697 		for (ire = irb_ptr->irb_ire; ire != NULL;
4698 		    ire = ire->ire_next) {
4699 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
4700 				continue;
4701 			if (ire_match_args(ire, addr, mask, gateway, type, ipif,
4702 			    zoneid, ihandle, tsl, flags))
4703 				goto found_ire;
4704 		}
4705 		rw_exit(&irb_ptr->irb_lock);
4706 	} else {
4707 		/*
4708 		 * In this case we don't know the mask, we need to
4709 		 * search the table assuming different mask sizes.
4710 		 * we start with 32 bit mask, we don't allow default here.
4711 		 */
4712 		for (i = (IP_MASK_TABLE_SIZE - 1); i > 0; i--) {
4713 			ipaddr_t tmpmask;
4714 
4715 			if ((ip_forwarding_table[i]) == NULL)
4716 				continue;
4717 			tmpmask = ip_plen_to_mask(i);
4718 			irb_ptr = &ip_forwarding_table[i][
4719 			    IRE_ADDR_HASH(addr & tmpmask,
4720 			    ip_ftable_hash_size)];
4721 			rw_enter(&irb_ptr->irb_lock, RW_READER);
4722 			for (ire = irb_ptr->irb_ire; ire != NULL;
4723 			    ire = ire->ire_next) {
4724 				if (ire->ire_marks & IRE_MARK_CONDEMNED)
4725 					continue;
4726 				if (ire_match_args(ire, addr, ire->ire_mask,
4727 				    gateway, type, ipif, zoneid, ihandle,
4728 				    tsl, flags))
4729 					goto found_ire;
4730 			}
4731 			rw_exit(&irb_ptr->irb_lock);
4732 		}
4733 	}
4734 	/*
4735 	 * We come here if no route has yet been found.
4736 	 *
4737 	 * Handle the case where default route is
4738 	 * requested by specifying type as one of the possible
4739 	 * types for that can have a zero mask (IRE_DEFAULT and IRE_INTERFACE).
4740 	 *
4741 	 * If MATCH_IRE_MASK is specified, then the appropriate default route
4742 	 * would have been found above if it exists so it isn't looked up here.
4743 	 * If MATCH_IRE_DEFAULT was also specified, then a default route will be
4744 	 * searched for later.
4745 	 */
4746 	if ((flags & (MATCH_IRE_TYPE | MATCH_IRE_MASK)) == MATCH_IRE_TYPE &&
4747 	    (type & (IRE_DEFAULT | IRE_INTERFACE))) {
4748 		if ((ip_forwarding_table[0])) {
4749 			/* addr & mask is zero for defaults */
4750 			irb_ptr = &ip_forwarding_table[0][
4751 			    IRE_ADDR_HASH(0, ip_ftable_hash_size)];
4752 			rw_enter(&irb_ptr->irb_lock, RW_READER);
4753 			for (ire = irb_ptr->irb_ire; ire != NULL;
4754 			    ire = ire->ire_next) {
4755 				if (ire->ire_marks & IRE_MARK_CONDEMNED)
4756 					continue;
4757 				if (ire_match_args(ire, addr, (ipaddr_t)0,
4758 				    gateway, type, ipif, zoneid, ihandle,
4759 				    tsl, flags))
4760 					goto found_ire;
4761 			}
4762 			rw_exit(&irb_ptr->irb_lock);
4763 		}
4764 	}
4765 	/*
4766 	 * we come here only if no route is found.
4767 	 * see if the default route can be used which is allowed
4768 	 * only if the default matching criteria is specified.
4769 	 * The ip_ire_default_count tracks the number of IRE_DEFAULT
4770 	 * entries. However, the ip_forwarding_table[0] also contains
4771 	 * interface routes thus the count can be zero.
4772 	 */
4773 	if ((flags & (MATCH_IRE_DEFAULT | MATCH_IRE_MASK)) ==
4774 	    MATCH_IRE_DEFAULT) {
4775 		ire_t	*ire_origin;
4776 		uint_t  g_index;
4777 		uint_t	index;
4778 
4779 		if (ip_forwarding_table[0] == NULL)
4780 			return (NULL);
4781 		irb_ptr = &(ip_forwarding_table[0])[0];
4782 
4783 		/*
4784 		 * Keep a tab on the bucket while looking the IRE_DEFAULT
4785 		 * entries. We need to keep track of a particular IRE
4786 		 * (ire_origin) so this ensures that it will not be unlinked
4787 		 * from the hash list during the recursive lookup below.
4788 		 */
4789 		IRB_REFHOLD(irb_ptr);
4790 		ire = irb_ptr->irb_ire;
4791 		if (ire == NULL) {
4792 			IRB_REFRELE(irb_ptr);
4793 			return (NULL);
4794 		}
4795 
4796 		/*
4797 		 * Get the index first, since it can be changed by other
4798 		 * threads. Then get to the right default route skipping
4799 		 * default interface routes if any. As we hold a reference on
4800 		 * the IRE bucket, ip_ire_default_count can only increase so we
4801 		 * can't reach the end of the hash list unexpectedly.
4802 		 */
4803 		if (ip_ire_default_count != 0) {
4804 			g_index = ip_ire_default_index++;
4805 			index = g_index % ip_ire_default_count;
4806 			while (index != 0) {
4807 				if (!(ire->ire_type & IRE_INTERFACE))
4808 					index--;
4809 				ire = ire->ire_next;
4810 			}
4811 			ASSERT(ire != NULL);
4812 		} else {
4813 			/*
4814 			 * No default routes, so we only have default interface
4815 			 * routes: don't enter the first loop.
4816 			 */
4817 			ire = NULL;
4818 		}
4819 
4820 		/*
4821 		 * Round-robin the default routers list looking for a route that
4822 		 * matches the passed in parameters. If we can't find a default
4823 		 * route (IRE_DEFAULT), look for interface default routes.
4824 		 * We start with the ire we found above and we walk the hash
4825 		 * list until we're back where we started, see
4826 		 * ire_get_next_default_ire(). It doesn't matter if default
4827 		 * routes are added or deleted by other threads - we know this
4828 		 * ire will stay in the list because we hold a reference on the
4829 		 * ire bucket.
4830 		 * NB: if we only have interface default routes, ire is NULL so
4831 		 * we don't even enter this loop (see above).
4832 		 */
4833 		ire_origin = ire;
4834 		for (; ire != NULL;
4835 		    ire = ire_get_next_default_ire(ire, ire_origin)) {
4836 
4837 			if (ire_match_args(ire, addr, (ipaddr_t)0,
4838 			    gateway, type, ipif, zoneid, ihandle, tsl, flags)) {
4839 				int match_flags = 0;
4840 				ire_t *rire;
4841 
4842 				/*
4843 				 * The potentially expensive call to
4844 				 * ire_route_lookup() is avoided when we have
4845 				 * only one default route.
4846 				 */
4847 				if (ip_ire_default_count == 1 ||
4848 				    zoneid == ALL_ZONES) {
4849 					IRE_REFHOLD(ire);
4850 					IRB_REFRELE(irb_ptr);
4851 					goto found_ire_held;
4852 				}
4853 				/*
4854 				 * When we're in a local zone, we're only
4855 				 * interested in default routers that are
4856 				 * reachable through ipifs within our zone.
4857 				 */
4858 				if (ire->ire_ipif != NULL) {
4859 					match_flags |= MATCH_IRE_ILL_GROUP;
4860 				}
4861 				rire = ire_route_lookup(ire->ire_gateway_addr,
4862 				    0, 0, 0, ire->ire_ipif, NULL, zoneid, tsl,
4863 				    match_flags);
4864 				if (rire != NULL) {
4865 					ire_refrele(rire);
4866 					IRE_REFHOLD(ire);
4867 					IRB_REFRELE(irb_ptr);
4868 					goto found_ire_held;
4869 				}
4870 			}
4871 		}
4872 		/*
4873 		 * Either there are no default routes or we could not
4874 		 * find a default route. Look for a interface default
4875 		 * route matching the args passed in. No round robin
4876 		 * here. Just pick the right one.
4877 		 */
4878 		for (ire = irb_ptr->irb_ire; ire != NULL;
4879 		    ire = ire->ire_next) {
4880 
4881 			if (!(ire->ire_type & IRE_INTERFACE))
4882 				continue;
4883 
4884 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
4885 				continue;
4886 
4887 			if (ire_match_args(ire, addr, (ipaddr_t)0,
4888 			    gateway, type, ipif, zoneid, ihandle, tsl,
4889 			    flags)) {
4890 				IRE_REFHOLD(ire);
4891 				IRB_REFRELE(irb_ptr);
4892 				goto found_ire_held;
4893 			}
4894 		}
4895 		IRB_REFRELE(irb_ptr);
4896 	}
4897 	ASSERT(ire == NULL);
4898 	return (NULL);
4899 found_ire:
4900 	ASSERT((ire->ire_marks & IRE_MARK_CONDEMNED) == 0);
4901 	IRE_REFHOLD(ire);
4902 	rw_exit(&irb_ptr->irb_lock);
4903 
4904 found_ire_held:
4905 	ASSERT(ire->ire_type != IRE_MIPRTUN && ire->ire_in_ill == NULL);
4906 	if ((flags & MATCH_IRE_RJ_BHOLE) &&
4907 	    (ire->ire_flags & (RTF_BLACKHOLE | RTF_REJECT))) {
4908 		return (ire);
4909 	}
4910 	/*
4911 	 * At this point, IRE that was found must be an IRE_FORWARDTABLE
4912 	 * type.  If this is a recursive lookup and an IRE_INTERFACE type was
4913 	 * found, return that.  If it was some other IRE_FORWARDTABLE type of
4914 	 * IRE (one of the prefix types), then it is necessary to fill in the
4915 	 * parent IRE pointed to by pire, and then lookup the gateway address of
4916 	 * the parent.  For backwards compatiblity, if this lookup returns an
4917 	 * IRE other than a IRE_CACHETABLE or IRE_INTERFACE, then one more level
4918 	 * of lookup is done.
4919 	 */
4920 	if (flags & MATCH_IRE_RECURSIVE) {
4921 		const ipif_t *gw_ipif;
4922 		int match_flags = MATCH_IRE_DSTONLY;
4923 		ire_t *save_ire;
4924 
4925 		if (ire->ire_type & IRE_INTERFACE)
4926 			return (ire);
4927 		if (pire != NULL)
4928 			*pire = ire;
4929 		/*
4930 		 * If we can't find an IRE_INTERFACE or the caller has not
4931 		 * asked for pire, we need to REFRELE the save_ire.
4932 		 */
4933 		save_ire = ire;
4934 
4935 		/*
4936 		 * Currently MATCH_IRE_ILL is never used with
4937 		 * (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT) while
4938 		 * sending out packets as MATCH_IRE_ILL is used only
4939 		 * for communicating with on-link hosts. We can't assert
4940 		 * that here as RTM_GET calls this function with
4941 		 * MATCH_IRE_ILL | MATCH_IRE_DEFAULT | MATCH_IRE_RECURSIVE.
4942 		 * We have already used the MATCH_IRE_ILL in determining
4943 		 * the right prefix route at this point. To match the
4944 		 * behavior of how we locate routes while sending out
4945 		 * packets, we don't want to use MATCH_IRE_ILL below
4946 		 * while locating the interface route.
4947 		 */
4948 		if (ire->ire_ipif != NULL)
4949 			match_flags |= MATCH_IRE_ILL_GROUP;
4950 
4951 		ire = ire_route_lookup(ire->ire_gateway_addr, 0, 0, 0,
4952 		    ire->ire_ipif, NULL, zoneid, tsl, match_flags);
4953 		if (ire == NULL) {
4954 			/*
4955 			 * Do not release the parent ire if MATCH_IRE_PARENT
4956 			 * is set. Also return it via ire.
4957 			 */
4958 			if (flags & MATCH_IRE_PARENT) {
4959 				if (pire != NULL) {
4960 					/*
4961 					 * Need an extra REFHOLD, if the parent
4962 					 * ire is returned via both ire and
4963 					 * pire.
4964 					 */
4965 					IRE_REFHOLD(save_ire);
4966 				}
4967 				ire = save_ire;
4968 			} else {
4969 				ire_refrele(save_ire);
4970 				if (pire != NULL)
4971 					*pire = NULL;
4972 			}
4973 			return (ire);
4974 		}
4975 		if (ire->ire_type & (IRE_CACHETABLE | IRE_INTERFACE)) {
4976 			/*
4977 			 * If the caller did not ask for pire, release
4978 			 * it now.
4979 			 */
4980 			if (pire == NULL) {
4981 				ire_refrele(save_ire);
4982 			}
4983 			return (ire);
4984 		}
4985 		match_flags |= MATCH_IRE_TYPE;
4986 		gw_addr = ire->ire_gateway_addr;
4987 		gw_ipif = ire->ire_ipif;
4988 		ire_refrele(ire);
4989 		ire = ire_route_lookup(gw_addr, 0, 0,
4990 		    (IRE_CACHETABLE | IRE_INTERFACE), gw_ipif, NULL, zoneid,
4991 		    tsl, match_flags);
4992 		if (ire == NULL) {
4993 			/*
4994 			 * Do not release the parent ire if MATCH_IRE_PARENT
4995 			 * is set. Also return it via ire.
4996 			 */
4997 			if (flags & MATCH_IRE_PARENT) {
4998 				if (pire != NULL) {
4999 					/*
5000 					 * Need an extra REFHOLD, if the
5001 					 * parent ire is returned via both
5002 					 * ire and pire.
5003 					 */
5004 					IRE_REFHOLD(save_ire);
5005 				}
5006 				ire = save_ire;
5007 			} else {
5008 				ire_refrele(save_ire);
5009 				if (pire != NULL)
5010 					*pire = NULL;
5011 			}
5012 			return (ire);
5013 		} else if (pire == NULL) {
5014 			/*
5015 			 * If the caller did not ask for pire, release
5016 			 * it now.
5017 			 */
5018 			ire_refrele(save_ire);
5019 		}
5020 		return (ire);
5021 	}
5022 	ASSERT(pire == NULL || *pire == NULL);
5023 	return (ire);
5024 }
5025 
5026 /*
5027  * Delete the IRE cache for the gateway and all IRE caches whose
5028  * ire_gateway_addr points to this gateway, and allow them to
5029  * be created on demand by ip_newroute.
5030  */
5031 void
5032 ire_clookup_delete_cache_gw(ipaddr_t addr, zoneid_t zoneid)
5033 {
5034 	irb_t *irb;
5035 	ire_t *ire;
5036 
5037 	irb = &ip_cache_table[IRE_ADDR_HASH(addr, ip_cache_table_size)];
5038 	IRB_REFHOLD(irb);
5039 	for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
5040 		if (ire->ire_marks & IRE_MARK_CONDEMNED)
5041 			continue;
5042 
5043 		ASSERT(ire->ire_mask == IP_HOST_MASK);
5044 		ASSERT(ire->ire_type != IRE_MIPRTUN && ire->ire_in_ill == NULL);
5045 		if (ire_match_args(ire, addr, ire->ire_mask, 0, IRE_CACHE,
5046 		    NULL, zoneid, 0, NULL, MATCH_IRE_TYPE)) {
5047 			ire_delete(ire);
5048 		}
5049 	}
5050 	IRB_REFRELE(irb);
5051 
5052 	ire_walk_v4(ire_delete_cache_gw, &addr, zoneid);
5053 }
5054 
5055 /*
5056  * Looks up cache table for a route.
5057  * specific lookup can be indicated by
5058  * passing the MATCH_* flags and the
5059  * necessary parameters.
5060  */
5061 ire_t *
5062 ire_ctable_lookup(ipaddr_t addr, ipaddr_t gateway, int type, const ipif_t *ipif,
5063     zoneid_t zoneid, const ts_label_t *tsl, int flags)
5064 {
5065 	irb_t *irb_ptr;
5066 	ire_t *ire;
5067 
5068 	/*
5069 	 * ire_match_args() will dereference ipif MATCH_IRE_SRC or
5070 	 * MATCH_IRE_ILL is set.
5071 	 */
5072 	if ((flags & (MATCH_IRE_SRC | MATCH_IRE_ILL | MATCH_IRE_ILL_GROUP)) &&
5073 	    (ipif == NULL))
5074 		return (NULL);
5075 
5076 	irb_ptr = &ip_cache_table[IRE_ADDR_HASH(addr, ip_cache_table_size)];
5077 	rw_enter(&irb_ptr->irb_lock, RW_READER);
5078 	for (ire = irb_ptr->irb_ire; ire != NULL; ire = ire->ire_next) {
5079 		if (ire->ire_marks & IRE_MARK_CONDEMNED)
5080 			continue;
5081 		ASSERT(ire->ire_mask == IP_HOST_MASK);
5082 		ASSERT(ire->ire_type != IRE_MIPRTUN && ire->ire_in_ill == NULL);
5083 		if (ire_match_args(ire, addr, ire->ire_mask, gateway, type,
5084 		    ipif, zoneid, 0, tsl, flags)) {
5085 			IRE_REFHOLD(ire);
5086 			rw_exit(&irb_ptr->irb_lock);
5087 			return (ire);
5088 		}
5089 	}
5090 	rw_exit(&irb_ptr->irb_lock);
5091 	return (NULL);
5092 }
5093 
5094 /*
5095  * Lookup cache. Don't return IRE_MARK_HIDDEN entries. Callers
5096  * should use ire_ctable_lookup with MATCH_IRE_MARK_HIDDEN to get
5097  * to the hidden ones.
5098  */
5099 ire_t *
5100 ire_cache_lookup(ipaddr_t addr, zoneid_t zoneid, const ts_label_t *tsl)
5101 {
5102 	irb_t *irb_ptr;
5103 	ire_t *ire;
5104 
5105 	irb_ptr = &ip_cache_table[IRE_ADDR_HASH(addr, ip_cache_table_size)];
5106 	rw_enter(&irb_ptr->irb_lock, RW_READER);
5107 	for (ire = irb_ptr->irb_ire; ire != NULL; ire = ire->ire_next) {
5108 		if (ire->ire_marks & (IRE_MARK_CONDEMNED |
5109 		    IRE_MARK_HIDDEN | IRE_MARK_PRIVATE_ADDR)) {
5110 			continue;
5111 		}
5112 		if (ire->ire_addr == addr) {
5113 			/*
5114 			 * Finally, check if the security policy has any
5115 			 * restriction on using this route for the specified
5116 			 * message.
5117 			 */
5118 			if (tsl != NULL &&
5119 			    ire->ire_gw_secattr != NULL &&
5120 			    tsol_ire_match_gwattr(ire, tsl) != 0) {
5121 				continue;
5122 			}
5123 
5124 			if (zoneid == ALL_ZONES || ire->ire_zoneid == zoneid ||
5125 			    ire->ire_zoneid == ALL_ZONES ||
5126 			    ire->ire_type == IRE_LOCAL) {
5127 				IRE_REFHOLD(ire);
5128 				rw_exit(&irb_ptr->irb_lock);
5129 				return (ire);
5130 			}
5131 		}
5132 	}
5133 	rw_exit(&irb_ptr->irb_lock);
5134 	return (NULL);
5135 }
5136 
5137 /*
5138  * Locate the interface ire that is tied to the cache ire 'cire' via
5139  * cire->ire_ihandle.
5140  *
5141  * We are trying to create the cache ire for an offlink destn based
5142  * on the cache ire of the gateway in 'cire'. 'pire' is the prefix ire
5143  * as found by ip_newroute(). We are called from ip_newroute() in
5144  * the IRE_CACHE case.
5145  */
5146 ire_t *
5147 ire_ihandle_lookup_offlink(ire_t *cire, ire_t *pire)
5148 {
5149 	ire_t	*ire;
5150 	int	match_flags;
5151 	ipaddr_t gw_addr;
5152 	ipif_t	*gw_ipif;
5153 
5154 	ASSERT(cire != NULL && pire != NULL);
5155 
5156 	/*
5157 	 * We don't need to specify the zoneid to ire_ftable_lookup() below
5158 	 * because the ihandle refers to an ipif which can be in only one zone.
5159 	 */
5160 	match_flags =  MATCH_IRE_TYPE | MATCH_IRE_IHANDLE | MATCH_IRE_MASK;
5161 	/*
5162 	 * ip_newroute calls ire_ftable_lookup with MATCH_IRE_ILL only
5163 	 * for on-link hosts. We should never be here for onlink.
5164 	 * Thus, use MATCH_IRE_ILL_GROUP.
5165 	 */
5166 	if (pire->ire_ipif != NULL)
5167 		match_flags |= MATCH_IRE_ILL_GROUP;
5168 	/*
5169 	 * We know that the mask of the interface ire equals cire->ire_cmask.
5170 	 * (When ip_newroute() created 'cire' for the gateway it set its
5171 	 * cmask from the interface ire's mask)
5172 	 */
5173 	ire = ire_ftable_lookup(cire->ire_addr, cire->ire_cmask, 0,
5174 	    IRE_INTERFACE, pire->ire_ipif, NULL, ALL_ZONES, cire->ire_ihandle,
5175 	    NULL, match_flags);
5176 	if (ire != NULL)
5177 		return (ire);
5178 	/*
5179 	 * If we didn't find an interface ire above, we can't declare failure.
5180 	 * For backwards compatibility, we need to support prefix routes
5181 	 * pointing to next hop gateways that are not on-link.
5182 	 *
5183 	 * Assume we are trying to ping some offlink destn, and we have the
5184 	 * routing table below.
5185 	 *
5186 	 * Eg.	default	- gw1		<--- pire	(line 1)
5187 	 *	gw1	- gw2				(line 2)
5188 	 *	gw2	- hme0				(line 3)
5189 	 *
5190 	 * If we already have a cache ire for gw1 in 'cire', the
5191 	 * ire_ftable_lookup above would have failed, since there is no
5192 	 * interface ire to reach gw1. We will fallthru below.
5193 	 *
5194 	 * Here we duplicate the steps that ire_ftable_lookup() did in
5195 	 * getting 'cire' from 'pire', in the MATCH_IRE_RECURSIVE case.
5196 	 * The differences are the following
5197 	 * i.   We want the interface ire only, so we call ire_ftable_lookup()
5198 	 *	instead of ire_route_lookup()
5199 	 * ii.  We look for only prefix routes in the 1st call below.
5200 	 * ii.  We want to match on the ihandle in the 2nd call below.
5201 	 */
5202 	match_flags =  MATCH_IRE_TYPE;
5203 	if (pire->ire_ipif != NULL)
5204 		match_flags |= MATCH_IRE_ILL_GROUP;
5205 	ire = ire_ftable_lookup(pire->ire_gateway_addr, 0, 0, IRE_OFFSUBNET,
5206 	    pire->ire_ipif, NULL, ALL_ZONES, 0, NULL, match_flags);
5207 	if (ire == NULL)
5208 		return (NULL);
5209 	/*
5210 	 * At this point 'ire' corresponds to the entry shown in line 2.
5211 	 * gw_addr is 'gw2' in the example above.
5212 	 */
5213 	gw_addr = ire->ire_gateway_addr;
5214 	gw_ipif = ire->ire_ipif;
5215 	ire_refrele(ire);
5216 
5217 	match_flags |= MATCH_IRE_IHANDLE;
5218 	ire = ire_ftable_lookup(gw_addr, 0, 0, IRE_INTERFACE,
5219 	    gw_ipif, NULL, ALL_ZONES, cire->ire_ihandle, NULL, match_flags);
5220 	return (ire);
5221 }
5222 
5223 /*
5224  * Locate the interface ire that is tied to the cache ire 'cire' via
5225  * cire->ire_ihandle.
5226  *
5227  * We are trying to create the cache ire for an onlink destn. or
5228  * gateway in 'cire'. We are called from ire_add_v4() in the IRE_IF_RESOLVER
5229  * case, after the ire has come back from ARP.
5230  */
5231 ire_t *
5232 ire_ihandle_lookup_onlink(ire_t *cire)
5233 {
5234 	ire_t	*ire;
5235 	int	match_flags;
5236 	int	i;
5237 	int	j;
5238 	irb_t	*irb_ptr;
5239 
5240 	ASSERT(cire != NULL);
5241 
5242 	/*
5243 	 * We don't need to specify the zoneid to ire_ftable_lookup() below
5244 	 * because the ihandle refers to an ipif which can be in only one zone.
5245 	 */
5246 	match_flags =  MATCH_IRE_TYPE | MATCH_IRE_IHANDLE | MATCH_IRE_MASK;
5247 	/*
5248 	 * We know that the mask of the interface ire equals cire->ire_cmask.
5249 	 * (When ip_newroute() created 'cire' for an on-link destn. it set its
5250 	 * cmask from the interface ire's mask)
5251 	 */
5252 	ire = ire_ftable_lookup(cire->ire_addr, cire->ire_cmask, 0,
5253 	    IRE_INTERFACE, NULL, NULL, ALL_ZONES, cire->ire_ihandle,
5254 	    NULL, match_flags);
5255 	if (ire != NULL)
5256 		return (ire);
5257 	/*
5258 	 * If we didn't find an interface ire above, we can't declare failure.
5259 	 * For backwards compatibility, we need to support prefix routes
5260 	 * pointing to next hop gateways that are not on-link.
5261 	 *
5262 	 * In the resolver/noresolver case, ip_newroute() thinks it is creating
5263 	 * the cache ire for an onlink destination in 'cire'. But 'cire' is
5264 	 * not actually onlink, because ire_ftable_lookup() cheated it, by
5265 	 * doing ire_route_lookup() twice and returning an interface ire.
5266 	 *
5267 	 * Eg. default	-	gw1			(line 1)
5268 	 *	gw1	-	gw2			(line 2)
5269 	 *	gw2	-	hme0			(line 3)
5270 	 *
5271 	 * In the above example, ip_newroute() tried to create the cache ire
5272 	 * 'cire' for gw1, based on the interface route in line 3. The
5273 	 * ire_ftable_lookup() above fails, because there is no interface route
5274 	 * to reach gw1. (it is gw2). We fall thru below.
5275 	 *
5276 	 * Do a brute force search based on the ihandle in a subset of the
5277 	 * forwarding tables, corresponding to cire->ire_cmask. Otherwise
5278 	 * things become very complex, since we don't have 'pire' in this
5279 	 * case. (Also note that this method is not possible in the offlink
5280 	 * case because we don't know the mask)
5281 	 */
5282 	i = ip_mask_to_plen(cire->ire_cmask);
5283 	if ((ip_forwarding_table[i]) == NULL)
5284 		return (NULL);
5285 	for (j = 0; j < ip_ftable_hash_size; j++) {
5286 		irb_ptr = &ip_forwarding_table[i][j];
5287 		rw_enter(&irb_ptr->irb_lock, RW_READER);
5288 		for (ire = irb_ptr->irb_ire; ire != NULL;
5289 		    ire = ire->ire_next) {
5290 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
5291 				continue;
5292 			if ((ire->ire_type & IRE_INTERFACE) &&
5293 			    (ire->ire_ihandle == cire->ire_ihandle)) {
5294 				IRE_REFHOLD(ire);
5295 				rw_exit(&irb_ptr->irb_lock);
5296 				return (ire);
5297 			}
5298 		}
5299 		rw_exit(&irb_ptr->irb_lock);
5300 	}
5301 	return (NULL);
5302 }
5303 
5304 /*
5305  * ire_mrtun_lookup() is called by ip_rput() when packet is to be
5306  * tunneled through reverse tunnel. This is only supported for
5307  * IPv4 packets
5308  */
5309 
5310 ire_t *
5311 ire_mrtun_lookup(ipaddr_t srcaddr, ill_t *ill)
5312 {
5313 	irb_t *irb_ptr;
5314 	ire_t *ire;
5315 
5316 	ASSERT(ill != NULL);
5317 	ASSERT(!(ill->ill_isv6));
5318 
5319 	if (ip_mrtun_table == NULL)
5320 		return (NULL);
5321 	irb_ptr = &ip_mrtun_table[IRE_ADDR_HASH(srcaddr, IP_MRTUN_TABLE_SIZE)];
5322 	rw_enter(&irb_ptr->irb_lock, RW_READER);
5323 	for (ire = irb_ptr->irb_ire; ire != NULL; ire = ire->ire_next) {
5324 		if (ire->ire_marks & IRE_MARK_CONDEMNED)
5325 			continue;
5326 		if ((ire->ire_in_src_addr == srcaddr) &&
5327 		    ire->ire_in_ill == ill) {
5328 			IRE_REFHOLD(ire);
5329 			rw_exit(&irb_ptr->irb_lock);
5330 			return (ire);
5331 		}
5332 	}
5333 	rw_exit(&irb_ptr->irb_lock);
5334 	return (NULL);
5335 }
5336 
5337 /*
5338  * Return the IRE_LOOPBACK, IRE_IF_RESOLVER or IRE_IF_NORESOLVER
5339  * ire associated with the specified ipif.
5340  *
5341  * This might occasionally be called when IPIF_UP is not set since
5342  * the IP_MULTICAST_IF as well as creating interface routes
5343  * allows specifying a down ipif (ipif_lookup* match ipifs that are down).
5344  *
5345  * Note that if IPIF_NOLOCAL, IPIF_NOXMIT, or IPIF_DEPRECATED is set on
5346  * the ipif, this routine might return NULL.
5347  */
5348 ire_t *
5349 ipif_to_ire(const ipif_t *ipif)
5350 {
5351 	ire_t	*ire;
5352 
5353 	ASSERT(!ipif->ipif_isv6);
5354 	if (ipif->ipif_ire_type == IRE_LOOPBACK) {
5355 		ire = ire_ctable_lookup(ipif->ipif_lcl_addr, 0, IRE_LOOPBACK,
5356 		    ipif, ALL_ZONES, NULL, (MATCH_IRE_TYPE | MATCH_IRE_IPIF));
5357 	} else if (ipif->ipif_flags & IPIF_POINTOPOINT) {
5358 		/* In this case we need to lookup destination address. */
5359 		ire = ire_ftable_lookup(ipif->ipif_pp_dst_addr, IP_HOST_MASK, 0,
5360 		    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0, NULL,
5361 		    (MATCH_IRE_TYPE | MATCH_IRE_IPIF | MATCH_IRE_MASK));
5362 	} else {
5363 		ire = ire_ftable_lookup(ipif->ipif_subnet,
5364 		    ipif->ipif_net_mask, 0, IRE_INTERFACE, ipif, NULL,
5365 		    ALL_ZONES, 0, NULL, (MATCH_IRE_TYPE | MATCH_IRE_IPIF |
5366 		    MATCH_IRE_MASK));
5367 	}
5368 	return (ire);
5369 }
5370 
5371 /*
5372  * ire_walk function.
5373  * Count the number of IRE_CACHE entries in different categories.
5374  */
5375 void
5376 ire_cache_count(ire_t *ire, char *arg)
5377 {
5378 	ire_cache_count_t *icc = (ire_cache_count_t *)arg;
5379 
5380 	if (ire->ire_type != IRE_CACHE)
5381 		return;
5382 
5383 	icc->icc_total++;
5384 
5385 	if (ire->ire_ipversion == IPV6_VERSION) {
5386 		mutex_enter(&ire->ire_lock);
5387 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6)) {
5388 			mutex_exit(&ire->ire_lock);
5389 			icc->icc_onlink++;
5390 			return;
5391 		}
5392 		mutex_exit(&ire->ire_lock);
5393 	} else {
5394 		if (ire->ire_gateway_addr == 0) {
5395 			icc->icc_onlink++;
5396 			return;
5397 		}
5398 	}
5399 
5400 	ASSERT(ire->ire_ipif != NULL);
5401 	if (ire->ire_max_frag < ire->ire_ipif->ipif_mtu)
5402 		icc->icc_pmtu++;
5403 	else if (ire->ire_tire_mark != ire->ire_ob_pkt_count +
5404 	    ire->ire_ib_pkt_count)
5405 		icc->icc_offlink++;
5406 	else
5407 		icc->icc_unused++;
5408 }
5409 
5410 /*
5411  * ire_walk function called by ip_trash_ire_reclaim().
5412  * Free a fraction of the IRE_CACHE cache entries. The fractions are
5413  * different for different categories of IRE_CACHE entries.
5414  * A fraction of zero means to not free any in that category.
5415  * Use the hash bucket id plus lbolt as a random number. Thus if the fraction
5416  * is N then every Nth hash bucket chain will be freed.
5417  */
5418 void
5419 ire_cache_reclaim(ire_t *ire, char *arg)
5420 {
5421 	ire_cache_reclaim_t *icr = (ire_cache_reclaim_t *)arg;
5422 	uint_t rand;
5423 
5424 	if (ire->ire_type != IRE_CACHE)
5425 		return;
5426 
5427 	if (ire->ire_ipversion == IPV6_VERSION) {
5428 		rand = (uint_t)lbolt +
5429 		    IRE_ADDR_HASH_V6(ire->ire_addr_v6, ip6_cache_table_size);
5430 		mutex_enter(&ire->ire_lock);
5431 		if (IN6_IS_ADDR_UNSPECIFIED(&ire->ire_gateway_addr_v6)) {
5432 			mutex_exit(&ire->ire_lock);
5433 			if (icr->icr_onlink != 0 &&
5434 			    (rand/icr->icr_onlink)*icr->icr_onlink == rand) {
5435 				ire_delete(ire);
5436 				return;
5437 			}
5438 			goto done;
5439 		}
5440 		mutex_exit(&ire->ire_lock);
5441 	} else {
5442 		rand = (uint_t)lbolt +
5443 		    IRE_ADDR_HASH(ire->ire_addr, ip_cache_table_size);
5444 		if (ire->ire_gateway_addr == 0) {
5445 			if (icr->icr_onlink != 0 &&
5446 			    (rand/icr->icr_onlink)*icr->icr_onlink == rand) {
5447 				ire_delete(ire);
5448 				return;
5449 			}
5450 			goto done;
5451 		}
5452 	}
5453 	/* Not onlink IRE */
5454 	ASSERT(ire->ire_ipif != NULL);
5455 	if (ire->ire_max_frag < ire->ire_ipif->ipif_mtu) {
5456 		/* Use ptmu fraction */
5457 		if (icr->icr_pmtu != 0 &&
5458 		    (rand/icr->icr_pmtu)*icr->icr_pmtu == rand) {
5459 			ire_delete(ire);
5460 			return;
5461 		}
5462 	} else if (ire->ire_tire_mark != ire->ire_ob_pkt_count +
5463 	    ire->ire_ib_pkt_count) {
5464 		/* Use offlink fraction */
5465 		if (icr->icr_offlink != 0 &&
5466 		    (rand/icr->icr_offlink)*icr->icr_offlink == rand) {
5467 			ire_delete(ire);
5468 			return;
5469 		}
5470 	} else {
5471 		/* Use unused fraction */
5472 		if (icr->icr_unused != 0 &&
5473 		    (rand/icr->icr_unused)*icr->icr_unused == rand) {
5474 			ire_delete(ire);
5475 			return;
5476 		}
5477 	}
5478 done:
5479 	/*
5480 	 * Update tire_mark so that those that haven't been used since this
5481 	 * reclaim will be considered unused next time we reclaim.
5482 	 */
5483 	ire->ire_tire_mark = ire->ire_ob_pkt_count + ire->ire_ib_pkt_count;
5484 }
5485 
5486 static void
5487 power2_roundup(uint32_t *value)
5488 {
5489 	int i;
5490 
5491 	for (i = 1; i < 31; i++) {
5492 		if (*value <= (1 << i))
5493 			break;
5494 	}
5495 	*value = (1 << i);
5496 }
5497 
5498 void
5499 ip_ire_init()
5500 {
5501 	int i;
5502 
5503 	mutex_init(&ire_ft_init_lock, NULL, MUTEX_DEFAULT, 0);
5504 	mutex_init(&ire_handle_lock, NULL, MUTEX_DEFAULT, NULL);
5505 	mutex_init(&ire_mrtun_lock, NULL, MUTEX_DEFAULT, NULL);
5506 	mutex_init(&ire_srcif_table_lock, NULL, MUTEX_DEFAULT, NULL);
5507 
5508 	/* Calculate the IPv4 cache table size. */
5509 	ip_cache_table_size = MAX(ip_cache_table_size,
5510 	    ((kmem_avail() >> ip_ire_mem_ratio) / sizeof (ire_t) /
5511 	    ip_ire_max_bucket_cnt));
5512 	if (ip_cache_table_size > ip_max_cache_table_size)
5513 		ip_cache_table_size = ip_max_cache_table_size;
5514 	/*
5515 	 * Make sure that the table size is always a power of 2.  The
5516 	 * hash macro IRE_ADDR_HASH() depends on that.
5517 	 */
5518 	power2_roundup(&ip_cache_table_size);
5519 
5520 	ip_cache_table = (irb_t *)kmem_zalloc(ip_cache_table_size *
5521 	    sizeof (irb_t), KM_SLEEP);
5522 
5523 	for (i = 0; i < ip_cache_table_size; i++) {
5524 		rw_init(&ip_cache_table[i].irb_lock, NULL,
5525 		    RW_DEFAULT, NULL);
5526 	}
5527 
5528 	/* Calculate the IPv6 cache table size. */
5529 	ip6_cache_table_size = MAX(ip6_cache_table_size,
5530 	    ((kmem_avail() >> ip_ire_mem_ratio) / sizeof (ire_t) /
5531 	    ip6_ire_max_bucket_cnt));
5532 	if (ip6_cache_table_size > ip6_max_cache_table_size)
5533 		ip6_cache_table_size = ip6_max_cache_table_size;
5534 	/*
5535 	 * Make sure that the table size is always a power of 2.  The
5536 	 * hash macro IRE_ADDR_HASH_V6() depends on that.
5537 	 */
5538 	power2_roundup(&ip6_cache_table_size);
5539 
5540 	ip_cache_table_v6 = (irb_t *)kmem_zalloc(ip6_cache_table_size *
5541 	    sizeof (irb_t), KM_SLEEP);
5542 
5543 	for (i = 0; i < ip6_cache_table_size; i++) {
5544 		rw_init(&ip_cache_table_v6[i].irb_lock, NULL,
5545 		    RW_DEFAULT, NULL);
5546 	}
5547 	/*
5548 	 * Create ire caches, ire_reclaim()
5549 	 * will give IRE_CACHE back to system when needed.
5550 	 * This needs to be done here before anything else, since
5551 	 * ire_add() expects the cache to be created.
5552 	 */
5553 	ire_cache = kmem_cache_create("ire_cache",
5554 		sizeof (ire_t), 0, ip_ire_constructor,
5555 		ip_ire_destructor, ip_trash_ire_reclaim, NULL, NULL, 0);
5556 
5557 	/*
5558 	 * Initialize ip_mrtun_table to NULL now, it will be
5559 	 * populated by ip_rt_add if reverse tunnel is created
5560 	 */
5561 	ip_mrtun_table = NULL;
5562 
5563 	/*
5564 	 * Make sure that the forwarding table size is a power of 2.
5565 	 * The IRE*_ADDR_HASH() macroes depend on that.
5566 	 */
5567 	power2_roundup(&ip_ftable_hash_size);
5568 	power2_roundup(&ip6_ftable_hash_size);
5569 }
5570 
5571 void
5572 ip_ire_fini()
5573 {
5574 	int i;
5575 
5576 	mutex_destroy(&ire_ft_init_lock);
5577 	mutex_destroy(&ire_handle_lock);
5578 
5579 	for (i = 0; i < ip_cache_table_size; i++) {
5580 		rw_destroy(&ip_cache_table[i].irb_lock);
5581 	}
5582 	kmem_free(ip_cache_table, ip_cache_table_size * sizeof (irb_t));
5583 
5584 	for (i = 0; i < ip6_cache_table_size; i++) {
5585 		rw_destroy(&ip_cache_table_v6[i].irb_lock);
5586 	}
5587 	kmem_free(ip_cache_table_v6, ip6_cache_table_size * sizeof (irb_t));
5588 
5589 	if (ip_mrtun_table != NULL) {
5590 		for (i = 0; i < IP_MRTUN_TABLE_SIZE; i++) {
5591 			rw_destroy(&ip_mrtun_table[i].irb_lock);
5592 		}
5593 		kmem_free(ip_mrtun_table, IP_MRTUN_TABLE_SIZE * sizeof (irb_t));
5594 	}
5595 	kmem_cache_destroy(ire_cache);
5596 }
5597 
5598 int
5599 ire_add_mrtun(ire_t **ire_p, queue_t *q, mblk_t *mp, ipsq_func_t func)
5600 {
5601 	ire_t   *ire1;
5602 	irb_t	*irb_ptr;
5603 	ire_t	**irep;
5604 	ire_t	*ire;
5605 	int	i;
5606 	uint_t	max_frag;
5607 	ill_t	*stq_ill;
5608 	int error;
5609 
5610 	ire = *ire_p;
5611 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
5612 	/* Is ip_mrtun_table empty ? */
5613 
5614 	if (ip_mrtun_table == NULL) {
5615 		/* create the mrtun table */
5616 		mutex_enter(&ire_mrtun_lock);
5617 		if (ip_mrtun_table == NULL) {
5618 			ip_mrtun_table =
5619 			    (irb_t *)kmem_zalloc(IP_MRTUN_TABLE_SIZE *
5620 			    sizeof (irb_t), KM_NOSLEEP);
5621 
5622 			if (ip_mrtun_table == NULL) {
5623 				ip2dbg(("ire_add_mrtun: allocation failure\n"));
5624 				mutex_exit(&ire_mrtun_lock);
5625 				ire_refrele(ire);
5626 				*ire_p = NULL;
5627 				return (ENOMEM);
5628 			}
5629 
5630 			for (i = 0; i < IP_MRTUN_TABLE_SIZE; i++) {
5631 			    rw_init(&ip_mrtun_table[i].irb_lock, NULL,
5632 				    RW_DEFAULT, NULL);
5633 			}
5634 			ip2dbg(("ire_add_mrtun: mrtun table is created\n"));
5635 		}
5636 		/* some other thread got it and created the table */
5637 		mutex_exit(&ire_mrtun_lock);
5638 	}
5639 
5640 	/*
5641 	 * Check for duplicate in the bucket and insert in the table
5642 	 */
5643 	irb_ptr = &(ip_mrtun_table[IRE_ADDR_HASH(ire->ire_in_src_addr,
5644 	    IP_MRTUN_TABLE_SIZE)]);
5645 
5646 	/*
5647 	 * Start the atomic add of the ire. Grab the ill locks,
5648 	 * ill_g_usesrc_lock and the bucket lock.
5649 	 *
5650 	 * If ipif or ill is changing ire_atomic_start() may queue the
5651 	 * request and return EINPROGRESS.
5652 	 */
5653 	error = ire_atomic_start(irb_ptr, ire, q, mp, func);
5654 	if (error != 0) {
5655 		/*
5656 		 * We don't know whether it is a valid ipif or not.
5657 		 * So, set it to NULL. This assumes that the ire has not added
5658 		 * a reference to the ipif.
5659 		 */
5660 		ire->ire_ipif = NULL;
5661 		ire_delete(ire);
5662 		ip1dbg(("ire_add_mrtun: ire_atomic_start failed\n"));
5663 		*ire_p = NULL;
5664 		return (error);
5665 	}
5666 	for (ire1 = irb_ptr->irb_ire; ire1 != NULL; ire1 = ire1->ire_next) {
5667 		if (ire1->ire_marks & IRE_MARK_CONDEMNED)
5668 			continue;
5669 		/* has anyone inserted the route in the meanwhile ? */
5670 		if (ire1->ire_in_ill == ire->ire_in_ill &&
5671 		    ire1->ire_in_src_addr == ire->ire_in_src_addr) {
5672 			ip1dbg(("ire_add_mrtun: Duplicate entry exists\n"));
5673 			IRE_REFHOLD(ire1);
5674 			ire_atomic_end(irb_ptr, ire);
5675 			ire_delete(ire);
5676 			/* Return the old ire */
5677 			*ire_p = ire1;
5678 			return (0);
5679 		}
5680 	}
5681 
5682 	/* Atomically set the ire_max_frag */
5683 	max_frag = *ire->ire_max_fragp;
5684 	ire->ire_max_fragp = NULL;
5685 	ire->ire_max_frag = MIN(max_frag, IP_MAXPACKET);
5686 
5687 	irep = (ire_t **)irb_ptr;
5688 	if (*irep != NULL) {
5689 		/* Find the last ire which matches ire_in_src_addr */
5690 		ire1 = *irep;
5691 		while (ire1->ire_in_src_addr == ire->ire_in_src_addr) {
5692 			irep = &ire1->ire_next;
5693 			ire1 = *irep;
5694 			if (ire1 == NULL)
5695 				break;
5696 		}
5697 	}
5698 	ire1 = *irep;
5699 	if (ire1 != NULL)
5700 		ire1->ire_ptpn = &ire->ire_next;
5701 	ire->ire_next = ire1;
5702 	/* Link the new one in. */
5703 	ire->ire_ptpn = irep;
5704 	membar_producer();
5705 	*irep = ire;
5706 	ire->ire_bucket = irb_ptr;
5707 	IRE_REFHOLD_LOCKED(ire);
5708 
5709 	ip2dbg(("ire_add_mrtun: created and linked ire %p\n", (void *)*irep));
5710 
5711 	/*
5712 	 * Protect ire_mrtun_count and ill_mrtun_refcnt from
5713 	 * another thread trying to add ire in the table
5714 	 */
5715 	mutex_enter(&ire_mrtun_lock);
5716 	ire_mrtun_count++;
5717 	mutex_exit(&ire_mrtun_lock);
5718 	/*
5719 	 * ill_mrtun_refcnt is protected by the ill_lock held via
5720 	 * ire_atomic_start
5721 	 */
5722 	ire->ire_in_ill->ill_mrtun_refcnt++;
5723 
5724 	if (ire->ire_ipif != NULL) {
5725 		ire->ire_ipif->ipif_ire_cnt++;
5726 		if (ire->ire_stq != NULL) {
5727 			stq_ill = (ill_t *)ire->ire_stq->q_ptr;
5728 			stq_ill->ill_ire_cnt++;
5729 		}
5730 	} else {
5731 		ASSERT(ire->ire_stq == NULL);
5732 	}
5733 
5734 	ire_atomic_end(irb_ptr, ire);
5735 	ire_fastpath(ire);
5736 	*ire_p = ire;
5737 	return (0);
5738 }
5739 
5740 
5741 /* Walks down the mrtun table */
5742 
5743 void
5744 ire_walk_ill_mrtun(uint_t match_flags, uint_t ire_type, pfv_t func, void *arg,
5745     ill_t *ill)
5746 {
5747 	irb_t	*irb;
5748 	ire_t	*ire;
5749 	int	i;
5750 	int	ret;
5751 
5752 	ASSERT((!(match_flags & (MATCH_IRE_WQ | MATCH_IRE_ILL |
5753 	    MATCH_IRE_ILL_GROUP))) || (ill != NULL));
5754 	ASSERT(match_flags == 0 || ire_type == IRE_MIPRTUN);
5755 
5756 	mutex_enter(&ire_mrtun_lock);
5757 	if (ire_mrtun_count == 0) {
5758 		mutex_exit(&ire_mrtun_lock);
5759 		return;
5760 	}
5761 	mutex_exit(&ire_mrtun_lock);
5762 
5763 	ip2dbg(("ire_walk_ill_mrtun:walking the reverse tunnel table \n"));
5764 	for (i = 0; i < IP_MRTUN_TABLE_SIZE; i++) {
5765 
5766 		irb = &(ip_mrtun_table[i]);
5767 		if (irb->irb_ire == NULL)
5768 			continue;
5769 		IRB_REFHOLD(irb);
5770 		for (ire = irb->irb_ire; ire != NULL;
5771 		    ire = ire->ire_next) {
5772 			ASSERT(ire->ire_ipversion == IPV4_VERSION);
5773 			if (match_flags != 0) {
5774 				ret = ire_walk_ill_match(
5775 				    match_flags, ire_type,
5776 				    ire, ill, ALL_ZONES);
5777 			}
5778 			if (match_flags == 0 || ret)
5779 				(*func)(ire, arg);
5780 		}
5781 		IRB_REFRELE(irb);
5782 	}
5783 }
5784 
5785 /*
5786  * Source interface based lookup routine (IPV4 only).
5787  * This routine is called only when RTA_SRCIFP bitflag is set
5788  * by routing socket while adding/deleting the route and it is
5789  * also called from ip_rput() when packets arrive from an interface
5790  * for which ill_srcif_ref_cnt is positive. This function is useful
5791  * when a packet coming from one interface must be forwarded to another
5792  * designated interface to reach the correct node. This function is also
5793  * called from ip_newroute when the link-layer address of an ire is resolved.
5794  * We need to make sure that ip_newroute searches for IRE_IF_RESOLVER type
5795  * ires--thus the ire_type parameter is needed.
5796  */
5797 
5798 ire_t *
5799 ire_srcif_table_lookup(ipaddr_t dst_addr, int ire_type, ipif_t *ipif,
5800     ill_t *in_ill, int flags)
5801 {
5802 	irb_t	*irb_ptr;
5803 	ire_t	*ire;
5804 	irb_t	*ire_srcif_table;
5805 
5806 	ASSERT(in_ill != NULL && !in_ill->ill_isv6);
5807 	ASSERT(!(flags & (MATCH_IRE_ILL|MATCH_IRE_ILL_GROUP)) ||
5808 	    (ipif != NULL && !ipif->ipif_isv6));
5809 
5810 	/*
5811 	 * No need to lock the ill since it is refheld by the caller of this
5812 	 * function
5813 	 */
5814 	if (in_ill->ill_srcif_table == NULL) {
5815 		return (NULL);
5816 	}
5817 
5818 	if (!(flags & MATCH_IRE_TYPE)) {
5819 		flags |= MATCH_IRE_TYPE;
5820 		ire_type = IRE_INTERFACE;
5821 	}
5822 	ire_srcif_table = in_ill->ill_srcif_table;
5823 	irb_ptr = &ire_srcif_table[IRE_ADDR_HASH(dst_addr,
5824 	    IP_SRCIF_TABLE_SIZE)];
5825 	rw_enter(&irb_ptr->irb_lock, RW_READER);
5826 	for (ire = irb_ptr->irb_ire; ire != NULL; ire = ire->ire_next) {
5827 		if (ire->ire_marks & IRE_MARK_CONDEMNED)
5828 			continue;
5829 		if (ire_match_args(ire, dst_addr, ire->ire_mask, 0,
5830 		    ire_type, ipif, ire->ire_zoneid, 0, NULL, flags)) {
5831 			IRE_REFHOLD(ire);
5832 			rw_exit(&irb_ptr->irb_lock);
5833 			return (ire);
5834 		}
5835 	}
5836 	/* Not Found */
5837 	rw_exit(&irb_ptr->irb_lock);
5838 	return (NULL);
5839 }
5840 
5841 
5842 /*
5843  * Adds the ire into the special routing table which is hanging off of
5844  * the src_ipif->ipif_ill. It also increments the refcnt in the ill.
5845  * The forward table contains only IRE_IF_RESOLVER, IRE_IF_NORESOLVER
5846  * i,e. IRE_INTERFACE entries. Originally the dlureq_mp field is NULL
5847  * for IRE_IF_RESOLVER entry because we do not have the dst_addr's
5848  * link-layer address at the time of addition.
5849  * Upon resolving the address from ARP, dlureq_mp field is updated with
5850  * proper information in ire_update_srcif_v4.
5851  */
5852 static int
5853 ire_add_srcif_v4(ire_t **ire_p, queue_t *q, mblk_t *mp, ipsq_func_t func)
5854 {
5855 	ire_t	*ire1;
5856 	irb_t	*ire_srcifp_table = NULL;
5857 	irb_t	*irb_ptr = NULL;
5858 	ire_t   **irep;
5859 	ire_t   *ire;
5860 	int	flags;
5861 	int	i;
5862 	ill_t	*stq_ill;
5863 	uint_t	max_frag;
5864 	int error = 0;
5865 
5866 	ire = *ire_p;
5867 	ASSERT(ire->ire_in_ill != NULL);
5868 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
5869 	ASSERT(ire->ire_type == IRE_IF_NORESOLVER ||
5870 	    ire->ire_type == IRE_IF_RESOLVER);
5871 
5872 	ire->ire_mask = IP_HOST_MASK;
5873 	/* Update ire_dlureq_mp with NULL value upon creation */
5874 	if (ire->ire_type == IRE_IF_RESOLVER) {
5875 		/*
5876 		 * assign NULL now, it will be updated
5877 		 * with correct value upon returning from
5878 		 * ARP
5879 		 */
5880 		ire->ire_dlureq_mp = NULL;
5881 	} else {
5882 		ire->ire_dlureq_mp = ill_dlur_gen(NULL,
5883 		    ire->ire_ipif->ipif_ill->ill_phys_addr_length,
5884 		    ire->ire_ipif->ipif_ill->ill_sap,
5885 		    ire->ire_ipif->ipif_ill->ill_sap_length);
5886 	}
5887 	/* Make sure the address is properly masked. */
5888 	ire->ire_addr &= ire->ire_mask;
5889 
5890 	ASSERT(ire->ire_max_fragp != NULL);
5891 	max_frag = *ire->ire_max_fragp;
5892 	ire->ire_max_fragp = NULL;
5893 	ire->ire_max_frag = MIN(max_frag, IP_MAXPACKET);
5894 
5895 	mutex_enter(&ire->ire_in_ill->ill_lock);
5896 	if (ire->ire_in_ill->ill_srcif_table == NULL) {
5897 		/* create the incoming interface based table */
5898 		ire->ire_in_ill->ill_srcif_table =
5899 		    (irb_t *)kmem_zalloc(IP_SRCIF_TABLE_SIZE *
5900 			sizeof (irb_t), KM_NOSLEEP);
5901 		if (ire->ire_in_ill->ill_srcif_table == NULL) {
5902 			ip1dbg(("ire_add_srcif_v4: Allocation fail\n"));
5903 			mutex_exit(&ire->ire_in_ill->ill_lock);
5904 			ire_delete(ire);
5905 			*ire_p = NULL;
5906 			return (ENOMEM);
5907 		}
5908 		ire_srcifp_table = ire->ire_in_ill->ill_srcif_table;
5909 		for (i = 0; i < IP_SRCIF_TABLE_SIZE; i++) {
5910 			rw_init(&ire_srcifp_table[i].irb_lock, NULL,
5911 			    RW_DEFAULT, NULL);
5912 		}
5913 		ip2dbg(("ire_add_srcif_v4: table created for ill %p\n",
5914 		    (void *)ire->ire_in_ill));
5915 	}
5916 	/* Check for duplicate and insert */
5917 	ASSERT(ire->ire_in_ill->ill_srcif_table != NULL);
5918 	irb_ptr =
5919 	    &(ire->ire_in_ill->ill_srcif_table[IRE_ADDR_HASH(ire->ire_addr,
5920 	    IP_SRCIF_TABLE_SIZE)]);
5921 	mutex_exit(&ire->ire_in_ill->ill_lock);
5922 	flags = (MATCH_IRE_MASK | MATCH_IRE_TYPE | MATCH_IRE_GW);
5923 	flags |= MATCH_IRE_IPIF;
5924 
5925 	/*
5926 	 * Start the atomic add of the ire. Grab the ill locks,
5927 	 * ill_g_usesrc_lock and the bucket lock.
5928 	 *
5929 	 * If ipif or ill is changing ire_atomic_start() may queue the
5930 	 * request and return EINPROGRESS.
5931 	 */
5932 	error = ire_atomic_start(irb_ptr, ire, q, mp, func);
5933 	if (error != 0) {
5934 		/*
5935 		 * We don't know whether it is a valid ipif or not.
5936 		 * So, set it to NULL. This assumes that the ire has not added
5937 		 * a reference to the ipif.
5938 		 */
5939 		ire->ire_ipif = NULL;
5940 		ire_delete(ire);
5941 		ip1dbg(("ire_add_srcif_v4: ire_atomic_start failed\n"));
5942 		*ire_p = NULL;
5943 		return (error);
5944 	}
5945 	for (ire1 = irb_ptr->irb_ire; ire1 != NULL; ire1 = ire1->ire_next) {
5946 		if (ire1->ire_marks & IRE_MARK_CONDEMNED)
5947 			continue;
5948 		if (ire1->ire_zoneid != ire->ire_zoneid)
5949 			continue;
5950 		/* Has anyone inserted route in the meanwhile ? */
5951 		if (ire_match_args(ire1, ire->ire_addr, ire->ire_mask, 0,
5952 		    ire->ire_type, ire->ire_ipif, ire->ire_zoneid, 0, NULL,
5953 		    flags)) {
5954 			ip1dbg(("ire_add_srcif_v4 : Duplicate entry exists\n"));
5955 			IRE_REFHOLD(ire1);
5956 			ire_atomic_end(irb_ptr, ire);
5957 			ire_delete(ire);
5958 			/* Return old ire as in ire_add_v4 */
5959 			*ire_p = ire1;
5960 			return (0);
5961 		}
5962 	}
5963 	irep = (ire_t **)irb_ptr;
5964 	if (*irep != NULL) {
5965 		/* Find the last ire which matches ire_addr */
5966 		ire1 = *irep;
5967 		while (ire1->ire_addr == ire->ire_addr) {
5968 			irep = &ire1->ire_next;
5969 			ire1 = *irep;
5970 			if (ire1 == NULL)
5971 				break;
5972 		}
5973 	}
5974 	ire1 = *irep;
5975 	if (ire1 != NULL)
5976 		ire1->ire_ptpn = &ire->ire_next;
5977 	ire->ire_next = ire1;
5978 	/* Link the new one in. */
5979 	ire->ire_ptpn = irep;
5980 	membar_producer();
5981 	*irep = ire;
5982 	ire->ire_bucket = irb_ptr;
5983 	IRE_REFHOLD_LOCKED(ire);
5984 
5985 	/*
5986 	 * Protect ire_in_ill->ill_srcif_refcnt and table reference count.
5987 	 * Note, ire_atomic_start already grabs the ire_in_ill->ill_lock
5988 	 * so ill_srcif_refcnt is already protected.
5989 	 */
5990 	ire->ire_in_ill->ill_srcif_refcnt++;
5991 	mutex_enter(&ire_srcif_table_lock);
5992 	ire_srcif_table_count++;
5993 	mutex_exit(&ire_srcif_table_lock);
5994 	irb_ptr->irb_ire_cnt++;
5995 	if (ire->ire_ipif != NULL) {
5996 		ire->ire_ipif->ipif_ire_cnt++;
5997 		if (ire->ire_stq != NULL) {
5998 			stq_ill = (ill_t *)ire->ire_stq->q_ptr;
5999 			stq_ill->ill_ire_cnt++;
6000 		}
6001 	} else {
6002 		ASSERT(ire->ire_stq == NULL);
6003 	}
6004 
6005 	ire_atomic_end(irb_ptr, ire);
6006 	*ire_p = ire;
6007 	return (0);
6008 }
6009 
6010 
6011 /*
6012  * This function is called by ire_add_then_send when ARP request comes
6013  * back to ip_wput->ire_add_then_send for resolved ire in the interface
6014  * based routing table. At this point, it only needs to update the resolver
6015  * information for the ire. The passed ire is returned to the caller as it
6016  * is the ire which is created as mblk.
6017  */
6018 
6019 static ire_t *
6020 ire_update_srcif_v4(ire_t *ire)
6021 {
6022 	ire_t   *ire1;
6023 	irb_t	*irb;
6024 	int	error;
6025 
6026 	ASSERT(ire->ire_type != IRE_MIPRTUN &&
6027 	    ire->ire_ipif->ipif_net_type == IRE_IF_RESOLVER);
6028 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
6029 
6030 	/*
6031 	 * This ire is from ARP. Update
6032 	 * ire_dlureq_mp info
6033 	 */
6034 	ire1 = ire_srcif_table_lookup(ire->ire_addr,
6035 	    IRE_IF_RESOLVER, ire->ire_ipif,
6036 	    ire->ire_in_ill,
6037 	    MATCH_IRE_ILL | MATCH_IRE_TYPE);
6038 	if (ire1 == NULL) {
6039 		/* Mobile node registration expired ? */
6040 		ire_delete(ire);
6041 		return (NULL);
6042 	}
6043 	irb = ire1->ire_bucket;
6044 	ASSERT(irb != NULL);
6045 	/*
6046 	 * Start the atomic add of the ire. Grab the ill locks,
6047 	 * ill_g_usesrc_lock and the bucket lock.
6048 	 */
6049 	error = ire_atomic_start(irb, ire1, NULL, NULL, NULL);
6050 	if (error != 0) {
6051 		/*
6052 		 * We don't know whether it is a valid ipif or not.
6053 		 * So, set it to NULL. This assumes that the ire has not added
6054 		 * a reference to the ipif.
6055 		 */
6056 		ire->ire_ipif = NULL;
6057 		ire_delete(ire);
6058 		ip1dbg(("ire_update_srcif_v4: ire_atomic_start failed\n"));
6059 		return (NULL);
6060 	}
6061 	ASSERT(ire->ire_max_fragp == NULL);
6062 	ire->ire_max_frag = ire1->ire_max_frag;
6063 	/*
6064 	 * Update resolver information and
6065 	 * send-to queue.
6066 	 */
6067 	ASSERT(ire->ire_dlureq_mp != NULL);
6068 	ire1->ire_dlureq_mp = copyb(ire->ire_dlureq_mp);
6069 	if (ire1->ire_dlureq_mp ==  NULL) {
6070 		ip0dbg(("ire_update_srcif: copyb failed\n"));
6071 		ire_refrele(ire1);
6072 		ire_refrele(ire);
6073 		ire_atomic_end(irb, ire1);
6074 		return (NULL);
6075 	}
6076 	ire1->ire_stq = ire->ire_stq;
6077 
6078 	ASSERT(ire->ire_fp_mp == NULL);
6079 
6080 	ire_atomic_end(irb, ire1);
6081 	ire_refrele(ire1);
6082 	/* Return the passed ire */
6083 	return (ire);   /* Update done */
6084 }
6085 
6086 
6087 /*
6088  * Check if another multirt route resolution is needed.
6089  * B_TRUE is returned is there remain a resolvable route,
6090  * or if no route for that dst is resolved yet.
6091  * B_FALSE is returned if all routes for that dst are resolved
6092  * or if the remaining unresolved routes are actually not
6093  * resolvable.
6094  * This only works in the global zone.
6095  */
6096 boolean_t
6097 ire_multirt_need_resolve(ipaddr_t dst, const ts_label_t *tsl)
6098 {
6099 	ire_t	*first_fire;
6100 	ire_t	*first_cire;
6101 	ire_t	*fire;
6102 	ire_t	*cire;
6103 	irb_t	*firb;
6104 	irb_t	*cirb;
6105 	int	unres_cnt = 0;
6106 	boolean_t resolvable = B_FALSE;
6107 
6108 	/* Retrieve the first IRE_HOST that matches the destination */
6109 	first_fire = ire_ftable_lookup(dst, IP_HOST_MASK, 0, IRE_HOST, NULL,
6110 	    NULL, ALL_ZONES, 0, tsl,
6111 	    MATCH_IRE_MASK | MATCH_IRE_TYPE | MATCH_IRE_SECATTR);
6112 
6113 	/* No route at all */
6114 	if (first_fire == NULL) {
6115 		return (B_TRUE);
6116 	}
6117 
6118 	firb = first_fire->ire_bucket;
6119 	ASSERT(firb != NULL);
6120 
6121 	/* Retrieve the first IRE_CACHE ire for that destination. */
6122 	first_cire = ire_cache_lookup(dst, GLOBAL_ZONEID, tsl);
6123 
6124 	/* No resolved route. */
6125 	if (first_cire == NULL) {
6126 		ire_refrele(first_fire);
6127 		return (B_TRUE);
6128 	}
6129 
6130 	/*
6131 	 * At least one route is resolved. Here we look through the forward
6132 	 * and cache tables, to compare the number of declared routes
6133 	 * with the number of resolved routes. The search for a resolvable
6134 	 * route is performed only if at least one route remains
6135 	 * unresolved.
6136 	 */
6137 	cirb = first_cire->ire_bucket;
6138 	ASSERT(cirb != NULL);
6139 
6140 	/* Count the number of routes to that dest that are declared. */
6141 	IRB_REFHOLD(firb);
6142 	for (fire = first_fire; fire != NULL; fire = fire->ire_next) {
6143 		if (!(fire->ire_flags & RTF_MULTIRT))
6144 			continue;
6145 		if (fire->ire_addr != dst)
6146 			continue;
6147 		unres_cnt++;
6148 	}
6149 	IRB_REFRELE(firb);
6150 
6151 	/* Then subtract the number of routes to that dst that are resolved */
6152 	IRB_REFHOLD(cirb);
6153 	for (cire = first_cire; cire != NULL; cire = cire->ire_next) {
6154 		if (!(cire->ire_flags & RTF_MULTIRT))
6155 			continue;
6156 		if (cire->ire_addr != dst)
6157 			continue;
6158 		if (cire->ire_marks & (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
6159 			continue;
6160 		unres_cnt--;
6161 	}
6162 	IRB_REFRELE(cirb);
6163 
6164 	/* At least one route is unresolved; search for a resolvable route. */
6165 	if (unres_cnt > 0)
6166 		resolvable = ire_multirt_lookup(&first_cire, &first_fire,
6167 		    MULTIRT_USESTAMP | MULTIRT_CACHEGW, tsl);
6168 
6169 	if (first_fire != NULL)
6170 		ire_refrele(first_fire);
6171 
6172 	if (first_cire != NULL)
6173 		ire_refrele(first_cire);
6174 
6175 	return (resolvable);
6176 }
6177 
6178 
6179 /*
6180  * Explore a forward_table bucket, starting from fire_arg.
6181  * fire_arg MUST be an IRE_HOST entry.
6182  *
6183  * Return B_TRUE and update *ire_arg and *fire_arg
6184  * if at least one resolvable route is found. *ire_arg
6185  * is the IRE entry for *fire_arg's gateway.
6186  *
6187  * Return B_FALSE otherwise (all routes are resolved or
6188  * the remaining unresolved routes are all unresolvable).
6189  *
6190  * The IRE selection relies on a priority mechanism
6191  * driven by the flags passed in by the caller.
6192  * The caller, such as ip_newroute_ipif(), can get the most
6193  * relevant ire at each stage of a multiple route resolution.
6194  *
6195  * The rules are:
6196  *
6197  * - if MULTIRT_CACHEGW is specified in flags, IRE_CACHETABLE
6198  *   ires are preferred for the gateway. This gives the highest
6199  *   priority to routes that can be resolved without using
6200  *   a resolver.
6201  *
6202  * - if MULTIRT_CACHEGW is not specified, or if MULTIRT_CACHEGW
6203  *   is specified but no IRE_CACHETABLE ire entry for the gateway
6204  *   is found, the following rules apply.
6205  *
6206  * - if MULTIRT_USESTAMP is specified in flags, IRE_INTERFACE
6207  *   ires for the gateway, that have not been tried since
6208  *   a configurable amount of time, are preferred.
6209  *   This applies when a resolver must be invoked for
6210  *   a missing route, but we don't want to use the resolver
6211  *   upon each packet emission. If no such resolver is found,
6212  *   B_FALSE is returned.
6213  *   The MULTIRT_USESTAMP flag can be combined with
6214  *   MULTIRT_CACHEGW.
6215  *
6216  * - if MULTIRT_USESTAMP is not specified in flags, the first
6217  *   unresolved but resolvable route is selected.
6218  *
6219  * - Otherwise, there is no resolvalble route, and
6220  *   B_FALSE is returned.
6221  *
6222  * At last, MULTIRT_SETSTAMP can be specified in flags to
6223  * request the timestamp of unresolvable routes to
6224  * be refreshed. This prevents the useless exploration
6225  * of those routes for a while, when MULTIRT_USESTAMP is used.
6226  *
6227  * This only works in the global zone.
6228  */
6229 boolean_t
6230 ire_multirt_lookup(ire_t **ire_arg, ire_t **fire_arg, uint32_t flags,
6231     const ts_label_t *tsl)
6232 {
6233 	clock_t	delta;
6234 	ire_t	*best_fire = NULL;
6235 	ire_t	*best_cire = NULL;
6236 	ire_t	*first_fire;
6237 	ire_t	*first_cire;
6238 	ire_t	*fire;
6239 	ire_t	*cire;
6240 	irb_t	*firb = NULL;
6241 	irb_t	*cirb = NULL;
6242 	ire_t	*gw_ire;
6243 	boolean_t	already_resolved;
6244 	boolean_t	res;
6245 	ipaddr_t	dst;
6246 	ipaddr_t	gw;
6247 
6248 	ip2dbg(("ire_multirt_lookup: *ire_arg %p, *fire_arg %p, flags %04x\n",
6249 	    (void *)*ire_arg, (void *)*fire_arg, flags));
6250 
6251 	ASSERT(ire_arg != NULL);
6252 	ASSERT(fire_arg != NULL);
6253 
6254 	/* Not an IRE_HOST ire; give up. */
6255 	if ((*fire_arg == NULL) || ((*fire_arg)->ire_type != IRE_HOST)) {
6256 		return (B_FALSE);
6257 	}
6258 
6259 	/* This is the first IRE_HOST ire for that destination. */
6260 	first_fire = *fire_arg;
6261 	firb = first_fire->ire_bucket;
6262 	ASSERT(firb != NULL);
6263 
6264 	dst = first_fire->ire_addr;
6265 
6266 	ip2dbg(("ire_multirt_lookup: dst %08x\n", ntohl(dst)));
6267 
6268 	/*
6269 	 * Retrieve the first IRE_CACHE ire for that destination;
6270 	 * if we don't find one, no route for that dest is
6271 	 * resolved yet.
6272 	 */
6273 	first_cire = ire_cache_lookup(dst, GLOBAL_ZONEID, tsl);
6274 	if (first_cire != NULL) {
6275 		cirb = first_cire->ire_bucket;
6276 	}
6277 
6278 	ip2dbg(("ire_multirt_lookup: first_cire %p\n", (void *)first_cire));
6279 
6280 	/*
6281 	 * Search for a resolvable route, giving the top priority
6282 	 * to routes that can be resolved without any call to the resolver.
6283 	 */
6284 	IRB_REFHOLD(firb);
6285 
6286 	if (!CLASSD(dst)) {
6287 		/*
6288 		 * For all multiroute IRE_HOST ires for that destination,
6289 		 * check if the route via the IRE_HOST's gateway is
6290 		 * resolved yet.
6291 		 */
6292 		for (fire = first_fire; fire != NULL; fire = fire->ire_next) {
6293 
6294 			if (!(fire->ire_flags & RTF_MULTIRT))
6295 				continue;
6296 			if (fire->ire_addr != dst)
6297 				continue;
6298 
6299 			if (fire->ire_gw_secattr != NULL &&
6300 			    tsol_ire_match_gwattr(fire, tsl) != 0) {
6301 				continue;
6302 			}
6303 
6304 			gw = fire->ire_gateway_addr;
6305 
6306 			ip2dbg(("ire_multirt_lookup: fire %p, "
6307 			    "ire_addr %08x, ire_gateway_addr %08x\n",
6308 			    (void *)fire, ntohl(fire->ire_addr), ntohl(gw)));
6309 
6310 			already_resolved = B_FALSE;
6311 
6312 			if (first_cire != NULL) {
6313 				ASSERT(cirb != NULL);
6314 
6315 				IRB_REFHOLD(cirb);
6316 				/*
6317 				 * For all IRE_CACHE ires for that
6318 				 * destination.
6319 				 */
6320 				for (cire = first_cire;
6321 				    cire != NULL;
6322 				    cire = cire->ire_next) {
6323 
6324 					if (!(cire->ire_flags & RTF_MULTIRT))
6325 						continue;
6326 					if (cire->ire_addr != dst)
6327 						continue;
6328 					if (cire->ire_marks &
6329 					    (IRE_MARK_CONDEMNED |
6330 						IRE_MARK_HIDDEN))
6331 						continue;
6332 
6333 					if (cire->ire_gw_secattr != NULL &&
6334 					    tsol_ire_match_gwattr(cire,
6335 					    tsl) != 0) {
6336 						continue;
6337 					}
6338 
6339 					/*
6340 					 * Check if the IRE_CACHE's gateway
6341 					 * matches the IRE_HOST's gateway.
6342 					 */
6343 					if (cire->ire_gateway_addr == gw) {
6344 						already_resolved = B_TRUE;
6345 						break;
6346 					}
6347 				}
6348 				IRB_REFRELE(cirb);
6349 			}
6350 
6351 			/*
6352 			 * This route is already resolved;
6353 			 * proceed with next one.
6354 			 */
6355 			if (already_resolved) {
6356 				ip2dbg(("ire_multirt_lookup: found cire %p, "
6357 				    "already resolved\n", (void *)cire));
6358 				continue;
6359 			}
6360 
6361 			/*
6362 			 * The route is unresolved; is it actually
6363 			 * resolvable, i.e. is there a cache or a resolver
6364 			 * for the gateway?
6365 			 */
6366 			gw_ire = ire_route_lookup(gw, 0, 0, 0, NULL, NULL,
6367 			    ALL_ZONES, tsl,
6368 			    MATCH_IRE_RECURSIVE | MATCH_IRE_SECATTR);
6369 
6370 			ip2dbg(("ire_multirt_lookup: looked up gw_ire %p\n",
6371 			    (void *)gw_ire));
6372 
6373 			/*
6374 			 * If gw_ire is typed IRE_CACHETABLE,
6375 			 * this route can be resolved without any call to the
6376 			 * resolver. If the MULTIRT_CACHEGW flag is set,
6377 			 * give the top priority to this ire and exit the
6378 			 * loop.
6379 			 * This is typically the case when an ARP reply
6380 			 * is processed through ip_wput_nondata().
6381 			 */
6382 			if ((flags & MULTIRT_CACHEGW) &&
6383 			    (gw_ire != NULL) &&
6384 			    (gw_ire->ire_type & IRE_CACHETABLE)) {
6385 				/*
6386 				 * Release the resolver associated to the
6387 				 * previous candidate best ire, if any.
6388 				 */
6389 				if (best_cire != NULL) {
6390 					ire_refrele(best_cire);
6391 					ASSERT(best_fire != NULL);
6392 				}
6393 
6394 				best_fire = fire;
6395 				best_cire = gw_ire;
6396 
6397 				ip2dbg(("ire_multirt_lookup: found top prio "
6398 				    "best_fire %p, best_cire %p\n",
6399 				    (void *)best_fire, (void *)best_cire));
6400 				break;
6401 			}
6402 
6403 			/*
6404 			 * Compute the time elapsed since our preceding
6405 			 * attempt to  resolve that route.
6406 			 * If the MULTIRT_USESTAMP flag is set, we take that
6407 			 * route into account only if this time interval
6408 			 * exceeds ip_multirt_resolution_interval;
6409 			 * this prevents us from attempting to resolve a
6410 			 * broken route upon each sending of a packet.
6411 			 */
6412 			delta = lbolt - fire->ire_last_used_time;
6413 			delta = TICK_TO_MSEC(delta);
6414 
6415 			res = (boolean_t)
6416 			    ((delta > ip_multirt_resolution_interval) ||
6417 				(!(flags & MULTIRT_USESTAMP)));
6418 
6419 			ip2dbg(("ire_multirt_lookup: fire %p, delta %lu, "
6420 			    "res %d\n",
6421 			    (void *)fire, delta, res));
6422 
6423 			if (res) {
6424 				/*
6425 				 * We are here if MULTIRT_USESTAMP flag is set
6426 				 * and the resolver for fire's gateway
6427 				 * has not been tried since
6428 				 * ip_multirt_resolution_interval, or if
6429 				 * MULTIRT_USESTAMP is not set but gw_ire did
6430 				 * not fill the conditions for MULTIRT_CACHEGW,
6431 				 * or if neither MULTIRT_USESTAMP nor
6432 				 * MULTIRT_CACHEGW are set.
6433 				 */
6434 				if (gw_ire != NULL) {
6435 					if (best_fire == NULL) {
6436 						ASSERT(best_cire == NULL);
6437 
6438 						best_fire = fire;
6439 						best_cire = gw_ire;
6440 
6441 						ip2dbg(("ire_multirt_lookup:"
6442 						    "found candidate "
6443 						    "best_fire %p, "
6444 						    "best_cire %p\n",
6445 						    (void *)best_fire,
6446 						    (void *)best_cire));
6447 
6448 						/*
6449 						 * If MULTIRT_CACHEGW is not
6450 						 * set, we ignore the top
6451 						 * priority ires that can
6452 						 * be resolved without any
6453 						 * call to the resolver;
6454 						 * In that case, there is
6455 						 * actually no need
6456 						 * to continue the loop.
6457 						 */
6458 						if (!(flags &
6459 						    MULTIRT_CACHEGW)) {
6460 							break;
6461 						}
6462 						continue;
6463 					}
6464 				} else {
6465 					/*
6466 					 * No resolver for the gateway: the
6467 					 * route is not resolvable.
6468 					 * If the MULTIRT_SETSTAMP flag is
6469 					 * set, we stamp the IRE_HOST ire,
6470 					 * so we will not select it again
6471 					 * during this resolution interval.
6472 					 */
6473 					if (flags & MULTIRT_SETSTAMP)
6474 						fire->ire_last_used_time =
6475 						    lbolt;
6476 				}
6477 			}
6478 
6479 			if (gw_ire != NULL)
6480 				ire_refrele(gw_ire);
6481 		}
6482 	} else { /* CLASSD(dst) */
6483 
6484 		for (fire = first_fire;
6485 		    fire != NULL;
6486 		    fire = fire->ire_next) {
6487 
6488 			if (!(fire->ire_flags & RTF_MULTIRT))
6489 				continue;
6490 			if (fire->ire_addr != dst)
6491 				continue;
6492 
6493 			if (fire->ire_gw_secattr != NULL &&
6494 			    tsol_ire_match_gwattr(fire, tsl) != 0) {
6495 				continue;
6496 			}
6497 
6498 			already_resolved = B_FALSE;
6499 
6500 			gw = fire->ire_gateway_addr;
6501 
6502 			gw_ire = ire_ftable_lookup(gw, 0, 0, IRE_INTERFACE,
6503 			    NULL, NULL, ALL_ZONES, 0, tsl,
6504 			    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE |
6505 			    MATCH_IRE_SECATTR);
6506 
6507 			/* No resolver for the gateway; we skip this ire. */
6508 			if (gw_ire == NULL) {
6509 				continue;
6510 			}
6511 
6512 			if (first_cire != NULL) {
6513 
6514 				IRB_REFHOLD(cirb);
6515 				/*
6516 				 * For all IRE_CACHE ires for that
6517 				 * destination.
6518 				 */
6519 				for (cire = first_cire;
6520 				    cire != NULL;
6521 				    cire = cire->ire_next) {
6522 
6523 					if (!(cire->ire_flags & RTF_MULTIRT))
6524 						continue;
6525 					if (cire->ire_addr != dst)
6526 						continue;
6527 					if (cire->ire_marks &
6528 					    (IRE_MARK_CONDEMNED |
6529 						IRE_MARK_HIDDEN))
6530 						continue;
6531 
6532 					if (cire->ire_gw_secattr != NULL &&
6533 					    tsol_ire_match_gwattr(cire,
6534 					    tsl) != 0) {
6535 						continue;
6536 					}
6537 
6538 					/*
6539 					 * Cache entries are linked to the
6540 					 * parent routes using the parent handle
6541 					 * (ire_phandle). If no cache entry has
6542 					 * the same handle as fire, fire is
6543 					 * still unresolved.
6544 					 */
6545 					ASSERT(cire->ire_phandle != 0);
6546 					if (cire->ire_phandle ==
6547 					    fire->ire_phandle) {
6548 						already_resolved = B_TRUE;
6549 						break;
6550 					}
6551 				}
6552 				IRB_REFRELE(cirb);
6553 			}
6554 
6555 			/*
6556 			 * This route is already resolved; proceed with
6557 			 * next one.
6558 			 */
6559 			if (already_resolved) {
6560 				ire_refrele(gw_ire);
6561 				continue;
6562 			}
6563 
6564 			/*
6565 			 * Compute the time elapsed since our preceding
6566 			 * attempt to resolve that route.
6567 			 * If the MULTIRT_USESTAMP flag is set, we take
6568 			 * that route into account only if this time
6569 			 * interval exceeds ip_multirt_resolution_interval;
6570 			 * this prevents us from attempting to resolve a
6571 			 * broken route upon each sending of a packet.
6572 			 */
6573 			delta = lbolt - fire->ire_last_used_time;
6574 			delta = TICK_TO_MSEC(delta);
6575 
6576 			res = (boolean_t)
6577 			    ((delta > ip_multirt_resolution_interval) ||
6578 			    (!(flags & MULTIRT_USESTAMP)));
6579 
6580 			ip3dbg(("ire_multirt_lookup: fire %p, delta %lx, "
6581 			    "flags %04x, res %d\n",
6582 			    (void *)fire, delta, flags, res));
6583 
6584 			if (res) {
6585 				if (best_cire != NULL) {
6586 					/*
6587 					 * Release the resolver associated
6588 					 * to the preceding candidate best
6589 					 * ire, if any.
6590 					 */
6591 					ire_refrele(best_cire);
6592 					ASSERT(best_fire != NULL);
6593 				}
6594 				best_fire = fire;
6595 				best_cire = gw_ire;
6596 				continue;
6597 			}
6598 
6599 			ire_refrele(gw_ire);
6600 		}
6601 	}
6602 
6603 	if (best_fire != NULL) {
6604 		IRE_REFHOLD(best_fire);
6605 	}
6606 	IRB_REFRELE(firb);
6607 
6608 	/* Release the first IRE_CACHE we initially looked up, if any. */
6609 	if (first_cire != NULL)
6610 		ire_refrele(first_cire);
6611 
6612 	/* Found a resolvable route. */
6613 	if (best_fire != NULL) {
6614 		ASSERT(best_cire != NULL);
6615 
6616 		if (*fire_arg != NULL)
6617 			ire_refrele(*fire_arg);
6618 		if (*ire_arg != NULL)
6619 			ire_refrele(*ire_arg);
6620 
6621 		/*
6622 		 * Update the passed-in arguments with the
6623 		 * resolvable multirt route we found.
6624 		 */
6625 		*fire_arg = best_fire;
6626 		*ire_arg = best_cire;
6627 
6628 		ip2dbg(("ire_multirt_lookup: returning B_TRUE, "
6629 		    "*fire_arg %p, *ire_arg %p\n",
6630 		    (void *)best_fire, (void *)best_cire));
6631 
6632 		return (B_TRUE);
6633 	}
6634 
6635 	ASSERT(best_cire == NULL);
6636 
6637 	ip2dbg(("ire_multirt_lookup: returning B_FALSE, *fire_arg %p, "
6638 	    "*ire_arg %p\n",
6639 	    (void *)*fire_arg, (void *)*ire_arg));
6640 
6641 	/* No resolvable route. */
6642 	return (B_FALSE);
6643 }
6644 
6645 /*
6646  * Find an IRE_OFFSUBNET IRE entry for the multicast address 'group'
6647  * that goes through 'ipif'. As a fallback, a route that goes through
6648  * ipif->ipif_ill can be returned.
6649  */
6650 ire_t *
6651 ipif_lookup_multi_ire(ipif_t *ipif, ipaddr_t group)
6652 {
6653 	ire_t	*ire;
6654 	ire_t	*save_ire = NULL;
6655 	ire_t   *gw_ire;
6656 	irb_t   *irb;
6657 	ipaddr_t gw_addr;
6658 	int	match_flags = MATCH_IRE_TYPE | MATCH_IRE_ILL;
6659 
6660 	ASSERT(CLASSD(group));
6661 
6662 	ire = ire_ftable_lookup(group, 0, 0, 0, NULL, NULL, ALL_ZONES, 0,
6663 	    NULL, MATCH_IRE_DEFAULT);
6664 
6665 	if (ire == NULL)
6666 		return (NULL);
6667 
6668 	irb = ire->ire_bucket;
6669 	ASSERT(irb);
6670 
6671 	IRB_REFHOLD(irb);
6672 	ire_refrele(ire);
6673 	for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
6674 		if (ire->ire_addr != group ||
6675 		    (ipif->ipif_zoneid != ire->ire_zoneid &&
6676 		    ire->ire_zoneid != ALL_ZONES)) {
6677 			continue;
6678 		}
6679 
6680 		switch (ire->ire_type) {
6681 		case IRE_DEFAULT:
6682 		case IRE_PREFIX:
6683 		case IRE_HOST:
6684 			gw_addr = ire->ire_gateway_addr;
6685 			gw_ire = ire_ftable_lookup(gw_addr, 0, 0, IRE_INTERFACE,
6686 			    ipif, NULL, ALL_ZONES, 0, NULL, match_flags);
6687 
6688 			if (gw_ire != NULL) {
6689 				if (save_ire != NULL) {
6690 					ire_refrele(save_ire);
6691 				}
6692 				IRE_REFHOLD(ire);
6693 				if (gw_ire->ire_ipif == ipif) {
6694 					ire_refrele(gw_ire);
6695 
6696 					IRB_REFRELE(irb);
6697 					return (ire);
6698 				}
6699 				ire_refrele(gw_ire);
6700 				save_ire = ire;
6701 			}
6702 			break;
6703 		case IRE_IF_NORESOLVER:
6704 		case IRE_IF_RESOLVER:
6705 			if (ire->ire_ipif == ipif) {
6706 				if (save_ire != NULL) {
6707 					ire_refrele(save_ire);
6708 				}
6709 				IRE_REFHOLD(ire);
6710 
6711 				IRB_REFRELE(irb);
6712 				return (ire);
6713 			}
6714 			break;
6715 		}
6716 	}
6717 	IRB_REFRELE(irb);
6718 
6719 	return (save_ire);
6720 }
6721 
6722 /*
6723  * The purpose of the next two functions is to provide some external access to
6724  * routing/l2 lookup functionality while hiding the implementation of routing
6725  * and interface data structures (IRE/ILL).  Thus, interfaces are passed/
6726  * returned by name instead of by ILL reference.  These functions are used by
6727  * IP Filter.
6728  * Return a link layer header suitable for an IP packet being sent to the
6729  * dst_addr IP address.  The interface associated with the route is put into
6730  * ifname, which must be a buffer of LIFNAMSIZ bytes.  The dst_addr is the
6731  * packet's ultimate destination address, not a router address.
6732  *
6733  * This function is used when the caller wants to know the outbound interface
6734  * and MAC header for a packet given only the address.
6735  */
6736 mblk_t *
6737 ip_nexthop_route(const struct sockaddr *target, char *ifname)
6738 {
6739 	struct nce_s *nce;
6740 	ire_t *dir;
6741 	ill_t *ill;
6742 	mblk_t *mp;
6743 
6744 	/* parameter sanity */
6745 	if (ifname == NULL || target == NULL)
6746 		return (NULL);
6747 
6748 	/* Find the route entry, if it exists. */
6749 	switch (target->sa_family) {
6750 	case AF_INET:
6751 		dir = ire_route_lookup(
6752 		    ((struct sockaddr_in *)target)->sin_addr.s_addr,
6753 		    0xffffffff,
6754 		    0, 0, NULL, NULL, ALL_ZONES, NULL,
6755 		    MATCH_IRE_DSTONLY|MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE);
6756 		break;
6757 	case AF_INET6:
6758 		dir = ire_route_lookup_v6(
6759 		    &((struct sockaddr_in6 *)target)->sin6_addr,
6760 		    NULL,
6761 		    0, 0, NULL, NULL, ALL_ZONES, NULL,
6762 		    MATCH_IRE_DSTONLY|MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE);
6763 		if ((dir != NULL) && (dir->ire_nce == NULL)) {
6764 			ire_refrele(dir);
6765 			dir = NULL;
6766 		}
6767 		break;
6768 	default:
6769 		dir = NULL;
6770 		break;
6771 	}
6772 
6773 
6774 	if (dir == NULL)
6775 		return (NULL);
6776 
6777 	/* Map the IRE to an ILL so we can fill in ifname. */
6778 	ill = ire_to_ill(dir);
6779 	if (ill == NULL) {
6780 		ire_refrele(dir);
6781 		return (NULL);
6782 	}
6783 	(void) strncpy(ifname, ill->ill_name, LIFNAMSIZ);
6784 
6785 	/* Return a copy of the header to the caller. */
6786 	switch (target->sa_family) {
6787 	case AF_INET :
6788 		if (dir->ire_fp_mp != NULL) {
6789 			if ((mp = dupb(dir->ire_fp_mp)) == NULL)
6790 				mp = copyb(dir->ire_fp_mp);
6791 		} else if (dir->ire_dlureq_mp != NULL) {
6792 			if ((mp = dupb(dir->ire_dlureq_mp)) == NULL)
6793 				mp = copyb(dir->ire_dlureq_mp);
6794 		} else {
6795 			mp = NULL;
6796 		}
6797 		break;
6798 	case AF_INET6 :
6799 		nce = dir->ire_nce;
6800 		if (nce->nce_fp_mp != NULL) {
6801 			if ((mp = dupb(nce->nce_fp_mp)) == NULL)
6802 				mp = copyb(nce->nce_fp_mp);
6803 		} else if (nce->nce_res_mp != NULL) {
6804 			if ((mp = dupb(nce->nce_res_mp)) == NULL)
6805 				mp = copyb(nce->nce_res_mp);
6806 		} else {
6807 			mp = NULL;
6808 		}
6809 		break;
6810 	}
6811 
6812 	ire_refrele(dir);
6813 	return (mp);
6814 }
6815 
6816 
6817 /*
6818  * Return a link layer header suitable for an IP packet being sent to the
6819  * dst_addr IP address on the specified output interface.  The dst_addr
6820  * may be the packet's ultimate destination or a predetermined next hop
6821  * router's address.
6822  * ifname must be nul-terminated.
6823  *
6824  * This function is used when the caller knows the outbound interface (usually
6825  * because it was specified by policy) and only needs the MAC header for a
6826  * packet.
6827  */
6828 mblk_t *
6829 ip_nexthop(const struct sockaddr *target, const char *ifname)
6830 {
6831 	struct nce_s *nce;
6832 	ill_walk_context_t ctx;
6833 	t_uscalar_t sap;
6834 	ire_t *dir;
6835 	ill_t *ill;
6836 	mblk_t *mp;
6837 
6838 	/* parameter sanity */
6839 	if (ifname == NULL || target == NULL)
6840 		return (NULL);
6841 
6842 	switch (target->sa_family) {
6843 	case AF_INET :
6844 		sap = IP_DL_SAP;
6845 		break;
6846 	case AF_INET6 :
6847 		sap = IP6_DL_SAP;
6848 		break;
6849 	default:
6850 		return (NULL);
6851 	}
6852 
6853 	/* Lock ill_g_lock before walking through the list */
6854 	rw_enter(&ill_g_lock, RW_READER);
6855 	/*
6856 	 * Can we find the interface name among those currently configured?
6857 	 */
6858 	for (ill = ILL_START_WALK_ALL(&ctx); ill != NULL;
6859 	    ill = ill_next(&ctx, ill)) {
6860 		if ((strcmp(ifname, ill->ill_name) == 0) &&
6861 		    (ill->ill_sap == sap))
6862 			break;
6863 	}
6864 	if (ill == NULL || ill->ill_ipif == NULL) {
6865 		rw_exit(&ill_g_lock);
6866 		return (NULL);
6867 	}
6868 
6869 	mutex_enter(&ill->ill_lock);
6870 	if (!ILL_CAN_LOOKUP(ill)) {
6871 		mutex_exit(&ill->ill_lock);
6872 		rw_exit(&ill_g_lock);
6873 		return (NULL);
6874 	}
6875 	ill_refhold_locked(ill);
6876 	mutex_exit(&ill->ill_lock);
6877 	rw_exit(&ill_g_lock);
6878 
6879 	/* Find the resolver entry, if it exists. */
6880 	switch (target->sa_family) {
6881 	case AF_INET:
6882 		dir = ire_route_lookup(
6883 			((struct sockaddr_in *)target)->sin_addr.s_addr,
6884 			0xffffffff,
6885 			0, 0, ill->ill_ipif, NULL, ALL_ZONES, NULL,
6886 			MATCH_IRE_DSTONLY|MATCH_IRE_DEFAULT|
6887 			MATCH_IRE_RECURSIVE|MATCH_IRE_IPIF);
6888 		break;
6889 	case AF_INET6:
6890 		dir = ire_route_lookup_v6(
6891 			&((struct sockaddr_in6 *)target)->sin6_addr, NULL,
6892 			0, 0, ill->ill_ipif, NULL, ALL_ZONES, NULL,
6893 			MATCH_IRE_DSTONLY|MATCH_IRE_DEFAULT|
6894 			MATCH_IRE_RECURSIVE|MATCH_IRE_IPIF);
6895 		if ((dir != NULL) && (dir->ire_nce == NULL)) {
6896 			ire_refrele(dir);
6897 			dir = NULL;
6898 		}
6899 		break;
6900 	default:
6901 		dir = NULL;
6902 		break;
6903 	}
6904 
6905 	ill_refrele(ill);
6906 
6907 	if (dir == NULL)
6908 		return (NULL);
6909 
6910 	/* Return a copy of the header to the caller. */
6911 	switch (target->sa_family) {
6912 	case AF_INET :
6913 		if (dir->ire_fp_mp != NULL) {
6914 			if ((mp = dupb(dir->ire_fp_mp)) == NULL)
6915 				mp = copyb(dir->ire_fp_mp);
6916 		} else if (dir->ire_dlureq_mp != NULL) {
6917 			if ((mp = dupb(dir->ire_dlureq_mp)) == NULL)
6918 				mp = copyb(dir->ire_dlureq_mp);
6919 		} else {
6920 			mp = NULL;
6921 		}
6922 		break;
6923 	case AF_INET6 :
6924 		nce = dir->ire_nce;
6925 		if (nce->nce_fp_mp != NULL) {
6926 			if ((mp = dupb(nce->nce_fp_mp)) == NULL)
6927 				mp = copyb(nce->nce_fp_mp);
6928 		} else if (nce->nce_res_mp != NULL) {
6929 			if ((mp = dupb(nce->nce_res_mp)) == NULL)
6930 				mp = copyb(nce->nce_res_mp);
6931 		} else {
6932 			mp = NULL;
6933 		}
6934 		break;
6935 	}
6936 
6937 	ire_refrele(dir);
6938 	return (mp);
6939 }
6940 
6941 /*
6942  * IRE iterator for inbound and loopback broadcast processing.
6943  * Given an IRE_BROADCAST ire, walk the ires with the same destination
6944  * address, but skip over the passed-in ire. Returns the next ire without
6945  * a hold - assumes that the caller holds a reference on the IRE bucket.
6946  */
6947 ire_t *
6948 ire_get_next_bcast_ire(ire_t *curr, ire_t *ire)
6949 {
6950 	ill_t *ill;
6951 
6952 	if (curr == NULL) {
6953 		for (curr = ire->ire_bucket->irb_ire; curr != NULL;
6954 		    curr = curr->ire_next) {
6955 			if (curr->ire_addr == ire->ire_addr)
6956 				break;
6957 		}
6958 	} else {
6959 		curr = curr->ire_next;
6960 	}
6961 	ill = ire_to_ill(ire);
6962 	for (; curr != NULL; curr = curr->ire_next) {
6963 		if (curr->ire_addr != ire->ire_addr) {
6964 			/*
6965 			 * All the IREs to a given destination are contiguous;
6966 			 * break out once the address doesn't match.
6967 			 */
6968 			break;
6969 		}
6970 		if (curr == ire) {
6971 			/* skip over the passed-in ire */
6972 			continue;
6973 		}
6974 		if ((curr->ire_stq != NULL && ire->ire_stq == NULL) ||
6975 		    (curr->ire_stq == NULL && ire->ire_stq != NULL)) {
6976 			/*
6977 			 * If the passed-in ire is loopback, skip over
6978 			 * non-loopback ires and vice versa.
6979 			 */
6980 			continue;
6981 		}
6982 		if (ire_to_ill(curr) != ill) {
6983 			/* skip over IREs going through a different interface */
6984 			continue;
6985 		}
6986 		if (curr->ire_marks & IRE_MARK_CONDEMNED) {
6987 			/* skip over deleted IREs */
6988 			continue;
6989 		}
6990 		return (curr);
6991 	}
6992 	return (NULL);
6993 }
6994 
6995 /*
6996  * IRE iterator used by ire_ftable_lookup[_v6]() to process multiple default
6997  * routes. Given a starting point in the hash list (ire_origin), walk the IREs
6998  * in the bucket skipping default interface routes and deleted entries.
6999  * Returns the next IRE (unheld), or NULL when we're back to the starting point.
7000  * Assumes that the caller holds a reference on the IRE bucket.
7001  */
7002 ire_t *
7003 ire_get_next_default_ire(ire_t *ire, ire_t *ire_origin)
7004 {
7005 	ASSERT(ire_origin->ire_bucket != NULL);
7006 	ASSERT(ire != NULL);
7007 
7008 	do {
7009 		ire = ire->ire_next;
7010 		if (ire == NULL)
7011 			ire = ire_origin->ire_bucket->irb_ire;
7012 		if (ire == ire_origin)
7013 			return (NULL);
7014 	} while ((ire->ire_type & IRE_INTERFACE) ||
7015 	    (ire->ire_marks & IRE_MARK_CONDEMNED));
7016 	ASSERT(ire != NULL);
7017 	return (ire);
7018 }
7019 
7020 #ifdef IRE_DEBUG
7021 th_trace_t *
7022 th_trace_ire_lookup(ire_t *ire)
7023 {
7024 	int bucket_id;
7025 	th_trace_t *th_trace;
7026 
7027 	ASSERT(MUTEX_HELD(&ire->ire_lock));
7028 
7029 	bucket_id = IP_TR_HASH(curthread);
7030 	ASSERT(bucket_id < IP_TR_HASH_MAX);
7031 
7032 	for (th_trace = ire->ire_trace[bucket_id]; th_trace != NULL;
7033 	    th_trace = th_trace->th_next) {
7034 		if (th_trace->th_id == curthread)
7035 			return (th_trace);
7036 	}
7037 	return (NULL);
7038 }
7039 
7040 void
7041 ire_trace_ref(ire_t *ire)
7042 {
7043 	int bucket_id;
7044 	th_trace_t *th_trace;
7045 
7046 	/*
7047 	 * Attempt to locate the trace buffer for the curthread.
7048 	 * If it does not exist, then allocate a new trace buffer
7049 	 * and link it in list of trace bufs for this ipif, at the head
7050 	 */
7051 	mutex_enter(&ire->ire_lock);
7052 	if (ire->ire_trace_disable == B_TRUE) {
7053 		mutex_exit(&ire->ire_lock);
7054 		return;
7055 	}
7056 	th_trace = th_trace_ire_lookup(ire);
7057 	if (th_trace == NULL) {
7058 		bucket_id = IP_TR_HASH(curthread);
7059 		th_trace = (th_trace_t *)kmem_zalloc(sizeof (th_trace_t),
7060 		    KM_NOSLEEP);
7061 		if (th_trace == NULL) {
7062 			ire->ire_trace_disable = B_TRUE;
7063 			mutex_exit(&ire->ire_lock);
7064 			ire_trace_inactive(ire);
7065 			return;
7066 		}
7067 
7068 		th_trace->th_id = curthread;
7069 		th_trace->th_next = ire->ire_trace[bucket_id];
7070 		th_trace->th_prev = &ire->ire_trace[bucket_id];
7071 		if (th_trace->th_next != NULL)
7072 			th_trace->th_next->th_prev = &th_trace->th_next;
7073 		ire->ire_trace[bucket_id] = th_trace;
7074 	}
7075 	ASSERT(th_trace->th_refcnt < TR_BUF_MAX - 1);
7076 	th_trace->th_refcnt++;
7077 	th_trace_rrecord(th_trace);
7078 	mutex_exit(&ire->ire_lock);
7079 }
7080 
7081 void
7082 ire_trace_free(th_trace_t *th_trace)
7083 {
7084 	/* unlink th_trace and free it */
7085 	*th_trace->th_prev = th_trace->th_next;
7086 	if (th_trace->th_next != NULL)
7087 		th_trace->th_next->th_prev = th_trace->th_prev;
7088 	th_trace->th_next = NULL;
7089 	th_trace->th_prev = NULL;
7090 	kmem_free(th_trace, sizeof (th_trace_t));
7091 }
7092 
7093 void
7094 ire_untrace_ref(ire_t *ire)
7095 {
7096 	th_trace_t *th_trace;
7097 
7098 	mutex_enter(&ire->ire_lock);
7099 
7100 	if (ire->ire_trace_disable == B_TRUE) {
7101 		mutex_exit(&ire->ire_lock);
7102 		return;
7103 	}
7104 
7105 	th_trace = th_trace_ire_lookup(ire);
7106 	ASSERT(th_trace != NULL && th_trace->th_refcnt > 0);
7107 	th_trace_rrecord(th_trace);
7108 	th_trace->th_refcnt--;
7109 
7110 	if (th_trace->th_refcnt == 0)
7111 		ire_trace_free(th_trace);
7112 
7113 	mutex_exit(&ire->ire_lock);
7114 }
7115 
7116 static void
7117 ire_trace_inactive(ire_t *ire)
7118 {
7119 	th_trace_t *th_trace;
7120 	int i;
7121 
7122 	mutex_enter(&ire->ire_lock);
7123 	for (i = 0; i < IP_TR_HASH_MAX; i++) {
7124 		while (ire->ire_trace[i] != NULL) {
7125 			th_trace = ire->ire_trace[i];
7126 
7127 			/* unlink th_trace and free it */
7128 			ire->ire_trace[i] = th_trace->th_next;
7129 			if (th_trace->th_next != NULL)
7130 				th_trace->th_next->th_prev =
7131 				    &ire->ire_trace[i];
7132 
7133 			th_trace->th_next = NULL;
7134 			th_trace->th_prev = NULL;
7135 			kmem_free(th_trace, sizeof (th_trace_t));
7136 		}
7137 	}
7138 
7139 	mutex_exit(&ire->ire_lock);
7140 }
7141 
7142 /* ARGSUSED */
7143 void
7144 ire_thread_exit(ire_t *ire, caddr_t arg)
7145 {
7146 	th_trace_t	*th_trace;
7147 
7148 	mutex_enter(&ire->ire_lock);
7149 	th_trace = th_trace_ire_lookup(ire);
7150 	if (th_trace == NULL) {
7151 		mutex_exit(&ire->ire_lock);
7152 		return;
7153 	}
7154 	ASSERT(th_trace->th_refcnt == 0);
7155 
7156 	ire_trace_free(th_trace);
7157 	mutex_exit(&ire->ire_lock);
7158 }
7159 
7160 #endif
7161