xref: /freebsd/sys/net/route.c (revision 0bf48626aaa33768078f5872b922b1487b3a9296)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1980, 1986, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)route.c	8.3.1.1 (Berkeley) 2/23/95
32  * $FreeBSD$
33  */
34 /************************************************************************
35  * Note: In this file a 'fib' is a "forwarding information base"	*
36  * Which is the new name for an in kernel routing (next hop) table.	*
37  ***********************************************************************/
38 
39 #include "opt_inet.h"
40 #include "opt_inet6.h"
41 #include "opt_route.h"
42 #include "opt_sctp.h"
43 #include "opt_mrouting.h"
44 #include "opt_mpath.h"
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/malloc.h>
49 #include <sys/mbuf.h>
50 #include <sys/socket.h>
51 #include <sys/sysctl.h>
52 #include <sys/syslog.h>
53 #include <sys/sysproto.h>
54 #include <sys/proc.h>
55 #include <sys/domain.h>
56 #include <sys/kernel.h>
57 #include <sys/lock.h>
58 #include <sys/rmlock.h>
59 
60 #include <net/if.h>
61 #include <net/if_var.h>
62 #include <net/if_dl.h>
63 #include <net/route.h>
64 #include <net/route_var.h>
65 #include <net/vnet.h>
66 
67 #ifdef RADIX_MPATH
68 #include <net/radix_mpath.h>
69 #endif
70 
71 #include <netinet/in.h>
72 #include <netinet/ip_mroute.h>
73 
74 #include <vm/uma.h>
75 
76 #define	RT_MAXFIBS	UINT16_MAX
77 
78 /* Kernel config default option. */
79 #ifdef ROUTETABLES
80 #if ROUTETABLES <= 0
81 #error "ROUTETABLES defined too low"
82 #endif
83 #if ROUTETABLES > RT_MAXFIBS
84 #error "ROUTETABLES defined too big"
85 #endif
86 #define	RT_NUMFIBS	ROUTETABLES
87 #endif /* ROUTETABLES */
88 /* Initialize to default if not otherwise set. */
89 #ifndef	RT_NUMFIBS
90 #define	RT_NUMFIBS	1
91 #endif
92 
93 #if defined(INET) || defined(INET6)
94 #ifdef SCTP
95 extern void sctp_addr_change(struct ifaddr *ifa, int cmd);
96 #endif /* SCTP */
97 #endif
98 
99 
100 /* This is read-only.. */
101 u_int rt_numfibs = RT_NUMFIBS;
102 SYSCTL_UINT(_net, OID_AUTO, fibs, CTLFLAG_RDTUN, &rt_numfibs, 0, "");
103 
104 /*
105  * By default add routes to all fibs for new interfaces.
106  * Once this is set to 0 then only allocate routes on interface
107  * changes for the FIB of the caller when adding a new set of addresses
108  * to an interface.  XXX this is a shotgun aproach to a problem that needs
109  * a more fine grained solution.. that will come.
110  * XXX also has the problems getting the FIB from curthread which will not
111  * always work given the fib can be overridden and prefixes can be added
112  * from the network stack context.
113  */
114 VNET_DEFINE(u_int, rt_add_addr_allfibs) = 1;
115 SYSCTL_UINT(_net, OID_AUTO, add_addr_allfibs, CTLFLAG_RWTUN | CTLFLAG_VNET,
116     &VNET_NAME(rt_add_addr_allfibs), 0, "");
117 
118 VNET_DEFINE(struct rtstat, rtstat);
119 #define	V_rtstat	VNET(rtstat)
120 
121 VNET_DEFINE(struct rib_head *, rt_tables);
122 #define	V_rt_tables	VNET(rt_tables)
123 
124 VNET_DEFINE(int, rttrash);		/* routes not in table but not freed */
125 #define	V_rttrash	VNET(rttrash)
126 
127 
128 /*
129  * Convert a 'struct radix_node *' to a 'struct rtentry *'.
130  * The operation can be done safely (in this code) because a
131  * 'struct rtentry' starts with two 'struct radix_node''s, the first
132  * one representing leaf nodes in the routing tree, which is
133  * what the code in radix.c passes us as a 'struct radix_node'.
134  *
135  * But because there are a lot of assumptions in this conversion,
136  * do not cast explicitly, but always use the macro below.
137  */
138 #define RNTORT(p)	((struct rtentry *)(p))
139 
140 VNET_DEFINE_STATIC(uma_zone_t, rtzone);		/* Routing table UMA zone. */
141 #define	V_rtzone	VNET(rtzone)
142 
143 static int rtrequest1_fib_change(struct rib_head *, struct rt_addrinfo *,
144     struct rtentry **, u_int);
145 static void rt_setmetrics(const struct rt_addrinfo *, struct rtentry *);
146 static int rt_ifdelroute(const struct rtentry *rt, void *arg);
147 static struct rtentry *rt_unlinkrte(struct rib_head *rnh,
148     struct rt_addrinfo *info, int *perror);
149 static void rt_notifydelete(struct rtentry *rt, struct rt_addrinfo *info);
150 #ifdef RADIX_MPATH
151 static struct radix_node *rt_mpath_unlink(struct rib_head *rnh,
152     struct rt_addrinfo *info, struct rtentry *rto, int *perror);
153 #endif
154 static int rt_exportinfo(struct rtentry *rt, struct rt_addrinfo *info,
155     int flags);
156 
157 struct if_mtuinfo
158 {
159 	struct ifnet	*ifp;
160 	int		mtu;
161 };
162 
163 static int	if_updatemtu_cb(struct radix_node *, void *);
164 
165 /*
166  * handler for net.my_fibnum
167  */
168 static int
169 sysctl_my_fibnum(SYSCTL_HANDLER_ARGS)
170 {
171         int fibnum;
172         int error;
173 
174         fibnum = curthread->td_proc->p_fibnum;
175         error = sysctl_handle_int(oidp, &fibnum, 0, req);
176         return (error);
177 }
178 
179 SYSCTL_PROC(_net, OID_AUTO, my_fibnum, CTLTYPE_INT|CTLFLAG_RD,
180             NULL, 0, &sysctl_my_fibnum, "I", "default FIB of caller");
181 
182 static __inline struct rib_head **
183 rt_tables_get_rnh_ptr(int table, int fam)
184 {
185 	struct rib_head **rnh;
186 
187 	KASSERT(table >= 0 && table < rt_numfibs, ("%s: table out of bounds.",
188 	    __func__));
189 	KASSERT(fam >= 0 && fam < (AF_MAX+1), ("%s: fam out of bounds.",
190 	    __func__));
191 
192 	/* rnh is [fib=0][af=0]. */
193 	rnh = (struct rib_head **)V_rt_tables;
194 	/* Get the offset to the requested table and fam. */
195 	rnh += table * (AF_MAX+1) + fam;
196 
197 	return (rnh);
198 }
199 
200 struct rib_head *
201 rt_tables_get_rnh(int table, int fam)
202 {
203 
204 	return (*rt_tables_get_rnh_ptr(table, fam));
205 }
206 
207 u_int
208 rt_tables_get_gen(int table, int fam)
209 {
210 	struct rib_head *rnh;
211 
212 	rnh = *rt_tables_get_rnh_ptr(table, fam);
213 	KASSERT(rnh != NULL, ("%s: NULL rib_head pointer table %d fam %d",
214 	    __func__, table, fam));
215 	return (rnh->rnh_gen);
216 }
217 
218 
219 /*
220  * route initialization must occur before ip6_init2(), which happenas at
221  * SI_ORDER_MIDDLE.
222  */
223 static void
224 route_init(void)
225 {
226 
227 	/* whack the tunable ints into  line. */
228 	if (rt_numfibs > RT_MAXFIBS)
229 		rt_numfibs = RT_MAXFIBS;
230 	if (rt_numfibs == 0)
231 		rt_numfibs = 1;
232 }
233 SYSINIT(route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, route_init, NULL);
234 
235 static int
236 rtentry_zinit(void *mem, int size, int how)
237 {
238 	struct rtentry *rt = mem;
239 
240 	rt->rt_pksent = counter_u64_alloc(how);
241 	if (rt->rt_pksent == NULL)
242 		return (ENOMEM);
243 
244 	RT_LOCK_INIT(rt);
245 
246 	return (0);
247 }
248 
249 static void
250 rtentry_zfini(void *mem, int size)
251 {
252 	struct rtentry *rt = mem;
253 
254 	RT_LOCK_DESTROY(rt);
255 	counter_u64_free(rt->rt_pksent);
256 }
257 
258 static int
259 rtentry_ctor(void *mem, int size, void *arg, int how)
260 {
261 	struct rtentry *rt = mem;
262 
263 	bzero(rt, offsetof(struct rtentry, rt_endzero));
264 	counter_u64_zero(rt->rt_pksent);
265 	rt->rt_chain = NULL;
266 
267 	return (0);
268 }
269 
270 static void
271 rtentry_dtor(void *mem, int size, void *arg)
272 {
273 	struct rtentry *rt = mem;
274 
275 	RT_UNLOCK_COND(rt);
276 }
277 
278 static void
279 vnet_route_init(const void *unused __unused)
280 {
281 	struct domain *dom;
282 	struct rib_head **rnh;
283 	int table;
284 	int fam;
285 
286 	V_rt_tables = malloc(rt_numfibs * (AF_MAX+1) *
287 	    sizeof(struct rib_head *), M_RTABLE, M_WAITOK|M_ZERO);
288 
289 	V_rtzone = uma_zcreate("rtentry", sizeof(struct rtentry),
290 	    rtentry_ctor, rtentry_dtor,
291 	    rtentry_zinit, rtentry_zfini, UMA_ALIGN_PTR, 0);
292 	for (dom = domains; dom; dom = dom->dom_next) {
293 		if (dom->dom_rtattach == NULL)
294 			continue;
295 
296 		for  (table = 0; table < rt_numfibs; table++) {
297 			fam = dom->dom_family;
298 			if (table != 0 && fam != AF_INET6 && fam != AF_INET)
299 				break;
300 
301 			rnh = rt_tables_get_rnh_ptr(table, fam);
302 			if (rnh == NULL)
303 				panic("%s: rnh NULL", __func__);
304 			dom->dom_rtattach((void **)rnh, 0);
305 		}
306 	}
307 }
308 VNET_SYSINIT(vnet_route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH,
309     vnet_route_init, 0);
310 
311 #ifdef VIMAGE
312 static void
313 vnet_route_uninit(const void *unused __unused)
314 {
315 	int table;
316 	int fam;
317 	struct domain *dom;
318 	struct rib_head **rnh;
319 
320 	for (dom = domains; dom; dom = dom->dom_next) {
321 		if (dom->dom_rtdetach == NULL)
322 			continue;
323 
324 		for (table = 0; table < rt_numfibs; table++) {
325 			fam = dom->dom_family;
326 
327 			if (table != 0 && fam != AF_INET6 && fam != AF_INET)
328 				break;
329 
330 			rnh = rt_tables_get_rnh_ptr(table, fam);
331 			if (rnh == NULL)
332 				panic("%s: rnh NULL", __func__);
333 			dom->dom_rtdetach((void **)rnh, 0);
334 		}
335 	}
336 
337 	free(V_rt_tables, M_RTABLE);
338 	uma_zdestroy(V_rtzone);
339 }
340 VNET_SYSUNINIT(vnet_route_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
341     vnet_route_uninit, 0);
342 #endif
343 
344 struct rib_head *
345 rt_table_init(int offset)
346 {
347 	struct rib_head *rh;
348 
349 	rh = malloc(sizeof(struct rib_head), M_RTABLE, M_WAITOK | M_ZERO);
350 
351 	/* TODO: These details should be hidded inside radix.c */
352 	/* Init masks tree */
353 	rn_inithead_internal(&rh->head, rh->rnh_nodes, offset);
354 	rn_inithead_internal(&rh->rmhead.head, rh->rmhead.mask_nodes, 0);
355 	rh->head.rnh_masks = &rh->rmhead;
356 
357 	/* Init locks */
358 	RIB_LOCK_INIT(rh);
359 
360 	/* Finally, set base callbacks */
361 	rh->rnh_addaddr = rn_addroute;
362 	rh->rnh_deladdr = rn_delete;
363 	rh->rnh_matchaddr = rn_match;
364 	rh->rnh_lookup = rn_lookup;
365 	rh->rnh_walktree = rn_walktree;
366 	rh->rnh_walktree_from = rn_walktree_from;
367 
368 	return (rh);
369 }
370 
371 static int
372 rt_freeentry(struct radix_node *rn, void *arg)
373 {
374 	struct radix_head * const rnh = arg;
375 	struct radix_node *x;
376 
377 	x = (struct radix_node *)rn_delete(rn + 2, NULL, rnh);
378 	if (x != NULL)
379 		R_Free(x);
380 	return (0);
381 }
382 
383 void
384 rt_table_destroy(struct rib_head *rh)
385 {
386 
387 	rn_walktree(&rh->rmhead.head, rt_freeentry, &rh->rmhead.head);
388 
389 	/* Assume table is already empty */
390 	RIB_LOCK_DESTROY(rh);
391 	free(rh, M_RTABLE);
392 }
393 
394 
395 #ifndef _SYS_SYSPROTO_H_
396 struct setfib_args {
397 	int     fibnum;
398 };
399 #endif
400 int
401 sys_setfib(struct thread *td, struct setfib_args *uap)
402 {
403 	if (uap->fibnum < 0 || uap->fibnum >= rt_numfibs)
404 		return EINVAL;
405 	td->td_proc->p_fibnum = uap->fibnum;
406 	return (0);
407 }
408 
409 /*
410  * Packet routing routines.
411  */
412 void
413 rtalloc_ign_fib(struct route *ro, u_long ignore, u_int fibnum)
414 {
415 	struct rtentry *rt;
416 
417 	if ((rt = ro->ro_rt) != NULL) {
418 		if (rt->rt_ifp != NULL && rt->rt_flags & RTF_UP)
419 			return;
420 		RTFREE(rt);
421 		ro->ro_rt = NULL;
422 	}
423 	ro->ro_rt = rtalloc1_fib(&ro->ro_dst, 1, ignore, fibnum);
424 	if (ro->ro_rt)
425 		RT_UNLOCK(ro->ro_rt);
426 }
427 
428 /*
429  * Look up the route that matches the address given
430  * Or, at least try.. Create a cloned route if needed.
431  *
432  * The returned route, if any, is locked.
433  */
434 struct rtentry *
435 rtalloc1(struct sockaddr *dst, int report, u_long ignflags)
436 {
437 
438 	return (rtalloc1_fib(dst, report, ignflags, RT_DEFAULT_FIB));
439 }
440 
441 struct rtentry *
442 rtalloc1_fib(struct sockaddr *dst, int report, u_long ignflags,
443 		    u_int fibnum)
444 {
445 	RIB_RLOCK_TRACKER;
446 	struct rib_head *rh;
447 	struct radix_node *rn;
448 	struct rtentry *newrt;
449 	struct rt_addrinfo info;
450 	int err = 0, msgtype = RTM_MISS;
451 
452 	KASSERT((fibnum < rt_numfibs), ("rtalloc1_fib: bad fibnum"));
453 	rh = rt_tables_get_rnh(fibnum, dst->sa_family);
454 	newrt = NULL;
455 	if (rh == NULL)
456 		goto miss;
457 
458 	/*
459 	 * Look up the address in the table for that Address Family
460 	 */
461 	if ((ignflags & RTF_RNH_LOCKED) == 0)
462 		RIB_RLOCK(rh);
463 #ifdef INVARIANTS
464 	else
465 		RIB_LOCK_ASSERT(rh);
466 #endif
467 	rn = rh->rnh_matchaddr(dst, &rh->head);
468 	if (rn && ((rn->rn_flags & RNF_ROOT) == 0)) {
469 		newrt = RNTORT(rn);
470 		RT_LOCK(newrt);
471 		RT_ADDREF(newrt);
472 		if ((ignflags & RTF_RNH_LOCKED) == 0)
473 			RIB_RUNLOCK(rh);
474 		return (newrt);
475 
476 	} else if ((ignflags & RTF_RNH_LOCKED) == 0)
477 		RIB_RUNLOCK(rh);
478 	/*
479 	 * Either we hit the root or could not find any match,
480 	 * which basically means: "cannot get there from here".
481 	 */
482 miss:
483 	V_rtstat.rts_unreach++;
484 
485 	if (report) {
486 		/*
487 		 * If required, report the failure to the supervising
488 		 * Authorities.
489 		 * For a delete, this is not an error. (report == 0)
490 		 */
491 		bzero(&info, sizeof(info));
492 		info.rti_info[RTAX_DST] = dst;
493 		rt_missmsg_fib(msgtype, &info, 0, err, fibnum);
494 	}
495 	return (newrt);
496 }
497 
498 /*
499  * Remove a reference count from an rtentry.
500  * If the count gets low enough, take it out of the routing table
501  */
502 void
503 rtfree(struct rtentry *rt)
504 {
505 	struct rib_head *rnh;
506 
507 	KASSERT(rt != NULL,("%s: NULL rt", __func__));
508 	rnh = rt_tables_get_rnh(rt->rt_fibnum, rt_key(rt)->sa_family);
509 	KASSERT(rnh != NULL,("%s: NULL rnh", __func__));
510 
511 	RT_LOCK_ASSERT(rt);
512 
513 	/*
514 	 * The callers should use RTFREE_LOCKED() or RTFREE(), so
515 	 * we should come here exactly with the last reference.
516 	 */
517 	RT_REMREF(rt);
518 	if (rt->rt_refcnt > 0) {
519 		log(LOG_DEBUG, "%s: %p has %d refs\n", __func__, rt, rt->rt_refcnt);
520 		goto done;
521 	}
522 
523 	/*
524 	 * On last reference give the "close method" a chance
525 	 * to cleanup private state.  This also permits (for
526 	 * IPv4 and IPv6) a chance to decide if the routing table
527 	 * entry should be purged immediately or at a later time.
528 	 * When an immediate purge is to happen the close routine
529 	 * typically calls rtexpunge which clears the RTF_UP flag
530 	 * on the entry so that the code below reclaims the storage.
531 	 */
532 	if (rt->rt_refcnt == 0 && rnh->rnh_close)
533 		rnh->rnh_close((struct radix_node *)rt, &rnh->head);
534 
535 	/*
536 	 * If we are no longer "up" (and ref == 0)
537 	 * then we can free the resources associated
538 	 * with the route.
539 	 */
540 	if ((rt->rt_flags & RTF_UP) == 0) {
541 		if (rt->rt_nodes->rn_flags & (RNF_ACTIVE | RNF_ROOT))
542 			panic("rtfree 2");
543 		/*
544 		 * the rtentry must have been removed from the routing table
545 		 * so it is represented in rttrash.. remove that now.
546 		 */
547 		V_rttrash--;
548 #ifdef	DIAGNOSTIC
549 		if (rt->rt_refcnt < 0) {
550 			printf("rtfree: %p not freed (neg refs)\n", rt);
551 			goto done;
552 		}
553 #endif
554 		/*
555 		 * release references on items we hold them on..
556 		 * e.g other routes and ifaddrs.
557 		 */
558 		if (rt->rt_ifa)
559 			ifa_free(rt->rt_ifa);
560 		/*
561 		 * The key is separatly alloc'd so free it (see rt_setgate()).
562 		 * This also frees the gateway, as they are always malloc'd
563 		 * together.
564 		 */
565 		R_Free(rt_key(rt));
566 
567 		/*
568 		 * and the rtentry itself of course
569 		 */
570 		uma_zfree(V_rtzone, rt);
571 		return;
572 	}
573 done:
574 	RT_UNLOCK(rt);
575 }
576 
577 
578 /*
579  * Force a routing table entry to the specified
580  * destination to go through the given gateway.
581  * Normally called as a result of a routing redirect
582  * message from the network layer.
583  */
584 void
585 rtredirect_fib(struct sockaddr *dst,
586 	struct sockaddr *gateway,
587 	struct sockaddr *netmask,
588 	int flags,
589 	struct sockaddr *src,
590 	u_int fibnum)
591 {
592 	struct rtentry *rt;
593 	int error = 0;
594 	short *stat = NULL;
595 	struct rt_addrinfo info;
596 	struct epoch_tracker et;
597 	struct ifaddr *ifa;
598 	struct rib_head *rnh;
599 
600 	ifa = NULL;
601 	NET_EPOCH_ENTER(et);
602 	rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
603 	if (rnh == NULL) {
604 		error = EAFNOSUPPORT;
605 		goto out;
606 	}
607 	/* verify the gateway is directly reachable */
608 	if ((ifa = ifa_ifwithnet(gateway, 0, fibnum)) == NULL) {
609 		error = ENETUNREACH;
610 		goto out;
611 	}
612 	rt = rtalloc1_fib(dst, 0, 0UL, fibnum);	/* NB: rt is locked */
613 	/*
614 	 * If the redirect isn't from our current router for this dst,
615 	 * it's either old or wrong.  If it redirects us to ourselves,
616 	 * we have a routing loop, perhaps as a result of an interface
617 	 * going down recently.
618 	 */
619 	if (!(flags & RTF_DONE) && rt) {
620 		if (!sa_equal(src, rt->rt_gateway)) {
621 			error = EINVAL;
622 			goto done;
623 		}
624 		if (rt->rt_ifa != ifa && ifa->ifa_addr->sa_family != AF_LINK) {
625 			error = EINVAL;
626 			goto done;
627 		}
628 	}
629 	if ((flags & RTF_GATEWAY) && ifa_ifwithaddr_check(gateway)) {
630 		error = EHOSTUNREACH;
631 		goto done;
632 	}
633 	/*
634 	 * Create a new entry if we just got back a wildcard entry
635 	 * or the lookup failed.  This is necessary for hosts
636 	 * which use routing redirects generated by smart gateways
637 	 * to dynamically build the routing tables.
638 	 */
639 	if (rt == NULL || (rt_mask(rt) && rt_mask(rt)->sa_len < 2))
640 		goto create;
641 	/*
642 	 * Don't listen to the redirect if it's
643 	 * for a route to an interface.
644 	 */
645 	if (rt->rt_flags & RTF_GATEWAY) {
646 		if (((rt->rt_flags & RTF_HOST) == 0) && (flags & RTF_HOST)) {
647 			/*
648 			 * Changing from route to net => route to host.
649 			 * Create new route, rather than smashing route to net.
650 			 */
651 		create:
652 			if (rt != NULL)
653 				RTFREE_LOCKED(rt);
654 
655 			flags |= RTF_DYNAMIC;
656 			bzero((caddr_t)&info, sizeof(info));
657 			info.rti_info[RTAX_DST] = dst;
658 			info.rti_info[RTAX_GATEWAY] = gateway;
659 			info.rti_info[RTAX_NETMASK] = netmask;
660 			ifa_ref(ifa);
661 			info.rti_ifa = ifa;
662 			info.rti_flags = flags;
663 			error = rtrequest1_fib(RTM_ADD, &info, &rt, fibnum);
664 			if (rt != NULL) {
665 				RT_LOCK(rt);
666 				flags = rt->rt_flags;
667 			}
668 
669 			stat = &V_rtstat.rts_dynamic;
670 		} else {
671 
672 			/*
673 			 * Smash the current notion of the gateway to
674 			 * this destination.  Should check about netmask!!!
675 			 */
676 			if ((flags & RTF_GATEWAY) == 0)
677 				rt->rt_flags &= ~RTF_GATEWAY;
678 			rt->rt_flags |= RTF_MODIFIED;
679 			flags |= RTF_MODIFIED;
680 			stat = &V_rtstat.rts_newgateway;
681 			/*
682 			 * add the key and gateway (in one malloc'd chunk).
683 			 */
684 			RT_UNLOCK(rt);
685 			RIB_WLOCK(rnh);
686 			RT_LOCK(rt);
687 			rt_setgate(rt, rt_key(rt), gateway);
688 			RIB_WUNLOCK(rnh);
689 		}
690 	} else
691 		error = EHOSTUNREACH;
692 done:
693 	if (rt)
694 		RTFREE_LOCKED(rt);
695  out:
696 	NET_EPOCH_EXIT(et);
697 	if (error)
698 		V_rtstat.rts_badredirect++;
699 	else if (stat != NULL)
700 		(*stat)++;
701 	bzero((caddr_t)&info, sizeof(info));
702 	info.rti_info[RTAX_DST] = dst;
703 	info.rti_info[RTAX_GATEWAY] = gateway;
704 	info.rti_info[RTAX_NETMASK] = netmask;
705 	info.rti_info[RTAX_AUTHOR] = src;
706 	rt_missmsg_fib(RTM_REDIRECT, &info, flags, error, fibnum);
707 }
708 
709 /*
710  * Routing table ioctl interface.
711  */
712 int
713 rtioctl_fib(u_long req, caddr_t data, u_int fibnum)
714 {
715 
716 	/*
717 	 * If more ioctl commands are added here, make sure the proper
718 	 * super-user checks are being performed because it is possible for
719 	 * prison-root to make it this far if raw sockets have been enabled
720 	 * in jails.
721 	 */
722 #ifdef INET
723 	/* Multicast goop, grrr... */
724 	return mrt_ioctl ? mrt_ioctl(req, data, fibnum) : EOPNOTSUPP;
725 #else /* INET */
726 	return ENXIO;
727 #endif /* INET */
728 }
729 
730 struct ifaddr *
731 ifa_ifwithroute(int flags, const struct sockaddr *dst, struct sockaddr *gateway,
732 				u_int fibnum)
733 {
734 	struct ifaddr *ifa;
735 	int not_found = 0;
736 
737 	MPASS(in_epoch(net_epoch_preempt));
738 	if ((flags & RTF_GATEWAY) == 0) {
739 		/*
740 		 * If we are adding a route to an interface,
741 		 * and the interface is a pt to pt link
742 		 * we should search for the destination
743 		 * as our clue to the interface.  Otherwise
744 		 * we can use the local address.
745 		 */
746 		ifa = NULL;
747 		if (flags & RTF_HOST)
748 			ifa = ifa_ifwithdstaddr(dst, fibnum);
749 		if (ifa == NULL)
750 			ifa = ifa_ifwithaddr(gateway);
751 	} else {
752 		/*
753 		 * If we are adding a route to a remote net
754 		 * or host, the gateway may still be on the
755 		 * other end of a pt to pt link.
756 		 */
757 		ifa = ifa_ifwithdstaddr(gateway, fibnum);
758 	}
759 	if (ifa == NULL)
760 		ifa = ifa_ifwithnet(gateway, 0, fibnum);
761 	if (ifa == NULL) {
762 		struct rtentry *rt;
763 
764 		rt = rtalloc1_fib(gateway, 0, flags, fibnum);
765 		if (rt == NULL)
766 			goto out;
767 		/*
768 		 * dismiss a gateway that is reachable only
769 		 * through the default router
770 		 */
771 		switch (gateway->sa_family) {
772 		case AF_INET:
773 			if (satosin(rt_key(rt))->sin_addr.s_addr == INADDR_ANY)
774 				not_found = 1;
775 			break;
776 		case AF_INET6:
777 			if (IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(rt))->sin6_addr))
778 				not_found = 1;
779 			break;
780 		default:
781 			break;
782 		}
783 		if (!not_found && rt->rt_ifa != NULL) {
784 			ifa = rt->rt_ifa;
785 		}
786 		RT_REMREF(rt);
787 		RT_UNLOCK(rt);
788 		if (not_found || ifa == NULL)
789 			goto out;
790 	}
791 	if (ifa->ifa_addr->sa_family != dst->sa_family) {
792 		struct ifaddr *oifa = ifa;
793 		ifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
794 		if (ifa == NULL)
795 			ifa = oifa;
796 	}
797  out:
798 	return (ifa);
799 }
800 
801 /*
802  * Do appropriate manipulations of a routing tree given
803  * all the bits of info needed
804  */
805 int
806 rtrequest_fib(int req,
807 	struct sockaddr *dst,
808 	struct sockaddr *gateway,
809 	struct sockaddr *netmask,
810 	int flags,
811 	struct rtentry **ret_nrt,
812 	u_int fibnum)
813 {
814 	struct rt_addrinfo info;
815 
816 	if (dst->sa_len == 0)
817 		return(EINVAL);
818 
819 	bzero((caddr_t)&info, sizeof(info));
820 	info.rti_flags = flags;
821 	info.rti_info[RTAX_DST] = dst;
822 	info.rti_info[RTAX_GATEWAY] = gateway;
823 	info.rti_info[RTAX_NETMASK] = netmask;
824 	return rtrequest1_fib(req, &info, ret_nrt, fibnum);
825 }
826 
827 
828 /*
829  * Copy most of @rt data into @info.
830  *
831  * If @flags contains NHR_COPY, copies dst,netmask and gw to the
832  * pointers specified by @info structure. Assume such pointers
833  * are zeroed sockaddr-like structures with sa_len field initialized
834  * to reflect size of the provided buffer. if no NHR_COPY is specified,
835  * point dst,netmask and gw @info fields to appropriate @rt values.
836  *
837  * if @flags contains NHR_REF, do refcouting on rt_ifp.
838  *
839  * Returns 0 on success.
840  */
841 int
842 rt_exportinfo(struct rtentry *rt, struct rt_addrinfo *info, int flags)
843 {
844 	struct rt_metrics *rmx;
845 	struct sockaddr *src, *dst;
846 	int sa_len;
847 
848 	if (flags & NHR_COPY) {
849 		/* Copy destination if dst is non-zero */
850 		src = rt_key(rt);
851 		dst = info->rti_info[RTAX_DST];
852 		sa_len = src->sa_len;
853 		if (dst != NULL) {
854 			if (src->sa_len > dst->sa_len)
855 				return (ENOMEM);
856 			memcpy(dst, src, src->sa_len);
857 			info->rti_addrs |= RTA_DST;
858 		}
859 
860 		/* Copy mask if set && dst is non-zero */
861 		src = rt_mask(rt);
862 		dst = info->rti_info[RTAX_NETMASK];
863 		if (src != NULL && dst != NULL) {
864 
865 			/*
866 			 * Radix stores different value in sa_len,
867 			 * assume rt_mask() to have the same length
868 			 * as rt_key()
869 			 */
870 			if (sa_len > dst->sa_len)
871 				return (ENOMEM);
872 			memcpy(dst, src, src->sa_len);
873 			info->rti_addrs |= RTA_NETMASK;
874 		}
875 
876 		/* Copy gateway is set && dst is non-zero */
877 		src = rt->rt_gateway;
878 		dst = info->rti_info[RTAX_GATEWAY];
879 		if ((rt->rt_flags & RTF_GATEWAY) && src != NULL && dst != NULL){
880 			if (src->sa_len > dst->sa_len)
881 				return (ENOMEM);
882 			memcpy(dst, src, src->sa_len);
883 			info->rti_addrs |= RTA_GATEWAY;
884 		}
885 	} else {
886 		info->rti_info[RTAX_DST] = rt_key(rt);
887 		info->rti_addrs |= RTA_DST;
888 		if (rt_mask(rt) != NULL) {
889 			info->rti_info[RTAX_NETMASK] = rt_mask(rt);
890 			info->rti_addrs |= RTA_NETMASK;
891 		}
892 		if (rt->rt_flags & RTF_GATEWAY) {
893 			info->rti_info[RTAX_GATEWAY] = rt->rt_gateway;
894 			info->rti_addrs |= RTA_GATEWAY;
895 		}
896 	}
897 
898 	rmx = info->rti_rmx;
899 	if (rmx != NULL) {
900 		info->rti_mflags |= RTV_MTU;
901 		rmx->rmx_mtu = rt->rt_mtu;
902 	}
903 
904 	info->rti_flags = rt->rt_flags;
905 	info->rti_ifp = rt->rt_ifp;
906 	info->rti_ifa = rt->rt_ifa;
907 	ifa_ref(info->rti_ifa);
908 	if (flags & NHR_REF) {
909 		/* Do 'traditional' refcouting */
910 		if_ref(info->rti_ifp);
911 	}
912 
913 	return (0);
914 }
915 
916 /*
917  * Lookups up route entry for @dst in RIB database for fib @fibnum.
918  * Exports entry data to @info using rt_exportinfo().
919  *
920  * if @flags contains NHR_REF, refcouting is performed on rt_ifp.
921  *   All references can be released later by calling rib_free_info()
922  *
923  * Returns 0 on success.
924  * Returns ENOENT for lookup failure, ENOMEM for export failure.
925  */
926 int
927 rib_lookup_info(uint32_t fibnum, const struct sockaddr *dst, uint32_t flags,
928     uint32_t flowid, struct rt_addrinfo *info)
929 {
930 	RIB_RLOCK_TRACKER;
931 	struct rib_head *rh;
932 	struct radix_node *rn;
933 	struct rtentry *rt;
934 	int error;
935 
936 	KASSERT((fibnum < rt_numfibs), ("rib_lookup_rte: bad fibnum"));
937 	rh = rt_tables_get_rnh(fibnum, dst->sa_family);
938 	if (rh == NULL)
939 		return (ENOENT);
940 
941 	RIB_RLOCK(rh);
942 	rn = rh->rnh_matchaddr(__DECONST(void *, dst), &rh->head);
943 	if (rn != NULL && ((rn->rn_flags & RNF_ROOT) == 0)) {
944 		rt = RNTORT(rn);
945 		/* Ensure route & ifp is UP */
946 		if (RT_LINK_IS_UP(rt->rt_ifp)) {
947 			flags = (flags & NHR_REF) | NHR_COPY;
948 			error = rt_exportinfo(rt, info, flags);
949 			RIB_RUNLOCK(rh);
950 
951 			return (error);
952 		}
953 	}
954 	RIB_RUNLOCK(rh);
955 
956 	return (ENOENT);
957 }
958 
959 /*
960  * Releases all references acquired by rib_lookup_info() when
961  * called with NHR_REF flags.
962  */
963 void
964 rib_free_info(struct rt_addrinfo *info)
965 {
966 
967 	if_rele(info->rti_ifp);
968 }
969 
970 /*
971  * Iterates over all existing fibs in system calling
972  *  @setwa_f function prior to traversing each fib.
973  *  Calls @wa_f function for each element in current fib.
974  * If af is not AF_UNSPEC, iterates over fibs in particular
975  * address family.
976  */
977 void
978 rt_foreach_fib_walk(int af, rt_setwarg_t *setwa_f, rt_walktree_f_t *wa_f,
979     void *arg)
980 {
981 	struct rib_head *rnh;
982 	uint32_t fibnum;
983 	int i;
984 
985 	for (fibnum = 0; fibnum < rt_numfibs; fibnum++) {
986 		/* Do we want some specific family? */
987 		if (af != AF_UNSPEC) {
988 			rnh = rt_tables_get_rnh(fibnum, af);
989 			if (rnh == NULL)
990 				continue;
991 			if (setwa_f != NULL)
992 				setwa_f(rnh, fibnum, af, arg);
993 
994 			RIB_WLOCK(rnh);
995 			rnh->rnh_walktree(&rnh->head, (walktree_f_t *)wa_f,arg);
996 			RIB_WUNLOCK(rnh);
997 			continue;
998 		}
999 
1000 		for (i = 1; i <= AF_MAX; i++) {
1001 			rnh = rt_tables_get_rnh(fibnum, i);
1002 			if (rnh == NULL)
1003 				continue;
1004 			if (setwa_f != NULL)
1005 				setwa_f(rnh, fibnum, i, arg);
1006 
1007 			RIB_WLOCK(rnh);
1008 			rnh->rnh_walktree(&rnh->head, (walktree_f_t *)wa_f,arg);
1009 			RIB_WUNLOCK(rnh);
1010 		}
1011 	}
1012 }
1013 
1014 struct rt_delinfo
1015 {
1016 	struct rt_addrinfo info;
1017 	struct rib_head *rnh;
1018 	struct rtentry *head;
1019 };
1020 
1021 /*
1022  * Conditionally unlinks @rn from radix tree based
1023  * on info data passed in @arg.
1024  */
1025 static int
1026 rt_checkdelroute(struct radix_node *rn, void *arg)
1027 {
1028 	struct rt_delinfo *di;
1029 	struct rt_addrinfo *info;
1030 	struct rtentry *rt;
1031 	int error;
1032 
1033 	di = (struct rt_delinfo *)arg;
1034 	rt = (struct rtentry *)rn;
1035 	info = &di->info;
1036 	error = 0;
1037 
1038 	info->rti_info[RTAX_DST] = rt_key(rt);
1039 	info->rti_info[RTAX_NETMASK] = rt_mask(rt);
1040 	info->rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1041 
1042 	rt = rt_unlinkrte(di->rnh, info, &error);
1043 	if (rt == NULL) {
1044 		/* Either not allowed or not matched. Skip entry */
1045 		return (0);
1046 	}
1047 
1048 	/* Entry was unlinked. Add to the list and return */
1049 	rt->rt_chain = di->head;
1050 	di->head = rt;
1051 
1052 	return (0);
1053 }
1054 
1055 /*
1056  * Iterates over all existing fibs in system.
1057  * Deletes each element for which @filter_f function returned
1058  * non-zero value.
1059  * If @af is not AF_UNSPEC, iterates over fibs in particular
1060  * address family.
1061  */
1062 void
1063 rt_foreach_fib_walk_del(int af, rt_filter_f_t *filter_f, void *arg)
1064 {
1065 	struct rib_head *rnh;
1066 	struct rt_delinfo di;
1067 	struct rtentry *rt;
1068 	uint32_t fibnum;
1069 	int i, start, end;
1070 
1071 	bzero(&di, sizeof(di));
1072 	di.info.rti_filter = filter_f;
1073 	di.info.rti_filterdata = arg;
1074 
1075 	for (fibnum = 0; fibnum < rt_numfibs; fibnum++) {
1076 		/* Do we want some specific family? */
1077 		if (af != AF_UNSPEC) {
1078 			start = af;
1079 			end = af;
1080 		} else {
1081 			start = 1;
1082 			end = AF_MAX;
1083 		}
1084 
1085 		for (i = start; i <= end; i++) {
1086 			rnh = rt_tables_get_rnh(fibnum, i);
1087 			if (rnh == NULL)
1088 				continue;
1089 			di.rnh = rnh;
1090 
1091 			RIB_WLOCK(rnh);
1092 			rnh->rnh_walktree(&rnh->head, rt_checkdelroute, &di);
1093 			RIB_WUNLOCK(rnh);
1094 
1095 			if (di.head == NULL)
1096 				continue;
1097 
1098 			/* We might have something to reclaim */
1099 			while (di.head != NULL) {
1100 				rt = di.head;
1101 				di.head = rt->rt_chain;
1102 				rt->rt_chain = NULL;
1103 
1104 				/* TODO std rt -> rt_addrinfo export */
1105 				di.info.rti_info[RTAX_DST] = rt_key(rt);
1106 				di.info.rti_info[RTAX_NETMASK] = rt_mask(rt);
1107 
1108 				rt_notifydelete(rt, &di.info);
1109 				RTFREE_LOCKED(rt);
1110 			}
1111 
1112 		}
1113 	}
1114 }
1115 
1116 /*
1117  * Delete Routes for a Network Interface
1118  *
1119  * Called for each routing entry via the rnh->rnh_walktree() call above
1120  * to delete all route entries referencing a detaching network interface.
1121  *
1122  * Arguments:
1123  *	rt	pointer to rtentry
1124  *	arg	argument passed to rnh->rnh_walktree() - detaching interface
1125  *
1126  * Returns:
1127  *	0	successful
1128  *	errno	failed - reason indicated
1129  */
1130 static int
1131 rt_ifdelroute(const struct rtentry *rt, void *arg)
1132 {
1133 	struct ifnet	*ifp = arg;
1134 
1135 	if (rt->rt_ifp != ifp)
1136 		return (0);
1137 
1138 	/*
1139 	 * Protect (sorta) against walktree recursion problems
1140 	 * with cloned routes
1141 	 */
1142 	if ((rt->rt_flags & RTF_UP) == 0)
1143 		return (0);
1144 
1145 	return (1);
1146 }
1147 
1148 /*
1149  * Delete all remaining routes using this interface
1150  * Unfortuneatly the only way to do this is to slog through
1151  * the entire routing table looking for routes which point
1152  * to this interface...oh well...
1153  */
1154 void
1155 rt_flushifroutes_af(struct ifnet *ifp, int af)
1156 {
1157 	KASSERT((af >= 1 && af <= AF_MAX), ("%s: af %d not >= 1 and <= %d",
1158 	    __func__, af, AF_MAX));
1159 
1160 	rt_foreach_fib_walk_del(af, rt_ifdelroute, ifp);
1161 }
1162 
1163 void
1164 rt_flushifroutes(struct ifnet *ifp)
1165 {
1166 
1167 	rt_foreach_fib_walk_del(AF_UNSPEC, rt_ifdelroute, ifp);
1168 }
1169 
1170 /*
1171  * Conditionally unlinks rtentry matching data inside @info from @rnh.
1172  * Returns unlinked, locked and referenced @rtentry on success,
1173  * Returns NULL and sets @perror to:
1174  * ESRCH - if prefix was not found,
1175  * EADDRINUSE - if trying to delete PINNED route without appropriate flag.
1176  * ENOENT - if supplied filter function returned 0 (not matched).
1177  */
1178 static struct rtentry *
1179 rt_unlinkrte(struct rib_head *rnh, struct rt_addrinfo *info, int *perror)
1180 {
1181 	struct sockaddr *dst, *netmask;
1182 	struct rtentry *rt;
1183 	struct radix_node *rn;
1184 
1185 	dst = info->rti_info[RTAX_DST];
1186 	netmask = info->rti_info[RTAX_NETMASK];
1187 
1188 	rt = (struct rtentry *)rnh->rnh_lookup(dst, netmask, &rnh->head);
1189 	if (rt == NULL) {
1190 		*perror = ESRCH;
1191 		return (NULL);
1192 	}
1193 
1194 	if ((info->rti_flags & RTF_PINNED) == 0) {
1195 		/* Check if target route can be deleted */
1196 		if (rt->rt_flags & RTF_PINNED) {
1197 			*perror = EADDRINUSE;
1198 			return (NULL);
1199 		}
1200 	}
1201 
1202 	if (info->rti_filter != NULL) {
1203 		if (info->rti_filter(rt, info->rti_filterdata) == 0) {
1204 			/* Not matched */
1205 			*perror = ENOENT;
1206 			return (NULL);
1207 		}
1208 
1209 		/*
1210 		 * Filter function requested rte deletion.
1211 		 * Ease the caller work by filling in remaining info
1212 		 * from that particular entry.
1213 		 */
1214 		info->rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1215 	}
1216 
1217 	/*
1218 	 * Remove the item from the tree and return it.
1219 	 * Complain if it is not there and do no more processing.
1220 	 */
1221 	*perror = ESRCH;
1222 #ifdef RADIX_MPATH
1223 	if (rt_mpath_capable(rnh))
1224 		rn = rt_mpath_unlink(rnh, info, rt, perror);
1225 	else
1226 #endif
1227 	rn = rnh->rnh_deladdr(dst, netmask, &rnh->head);
1228 	if (rn == NULL)
1229 		return (NULL);
1230 
1231 	if (rn->rn_flags & (RNF_ACTIVE | RNF_ROOT))
1232 		panic ("rtrequest delete");
1233 
1234 	rt = RNTORT(rn);
1235 	RT_LOCK(rt);
1236 	RT_ADDREF(rt);
1237 	rt->rt_flags &= ~RTF_UP;
1238 
1239 	*perror = 0;
1240 
1241 	return (rt);
1242 }
1243 
1244 static void
1245 rt_notifydelete(struct rtentry *rt, struct rt_addrinfo *info)
1246 {
1247 	struct ifaddr *ifa;
1248 
1249 	/*
1250 	 * give the protocol a chance to keep things in sync.
1251 	 */
1252 	ifa = rt->rt_ifa;
1253 	if (ifa != NULL && ifa->ifa_rtrequest != NULL)
1254 		ifa->ifa_rtrequest(RTM_DELETE, rt, info);
1255 
1256 	/*
1257 	 * One more rtentry floating around that is not
1258 	 * linked to the routing table. rttrash will be decremented
1259 	 * when RTFREE(rt) is eventually called.
1260 	 */
1261 	V_rttrash++;
1262 }
1263 
1264 
1265 /*
1266  * These (questionable) definitions of apparent local variables apply
1267  * to the next two functions.  XXXXXX!!!
1268  */
1269 #define	dst	info->rti_info[RTAX_DST]
1270 #define	gateway	info->rti_info[RTAX_GATEWAY]
1271 #define	netmask	info->rti_info[RTAX_NETMASK]
1272 #define	ifaaddr	info->rti_info[RTAX_IFA]
1273 #define	ifpaddr	info->rti_info[RTAX_IFP]
1274 #define	flags	info->rti_flags
1275 
1276 /*
1277  * Look up rt_addrinfo for a specific fib.  Note that if rti_ifa is defined,
1278  * it will be referenced so the caller must free it.
1279  *
1280  * Assume basic consistency checks are executed by callers:
1281  * RTAX_DST exists, if RTF_GATEWAY is set, RTAX_GATEWAY exists as well.
1282  */
1283 int
1284 rt_getifa_fib(struct rt_addrinfo *info, u_int fibnum)
1285 {
1286 	struct epoch_tracker et;
1287 	int needref, error;
1288 
1289 	/*
1290 	 * ifp may be specified by sockaddr_dl
1291 	 * when protocol address is ambiguous.
1292 	 */
1293 	error = 0;
1294 	needref = (info->rti_ifa == NULL);
1295 	NET_EPOCH_ENTER(et);
1296 
1297 	/* If we have interface specified by the ifindex in the address, use it */
1298 	if (info->rti_ifp == NULL && ifpaddr != NULL &&
1299 	    ifpaddr->sa_family == AF_LINK) {
1300 	    const struct sockaddr_dl *sdl = (const struct sockaddr_dl *)ifpaddr;
1301 	    if (sdl->sdl_index != 0)
1302 		    info->rti_ifp = ifnet_byindex_locked(sdl->sdl_index);
1303 	}
1304 	/*
1305 	 * If we have source address specified, try to find it
1306 	 * TODO: avoid enumerating all ifas on all interfaces.
1307 	 */
1308 	if (info->rti_ifa == NULL && ifaaddr != NULL)
1309 		info->rti_ifa = ifa_ifwithaddr(ifaaddr);
1310 	if (info->rti_ifa == NULL) {
1311 		struct sockaddr *sa;
1312 
1313 		/*
1314 		 * Most common use case for the userland-supplied routes.
1315 		 *
1316 		 * Choose sockaddr to select ifa.
1317 		 * -- if ifp is set --
1318 		 * Order of preference:
1319 		 * 1) IFA address
1320 		 * 2) gateway address
1321 		 *   Note: for interface routes link-level gateway address
1322 		 *     is specified to indicate the interface index without
1323 		 *     specifying RTF_GATEWAY. In this case, ignore gateway
1324 		 *   Note: gateway AF may be different from dst AF. In this case,
1325 		 *   ignore gateway
1326 		 * 3) final destination.
1327 		 * 4) if all of these fails, try to get at least link-level ifa.
1328 		 * -- else --
1329 		 * try to lookup gateway or dst in the routing table to get ifa
1330 		 */
1331 		if (info->rti_info[RTAX_IFA] != NULL)
1332 			sa = info->rti_info[RTAX_IFA];
1333 		else if ((info->rti_flags & RTF_GATEWAY) != 0 &&
1334 		    gateway->sa_family == dst->sa_family)
1335 			sa = gateway;
1336 		else
1337 			sa = dst;
1338 		if (info->rti_ifp != NULL) {
1339 			info->rti_ifa = ifaof_ifpforaddr(sa, info->rti_ifp);
1340 			/* Case 4 */
1341 			if (info->rti_ifa == NULL && gateway != NULL)
1342 				info->rti_ifa = ifaof_ifpforaddr(gateway, info->rti_ifp);
1343 		} else if (dst != NULL && gateway != NULL)
1344 			info->rti_ifa = ifa_ifwithroute(flags, dst, gateway,
1345 							fibnum);
1346 		else if (sa != NULL)
1347 			info->rti_ifa = ifa_ifwithroute(flags, sa, sa,
1348 							fibnum);
1349 	}
1350 	if (needref && info->rti_ifa != NULL) {
1351 		if (info->rti_ifp == NULL)
1352 			info->rti_ifp = info->rti_ifa->ifa_ifp;
1353 		ifa_ref(info->rti_ifa);
1354 	} else
1355 		error = ENETUNREACH;
1356 	NET_EPOCH_EXIT(et);
1357 	return (error);
1358 }
1359 
1360 static int
1361 if_updatemtu_cb(struct radix_node *rn, void *arg)
1362 {
1363 	struct rtentry *rt;
1364 	struct if_mtuinfo *ifmtu;
1365 
1366 	rt = (struct rtentry *)rn;
1367 	ifmtu = (struct if_mtuinfo *)arg;
1368 
1369 	if (rt->rt_ifp != ifmtu->ifp)
1370 		return (0);
1371 
1372 	if (rt->rt_mtu >= ifmtu->mtu) {
1373 		/* We have to decrease mtu regardless of flags */
1374 		rt->rt_mtu = ifmtu->mtu;
1375 		return (0);
1376 	}
1377 
1378 	/*
1379 	 * New MTU is bigger. Check if are allowed to alter it
1380 	 */
1381 	if ((rt->rt_flags & (RTF_FIXEDMTU | RTF_GATEWAY | RTF_HOST)) != 0) {
1382 
1383 		/*
1384 		 * Skip routes with user-supplied MTU and
1385 		 * non-interface routes
1386 		 */
1387 		return (0);
1388 	}
1389 
1390 	/* We are safe to update route MTU */
1391 	rt->rt_mtu = ifmtu->mtu;
1392 
1393 	return (0);
1394 }
1395 
1396 void
1397 rt_updatemtu(struct ifnet *ifp)
1398 {
1399 	struct if_mtuinfo ifmtu;
1400 	struct rib_head *rnh;
1401 	int i, j;
1402 
1403 	ifmtu.ifp = ifp;
1404 
1405 	/*
1406 	 * Try to update rt_mtu for all routes using this interface
1407 	 * Unfortunately the only way to do this is to traverse all
1408 	 * routing tables in all fibs/domains.
1409 	 */
1410 	for (i = 1; i <= AF_MAX; i++) {
1411 		ifmtu.mtu = if_getmtu_family(ifp, i);
1412 		for (j = 0; j < rt_numfibs; j++) {
1413 			rnh = rt_tables_get_rnh(j, i);
1414 			if (rnh == NULL)
1415 				continue;
1416 			RIB_WLOCK(rnh);
1417 			rnh->rnh_walktree(&rnh->head, if_updatemtu_cb, &ifmtu);
1418 			RIB_WUNLOCK(rnh);
1419 		}
1420 	}
1421 }
1422 
1423 
1424 #if 0
1425 int p_sockaddr(char *buf, int buflen, struct sockaddr *s);
1426 int rt_print(char *buf, int buflen, struct rtentry *rt);
1427 
1428 int
1429 p_sockaddr(char *buf, int buflen, struct sockaddr *s)
1430 {
1431 	void *paddr = NULL;
1432 
1433 	switch (s->sa_family) {
1434 	case AF_INET:
1435 		paddr = &((struct sockaddr_in *)s)->sin_addr;
1436 		break;
1437 	case AF_INET6:
1438 		paddr = &((struct sockaddr_in6 *)s)->sin6_addr;
1439 		break;
1440 	}
1441 
1442 	if (paddr == NULL)
1443 		return (0);
1444 
1445 	if (inet_ntop(s->sa_family, paddr, buf, buflen) == NULL)
1446 		return (0);
1447 
1448 	return (strlen(buf));
1449 }
1450 
1451 int
1452 rt_print(char *buf, int buflen, struct rtentry *rt)
1453 {
1454 	struct sockaddr *addr, *mask;
1455 	int i = 0;
1456 
1457 	addr = rt_key(rt);
1458 	mask = rt_mask(rt);
1459 
1460 	i = p_sockaddr(buf, buflen, addr);
1461 	if (!(rt->rt_flags & RTF_HOST)) {
1462 		buf[i++] = '/';
1463 		i += p_sockaddr(buf + i, buflen - i, mask);
1464 	}
1465 
1466 	if (rt->rt_flags & RTF_GATEWAY) {
1467 		buf[i++] = '>';
1468 		i += p_sockaddr(buf + i, buflen - i, rt->rt_gateway);
1469 	}
1470 
1471 	return (i);
1472 }
1473 #endif
1474 
1475 #ifdef RADIX_MPATH
1476 /*
1477  * Deletes key for single-path routes, unlinks rtentry with
1478  * gateway specified in @info from multi-path routes.
1479  *
1480  * Returnes unlinked entry. In case of failure, returns NULL
1481  * and sets @perror to ESRCH.
1482  */
1483 static struct radix_node *
1484 rt_mpath_unlink(struct rib_head *rnh, struct rt_addrinfo *info,
1485     struct rtentry *rto, int *perror)
1486 {
1487 	/*
1488 	 * if we got multipath routes, we require users to specify
1489 	 * a matching RTAX_GATEWAY.
1490 	 */
1491 	struct rtentry *rt; // *rto = NULL;
1492 	struct radix_node *rn;
1493 	struct sockaddr *gw;
1494 
1495 	gw = info->rti_info[RTAX_GATEWAY];
1496 	rt = rt_mpath_matchgate(rto, gw);
1497 	if (rt == NULL) {
1498 		*perror = ESRCH;
1499 		return (NULL);
1500 	}
1501 
1502 	/*
1503 	 * this is the first entry in the chain
1504 	 */
1505 	if (rto == rt) {
1506 		rn = rn_mpath_next((struct radix_node *)rt);
1507 		/*
1508 		 * there is another entry, now it's active
1509 		 */
1510 		if (rn) {
1511 			rto = RNTORT(rn);
1512 			RT_LOCK(rto);
1513 			rto->rt_flags |= RTF_UP;
1514 			RT_UNLOCK(rto);
1515 		} else if (rt->rt_flags & RTF_GATEWAY) {
1516 			/*
1517 			 * For gateway routes, we need to
1518 			 * make sure that we we are deleting
1519 			 * the correct gateway.
1520 			 * rt_mpath_matchgate() does not
1521 			 * check the case when there is only
1522 			 * one route in the chain.
1523 			 */
1524 			if (gw &&
1525 			    (rt->rt_gateway->sa_len != gw->sa_len ||
1526 				memcmp(rt->rt_gateway, gw, gw->sa_len))) {
1527 				*perror = ESRCH;
1528 				return (NULL);
1529 			}
1530 		}
1531 
1532 		/*
1533 		 * use the normal delete code to remove
1534 		 * the first entry
1535 		 */
1536 		rn = rnh->rnh_deladdr(dst, netmask, &rnh->head);
1537 		*perror = 0;
1538 		return (rn);
1539 	}
1540 
1541 	/*
1542 	 * if the entry is 2nd and on up
1543 	 */
1544 	if (rt_mpath_deldup(rto, rt) == 0)
1545 		panic ("rtrequest1: rt_mpath_deldup");
1546 	*perror = 0;
1547 	rn = (struct radix_node *)rt;
1548 	return (rn);
1549 }
1550 #endif
1551 
1552 int
1553 rtrequest1_fib(int req, struct rt_addrinfo *info, struct rtentry **ret_nrt,
1554 				u_int fibnum)
1555 {
1556 	int error = 0;
1557 	struct rtentry *rt, *rt_old;
1558 	struct radix_node *rn;
1559 	struct rib_head *rnh;
1560 	struct ifaddr *ifa;
1561 	struct sockaddr *ndst;
1562 	struct sockaddr_storage mdst;
1563 
1564 	KASSERT((fibnum < rt_numfibs), ("rtrequest1_fib: bad fibnum"));
1565 	KASSERT((flags & RTF_RNH_LOCKED) == 0, ("rtrequest1_fib: locked"));
1566 	switch (dst->sa_family) {
1567 	case AF_INET6:
1568 	case AF_INET:
1569 		/* We support multiple FIBs. */
1570 		break;
1571 	default:
1572 		fibnum = RT_DEFAULT_FIB;
1573 		break;
1574 	}
1575 
1576 	/*
1577 	 * Find the correct routing tree to use for this Address Family
1578 	 */
1579 	rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1580 	if (rnh == NULL)
1581 		return (EAFNOSUPPORT);
1582 
1583 	/*
1584 	 * If we are adding a host route then we don't want to put
1585 	 * a netmask in the tree, nor do we want to clone it.
1586 	 */
1587 	if (flags & RTF_HOST)
1588 		netmask = NULL;
1589 
1590 	switch (req) {
1591 	case RTM_DELETE:
1592 		if (netmask) {
1593 			if (dst->sa_len > sizeof(mdst))
1594 				return (EINVAL);
1595 			rt_maskedcopy(dst, (struct sockaddr *)&mdst, netmask);
1596 			dst = (struct sockaddr *)&mdst;
1597 		}
1598 
1599 		RIB_WLOCK(rnh);
1600 		rt = rt_unlinkrte(rnh, info, &error);
1601 		RIB_WUNLOCK(rnh);
1602 		if (error != 0)
1603 			return (error);
1604 
1605 		rt_notifydelete(rt, info);
1606 
1607 		/*
1608 		 * If the caller wants it, then it can have it,
1609 		 * but it's up to it to free the rtentry as we won't be
1610 		 * doing it.
1611 		 */
1612 		if (ret_nrt) {
1613 			*ret_nrt = rt;
1614 			RT_UNLOCK(rt);
1615 		} else
1616 			RTFREE_LOCKED(rt);
1617 		break;
1618 	case RTM_RESOLVE:
1619 		/*
1620 		 * resolve was only used for route cloning
1621 		 * here for compat
1622 		 */
1623 		break;
1624 	case RTM_ADD:
1625 		if ((flags & RTF_GATEWAY) && !gateway)
1626 			return (EINVAL);
1627 		if (dst && gateway && (dst->sa_family != gateway->sa_family) &&
1628 		    (gateway->sa_family != AF_UNSPEC) && (gateway->sa_family != AF_LINK))
1629 			return (EINVAL);
1630 
1631 		if (info->rti_ifa == NULL) {
1632 			error = rt_getifa_fib(info, fibnum);
1633 			if (error)
1634 				return (error);
1635 		}
1636 		rt = uma_zalloc(V_rtzone, M_NOWAIT);
1637 		if (rt == NULL) {
1638 			return (ENOBUFS);
1639 		}
1640 		rt->rt_flags = RTF_UP | flags;
1641 		rt->rt_fibnum = fibnum;
1642 		/*
1643 		 * Add the gateway. Possibly re-malloc-ing the storage for it.
1644 		 */
1645 		if ((error = rt_setgate(rt, dst, gateway)) != 0) {
1646 			uma_zfree(V_rtzone, rt);
1647 			return (error);
1648 		}
1649 
1650 		/*
1651 		 * point to the (possibly newly malloc'd) dest address.
1652 		 */
1653 		ndst = (struct sockaddr *)rt_key(rt);
1654 
1655 		/*
1656 		 * make sure it contains the value we want (masked if needed).
1657 		 */
1658 		if (netmask) {
1659 			rt_maskedcopy(dst, ndst, netmask);
1660 		} else
1661 			bcopy(dst, ndst, dst->sa_len);
1662 
1663 		/*
1664 		 * We use the ifa reference returned by rt_getifa_fib().
1665 		 * This moved from below so that rnh->rnh_addaddr() can
1666 		 * examine the ifa and  ifa->ifa_ifp if it so desires.
1667 		 */
1668 		ifa = info->rti_ifa;
1669 		ifa_ref(ifa);
1670 		rt->rt_ifa = ifa;
1671 		rt->rt_ifp = ifa->ifa_ifp;
1672 		rt->rt_weight = 1;
1673 
1674 		rt_setmetrics(info, rt);
1675 
1676 		RIB_WLOCK(rnh);
1677 		RT_LOCK(rt);
1678 #ifdef RADIX_MPATH
1679 		/* do not permit exactly the same dst/mask/gw pair */
1680 		if (rt_mpath_capable(rnh) &&
1681 			rt_mpath_conflict(rnh, rt, netmask)) {
1682 			RIB_WUNLOCK(rnh);
1683 
1684 			ifa_free(rt->rt_ifa);
1685 			R_Free(rt_key(rt));
1686 			uma_zfree(V_rtzone, rt);
1687 			return (EEXIST);
1688 		}
1689 #endif
1690 
1691 		/* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
1692 		rn = rnh->rnh_addaddr(ndst, netmask, &rnh->head, rt->rt_nodes);
1693 
1694 		rt_old = NULL;
1695 		if (rn == NULL && (info->rti_flags & RTF_PINNED) != 0) {
1696 
1697 			/*
1698 			 * Force removal and re-try addition
1699 			 * TODO: better multipath&pinned support
1700 			 */
1701 			struct sockaddr *info_dst = info->rti_info[RTAX_DST];
1702 			info->rti_info[RTAX_DST] = ndst;
1703 			/* Do not delete existing PINNED(interface) routes */
1704 			info->rti_flags &= ~RTF_PINNED;
1705 			rt_old = rt_unlinkrte(rnh, info, &error);
1706 			info->rti_flags |= RTF_PINNED;
1707 			info->rti_info[RTAX_DST] = info_dst;
1708 			if (rt_old != NULL)
1709 				rn = rnh->rnh_addaddr(ndst, netmask, &rnh->head,
1710 				    rt->rt_nodes);
1711 		}
1712 		RIB_WUNLOCK(rnh);
1713 
1714 		if (rt_old != NULL)
1715 			RT_UNLOCK(rt_old);
1716 
1717 		/*
1718 		 * If it still failed to go into the tree,
1719 		 * then un-make it (this should be a function)
1720 		 */
1721 		if (rn == NULL) {
1722 			ifa_free(rt->rt_ifa);
1723 			R_Free(rt_key(rt));
1724 			uma_zfree(V_rtzone, rt);
1725 			return (EEXIST);
1726 		}
1727 
1728 		if (rt_old != NULL) {
1729 			rt_notifydelete(rt_old, info);
1730 			RTFREE(rt_old);
1731 		}
1732 
1733 		/*
1734 		 * If this protocol has something to add to this then
1735 		 * allow it to do that as well.
1736 		 */
1737 		if (ifa->ifa_rtrequest)
1738 			ifa->ifa_rtrequest(req, rt, info);
1739 
1740 		/*
1741 		 * actually return a resultant rtentry and
1742 		 * give the caller a single reference.
1743 		 */
1744 		if (ret_nrt) {
1745 			*ret_nrt = rt;
1746 			RT_ADDREF(rt);
1747 		}
1748 		rnh->rnh_gen++;		/* Routing table updated */
1749 		RT_UNLOCK(rt);
1750 		break;
1751 	case RTM_CHANGE:
1752 		RIB_WLOCK(rnh);
1753 		error = rtrequest1_fib_change(rnh, info, ret_nrt, fibnum);
1754 		RIB_WUNLOCK(rnh);
1755 		break;
1756 	default:
1757 		error = EOPNOTSUPP;
1758 	}
1759 
1760 	return (error);
1761 }
1762 
1763 #undef dst
1764 #undef gateway
1765 #undef netmask
1766 #undef ifaaddr
1767 #undef ifpaddr
1768 #undef flags
1769 
1770 static int
1771 rtrequest1_fib_change(struct rib_head *rnh, struct rt_addrinfo *info,
1772     struct rtentry **ret_nrt, u_int fibnum)
1773 {
1774 	struct rtentry *rt = NULL;
1775 	int error = 0;
1776 	int free_ifa = 0;
1777 	int family, mtu;
1778 	struct if_mtuinfo ifmtu;
1779 
1780 	RIB_WLOCK_ASSERT(rnh);
1781 
1782 	rt = (struct rtentry *)rnh->rnh_lookup(info->rti_info[RTAX_DST],
1783 	    info->rti_info[RTAX_NETMASK], &rnh->head);
1784 
1785 	if (rt == NULL)
1786 		return (ESRCH);
1787 
1788 #ifdef RADIX_MPATH
1789 	/*
1790 	 * If we got multipath routes,
1791 	 * we require users to specify a matching RTAX_GATEWAY.
1792 	 */
1793 	if (rt_mpath_capable(rnh)) {
1794 		rt = rt_mpath_matchgate(rt, info->rti_info[RTAX_GATEWAY]);
1795 		if (rt == NULL)
1796 			return (ESRCH);
1797 	}
1798 #endif
1799 
1800 	RT_LOCK(rt);
1801 
1802 	rt_setmetrics(info, rt);
1803 
1804 	/*
1805 	 * New gateway could require new ifaddr, ifp;
1806 	 * flags may also be different; ifp may be specified
1807 	 * by ll sockaddr when protocol address is ambiguous
1808 	 */
1809 	if (((rt->rt_flags & RTF_GATEWAY) &&
1810 	    info->rti_info[RTAX_GATEWAY] != NULL) ||
1811 	    info->rti_info[RTAX_IFP] != NULL ||
1812 	    (info->rti_info[RTAX_IFA] != NULL &&
1813 	     !sa_equal(info->rti_info[RTAX_IFA], rt->rt_ifa->ifa_addr))) {
1814 		/*
1815 		 * XXX: Temporarily set RTF_RNH_LOCKED flag in the rti_flags
1816 		 *	to avoid rlock in the ifa_ifwithroute().
1817 		 */
1818 		info->rti_flags |= RTF_RNH_LOCKED;
1819 		error = rt_getifa_fib(info, fibnum);
1820 		info->rti_flags &= ~RTF_RNH_LOCKED;
1821 		if (info->rti_ifa != NULL)
1822 			free_ifa = 1;
1823 
1824 		if (error != 0)
1825 			goto bad;
1826 	}
1827 
1828 	/* Check if outgoing interface has changed */
1829 	if (info->rti_ifa != NULL && info->rti_ifa != rt->rt_ifa &&
1830 	    rt->rt_ifa != NULL) {
1831 		if (rt->rt_ifa->ifa_rtrequest != NULL)
1832 			rt->rt_ifa->ifa_rtrequest(RTM_DELETE, rt, info);
1833 		ifa_free(rt->rt_ifa);
1834 		rt->rt_ifa = NULL;
1835 	}
1836 	/* Update gateway address */
1837 	if (info->rti_info[RTAX_GATEWAY] != NULL) {
1838 		error = rt_setgate(rt, rt_key(rt), info->rti_info[RTAX_GATEWAY]);
1839 		if (error != 0)
1840 			goto bad;
1841 
1842 		rt->rt_flags &= ~RTF_GATEWAY;
1843 		rt->rt_flags |= (RTF_GATEWAY & info->rti_flags);
1844 	}
1845 
1846 	if (info->rti_ifa != NULL && info->rti_ifa != rt->rt_ifa) {
1847 		ifa_ref(info->rti_ifa);
1848 		rt->rt_ifa = info->rti_ifa;
1849 		rt->rt_ifp = info->rti_ifp;
1850 	}
1851 	/* Allow some flags to be toggled on change. */
1852 	rt->rt_flags &= ~RTF_FMASK;
1853 	rt->rt_flags |= info->rti_flags & RTF_FMASK;
1854 
1855 	if (rt->rt_ifa && rt->rt_ifa->ifa_rtrequest != NULL)
1856 	       rt->rt_ifa->ifa_rtrequest(RTM_ADD, rt, info);
1857 
1858 	/* Alter route MTU if necessary */
1859 	if (rt->rt_ifp != NULL) {
1860 		family = info->rti_info[RTAX_DST]->sa_family;
1861 		mtu = if_getmtu_family(rt->rt_ifp, family);
1862 		/* Set default MTU */
1863 		if (rt->rt_mtu == 0)
1864 			rt->rt_mtu = mtu;
1865 		if (rt->rt_mtu != mtu) {
1866 			/* Check if we really need to update */
1867 			ifmtu.ifp = rt->rt_ifp;
1868 			ifmtu.mtu = mtu;
1869 			if_updatemtu_cb(rt->rt_nodes, &ifmtu);
1870 		}
1871 	}
1872 
1873 	/*
1874 	 * This route change may have modified the route's gateway.  In that
1875 	 * case, any inpcbs that have cached this route need to invalidate their
1876 	 * llentry cache.
1877 	 */
1878 	rnh->rnh_gen++;
1879 
1880 	if (ret_nrt) {
1881 		*ret_nrt = rt;
1882 		RT_ADDREF(rt);
1883 	}
1884 bad:
1885 	RT_UNLOCK(rt);
1886 	if (free_ifa != 0) {
1887 		ifa_free(info->rti_ifa);
1888 		info->rti_ifa = NULL;
1889 	}
1890 	return (error);
1891 }
1892 
1893 static void
1894 rt_setmetrics(const struct rt_addrinfo *info, struct rtentry *rt)
1895 {
1896 
1897 	if (info->rti_mflags & RTV_MTU) {
1898 		if (info->rti_rmx->rmx_mtu != 0) {
1899 
1900 			/*
1901 			 * MTU was explicitly provided by user.
1902 			 * Keep it.
1903 			 */
1904 			rt->rt_flags |= RTF_FIXEDMTU;
1905 		} else {
1906 
1907 			/*
1908 			 * User explicitly sets MTU to 0.
1909 			 * Assume rollback to default.
1910 			 */
1911 			rt->rt_flags &= ~RTF_FIXEDMTU;
1912 		}
1913 		rt->rt_mtu = info->rti_rmx->rmx_mtu;
1914 	}
1915 	if (info->rti_mflags & RTV_WEIGHT)
1916 		rt->rt_weight = info->rti_rmx->rmx_weight;
1917 	/* Kernel -> userland timebase conversion. */
1918 	if (info->rti_mflags & RTV_EXPIRE)
1919 		rt->rt_expire = info->rti_rmx->rmx_expire ?
1920 		    info->rti_rmx->rmx_expire - time_second + time_uptime : 0;
1921 }
1922 
1923 int
1924 rt_setgate(struct rtentry *rt, struct sockaddr *dst, struct sockaddr *gate)
1925 {
1926 	/* XXX dst may be overwritten, can we move this to below */
1927 	int dlen = SA_SIZE(dst), glen = SA_SIZE(gate);
1928 
1929 	/*
1930 	 * Prepare to store the gateway in rt->rt_gateway.
1931 	 * Both dst and gateway are stored one after the other in the same
1932 	 * malloc'd chunk. If we have room, we can reuse the old buffer,
1933 	 * rt_gateway already points to the right place.
1934 	 * Otherwise, malloc a new block and update the 'dst' address.
1935 	 */
1936 	if (rt->rt_gateway == NULL || glen > SA_SIZE(rt->rt_gateway)) {
1937 		caddr_t new;
1938 
1939 		R_Malloc(new, caddr_t, dlen + glen);
1940 		if (new == NULL)
1941 			return ENOBUFS;
1942 		/*
1943 		 * XXX note, we copy from *dst and not *rt_key(rt) because
1944 		 * rt_setgate() can be called to initialize a newly
1945 		 * allocated route entry, in which case rt_key(rt) == NULL
1946 		 * (and also rt->rt_gateway == NULL).
1947 		 * Free()/free() handle a NULL argument just fine.
1948 		 */
1949 		bcopy(dst, new, dlen);
1950 		R_Free(rt_key(rt));	/* free old block, if any */
1951 		rt_key(rt) = (struct sockaddr *)new;
1952 		rt->rt_gateway = (struct sockaddr *)(new + dlen);
1953 	}
1954 
1955 	/*
1956 	 * Copy the new gateway value into the memory chunk.
1957 	 */
1958 	bcopy(gate, rt->rt_gateway, glen);
1959 
1960 	return (0);
1961 }
1962 
1963 void
1964 rt_maskedcopy(struct sockaddr *src, struct sockaddr *dst, struct sockaddr *netmask)
1965 {
1966 	u_char *cp1 = (u_char *)src;
1967 	u_char *cp2 = (u_char *)dst;
1968 	u_char *cp3 = (u_char *)netmask;
1969 	u_char *cplim = cp2 + *cp3;
1970 	u_char *cplim2 = cp2 + *cp1;
1971 
1972 	*cp2++ = *cp1++; *cp2++ = *cp1++; /* copies sa_len & sa_family */
1973 	cp3 += 2;
1974 	if (cplim > cplim2)
1975 		cplim = cplim2;
1976 	while (cp2 < cplim)
1977 		*cp2++ = *cp1++ & *cp3++;
1978 	if (cp2 < cplim2)
1979 		bzero((caddr_t)cp2, (unsigned)(cplim2 - cp2));
1980 }
1981 
1982 /*
1983  * Set up a routing table entry, normally
1984  * for an interface.
1985  */
1986 #define _SOCKADDR_TMPSIZE 128 /* Not too big.. kernel stack size is limited */
1987 static inline  int
1988 rtinit1(struct ifaddr *ifa, int cmd, int flags, int fibnum)
1989 {
1990 	RIB_RLOCK_TRACKER;
1991 	struct sockaddr *dst;
1992 	struct sockaddr *netmask;
1993 	struct rtentry *rt = NULL;
1994 	struct rt_addrinfo info;
1995 	int error = 0;
1996 	int startfib, endfib;
1997 	char tempbuf[_SOCKADDR_TMPSIZE];
1998 	int didwork = 0;
1999 	int a_failure = 0;
2000 	struct sockaddr_dl *sdl = NULL;
2001 	struct rib_head *rnh;
2002 
2003 	if (flags & RTF_HOST) {
2004 		dst = ifa->ifa_dstaddr;
2005 		netmask = NULL;
2006 	} else {
2007 		dst = ifa->ifa_addr;
2008 		netmask = ifa->ifa_netmask;
2009 	}
2010 	if (dst->sa_len == 0)
2011 		return(EINVAL);
2012 	switch (dst->sa_family) {
2013 	case AF_INET6:
2014 	case AF_INET:
2015 		/* We support multiple FIBs. */
2016 		break;
2017 	default:
2018 		fibnum = RT_DEFAULT_FIB;
2019 		break;
2020 	}
2021 	if (fibnum == RT_ALL_FIBS) {
2022 		if (V_rt_add_addr_allfibs == 0 && cmd == (int)RTM_ADD)
2023 			startfib = endfib = ifa->ifa_ifp->if_fib;
2024 		else {
2025 			startfib = 0;
2026 			endfib = rt_numfibs - 1;
2027 		}
2028 	} else {
2029 		KASSERT((fibnum < rt_numfibs), ("rtinit1: bad fibnum"));
2030 		startfib = fibnum;
2031 		endfib = fibnum;
2032 	}
2033 
2034 	/*
2035 	 * If it's a delete, check that if it exists,
2036 	 * it's on the correct interface or we might scrub
2037 	 * a route to another ifa which would
2038 	 * be confusing at best and possibly worse.
2039 	 */
2040 	if (cmd == RTM_DELETE) {
2041 		/*
2042 		 * It's a delete, so it should already exist..
2043 		 * If it's a net, mask off the host bits
2044 		 * (Assuming we have a mask)
2045 		 * XXX this is kinda inet specific..
2046 		 */
2047 		if (netmask != NULL) {
2048 			rt_maskedcopy(dst, (struct sockaddr *)tempbuf, netmask);
2049 			dst = (struct sockaddr *)tempbuf;
2050 		}
2051 	} else if (cmd == RTM_ADD) {
2052 		sdl = (struct sockaddr_dl *)tempbuf;
2053 		bzero(sdl, sizeof(struct sockaddr_dl));
2054 		sdl->sdl_family = AF_LINK;
2055 		sdl->sdl_len = sizeof(struct sockaddr_dl);
2056 		sdl->sdl_type = ifa->ifa_ifp->if_type;
2057 		sdl->sdl_index = ifa->ifa_ifp->if_index;
2058         }
2059 	/*
2060 	 * Now go through all the requested tables (fibs) and do the
2061 	 * requested action. Realistically, this will either be fib 0
2062 	 * for protocols that don't do multiple tables or all the
2063 	 * tables for those that do.
2064 	 */
2065 	for ( fibnum = startfib; fibnum <= endfib; fibnum++) {
2066 		if (cmd == RTM_DELETE) {
2067 			struct radix_node *rn;
2068 			/*
2069 			 * Look up an rtentry that is in the routing tree and
2070 			 * contains the correct info.
2071 			 */
2072 			rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
2073 			if (rnh == NULL)
2074 				/* this table doesn't exist but others might */
2075 				continue;
2076 			RIB_RLOCK(rnh);
2077 			rn = rnh->rnh_lookup(dst, netmask, &rnh->head);
2078 #ifdef RADIX_MPATH
2079 			if (rt_mpath_capable(rnh)) {
2080 
2081 				if (rn == NULL)
2082 					error = ESRCH;
2083 				else {
2084 					rt = RNTORT(rn);
2085 					/*
2086 					 * for interface route the
2087 					 * rt->rt_gateway is sockaddr_intf
2088 					 * for cloning ARP entries, so
2089 					 * rt_mpath_matchgate must use the
2090 					 * interface address
2091 					 */
2092 					rt = rt_mpath_matchgate(rt,
2093 					    ifa->ifa_addr);
2094 					if (rt == NULL)
2095 						error = ESRCH;
2096 				}
2097 			}
2098 #endif
2099 			error = (rn == NULL ||
2100 			    (rn->rn_flags & RNF_ROOT) ||
2101 			    RNTORT(rn)->rt_ifa != ifa);
2102 			RIB_RUNLOCK(rnh);
2103 			if (error) {
2104 				/* this is only an error if bad on ALL tables */
2105 				continue;
2106 			}
2107 		}
2108 		/*
2109 		 * Do the actual request
2110 		 */
2111 		bzero((caddr_t)&info, sizeof(info));
2112 		ifa_ref(ifa);
2113 		info.rti_ifa = ifa;
2114 		info.rti_flags = flags |
2115 		    (ifa->ifa_flags & ~IFA_RTSELF) | RTF_PINNED;
2116 		info.rti_info[RTAX_DST] = dst;
2117 		/*
2118 		 * doing this for compatibility reasons
2119 		 */
2120 		if (cmd == RTM_ADD)
2121 			info.rti_info[RTAX_GATEWAY] = (struct sockaddr *)sdl;
2122 		else
2123 			info.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
2124 		info.rti_info[RTAX_NETMASK] = netmask;
2125 		error = rtrequest1_fib(cmd, &info, &rt, fibnum);
2126 
2127 		if (error == 0 && rt != NULL) {
2128 			/*
2129 			 * notify any listening routing agents of the change
2130 			 */
2131 			RT_LOCK(rt);
2132 #ifdef RADIX_MPATH
2133 			/*
2134 			 * in case address alias finds the first address
2135 			 * e.g. ifconfig bge0 192.0.2.246/24
2136 			 * e.g. ifconfig bge0 192.0.2.247/24
2137 			 * the address set in the route is 192.0.2.246
2138 			 * so we need to replace it with 192.0.2.247
2139 			 */
2140 			if (memcmp(rt->rt_ifa->ifa_addr,
2141 			    ifa->ifa_addr, ifa->ifa_addr->sa_len)) {
2142 				ifa_free(rt->rt_ifa);
2143 				ifa_ref(ifa);
2144 				rt->rt_ifp = ifa->ifa_ifp;
2145 				rt->rt_ifa = ifa;
2146 			}
2147 #endif
2148 			RT_ADDREF(rt);
2149 			RT_UNLOCK(rt);
2150 			rt_newaddrmsg_fib(cmd, ifa, error, rt, fibnum);
2151 			RT_LOCK(rt);
2152 			RT_REMREF(rt);
2153 			if (cmd == RTM_DELETE) {
2154 				/*
2155 				 * If we are deleting, and we found an entry,
2156 				 * then it's been removed from the tree..
2157 				 * now throw it away.
2158 				 */
2159 				RTFREE_LOCKED(rt);
2160 			} else {
2161 				if (cmd == RTM_ADD) {
2162 					/*
2163 					 * We just wanted to add it..
2164 					 * we don't actually need a reference.
2165 					 */
2166 					RT_REMREF(rt);
2167 				}
2168 				RT_UNLOCK(rt);
2169 			}
2170 			didwork = 1;
2171 		}
2172 		if (error)
2173 			a_failure = error;
2174 	}
2175 	if (cmd == RTM_DELETE) {
2176 		if (didwork) {
2177 			error = 0;
2178 		} else {
2179 			/* we only give an error if it wasn't in any table */
2180 			error = ((flags & RTF_HOST) ?
2181 			    EHOSTUNREACH : ENETUNREACH);
2182 		}
2183 	} else {
2184 		if (a_failure) {
2185 			/* return an error if any of them failed */
2186 			error = a_failure;
2187 		}
2188 	}
2189 	return (error);
2190 }
2191 
2192 /*
2193  * Set up a routing table entry, normally
2194  * for an interface.
2195  */
2196 int
2197 rtinit(struct ifaddr *ifa, int cmd, int flags)
2198 {
2199 	struct sockaddr *dst;
2200 	int fib = RT_DEFAULT_FIB;
2201 
2202 	if (flags & RTF_HOST) {
2203 		dst = ifa->ifa_dstaddr;
2204 	} else {
2205 		dst = ifa->ifa_addr;
2206 	}
2207 
2208 	switch (dst->sa_family) {
2209 	case AF_INET6:
2210 	case AF_INET:
2211 		/* We do support multiple FIBs. */
2212 		fib = RT_ALL_FIBS;
2213 		break;
2214 	}
2215 	return (rtinit1(ifa, cmd, flags, fib));
2216 }
2217 
2218 /*
2219  * Announce interface address arrival/withdraw
2220  * Returns 0 on success.
2221  */
2222 int
2223 rt_addrmsg(int cmd, struct ifaddr *ifa, int fibnum)
2224 {
2225 
2226 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
2227 	    ("unexpected cmd %d", cmd));
2228 
2229 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
2230 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
2231 
2232 #if defined(INET) || defined(INET6)
2233 #ifdef SCTP
2234 	/*
2235 	 * notify the SCTP stack
2236 	 * this will only get called when an address is added/deleted
2237 	 * XXX pass the ifaddr struct instead if ifa->ifa_addr...
2238 	 */
2239 	sctp_addr_change(ifa, cmd);
2240 #endif /* SCTP */
2241 #endif
2242 	return (rtsock_addrmsg(cmd, ifa, fibnum));
2243 }
2244 
2245 /*
2246  * Announce route addition/removal.
2247  * Users of this function MUST validate input data BEFORE calling.
2248  * However we have to be able to handle invalid data:
2249  * if some userland app sends us "invalid" route message (invalid mask,
2250  * no dst, wrong address families, etc...) we need to pass it back
2251  * to app (and any other rtsock consumers) with rtm_errno field set to
2252  * non-zero value.
2253  * Returns 0 on success.
2254  */
2255 int
2256 rt_routemsg(int cmd, struct ifnet *ifp, int error, struct rtentry *rt,
2257     int fibnum)
2258 {
2259 
2260 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
2261 	    ("unexpected cmd %d", cmd));
2262 
2263 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
2264 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
2265 
2266 	KASSERT(rt_key(rt) != NULL, (":%s: rt_key must be supplied", __func__));
2267 
2268 	return (rtsock_routemsg(cmd, ifp, error, rt, fibnum));
2269 }
2270 
2271 void
2272 rt_newaddrmsg(int cmd, struct ifaddr *ifa, int error, struct rtentry *rt)
2273 {
2274 
2275 	rt_newaddrmsg_fib(cmd, ifa, error, rt, RT_ALL_FIBS);
2276 }
2277 
2278 /*
2279  * This is called to generate messages from the routing socket
2280  * indicating a network interface has had addresses associated with it.
2281  */
2282 void
2283 rt_newaddrmsg_fib(int cmd, struct ifaddr *ifa, int error, struct rtentry *rt,
2284     int fibnum)
2285 {
2286 
2287 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
2288 		("unexpected cmd %u", cmd));
2289 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
2290 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
2291 
2292 	if (cmd == RTM_ADD) {
2293 		rt_addrmsg(cmd, ifa, fibnum);
2294 		if (rt != NULL)
2295 			rt_routemsg(cmd, ifa->ifa_ifp, error, rt, fibnum);
2296 	} else {
2297 		if (rt != NULL)
2298 			rt_routemsg(cmd, ifa->ifa_ifp, error, rt, fibnum);
2299 		rt_addrmsg(cmd, ifa, fibnum);
2300 	}
2301 }
2302 
2303