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