route.c revision 263478
1/*-
2 * Copyright (c) 1980, 1986, 1991, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 *    may be used to endorse or promote products derived from this software
15 *    without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 *	@(#)route.c	8.3.1.1 (Berkeley) 2/23/95
30 * $FreeBSD: stable/10/sys/net/route.c 263478 2014-03-21 15:15:30Z glebius $
31 */
32/************************************************************************
33 * Note: In this file a 'fib' is a "forwarding information base"	*
34 * Which is the new name for an in kernel routing (next hop) table.	*
35 ***********************************************************************/
36
37#include "opt_inet.h"
38#include "opt_inet6.h"
39#include "opt_route.h"
40#include "opt_mrouting.h"
41#include "opt_mpath.h"
42
43#include <sys/param.h>
44#include <sys/systm.h>
45#include <sys/syslog.h>
46#include <sys/malloc.h>
47#include <sys/mbuf.h>
48#include <sys/socket.h>
49#include <sys/sysctl.h>
50#include <sys/syslog.h>
51#include <sys/sysproto.h>
52#include <sys/proc.h>
53#include <sys/domain.h>
54#include <sys/kernel.h>
55
56#include <net/if.h>
57#include <net/if_dl.h>
58#include <net/route.h>
59#include <net/vnet.h>
60#include <net/flowtable.h>
61
62#ifdef RADIX_MPATH
63#include <net/radix_mpath.h>
64#endif
65
66#include <netinet/in.h>
67#include <netinet/ip_mroute.h>
68
69#include <vm/uma.h>
70
71#define	RT_MAXFIBS	UINT16_MAX
72
73/* Kernel config default option. */
74#ifdef ROUTETABLES
75#if ROUTETABLES <= 0
76#error "ROUTETABLES defined too low"
77#endif
78#if ROUTETABLES > RT_MAXFIBS
79#error "ROUTETABLES defined too big"
80#endif
81#define	RT_NUMFIBS	ROUTETABLES
82#endif /* ROUTETABLES */
83/* Initialize to default if not otherwise set. */
84#ifndef	RT_NUMFIBS
85#define	RT_NUMFIBS	1
86#endif
87
88/* This is read-only.. */
89u_int rt_numfibs = RT_NUMFIBS;
90SYSCTL_UINT(_net, OID_AUTO, fibs, CTLFLAG_RD, &rt_numfibs, 0, "");
91/* and this can be set too big but will be fixed before it is used */
92TUNABLE_INT("net.fibs", &rt_numfibs);
93
94/*
95 * By default add routes to all fibs for new interfaces.
96 * Once this is set to 0 then only allocate routes on interface
97 * changes for the FIB of the caller when adding a new set of addresses
98 * to an interface.  XXX this is a shotgun aproach to a problem that needs
99 * a more fine grained solution.. that will come.
100 * XXX also has the problems getting the FIB from curthread which will not
101 * always work given the fib can be overridden and prefixes can be added
102 * from the network stack context.
103 */
104u_int rt_add_addr_allfibs = 1;
105SYSCTL_UINT(_net, OID_AUTO, add_addr_allfibs, CTLFLAG_RW,
106    &rt_add_addr_allfibs, 0, "");
107TUNABLE_INT("net.add_addr_allfibs", &rt_add_addr_allfibs);
108
109VNET_DEFINE(struct rtstat, rtstat);
110#define	V_rtstat	VNET(rtstat)
111
112VNET_DEFINE(struct radix_node_head *, rt_tables);
113#define	V_rt_tables	VNET(rt_tables)
114
115VNET_DEFINE(int, rttrash);		/* routes not in table but not freed */
116#define	V_rttrash	VNET(rttrash)
117
118
119/* compare two sockaddr structures */
120#define	sa_equal(a1, a2) (bcmp((a1), (a2), (a1)->sa_len) == 0)
121
122/*
123 * Convert a 'struct radix_node *' to a 'struct rtentry *'.
124 * The operation can be done safely (in this code) because a
125 * 'struct rtentry' starts with two 'struct radix_node''s, the first
126 * one representing leaf nodes in the routing tree, which is
127 * what the code in radix.c passes us as a 'struct radix_node'.
128 *
129 * But because there are a lot of assumptions in this conversion,
130 * do not cast explicitly, but always use the macro below.
131 */
132#define RNTORT(p)	((struct rtentry *)(p))
133
134static VNET_DEFINE(uma_zone_t, rtzone);		/* Routing table UMA zone. */
135#define	V_rtzone	VNET(rtzone)
136
137/*
138 * handler for net.my_fibnum
139 */
140static int
141sysctl_my_fibnum(SYSCTL_HANDLER_ARGS)
142{
143        int fibnum;
144        int error;
145
146        fibnum = curthread->td_proc->p_fibnum;
147        error = sysctl_handle_int(oidp, &fibnum, 0, req);
148        return (error);
149}
150
151SYSCTL_PROC(_net, OID_AUTO, my_fibnum, CTLTYPE_INT|CTLFLAG_RD,
152            NULL, 0, &sysctl_my_fibnum, "I", "default FIB of caller");
153
154static __inline struct radix_node_head **
155rt_tables_get_rnh_ptr(int table, int fam)
156{
157	struct radix_node_head **rnh;
158
159	KASSERT(table >= 0 && table < rt_numfibs, ("%s: table out of bounds.",
160	    __func__));
161	KASSERT(fam >= 0 && fam < (AF_MAX+1), ("%s: fam out of bounds.",
162	    __func__));
163
164	/* rnh is [fib=0][af=0]. */
165	rnh = (struct radix_node_head **)V_rt_tables;
166	/* Get the offset to the requested table and fam. */
167	rnh += table * (AF_MAX+1) + fam;
168
169	return (rnh);
170}
171
172struct radix_node_head *
173rt_tables_get_rnh(int table, int fam)
174{
175
176	return (*rt_tables_get_rnh_ptr(table, fam));
177}
178
179/*
180 * route initialization must occur before ip6_init2(), which happenas at
181 * SI_ORDER_MIDDLE.
182 */
183static void
184route_init(void)
185{
186	struct domain *dom;
187	int max_keylen = 0;
188
189	/* whack the tunable ints into  line. */
190	if (rt_numfibs > RT_MAXFIBS)
191		rt_numfibs = RT_MAXFIBS;
192	if (rt_numfibs == 0)
193		rt_numfibs = 1;
194
195	for (dom = domains; dom; dom = dom->dom_next)
196		if (dom->dom_maxrtkey > max_keylen)
197			max_keylen = dom->dom_maxrtkey;
198
199	rn_init(max_keylen);	/* init all zeroes, all ones, mask table */
200}
201SYSINIT(route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, route_init, 0);
202
203static int
204rtentry_zinit(void *mem, int size, int how)
205{
206	struct rtentry *rt = mem;
207
208	rt->rt_pksent = counter_u64_alloc(how);
209	if (rt->rt_pksent == NULL)
210		return (ENOMEM);
211
212	RT_LOCK_INIT(rt);
213
214	return (0);
215}
216
217static void
218rtentry_zfini(void *mem, int size)
219{
220	struct rtentry *rt = mem;
221
222	RT_LOCK_DESTROY(rt);
223	counter_u64_free(rt->rt_pksent);
224}
225
226static int
227rtentry_ctor(void *mem, int size, void *arg, int how)
228{
229	struct rtentry *rt = mem;
230
231	bzero(rt, offsetof(struct rtentry, rt_endzero));
232	counter_u64_zero(rt->rt_pksent);
233
234	return (0);
235}
236
237static void
238rtentry_dtor(void *mem, int size, void *arg)
239{
240	struct rtentry *rt = mem;
241
242	RT_UNLOCK_COND(rt);
243}
244
245static void
246vnet_route_init(const void *unused __unused)
247{
248	struct domain *dom;
249	struct radix_node_head **rnh;
250	int table;
251	int fam;
252
253	V_rt_tables = malloc(rt_numfibs * (AF_MAX+1) *
254	    sizeof(struct radix_node_head *), M_RTABLE, M_WAITOK|M_ZERO);
255
256	V_rtzone = uma_zcreate("rtentry", sizeof(struct rtentry),
257	    rtentry_ctor, rtentry_dtor,
258	    rtentry_zinit, rtentry_zfini, UMA_ALIGN_PTR, 0);
259	for (dom = domains; dom; dom = dom->dom_next) {
260		if (dom->dom_rtattach == NULL)
261			continue;
262
263		for  (table = 0; table < rt_numfibs; table++) {
264			fam = dom->dom_family;
265			if (table != 0 && fam != AF_INET6 && fam != AF_INET)
266				break;
267
268			/*
269			 * XXX MRT rtattach will be also called from
270			 * vfs_export.c but the offset will be 0 (only for
271			 * AF_INET and AF_INET6 which don't need it anyhow).
272			 */
273			rnh = rt_tables_get_rnh_ptr(table, fam);
274			if (rnh == NULL)
275				panic("%s: rnh NULL", __func__);
276			dom->dom_rtattach((void **)rnh, dom->dom_rtoffset);
277		}
278	}
279}
280VNET_SYSINIT(vnet_route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH,
281    vnet_route_init, 0);
282
283#ifdef VIMAGE
284static void
285vnet_route_uninit(const void *unused __unused)
286{
287	int table;
288	int fam;
289	struct domain *dom;
290	struct radix_node_head **rnh;
291
292	for (dom = domains; dom; dom = dom->dom_next) {
293		if (dom->dom_rtdetach == NULL)
294			continue;
295
296		for (table = 0; table < rt_numfibs; table++) {
297			fam = dom->dom_family;
298
299			if (table != 0 && fam != AF_INET6 && fam != AF_INET)
300				break;
301
302			rnh = rt_tables_get_rnh_ptr(table, fam);
303			if (rnh == NULL)
304				panic("%s: rnh NULL", __func__);
305			dom->dom_rtdetach((void **)rnh, dom->dom_rtoffset);
306		}
307	}
308
309	free(V_rt_tables, M_RTABLE);
310	uma_zdestroy(V_rtzone);
311}
312VNET_SYSUNINIT(vnet_route_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD,
313    vnet_route_uninit, 0);
314#endif
315
316#ifndef _SYS_SYSPROTO_H_
317struct setfib_args {
318	int     fibnum;
319};
320#endif
321int
322sys_setfib(struct thread *td, struct setfib_args *uap)
323{
324	if (uap->fibnum < 0 || uap->fibnum >= rt_numfibs)
325		return EINVAL;
326	td->td_proc->p_fibnum = uap->fibnum;
327	return (0);
328}
329
330/*
331 * Packet routing routines.
332 */
333void
334rtalloc(struct route *ro)
335{
336
337	rtalloc_ign_fib(ro, 0UL, RT_DEFAULT_FIB);
338}
339
340void
341rtalloc_fib(struct route *ro, u_int fibnum)
342{
343	rtalloc_ign_fib(ro, 0UL, fibnum);
344}
345
346void
347rtalloc_ign(struct route *ro, u_long ignore)
348{
349	struct rtentry *rt;
350
351	if ((rt = ro->ro_rt) != NULL) {
352		if (rt->rt_ifp != NULL && rt->rt_flags & RTF_UP)
353			return;
354		RTFREE(rt);
355		ro->ro_rt = NULL;
356	}
357	ro->ro_rt = rtalloc1_fib(&ro->ro_dst, 1, ignore, RT_DEFAULT_FIB);
358	if (ro->ro_rt)
359		RT_UNLOCK(ro->ro_rt);
360}
361
362void
363rtalloc_ign_fib(struct route *ro, u_long ignore, u_int fibnum)
364{
365	struct rtentry *rt;
366
367	if ((rt = ro->ro_rt) != NULL) {
368		if (rt->rt_ifp != NULL && rt->rt_flags & RTF_UP)
369			return;
370		RTFREE(rt);
371		ro->ro_rt = NULL;
372	}
373	ro->ro_rt = rtalloc1_fib(&ro->ro_dst, 1, ignore, fibnum);
374	if (ro->ro_rt)
375		RT_UNLOCK(ro->ro_rt);
376}
377
378/*
379 * Look up the route that matches the address given
380 * Or, at least try.. Create a cloned route if needed.
381 *
382 * The returned route, if any, is locked.
383 */
384struct rtentry *
385rtalloc1(struct sockaddr *dst, int report, u_long ignflags)
386{
387
388	return (rtalloc1_fib(dst, report, ignflags, RT_DEFAULT_FIB));
389}
390
391struct rtentry *
392rtalloc1_fib(struct sockaddr *dst, int report, u_long ignflags,
393		    u_int fibnum)
394{
395	struct radix_node_head *rnh;
396	struct radix_node *rn;
397	struct rtentry *newrt;
398	struct rt_addrinfo info;
399	int err = 0, msgtype = RTM_MISS;
400	int needlock;
401
402	KASSERT((fibnum < rt_numfibs), ("rtalloc1_fib: bad fibnum"));
403	switch (dst->sa_family) {
404	case AF_INET6:
405	case AF_INET:
406		/* We support multiple FIBs. */
407		break;
408	default:
409		fibnum = RT_DEFAULT_FIB;
410		break;
411	}
412	rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
413	newrt = NULL;
414	if (rnh == NULL)
415		goto miss;
416
417	/*
418	 * Look up the address in the table for that Address Family
419	 */
420	needlock = !(ignflags & RTF_RNH_LOCKED);
421	if (needlock)
422		RADIX_NODE_HEAD_RLOCK(rnh);
423#ifdef INVARIANTS
424	else
425		RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
426#endif
427	rn = rnh->rnh_matchaddr(dst, rnh);
428	if (rn && ((rn->rn_flags & RNF_ROOT) == 0)) {
429		newrt = RNTORT(rn);
430		RT_LOCK(newrt);
431		RT_ADDREF(newrt);
432		if (needlock)
433			RADIX_NODE_HEAD_RUNLOCK(rnh);
434		goto done;
435
436	} else if (needlock)
437		RADIX_NODE_HEAD_RUNLOCK(rnh);
438
439	/*
440	 * Either we hit the root or couldn't find any match,
441	 * Which basically means
442	 * "caint get there frm here"
443	 */
444miss:
445	V_rtstat.rts_unreach++;
446
447	if (report) {
448		/*
449		 * If required, report the failure to the supervising
450		 * Authorities.
451		 * For a delete, this is not an error. (report == 0)
452		 */
453		bzero(&info, sizeof(info));
454		info.rti_info[RTAX_DST] = dst;
455		rt_missmsg_fib(msgtype, &info, 0, err, fibnum);
456	}
457done:
458	if (newrt)
459		RT_LOCK_ASSERT(newrt);
460	return (newrt);
461}
462
463/*
464 * Remove a reference count from an rtentry.
465 * If the count gets low enough, take it out of the routing table
466 */
467void
468rtfree(struct rtentry *rt)
469{
470	struct radix_node_head *rnh;
471
472	KASSERT(rt != NULL,("%s: NULL rt", __func__));
473	rnh = rt_tables_get_rnh(rt->rt_fibnum, rt_key(rt)->sa_family);
474	KASSERT(rnh != NULL,("%s: NULL rnh", __func__));
475
476	RT_LOCK_ASSERT(rt);
477
478	/*
479	 * The callers should use RTFREE_LOCKED() or RTFREE(), so
480	 * we should come here exactly with the last reference.
481	 */
482	RT_REMREF(rt);
483	if (rt->rt_refcnt > 0) {
484		log(LOG_DEBUG, "%s: %p has %d refs\n", __func__, rt, rt->rt_refcnt);
485		goto done;
486	}
487
488	/*
489	 * On last reference give the "close method" a chance
490	 * to cleanup private state.  This also permits (for
491	 * IPv4 and IPv6) a chance to decide if the routing table
492	 * entry should be purged immediately or at a later time.
493	 * When an immediate purge is to happen the close routine
494	 * typically calls rtexpunge which clears the RTF_UP flag
495	 * on the entry so that the code below reclaims the storage.
496	 */
497	if (rt->rt_refcnt == 0 && rnh->rnh_close)
498		rnh->rnh_close((struct radix_node *)rt, rnh);
499
500	/*
501	 * If we are no longer "up" (and ref == 0)
502	 * then we can free the resources associated
503	 * with the route.
504	 */
505	if ((rt->rt_flags & RTF_UP) == 0) {
506		if (rt->rt_nodes->rn_flags & (RNF_ACTIVE | RNF_ROOT))
507			panic("rtfree 2");
508		/*
509		 * the rtentry must have been removed from the routing table
510		 * so it is represented in rttrash.. remove that now.
511		 */
512		V_rttrash--;
513#ifdef	DIAGNOSTIC
514		if (rt->rt_refcnt < 0) {
515			printf("rtfree: %p not freed (neg refs)\n", rt);
516			goto done;
517		}
518#endif
519		/*
520		 * release references on items we hold them on..
521		 * e.g other routes and ifaddrs.
522		 */
523		if (rt->rt_ifa)
524			ifa_free(rt->rt_ifa);
525		/*
526		 * The key is separatly alloc'd so free it (see rt_setgate()).
527		 * This also frees the gateway, as they are always malloc'd
528		 * together.
529		 */
530		Free(rt_key(rt));
531
532		/*
533		 * and the rtentry itself of course
534		 */
535		uma_zfree(V_rtzone, rt);
536		return;
537	}
538done:
539	RT_UNLOCK(rt);
540}
541
542
543/*
544 * Force a routing table entry to the specified
545 * destination to go through the given gateway.
546 * Normally called as a result of a routing redirect
547 * message from the network layer.
548 */
549void
550rtredirect(struct sockaddr *dst,
551	struct sockaddr *gateway,
552	struct sockaddr *netmask,
553	int flags,
554	struct sockaddr *src)
555{
556
557	rtredirect_fib(dst, gateway, netmask, flags, src, RT_DEFAULT_FIB);
558}
559
560void
561rtredirect_fib(struct sockaddr *dst,
562	struct sockaddr *gateway,
563	struct sockaddr *netmask,
564	int flags,
565	struct sockaddr *src,
566	u_int fibnum)
567{
568	struct rtentry *rt, *rt0 = NULL;
569	int error = 0;
570	short *stat = NULL;
571	struct rt_addrinfo info;
572	struct ifaddr *ifa;
573	struct radix_node_head *rnh;
574
575	ifa = NULL;
576	rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
577	if (rnh == NULL) {
578		error = EAFNOSUPPORT;
579		goto out;
580	}
581
582	/* verify the gateway is directly reachable */
583	if ((ifa = ifa_ifwithnet(gateway, 0)) == NULL) {
584		error = ENETUNREACH;
585		goto out;
586	}
587	rt = rtalloc1_fib(dst, 0, 0UL, fibnum);	/* NB: rt is locked */
588	/*
589	 * If the redirect isn't from our current router for this dst,
590	 * it's either old or wrong.  If it redirects us to ourselves,
591	 * we have a routing loop, perhaps as a result of an interface
592	 * going down recently.
593	 */
594	if (!(flags & RTF_DONE) && rt &&
595	     (!sa_equal(src, rt->rt_gateway) || rt->rt_ifa != ifa))
596		error = EINVAL;
597	else if (ifa_ifwithaddr_check(gateway))
598		error = EHOSTUNREACH;
599	if (error)
600		goto done;
601	/*
602	 * Create a new entry if we just got back a wildcard entry
603	 * or the lookup failed.  This is necessary for hosts
604	 * which use routing redirects generated by smart gateways
605	 * to dynamically build the routing tables.
606	 */
607	if (rt == NULL || (rt_mask(rt) && rt_mask(rt)->sa_len < 2))
608		goto create;
609	/*
610	 * Don't listen to the redirect if it's
611	 * for a route to an interface.
612	 */
613	if (rt->rt_flags & RTF_GATEWAY) {
614		if (((rt->rt_flags & RTF_HOST) == 0) && (flags & RTF_HOST)) {
615			/*
616			 * Changing from route to net => route to host.
617			 * Create new route, rather than smashing route to net.
618			 */
619		create:
620			rt0 = rt;
621			rt = NULL;
622
623			flags |=  RTF_GATEWAY | RTF_DYNAMIC;
624			bzero((caddr_t)&info, sizeof(info));
625			info.rti_info[RTAX_DST] = dst;
626			info.rti_info[RTAX_GATEWAY] = gateway;
627			info.rti_info[RTAX_NETMASK] = netmask;
628			info.rti_ifa = ifa;
629			info.rti_flags = flags;
630			if (rt0 != NULL)
631				RT_UNLOCK(rt0);	/* drop lock to avoid LOR with RNH */
632			error = rtrequest1_fib(RTM_ADD, &info, &rt, fibnum);
633			if (rt != NULL) {
634				RT_LOCK(rt);
635				if (rt0 != NULL)
636					EVENTHANDLER_INVOKE(route_redirect_event, rt0, rt, dst);
637				flags = rt->rt_flags;
638			}
639			if (rt0 != NULL)
640				RTFREE(rt0);
641
642			stat = &V_rtstat.rts_dynamic;
643		} else {
644			struct rtentry *gwrt;
645
646			/*
647			 * Smash the current notion of the gateway to
648			 * this destination.  Should check about netmask!!!
649			 */
650			rt->rt_flags |= RTF_MODIFIED;
651			flags |= RTF_MODIFIED;
652			stat = &V_rtstat.rts_newgateway;
653			/*
654			 * add the key and gateway (in one malloc'd chunk).
655			 */
656			RT_UNLOCK(rt);
657			RADIX_NODE_HEAD_LOCK(rnh);
658			RT_LOCK(rt);
659			rt_setgate(rt, rt_key(rt), gateway);
660			gwrt = rtalloc1(gateway, 1, RTF_RNH_LOCKED);
661			RADIX_NODE_HEAD_UNLOCK(rnh);
662			EVENTHANDLER_INVOKE(route_redirect_event, rt, gwrt, dst);
663			RTFREE_LOCKED(gwrt);
664		}
665	} else
666		error = EHOSTUNREACH;
667done:
668	if (rt)
669		RTFREE_LOCKED(rt);
670out:
671	if (error)
672		V_rtstat.rts_badredirect++;
673	else if (stat != NULL)
674		(*stat)++;
675	bzero((caddr_t)&info, sizeof(info));
676	info.rti_info[RTAX_DST] = dst;
677	info.rti_info[RTAX_GATEWAY] = gateway;
678	info.rti_info[RTAX_NETMASK] = netmask;
679	info.rti_info[RTAX_AUTHOR] = src;
680	rt_missmsg_fib(RTM_REDIRECT, &info, flags, error, fibnum);
681	if (ifa != NULL)
682		ifa_free(ifa);
683}
684
685int
686rtioctl(u_long req, caddr_t data)
687{
688
689	return (rtioctl_fib(req, data, RT_DEFAULT_FIB));
690}
691
692/*
693 * Routing table ioctl interface.
694 */
695int
696rtioctl_fib(u_long req, caddr_t data, u_int fibnum)
697{
698
699	/*
700	 * If more ioctl commands are added here, make sure the proper
701	 * super-user checks are being performed because it is possible for
702	 * prison-root to make it this far if raw sockets have been enabled
703	 * in jails.
704	 */
705#ifdef INET
706	/* Multicast goop, grrr... */
707	return mrt_ioctl ? mrt_ioctl(req, data, fibnum) : EOPNOTSUPP;
708#else /* INET */
709	return ENXIO;
710#endif /* INET */
711}
712
713/*
714 * For both ifa_ifwithroute() routines, 'ifa' is returned referenced.
715 */
716struct ifaddr *
717ifa_ifwithroute(int flags, struct sockaddr *dst, struct sockaddr *gateway)
718{
719
720	return (ifa_ifwithroute_fib(flags, dst, gateway, RT_DEFAULT_FIB));
721}
722
723struct ifaddr *
724ifa_ifwithroute_fib(int flags, struct sockaddr *dst, struct sockaddr *gateway,
725				u_int fibnum)
726{
727	register struct ifaddr *ifa;
728	int not_found = 0;
729
730	if ((flags & RTF_GATEWAY) == 0) {
731		/*
732		 * If we are adding a route to an interface,
733		 * and the interface is a pt to pt link
734		 * we should search for the destination
735		 * as our clue to the interface.  Otherwise
736		 * we can use the local address.
737		 */
738		ifa = NULL;
739		if (flags & RTF_HOST)
740			ifa = ifa_ifwithdstaddr(dst);
741		if (ifa == NULL)
742			ifa = ifa_ifwithaddr(gateway);
743	} else {
744		/*
745		 * If we are adding a route to a remote net
746		 * or host, the gateway may still be on the
747		 * other end of a pt to pt link.
748		 */
749		ifa = ifa_ifwithdstaddr(gateway);
750	}
751	if (ifa == NULL)
752		ifa = ifa_ifwithnet(gateway, 0);
753	if (ifa == NULL) {
754		struct rtentry *rt = rtalloc1_fib(gateway, 0, RTF_RNH_LOCKED, fibnum);
755		if (rt == NULL)
756			return (NULL);
757		/*
758		 * dismiss a gateway that is reachable only
759		 * through the default router
760		 */
761		switch (gateway->sa_family) {
762		case AF_INET:
763			if (satosin(rt_key(rt))->sin_addr.s_addr == INADDR_ANY)
764				not_found = 1;
765			break;
766		case AF_INET6:
767			if (IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(rt))->sin6_addr))
768				not_found = 1;
769			break;
770		default:
771			break;
772		}
773		if (!not_found && rt->rt_ifa != NULL) {
774			ifa = rt->rt_ifa;
775			ifa_ref(ifa);
776		}
777		RT_REMREF(rt);
778		RT_UNLOCK(rt);
779		if (not_found || ifa == NULL)
780			return (NULL);
781	}
782	if (ifa->ifa_addr->sa_family != dst->sa_family) {
783		struct ifaddr *oifa = ifa;
784		ifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
785		if (ifa == NULL)
786			ifa = oifa;
787		else
788			ifa_free(oifa);
789	}
790	return (ifa);
791}
792
793/*
794 * Do appropriate manipulations of a routing tree given
795 * all the bits of info needed
796 */
797int
798rtrequest(int req,
799	struct sockaddr *dst,
800	struct sockaddr *gateway,
801	struct sockaddr *netmask,
802	int flags,
803	struct rtentry **ret_nrt)
804{
805
806	return (rtrequest_fib(req, dst, gateway, netmask, flags, ret_nrt,
807	    RT_DEFAULT_FIB));
808}
809
810int
811rtrequest_fib(int req,
812	struct sockaddr *dst,
813	struct sockaddr *gateway,
814	struct sockaddr *netmask,
815	int flags,
816	struct rtentry **ret_nrt,
817	u_int fibnum)
818{
819	struct rt_addrinfo info;
820
821	if (dst->sa_len == 0)
822		return(EINVAL);
823
824	bzero((caddr_t)&info, sizeof(info));
825	info.rti_flags = flags;
826	info.rti_info[RTAX_DST] = dst;
827	info.rti_info[RTAX_GATEWAY] = gateway;
828	info.rti_info[RTAX_NETMASK] = netmask;
829	return rtrequest1_fib(req, &info, ret_nrt, fibnum);
830}
831
832/*
833 * These (questionable) definitions of apparent local variables apply
834 * to the next two functions.  XXXXXX!!!
835 */
836#define	dst	info->rti_info[RTAX_DST]
837#define	gateway	info->rti_info[RTAX_GATEWAY]
838#define	netmask	info->rti_info[RTAX_NETMASK]
839#define	ifaaddr	info->rti_info[RTAX_IFA]
840#define	ifpaddr	info->rti_info[RTAX_IFP]
841#define	flags	info->rti_flags
842
843int
844rt_getifa(struct rt_addrinfo *info)
845{
846
847	return (rt_getifa_fib(info, RT_DEFAULT_FIB));
848}
849
850/*
851 * Look up rt_addrinfo for a specific fib.  Note that if rti_ifa is defined,
852 * it will be referenced so the caller must free it.
853 */
854int
855rt_getifa_fib(struct rt_addrinfo *info, u_int fibnum)
856{
857	struct ifaddr *ifa;
858	int error = 0;
859
860	/*
861	 * ifp may be specified by sockaddr_dl
862	 * when protocol address is ambiguous.
863	 */
864	if (info->rti_ifp == NULL && ifpaddr != NULL &&
865	    ifpaddr->sa_family == AF_LINK &&
866	    (ifa = ifa_ifwithnet(ifpaddr, 0)) != NULL) {
867		info->rti_ifp = ifa->ifa_ifp;
868		ifa_free(ifa);
869	}
870	if (info->rti_ifa == NULL && ifaaddr != NULL)
871		info->rti_ifa = ifa_ifwithaddr(ifaaddr);
872	if (info->rti_ifa == NULL) {
873		struct sockaddr *sa;
874
875		sa = ifaaddr != NULL ? ifaaddr :
876		    (gateway != NULL ? gateway : dst);
877		if (sa != NULL && info->rti_ifp != NULL)
878			info->rti_ifa = ifaof_ifpforaddr(sa, info->rti_ifp);
879		else if (dst != NULL && gateway != NULL)
880			info->rti_ifa = ifa_ifwithroute_fib(flags, dst, gateway,
881							fibnum);
882		else if (sa != NULL)
883			info->rti_ifa = ifa_ifwithroute_fib(flags, sa, sa,
884							fibnum);
885	}
886	if ((ifa = info->rti_ifa) != NULL) {
887		if (info->rti_ifp == NULL)
888			info->rti_ifp = ifa->ifa_ifp;
889	} else
890		error = ENETUNREACH;
891	return (error);
892}
893
894/*
895 * Expunges references to a route that's about to be reclaimed.
896 * The route must be locked.
897 */
898int
899rtexpunge(struct rtentry *rt)
900{
901#if !defined(RADIX_MPATH)
902	struct radix_node *rn;
903#else
904	struct rt_addrinfo info;
905	int fib;
906	struct rtentry *rt0;
907#endif
908	struct radix_node_head *rnh;
909	struct ifaddr *ifa;
910	int error = 0;
911
912	/*
913	 * Find the correct routing tree to use for this Address Family
914	 */
915	rnh = rt_tables_get_rnh(rt->rt_fibnum, rt_key(rt)->sa_family);
916	RT_LOCK_ASSERT(rt);
917	if (rnh == NULL)
918		return (EAFNOSUPPORT);
919	RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
920
921#ifdef RADIX_MPATH
922	fib = rt->rt_fibnum;
923	bzero(&info, sizeof(info));
924	info.rti_ifp = rt->rt_ifp;
925	info.rti_flags = RTF_RNH_LOCKED;
926	info.rti_info[RTAX_DST] = rt_key(rt);
927	info.rti_info[RTAX_GATEWAY] = rt->rt_ifa->ifa_addr;
928
929	RT_UNLOCK(rt);
930	error = rtrequest1_fib(RTM_DELETE, &info, &rt0, fib);
931
932	if (error == 0 && rt0 != NULL) {
933		rt = rt0;
934		RT_LOCK(rt);
935	} else if (error != 0) {
936		RT_LOCK(rt);
937		return (error);
938	}
939#else
940	/*
941	 * Remove the item from the tree; it should be there,
942	 * but when callers invoke us blindly it may not (sigh).
943	 */
944	rn = rnh->rnh_deladdr(rt_key(rt), rt_mask(rt), rnh);
945	if (rn == NULL) {
946		error = ESRCH;
947		goto bad;
948	}
949	KASSERT((rn->rn_flags & (RNF_ACTIVE | RNF_ROOT)) == 0,
950		("unexpected flags 0x%x", rn->rn_flags));
951	KASSERT(rt == RNTORT(rn),
952		("lookup mismatch, rt %p rn %p", rt, rn));
953#endif /* RADIX_MPATH */
954
955	rt->rt_flags &= ~RTF_UP;
956
957	/*
958	 * Give the protocol a chance to keep things in sync.
959	 */
960	if ((ifa = rt->rt_ifa) && ifa->ifa_rtrequest) {
961		struct rt_addrinfo info;
962
963		bzero((caddr_t)&info, sizeof(info));
964		info.rti_flags = rt->rt_flags;
965		info.rti_info[RTAX_DST] = rt_key(rt);
966		info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
967		info.rti_info[RTAX_NETMASK] = rt_mask(rt);
968		ifa->ifa_rtrequest(RTM_DELETE, rt, &info);
969	}
970
971	/*
972	 * one more rtentry floating around that is not
973	 * linked to the routing table.
974	 */
975	V_rttrash++;
976#if !defined(RADIX_MPATH)
977bad:
978#endif
979	return (error);
980}
981
982#ifdef RADIX_MPATH
983static int
984rn_mpath_update(int req, struct rt_addrinfo *info,
985    struct radix_node_head *rnh, struct rtentry **ret_nrt)
986{
987	/*
988	 * if we got multipath routes, we require users to specify
989	 * a matching RTAX_GATEWAY.
990	 */
991	struct rtentry *rt, *rto = NULL;
992	register struct radix_node *rn;
993	int error = 0;
994
995	rn = rnh->rnh_matchaddr(dst, rnh);
996	if (rn == NULL)
997		return (ESRCH);
998	rto = rt = RNTORT(rn);
999	rt = rt_mpath_matchgate(rt, gateway);
1000	if (rt == NULL)
1001		return (ESRCH);
1002	/*
1003	 * this is the first entry in the chain
1004	 */
1005	if (rto == rt) {
1006		rn = rn_mpath_next((struct radix_node *)rt);
1007		/*
1008		 * there is another entry, now it's active
1009		 */
1010		if (rn) {
1011			rto = RNTORT(rn);
1012			RT_LOCK(rto);
1013			rto->rt_flags |= RTF_UP;
1014			RT_UNLOCK(rto);
1015		} else if (rt->rt_flags & RTF_GATEWAY) {
1016			/*
1017			 * For gateway routes, we need to
1018			 * make sure that we we are deleting
1019			 * the correct gateway.
1020			 * rt_mpath_matchgate() does not
1021			 * check the case when there is only
1022			 * one route in the chain.
1023			 */
1024			if (gateway &&
1025			    (rt->rt_gateway->sa_len != gateway->sa_len ||
1026				memcmp(rt->rt_gateway, gateway, gateway->sa_len)))
1027				error = ESRCH;
1028			else {
1029				/*
1030				 * remove from tree before returning it
1031				 * to the caller
1032				 */
1033				rn = rnh->rnh_deladdr(dst, netmask, rnh);
1034				KASSERT(rt == RNTORT(rn), ("radix node disappeared"));
1035				goto gwdelete;
1036			}
1037
1038		}
1039		/*
1040		 * use the normal delete code to remove
1041		 * the first entry
1042		 */
1043		if (req != RTM_DELETE)
1044			goto nondelete;
1045
1046		error = ENOENT;
1047		goto done;
1048	}
1049
1050	/*
1051	 * if the entry is 2nd and on up
1052	 */
1053	if ((req == RTM_DELETE) && !rt_mpath_deldup(rto, rt))
1054		panic ("rtrequest1: rt_mpath_deldup");
1055gwdelete:
1056	RT_LOCK(rt);
1057	RT_ADDREF(rt);
1058	if (req == RTM_DELETE) {
1059		rt->rt_flags &= ~RTF_UP;
1060		/*
1061		 * One more rtentry floating around that is not
1062		 * linked to the routing table. rttrash will be decremented
1063		 * when RTFREE(rt) is eventually called.
1064		 */
1065		V_rttrash++;
1066	}
1067
1068nondelete:
1069	if (req != RTM_DELETE)
1070		panic("unrecognized request %d", req);
1071
1072
1073	/*
1074	 * If the caller wants it, then it can have it,
1075	 * but it's up to it to free the rtentry as we won't be
1076	 * doing it.
1077	 */
1078	if (ret_nrt) {
1079		*ret_nrt = rt;
1080		RT_UNLOCK(rt);
1081	} else
1082		RTFREE_LOCKED(rt);
1083done:
1084	return (error);
1085}
1086#endif
1087
1088int
1089rtrequest1_fib(int req, struct rt_addrinfo *info, struct rtentry **ret_nrt,
1090				u_int fibnum)
1091{
1092	int error = 0, needlock = 0;
1093	register struct rtentry *rt;
1094#ifdef FLOWTABLE
1095	register struct rtentry *rt0;
1096#endif
1097	register struct radix_node *rn;
1098	register struct radix_node_head *rnh;
1099	struct ifaddr *ifa;
1100	struct sockaddr *ndst;
1101	struct sockaddr_storage mdst;
1102#define senderr(x) { error = x ; goto bad; }
1103
1104	KASSERT((fibnum < rt_numfibs), ("rtrequest1_fib: bad fibnum"));
1105	switch (dst->sa_family) {
1106	case AF_INET6:
1107	case AF_INET:
1108		/* We support multiple FIBs. */
1109		break;
1110	default:
1111		fibnum = RT_DEFAULT_FIB;
1112		break;
1113	}
1114
1115	/*
1116	 * Find the correct routing tree to use for this Address Family
1117	 */
1118	rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1119	if (rnh == NULL)
1120		return (EAFNOSUPPORT);
1121	needlock = ((flags & RTF_RNH_LOCKED) == 0);
1122	flags &= ~RTF_RNH_LOCKED;
1123	if (needlock)
1124		RADIX_NODE_HEAD_LOCK(rnh);
1125	else
1126		RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
1127	/*
1128	 * If we are adding a host route then we don't want to put
1129	 * a netmask in the tree, nor do we want to clone it.
1130	 */
1131	if (flags & RTF_HOST)
1132		netmask = NULL;
1133
1134	switch (req) {
1135	case RTM_DELETE:
1136		if (netmask) {
1137			rt_maskedcopy(dst, (struct sockaddr *)&mdst, netmask);
1138			dst = (struct sockaddr *)&mdst;
1139		}
1140#ifdef RADIX_MPATH
1141		if (rn_mpath_capable(rnh)) {
1142			error = rn_mpath_update(req, info, rnh, ret_nrt);
1143			/*
1144			 * "bad" holds true for the success case
1145			 * as well
1146			 */
1147			if (error != ENOENT)
1148				goto bad;
1149			error = 0;
1150		}
1151#endif
1152		if ((flags & RTF_PINNED) == 0) {
1153			/* Check if target route can be deleted */
1154			rt = (struct rtentry *)rnh->rnh_lookup(dst,
1155			    netmask, rnh);
1156			if ((rt != NULL) && (rt->rt_flags & RTF_PINNED))
1157				senderr(EADDRINUSE);
1158		}
1159
1160		/*
1161		 * Remove the item from the tree and return it.
1162		 * Complain if it is not there and do no more processing.
1163		 */
1164		rn = rnh->rnh_deladdr(dst, netmask, rnh);
1165		if (rn == NULL)
1166			senderr(ESRCH);
1167		if (rn->rn_flags & (RNF_ACTIVE | RNF_ROOT))
1168			panic ("rtrequest delete");
1169		rt = RNTORT(rn);
1170		RT_LOCK(rt);
1171		RT_ADDREF(rt);
1172		rt->rt_flags &= ~RTF_UP;
1173
1174		/*
1175		 * give the protocol a chance to keep things in sync.
1176		 */
1177		if ((ifa = rt->rt_ifa) && ifa->ifa_rtrequest)
1178			ifa->ifa_rtrequest(RTM_DELETE, rt, info);
1179
1180		/*
1181		 * One more rtentry floating around that is not
1182		 * linked to the routing table. rttrash will be decremented
1183		 * when RTFREE(rt) is eventually called.
1184		 */
1185		V_rttrash++;
1186
1187		/*
1188		 * If the caller wants it, then it can have it,
1189		 * but it's up to it to free the rtentry as we won't be
1190		 * doing it.
1191		 */
1192		if (ret_nrt) {
1193			*ret_nrt = rt;
1194			RT_UNLOCK(rt);
1195		} else
1196			RTFREE_LOCKED(rt);
1197		break;
1198	case RTM_RESOLVE:
1199		/*
1200		 * resolve was only used for route cloning
1201		 * here for compat
1202		 */
1203		break;
1204	case RTM_ADD:
1205		if ((flags & RTF_GATEWAY) && !gateway)
1206			senderr(EINVAL);
1207		if (dst && gateway && (dst->sa_family != gateway->sa_family) &&
1208		    (gateway->sa_family != AF_UNSPEC) && (gateway->sa_family != AF_LINK))
1209			senderr(EINVAL);
1210
1211		if (info->rti_ifa == NULL) {
1212			error = rt_getifa_fib(info, fibnum);
1213			if (error)
1214				senderr(error);
1215		} else
1216			ifa_ref(info->rti_ifa);
1217		ifa = info->rti_ifa;
1218		rt = uma_zalloc(V_rtzone, M_NOWAIT);
1219		if (rt == NULL) {
1220			ifa_free(ifa);
1221			senderr(ENOBUFS);
1222		}
1223		rt->rt_flags = RTF_UP | flags;
1224		rt->rt_fibnum = fibnum;
1225		/*
1226		 * Add the gateway. Possibly re-malloc-ing the storage for it.
1227		 */
1228		RT_LOCK(rt);
1229		if ((error = rt_setgate(rt, dst, gateway)) != 0) {
1230			ifa_free(ifa);
1231			uma_zfree(V_rtzone, rt);
1232			senderr(error);
1233		}
1234
1235		/*
1236		 * point to the (possibly newly malloc'd) dest address.
1237		 */
1238		ndst = (struct sockaddr *)rt_key(rt);
1239
1240		/*
1241		 * make sure it contains the value we want (masked if needed).
1242		 */
1243		if (netmask) {
1244			rt_maskedcopy(dst, ndst, netmask);
1245		} else
1246			bcopy(dst, ndst, dst->sa_len);
1247
1248		/*
1249		 * We use the ifa reference returned by rt_getifa_fib().
1250		 * This moved from below so that rnh->rnh_addaddr() can
1251		 * examine the ifa and  ifa->ifa_ifp if it so desires.
1252		 */
1253		rt->rt_ifa = ifa;
1254		rt->rt_ifp = ifa->ifa_ifp;
1255		rt->rt_weight = 1;
1256
1257#ifdef RADIX_MPATH
1258		/* do not permit exactly the same dst/mask/gw pair */
1259		if (rn_mpath_capable(rnh) &&
1260			rt_mpath_conflict(rnh, rt, netmask)) {
1261			ifa_free(rt->rt_ifa);
1262			Free(rt_key(rt));
1263			uma_zfree(V_rtzone, rt);
1264			senderr(EEXIST);
1265		}
1266#endif
1267
1268#ifdef FLOWTABLE
1269		rt0 = NULL;
1270		/* "flow-table" only supports IPv6 and IPv4 at the moment. */
1271		switch (dst->sa_family) {
1272#ifdef INET6
1273		case AF_INET6:
1274#endif
1275#ifdef INET
1276		case AF_INET:
1277#endif
1278#if defined(INET6) || defined(INET)
1279			rn = rnh->rnh_matchaddr(dst, rnh);
1280			if (rn && ((rn->rn_flags & RNF_ROOT) == 0)) {
1281				struct sockaddr *mask;
1282				u_char *m, *n;
1283				int len;
1284
1285				/*
1286				 * compare mask to see if the new route is
1287				 * more specific than the existing one
1288				 */
1289				rt0 = RNTORT(rn);
1290				RT_LOCK(rt0);
1291				RT_ADDREF(rt0);
1292				RT_UNLOCK(rt0);
1293				/*
1294				 * A host route is already present, so
1295				 * leave the flow-table entries as is.
1296				 */
1297				if (rt0->rt_flags & RTF_HOST) {
1298					RTFREE(rt0);
1299					rt0 = NULL;
1300				} else if (!(flags & RTF_HOST) && netmask) {
1301					mask = rt_mask(rt0);
1302					len = mask->sa_len;
1303					m = (u_char *)mask;
1304					n = (u_char *)netmask;
1305					while (len-- > 0) {
1306						if (*n != *m)
1307							break;
1308						n++;
1309						m++;
1310					}
1311					if (len == 0 || (*n < *m)) {
1312						RTFREE(rt0);
1313						rt0 = NULL;
1314					}
1315				}
1316			}
1317#endif/* INET6 || INET */
1318		}
1319#endif /* FLOWTABLE */
1320
1321		/* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
1322		rn = rnh->rnh_addaddr(ndst, netmask, rnh, rt->rt_nodes);
1323		/*
1324		 * If it still failed to go into the tree,
1325		 * then un-make it (this should be a function)
1326		 */
1327		if (rn == NULL) {
1328			ifa_free(rt->rt_ifa);
1329			Free(rt_key(rt));
1330			uma_zfree(V_rtzone, rt);
1331#ifdef FLOWTABLE
1332			if (rt0 != NULL)
1333				RTFREE(rt0);
1334#endif
1335			senderr(EEXIST);
1336		}
1337#ifdef FLOWTABLE
1338		else if (rt0 != NULL) {
1339			flowtable_route_flush(dst->sa_family, rt0);
1340			RTFREE(rt0);
1341		}
1342#endif
1343
1344		/*
1345		 * If this protocol has something to add to this then
1346		 * allow it to do that as well.
1347		 */
1348		if (ifa->ifa_rtrequest)
1349			ifa->ifa_rtrequest(req, rt, info);
1350
1351		/*
1352		 * actually return a resultant rtentry and
1353		 * give the caller a single reference.
1354		 */
1355		if (ret_nrt) {
1356			*ret_nrt = rt;
1357			RT_ADDREF(rt);
1358		}
1359		RT_UNLOCK(rt);
1360		break;
1361	default:
1362		error = EOPNOTSUPP;
1363	}
1364bad:
1365	if (needlock)
1366		RADIX_NODE_HEAD_UNLOCK(rnh);
1367	return (error);
1368#undef senderr
1369}
1370
1371#undef dst
1372#undef gateway
1373#undef netmask
1374#undef ifaaddr
1375#undef ifpaddr
1376#undef flags
1377
1378int
1379rt_setgate(struct rtentry *rt, struct sockaddr *dst, struct sockaddr *gate)
1380{
1381	/* XXX dst may be overwritten, can we move this to below */
1382	int dlen = SA_SIZE(dst), glen = SA_SIZE(gate);
1383#ifdef INVARIANTS
1384	struct radix_node_head *rnh;
1385
1386	rnh = rt_tables_get_rnh(rt->rt_fibnum, dst->sa_family);
1387#endif
1388
1389	RT_LOCK_ASSERT(rt);
1390	RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
1391
1392	/*
1393	 * Prepare to store the gateway in rt->rt_gateway.
1394	 * Both dst and gateway are stored one after the other in the same
1395	 * malloc'd chunk. If we have room, we can reuse the old buffer,
1396	 * rt_gateway already points to the right place.
1397	 * Otherwise, malloc a new block and update the 'dst' address.
1398	 */
1399	if (rt->rt_gateway == NULL || glen > SA_SIZE(rt->rt_gateway)) {
1400		caddr_t new;
1401
1402		R_Malloc(new, caddr_t, dlen + glen);
1403		if (new == NULL)
1404			return ENOBUFS;
1405		/*
1406		 * XXX note, we copy from *dst and not *rt_key(rt) because
1407		 * rt_setgate() can be called to initialize a newly
1408		 * allocated route entry, in which case rt_key(rt) == NULL
1409		 * (and also rt->rt_gateway == NULL).
1410		 * Free()/free() handle a NULL argument just fine.
1411		 */
1412		bcopy(dst, new, dlen);
1413		Free(rt_key(rt));	/* free old block, if any */
1414		rt_key(rt) = (struct sockaddr *)new;
1415		rt->rt_gateway = (struct sockaddr *)(new + dlen);
1416	}
1417
1418	/*
1419	 * Copy the new gateway value into the memory chunk.
1420	 */
1421	bcopy(gate, rt->rt_gateway, glen);
1422
1423	return (0);
1424}
1425
1426void
1427rt_maskedcopy(struct sockaddr *src, struct sockaddr *dst, struct sockaddr *netmask)
1428{
1429	register u_char *cp1 = (u_char *)src;
1430	register u_char *cp2 = (u_char *)dst;
1431	register u_char *cp3 = (u_char *)netmask;
1432	u_char *cplim = cp2 + *cp3;
1433	u_char *cplim2 = cp2 + *cp1;
1434
1435	*cp2++ = *cp1++; *cp2++ = *cp1++; /* copies sa_len & sa_family */
1436	cp3 += 2;
1437	if (cplim > cplim2)
1438		cplim = cplim2;
1439	while (cp2 < cplim)
1440		*cp2++ = *cp1++ & *cp3++;
1441	if (cp2 < cplim2)
1442		bzero((caddr_t)cp2, (unsigned)(cplim2 - cp2));
1443}
1444
1445/*
1446 * Set up a routing table entry, normally
1447 * for an interface.
1448 */
1449#define _SOCKADDR_TMPSIZE 128 /* Not too big.. kernel stack size is limited */
1450static inline  int
1451rtinit1(struct ifaddr *ifa, int cmd, int flags, int fibnum)
1452{
1453	struct sockaddr *dst;
1454	struct sockaddr *netmask;
1455	struct rtentry *rt = NULL;
1456	struct rt_addrinfo info;
1457	int error = 0;
1458	int startfib, endfib;
1459	char tempbuf[_SOCKADDR_TMPSIZE];
1460	int didwork = 0;
1461	int a_failure = 0;
1462	static struct sockaddr_dl null_sdl = {sizeof(null_sdl), AF_LINK};
1463	struct radix_node_head *rnh;
1464
1465	if (flags & RTF_HOST) {
1466		dst = ifa->ifa_dstaddr;
1467		netmask = NULL;
1468	} else {
1469		dst = ifa->ifa_addr;
1470		netmask = ifa->ifa_netmask;
1471	}
1472	if (dst->sa_len == 0)
1473		return(EINVAL);
1474	switch (dst->sa_family) {
1475	case AF_INET6:
1476	case AF_INET:
1477		/* We support multiple FIBs. */
1478		break;
1479	default:
1480		fibnum = RT_DEFAULT_FIB;
1481		break;
1482	}
1483	if (fibnum == -1) {
1484		if (rt_add_addr_allfibs == 0 && cmd == (int)RTM_ADD) {
1485			startfib = endfib = curthread->td_proc->p_fibnum;
1486		} else {
1487			startfib = 0;
1488			endfib = rt_numfibs - 1;
1489		}
1490	} else {
1491		KASSERT((fibnum < rt_numfibs), ("rtinit1: bad fibnum"));
1492		startfib = fibnum;
1493		endfib = fibnum;
1494	}
1495
1496	/*
1497	 * If it's a delete, check that if it exists,
1498	 * it's on the correct interface or we might scrub
1499	 * a route to another ifa which would
1500	 * be confusing at best and possibly worse.
1501	 */
1502	if (cmd == RTM_DELETE) {
1503		/*
1504		 * It's a delete, so it should already exist..
1505		 * If it's a net, mask off the host bits
1506		 * (Assuming we have a mask)
1507		 * XXX this is kinda inet specific..
1508		 */
1509		if (netmask != NULL) {
1510			rt_maskedcopy(dst, (struct sockaddr *)tempbuf, netmask);
1511			dst = (struct sockaddr *)tempbuf;
1512		}
1513	}
1514	/*
1515	 * Now go through all the requested tables (fibs) and do the
1516	 * requested action. Realistically, this will either be fib 0
1517	 * for protocols that don't do multiple tables or all the
1518	 * tables for those that do.
1519	 */
1520	for ( fibnum = startfib; fibnum <= endfib; fibnum++) {
1521		if (cmd == RTM_DELETE) {
1522			struct radix_node *rn;
1523			/*
1524			 * Look up an rtentry that is in the routing tree and
1525			 * contains the correct info.
1526			 */
1527			rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1528			if (rnh == NULL)
1529				/* this table doesn't exist but others might */
1530				continue;
1531			RADIX_NODE_HEAD_RLOCK(rnh);
1532#ifdef RADIX_MPATH
1533			if (rn_mpath_capable(rnh)) {
1534
1535				rn = rnh->rnh_matchaddr(dst, rnh);
1536				if (rn == NULL)
1537					error = ESRCH;
1538				else {
1539					rt = RNTORT(rn);
1540					/*
1541					 * for interface route the
1542					 * rt->rt_gateway is sockaddr_intf
1543					 * for cloning ARP entries, so
1544					 * rt_mpath_matchgate must use the
1545					 * interface address
1546					 */
1547					rt = rt_mpath_matchgate(rt,
1548					    ifa->ifa_addr);
1549					if (!rt)
1550						error = ESRCH;
1551				}
1552			}
1553			else
1554#endif
1555			rn = rnh->rnh_lookup(dst, netmask, rnh);
1556			error = (rn == NULL ||
1557			    (rn->rn_flags & RNF_ROOT) ||
1558			    RNTORT(rn)->rt_ifa != ifa ||
1559			    !sa_equal((struct sockaddr *)rn->rn_key, dst));
1560			RADIX_NODE_HEAD_RUNLOCK(rnh);
1561			if (error) {
1562				/* this is only an error if bad on ALL tables */
1563				continue;
1564			}
1565		}
1566		/*
1567		 * Do the actual request
1568		 */
1569		bzero((caddr_t)&info, sizeof(info));
1570		info.rti_ifa = ifa;
1571		info.rti_flags = flags |
1572		    (ifa->ifa_flags & ~IFA_RTSELF) | RTF_PINNED;
1573		info.rti_info[RTAX_DST] = dst;
1574		/*
1575		 * doing this for compatibility reasons
1576		 */
1577		if (cmd == RTM_ADD)
1578			info.rti_info[RTAX_GATEWAY] =
1579			    (struct sockaddr *)&null_sdl;
1580		else
1581			info.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
1582		info.rti_info[RTAX_NETMASK] = netmask;
1583		error = rtrequest1_fib(cmd, &info, &rt, fibnum);
1584
1585		if ((error == EEXIST) && (cmd == RTM_ADD)) {
1586			/*
1587			 * Interface route addition failed.
1588			 * Atomically delete current prefix generating
1589			 * RTM_DELETE message, and retry adding
1590			 * interface prefix.
1591			 */
1592			rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1593			RADIX_NODE_HEAD_LOCK(rnh);
1594
1595			/* Delete old prefix */
1596			info.rti_ifa = NULL;
1597			info.rti_flags = RTF_RNH_LOCKED;
1598
1599			error = rtrequest1_fib(RTM_DELETE, &info, NULL, fibnum);
1600			if (error == 0) {
1601				info.rti_ifa = ifa;
1602				info.rti_flags = flags | RTF_RNH_LOCKED |
1603				    (ifa->ifa_flags & ~IFA_RTSELF) | RTF_PINNED;
1604				error = rtrequest1_fib(cmd, &info, &rt, fibnum);
1605			}
1606
1607			RADIX_NODE_HEAD_UNLOCK(rnh);
1608		}
1609
1610
1611		if (error == 0 && rt != NULL) {
1612			/*
1613			 * notify any listening routing agents of the change
1614			 */
1615			RT_LOCK(rt);
1616#ifdef RADIX_MPATH
1617			/*
1618			 * in case address alias finds the first address
1619			 * e.g. ifconfig bge0 192.0.2.246/24
1620			 * e.g. ifconfig bge0 192.0.2.247/24
1621			 * the address set in the route is 192.0.2.246
1622			 * so we need to replace it with 192.0.2.247
1623			 */
1624			if (memcmp(rt->rt_ifa->ifa_addr,
1625			    ifa->ifa_addr, ifa->ifa_addr->sa_len)) {
1626				ifa_free(rt->rt_ifa);
1627				ifa_ref(ifa);
1628				rt->rt_ifp = ifa->ifa_ifp;
1629				rt->rt_ifa = ifa;
1630			}
1631#endif
1632			/*
1633			 * doing this for compatibility reasons
1634			 */
1635			if (cmd == RTM_ADD) {
1636			    ((struct sockaddr_dl *)rt->rt_gateway)->sdl_type  =
1637				rt->rt_ifp->if_type;
1638			    ((struct sockaddr_dl *)rt->rt_gateway)->sdl_index =
1639				rt->rt_ifp->if_index;
1640			}
1641			RT_ADDREF(rt);
1642			RT_UNLOCK(rt);
1643			rt_newaddrmsg_fib(cmd, ifa, error, rt, fibnum);
1644			RT_LOCK(rt);
1645			RT_REMREF(rt);
1646			if (cmd == RTM_DELETE) {
1647				/*
1648				 * If we are deleting, and we found an entry,
1649				 * then it's been removed from the tree..
1650				 * now throw it away.
1651				 */
1652				RTFREE_LOCKED(rt);
1653			} else {
1654				if (cmd == RTM_ADD) {
1655					/*
1656					 * We just wanted to add it..
1657					 * we don't actually need a reference.
1658					 */
1659					RT_REMREF(rt);
1660				}
1661				RT_UNLOCK(rt);
1662			}
1663			didwork = 1;
1664		}
1665		if (error)
1666			a_failure = error;
1667	}
1668	if (cmd == RTM_DELETE) {
1669		if (didwork) {
1670			error = 0;
1671		} else {
1672			/* we only give an error if it wasn't in any table */
1673			error = ((flags & RTF_HOST) ?
1674			    EHOSTUNREACH : ENETUNREACH);
1675		}
1676	} else {
1677		if (a_failure) {
1678			/* return an error if any of them failed */
1679			error = a_failure;
1680		}
1681	}
1682	return (error);
1683}
1684
1685#ifndef BURN_BRIDGES
1686/* special one for inet internal use. may not use. */
1687int
1688rtinit_fib(struct ifaddr *ifa, int cmd, int flags)
1689{
1690	return (rtinit1(ifa, cmd, flags, -1));
1691}
1692#endif
1693
1694/*
1695 * Set up a routing table entry, normally
1696 * for an interface.
1697 */
1698int
1699rtinit(struct ifaddr *ifa, int cmd, int flags)
1700{
1701	struct sockaddr *dst;
1702	int fib = RT_DEFAULT_FIB;
1703
1704	if (flags & RTF_HOST) {
1705		dst = ifa->ifa_dstaddr;
1706	} else {
1707		dst = ifa->ifa_addr;
1708	}
1709
1710	switch (dst->sa_family) {
1711	case AF_INET6:
1712	case AF_INET:
1713		/* We do support multiple FIBs. */
1714		fib = -1;
1715		break;
1716	}
1717	return (rtinit1(ifa, cmd, flags, fib));
1718}
1719