Home | History | Annotate | Line # | Download | only in net
route.c revision 1.235
      1 /*	$NetBSD: route.c,v 1.235 2022/11/25 08:39:32 knakahara Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1998, 2008 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Kevin M. Lahey of the Numerical Aerospace Simulation Facility,
      9  * NASA Ames Research Center.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     30  * POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 
     33 /*
     34  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
     35  * All rights reserved.
     36  *
     37  * Redistribution and use in source and binary forms, with or without
     38  * modification, are permitted provided that the following conditions
     39  * are met:
     40  * 1. Redistributions of source code must retain the above copyright
     41  *    notice, this list of conditions and the following disclaimer.
     42  * 2. Redistributions in binary form must reproduce the above copyright
     43  *    notice, this list of conditions and the following disclaimer in the
     44  *    documentation and/or other materials provided with the distribution.
     45  * 3. Neither the name of the project nor the names of its contributors
     46  *    may be used to endorse or promote products derived from this software
     47  *    without specific prior written permission.
     48  *
     49  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     59  * SUCH DAMAGE.
     60  */
     61 
     62 /*
     63  * Copyright (c) 1980, 1986, 1991, 1993
     64  *	The Regents of the University of California.  All rights reserved.
     65  *
     66  * Redistribution and use in source and binary forms, with or without
     67  * modification, are permitted provided that the following conditions
     68  * are met:
     69  * 1. Redistributions of source code must retain the above copyright
     70  *    notice, this list of conditions and the following disclaimer.
     71  * 2. Redistributions in binary form must reproduce the above copyright
     72  *    notice, this list of conditions and the following disclaimer in the
     73  *    documentation and/or other materials provided with the distribution.
     74  * 3. Neither the name of the University nor the names of its contributors
     75  *    may be used to endorse or promote products derived from this software
     76  *    without specific prior written permission.
     77  *
     78  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     79  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     80  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     81  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     82  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     83  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     84  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     85  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     86  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     87  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     88  * SUCH DAMAGE.
     89  *
     90  *	@(#)route.c	8.3 (Berkeley) 1/9/95
     91  */
     92 
     93 #ifdef _KERNEL_OPT
     94 #include "opt_inet.h"
     95 #include "opt_route.h"
     96 #include "opt_net_mpsafe.h"
     97 #endif
     98 
     99 #include <sys/cdefs.h>
    100 __KERNEL_RCSID(0, "$NetBSD: route.c,v 1.235 2022/11/25 08:39:32 knakahara Exp $");
    101 
    102 #include <sys/param.h>
    103 #ifdef RTFLUSH_DEBUG
    104 #include <sys/sysctl.h>
    105 #endif
    106 #include <sys/systm.h>
    107 #include <sys/callout.h>
    108 #include <sys/proc.h>
    109 #include <sys/mbuf.h>
    110 #include <sys/socket.h>
    111 #include <sys/socketvar.h>
    112 #include <sys/domain.h>
    113 #include <sys/kernel.h>
    114 #include <sys/ioctl.h>
    115 #include <sys/pool.h>
    116 #include <sys/kauth.h>
    117 #include <sys/workqueue.h>
    118 #include <sys/syslog.h>
    119 #include <sys/rwlock.h>
    120 #include <sys/mutex.h>
    121 #include <sys/cpu.h>
    122 #include <sys/kmem.h>
    123 
    124 #include <net/if.h>
    125 #include <net/if_dl.h>
    126 #include <net/route.h>
    127 #if defined(INET) || defined(INET6)
    128 #include <net/if_llatbl.h>
    129 #endif
    130 
    131 #include <netinet/in.h>
    132 #include <netinet/in_var.h>
    133 
    134 #define	PRESERVED_RTF	(RTF_UP | RTF_GATEWAY | RTF_HOST | RTF_DONE | RTF_MASK)
    135 
    136 #ifdef RTFLUSH_DEBUG
    137 #define	rtcache_debug() __predict_false(_rtcache_debug)
    138 #else /* RTFLUSH_DEBUG */
    139 #define	rtcache_debug() 0
    140 #endif /* RTFLUSH_DEBUG */
    141 
    142 #ifdef RT_DEBUG
    143 #define RT_REFCNT_TRACE(rt)	printf("%s:%d: rt=%p refcnt=%d\n", \
    144 				    __func__, __LINE__, (rt), (rt)->rt_refcnt)
    145 #else
    146 #define RT_REFCNT_TRACE(rt)	do {} while (0)
    147 #endif
    148 
    149 #ifdef RT_DEBUG
    150 #define dlog(level, fmt, args...)	log(level, fmt, ##args)
    151 #else
    152 #define dlog(level, fmt, args...)	do {} while (0)
    153 #endif
    154 
    155 struct rtstat		rtstat;
    156 
    157 static int		rttrash;	/* routes not in table but not freed */
    158 
    159 static struct pool	rtentry_pool;
    160 static struct pool	rttimer_pool;
    161 
    162 static struct callout	rt_timer_ch; /* callout for rt_timer_timer() */
    163 static struct workqueue	*rt_timer_wq;
    164 static struct work	rt_timer_wk;
    165 
    166 static void	rt_timer_init(void);
    167 static void	rt_timer_queue_remove_all(struct rttimer_queue *);
    168 static void	rt_timer_remove_all(struct rtentry *);
    169 static void	rt_timer_timer(void *);
    170 
    171 /*
    172  * Locking notes:
    173  * - The routing table is protected by a global rwlock
    174  *   - API: RT_RLOCK and friends
    175  * - rtcaches are NOT protected by the framework
    176  *   - Callers must guarantee a rtcache isn't accessed simultaneously
    177  *   - How the constraint is guaranteed in the wild
    178  *     - Protect a rtcache by a mutex (e.g., inp_route)
    179  *     - Make rtcache per-CPU and allow only accesses from softint
    180  *       (e.g., ipforward_rt_percpu)
    181  * - References to a rtentry is managed by reference counting and psref
    182  *   - Reference counting is used for temporal reference when a rtentry
    183  *     is fetched from the routing table
    184  *   - psref is used for temporal reference when a rtentry is fetched
    185  *     from a rtcache
    186  *     - struct route (rtcache) has struct psref, so we cannot obtain
    187  *       a reference twice on the same struct route
    188  *   - Before destroying or updating a rtentry, we have to wait for
    189  *     all references left (see below for details)
    190  *   - APIs
    191  *     - An obtained rtentry via rtalloc1 or rtrequest* must be
    192  *       unreferenced by rt_unref
    193  *     - An obtained rtentry via rtcache_* must be unreferenced by
    194  *       rtcache_unref
    195  *   - TODO: once we get a lockless routing table, we should use only
    196  *           psref for rtentries
    197  * - rtentry destruction
    198  *   - A rtentry is destroyed (freed) only when we call rtrequest(RTM_DELETE)
    199  *   - If a caller of rtrequest grabs a reference of a rtentry, the caller
    200  *     has a responsibility to destroy the rtentry by itself by calling
    201  *     rt_free
    202  *     - If not, rtrequest itself does that
    203  *   - If rt_free is called in softint, the actual destruction routine is
    204  *     deferred to a workqueue
    205  * - rtentry update
    206  *   - When updating a rtentry, RTF_UPDATING flag is set
    207  *   - If a rtentry is set RTF_UPDATING, fetching the rtentry from
    208  *     the routing table or a rtcache results in either of the following
    209  *     cases:
    210  *     - if the caller runs in softint, the caller fails to fetch
    211  *     - otherwise, the caller waits for the update completed and retries
    212  *       to fetch (probably succeed to fetch for the second time)
    213  * - rtcache invalidation
    214  *   - There is a global generation counter that is incremented when
    215  *     any routes have been added or deleted
    216  *   - When a rtcache caches a rtentry into itself, it also stores
    217  *     a snapshot of the generation counter
    218  *   - If the snapshot equals to the global counter, the cache is valid,
    219  *     otherwise the cache is invalidated
    220  */
    221 
    222 /*
    223  * Global lock for the routing table.
    224  */
    225 static krwlock_t		rt_lock __cacheline_aligned;
    226 #ifdef NET_MPSAFE
    227 #define RT_RLOCK()		rw_enter(&rt_lock, RW_READER)
    228 #define RT_WLOCK()		rw_enter(&rt_lock, RW_WRITER)
    229 #define RT_UNLOCK()		rw_exit(&rt_lock)
    230 #define RT_WLOCKED()		rw_write_held(&rt_lock)
    231 #define	RT_ASSERT_WLOCK()	KASSERT(rw_write_held(&rt_lock))
    232 #else
    233 #define RT_RLOCK()		do {} while (0)
    234 #define RT_WLOCK()		do {} while (0)
    235 #define RT_UNLOCK()		do {} while (0)
    236 #define RT_WLOCKED()		true
    237 #define	RT_ASSERT_WLOCK()	do {} while (0)
    238 #endif
    239 
    240 static uint64_t rtcache_generation;
    241 
    242 /*
    243  * mutex and cv that are used to wait for references to a rtentry left
    244  * before updating the rtentry.
    245  */
    246 static struct {
    247 	kmutex_t		lock;
    248 	kcondvar_t		cv;
    249 	bool			ongoing;
    250 	const struct lwp	*lwp;
    251 } rt_update_global __cacheline_aligned;
    252 
    253 /*
    254  * A workqueue and stuff that are used to defer the destruction routine
    255  * of rtentries.
    256  */
    257 static struct {
    258 	struct workqueue	*wq;
    259 	struct work		wk;
    260 	kmutex_t		lock;
    261 	SLIST_HEAD(, rtentry)	queue;
    262 	bool			enqueued;
    263 } rt_free_global __cacheline_aligned;
    264 
    265 /* psref for rtentry */
    266 static struct psref_class *rt_psref_class __read_mostly;
    267 
    268 #ifdef RTFLUSH_DEBUG
    269 static int _rtcache_debug = 0;
    270 #endif /* RTFLUSH_DEBUG */
    271 
    272 static kauth_listener_t route_listener;
    273 
    274 static int rtdeletemsg(struct rtentry *);
    275 
    276 static void rt_maskedcopy(const struct sockaddr *,
    277     struct sockaddr *, const struct sockaddr *);
    278 
    279 static void rtcache_invalidate(void);
    280 
    281 static void rt_ref(struct rtentry *);
    282 
    283 static struct rtentry *
    284     rtalloc1_locked(const struct sockaddr *, int, bool, bool);
    285 
    286 static struct ifaddr *rt_getifa(struct rt_addrinfo *, struct psref *);
    287 static struct ifnet *rt_getifp(struct rt_addrinfo *, struct psref *);
    288 static struct ifaddr *ifa_ifwithroute_psref(int, const struct sockaddr *,
    289     const struct sockaddr *, struct psref *);
    290 
    291 static void rtcache_ref(struct rtentry *, struct route *);
    292 
    293 #ifdef NET_MPSAFE
    294 static void rt_update_wait(void);
    295 #endif
    296 
    297 static bool rt_wait_ok(void);
    298 static void rt_wait_refcnt(const char *, struct rtentry *, int);
    299 static void rt_wait_psref(struct rtentry *);
    300 
    301 #ifdef DDB
    302 static void db_print_sa(const struct sockaddr *);
    303 static void db_print_ifa(struct ifaddr *);
    304 static int db_show_rtentry(struct rtentry *, void *);
    305 #endif
    306 
    307 #ifdef RTFLUSH_DEBUG
    308 static void sysctl_net_rtcache_setup(struct sysctllog **);
    309 static void
    310 sysctl_net_rtcache_setup(struct sysctllog **clog)
    311 {
    312 	const struct sysctlnode *rnode;
    313 
    314 	if (sysctl_createv(clog, 0, NULL, &rnode, CTLFLAG_PERMANENT,
    315 	    CTLTYPE_NODE,
    316 	    "rtcache", SYSCTL_DESCR("Route cache related settings"),
    317 	    NULL, 0, NULL, 0, CTL_NET, CTL_CREATE, CTL_EOL) != 0)
    318 		return;
    319 	if (sysctl_createv(clog, 0, &rnode, &rnode,
    320 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
    321 	    "debug", SYSCTL_DESCR("Debug route caches"),
    322 	    NULL, 0, &_rtcache_debug, 0, CTL_CREATE, CTL_EOL) != 0)
    323 		return;
    324 }
    325 #endif /* RTFLUSH_DEBUG */
    326 
    327 static inline void
    328 rt_destroy(struct rtentry *rt)
    329 {
    330 	if (rt->_rt_key != NULL)
    331 		sockaddr_free(rt->_rt_key);
    332 	if (rt->rt_gateway != NULL)
    333 		sockaddr_free(rt->rt_gateway);
    334 	if (rt_gettag(rt) != NULL)
    335 		sockaddr_free(rt_gettag(rt));
    336 	rt->_rt_key = rt->rt_gateway = rt->rt_tag = NULL;
    337 }
    338 
    339 static inline const struct sockaddr *
    340 rt_setkey(struct rtentry *rt, const struct sockaddr *key, int flags)
    341 {
    342 	if (rt->_rt_key == key)
    343 		goto out;
    344 
    345 	if (rt->_rt_key != NULL)
    346 		sockaddr_free(rt->_rt_key);
    347 	rt->_rt_key = sockaddr_dup(key, flags);
    348 out:
    349 	rt->rt_nodes->rn_key = (const char *)rt->_rt_key;
    350 	return rt->_rt_key;
    351 }
    352 
    353 struct ifaddr *
    354 rt_get_ifa(struct rtentry *rt)
    355 {
    356 	struct ifaddr *ifa;
    357 
    358 	ifa = rt->rt_ifa;
    359 	if (ifa->ifa_getifa == NULL)
    360 		return ifa;
    361 #if 0
    362 	else if (ifa->ifa_seqno != NULL && *ifa->ifa_seqno == rt->rt_ifa_seqno)
    363 		return ifa;
    364 #endif
    365 	else {
    366 		ifa = (*ifa->ifa_getifa)(ifa, rt_getkey(rt));
    367 		if (ifa == NULL)
    368 			return NULL;
    369 		rt_replace_ifa(rt, ifa);
    370 		return ifa;
    371 	}
    372 }
    373 
    374 static void
    375 rt_set_ifa1(struct rtentry *rt, struct ifaddr *ifa)
    376 {
    377 	rt->rt_ifa = ifa;
    378 	if (ifa->ifa_seqno != NULL)
    379 		rt->rt_ifa_seqno = *ifa->ifa_seqno;
    380 }
    381 
    382 /*
    383  * Is this route the connected route for the ifa?
    384  */
    385 static int
    386 rt_ifa_connected(const struct rtentry *rt, const struct ifaddr *ifa)
    387 {
    388 	const struct sockaddr *key, *dst, *odst;
    389 	struct sockaddr_storage maskeddst;
    390 
    391 	key = rt_getkey(rt);
    392 	dst = rt->rt_flags & RTF_HOST ? ifa->ifa_dstaddr : ifa->ifa_addr;
    393 	if (dst == NULL ||
    394 	    dst->sa_family != key->sa_family ||
    395 	    dst->sa_len != key->sa_len)
    396 		return 0;
    397 	if ((rt->rt_flags & RTF_HOST) == 0 && ifa->ifa_netmask) {
    398 		odst = dst;
    399 		dst = (struct sockaddr *)&maskeddst;
    400 		rt_maskedcopy(odst, (struct sockaddr *)&maskeddst,
    401 		    ifa->ifa_netmask);
    402 	}
    403 	return (memcmp(dst, key, dst->sa_len) == 0);
    404 }
    405 
    406 void
    407 rt_replace_ifa(struct rtentry *rt, struct ifaddr *ifa)
    408 {
    409 	struct ifaddr *old;
    410 
    411 	if (rt->rt_ifa == ifa)
    412 		return;
    413 
    414 	if (rt->rt_ifa != ifa &&
    415 	    rt->rt_ifa->ifa_flags & IFA_ROUTE &&
    416 	    rt_ifa_connected(rt, rt->rt_ifa))
    417 	{
    418 		RT_DPRINTF("rt->_rt_key = %p, ifa = %p, "
    419 		    "replace deleted IFA_ROUTE\n",
    420 		    (void *)rt->_rt_key, (void *)rt->rt_ifa);
    421 		rt->rt_ifa->ifa_flags &= ~IFA_ROUTE;
    422 		if (rt_ifa_connected(rt, ifa)) {
    423 			RT_DPRINTF("rt->_rt_key = %p, ifa = %p, "
    424 			    "replace added IFA_ROUTE\n",
    425 			    (void *)rt->_rt_key, (void *)ifa);
    426 			ifa->ifa_flags |= IFA_ROUTE;
    427 		}
    428 	}
    429 
    430 	ifaref(ifa);
    431 	old = rt->rt_ifa;
    432 	rt_set_ifa1(rt, ifa);
    433 	ifafree(old);
    434 }
    435 
    436 static void
    437 rt_set_ifa(struct rtentry *rt, struct ifaddr *ifa)
    438 {
    439 	ifaref(ifa);
    440 	rt_set_ifa1(rt, ifa);
    441 }
    442 
    443 static int
    444 route_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
    445     void *arg0, void *arg1, void *arg2, void *arg3)
    446 {
    447 	struct rt_msghdr *rtm;
    448 	int result;
    449 
    450 	result = KAUTH_RESULT_DEFER;
    451 	rtm = arg1;
    452 
    453 	if (action != KAUTH_NETWORK_ROUTE)
    454 		return result;
    455 
    456 	if (rtm->rtm_type == RTM_GET)
    457 		result = KAUTH_RESULT_ALLOW;
    458 
    459 	return result;
    460 }
    461 
    462 static void rt_free_work(struct work *, void *);
    463 
    464 void
    465 rt_init(void)
    466 {
    467 	int error;
    468 
    469 #ifdef RTFLUSH_DEBUG
    470 	sysctl_net_rtcache_setup(NULL);
    471 #endif
    472 
    473 	mutex_init(&rt_free_global.lock, MUTEX_DEFAULT, IPL_SOFTNET);
    474 	SLIST_INIT(&rt_free_global.queue);
    475 	rt_free_global.enqueued = false;
    476 
    477 	rt_psref_class = psref_class_create("rtentry", IPL_SOFTNET);
    478 
    479 	error = workqueue_create(&rt_free_global.wq, "rt_free",
    480 	    rt_free_work, NULL, PRI_SOFTNET, IPL_SOFTNET, WQ_MPSAFE);
    481 	if (error)
    482 		panic("%s: workqueue_create failed (%d)\n", __func__, error);
    483 
    484 	mutex_init(&rt_update_global.lock, MUTEX_DEFAULT, IPL_SOFTNET);
    485 	cv_init(&rt_update_global.cv, "rt_update");
    486 
    487 	pool_init(&rtentry_pool, sizeof(struct rtentry), 0, 0, 0, "rtentpl",
    488 	    NULL, IPL_SOFTNET);
    489 	pool_init(&rttimer_pool, sizeof(struct rttimer), 0, 0, 0, "rttmrpl",
    490 	    NULL, IPL_SOFTNET);
    491 
    492 	rn_init();	/* initialize all zeroes, all ones, mask table */
    493 	rtbl_init();
    494 
    495 	route_listener = kauth_listen_scope(KAUTH_SCOPE_NETWORK,
    496 	    route_listener_cb, NULL);
    497 }
    498 
    499 static void
    500 rtcache_invalidate(void)
    501 {
    502 
    503 	RT_ASSERT_WLOCK();
    504 
    505 	if (rtcache_debug())
    506 		printf("%s: enter\n", __func__);
    507 
    508 	rtcache_generation++;
    509 }
    510 
    511 #ifdef RT_DEBUG
    512 static void
    513 dump_rt(const struct rtentry *rt)
    514 {
    515 	char buf[512];
    516 
    517 	log(LOG_DEBUG, "rt: ");
    518 	log(LOG_DEBUG, "p=%p ", rt);
    519 	if (rt->_rt_key == NULL) {
    520 		log(LOG_DEBUG, "dst=(NULL) ");
    521 	} else {
    522 		sockaddr_format(rt->_rt_key, buf, sizeof(buf));
    523 		log(LOG_DEBUG, "dst=%s ", buf);
    524 	}
    525 	if (rt->rt_gateway == NULL) {
    526 		log(LOG_DEBUG, "gw=(NULL) ");
    527 	} else {
    528 		sockaddr_format(rt->_rt_key, buf, sizeof(buf));
    529 		log(LOG_DEBUG, "gw=%s ", buf);
    530 	}
    531 	log(LOG_DEBUG, "flags=%x ", rt->rt_flags);
    532 	if (rt->rt_ifp == NULL) {
    533 		log(LOG_DEBUG, "if=(NULL) ");
    534 	} else {
    535 		log(LOG_DEBUG, "if=%s ", rt->rt_ifp->if_xname);
    536 	}
    537 	log(LOG_DEBUG, "\n");
    538 }
    539 #endif /* RT_DEBUG */
    540 
    541 /*
    542  * Packet routing routines. If success, refcnt of a returned rtentry
    543  * will be incremented. The caller has to rtfree it by itself.
    544  */
    545 struct rtentry *
    546 rtalloc1_locked(const struct sockaddr *dst, int report, bool wait_ok,
    547     bool wlock)
    548 {
    549 	rtbl_t *rtbl;
    550 	struct rtentry *rt;
    551 	int s;
    552 
    553 #ifdef NET_MPSAFE
    554 retry:
    555 #endif
    556 	s = splsoftnet();
    557 	rtbl = rt_gettable(dst->sa_family);
    558 	if (rtbl == NULL)
    559 		goto miss;
    560 
    561 	rt = rt_matchaddr(rtbl, dst);
    562 	if (rt == NULL)
    563 		goto miss;
    564 
    565 	if (!ISSET(rt->rt_flags, RTF_UP))
    566 		goto miss;
    567 
    568 #ifdef NET_MPSAFE
    569 	if (ISSET(rt->rt_flags, RTF_UPDATING) &&
    570 	    /* XXX updater should be always able to acquire */
    571 	    curlwp != rt_update_global.lwp) {
    572 		if (!wait_ok || !rt_wait_ok())
    573 			goto miss;
    574 		RT_UNLOCK();
    575 		splx(s);
    576 
    577 		/* We can wait until the update is complete */
    578 		rt_update_wait();
    579 
    580 		if (wlock)
    581 			RT_WLOCK();
    582 		else
    583 			RT_RLOCK();
    584 		goto retry;
    585 	}
    586 #endif /* NET_MPSAFE */
    587 
    588 	rt_ref(rt);
    589 	RT_REFCNT_TRACE(rt);
    590 
    591 	splx(s);
    592 	return rt;
    593 miss:
    594 	rtstat.rts_unreach++;
    595 	if (report) {
    596 		struct rt_addrinfo info;
    597 
    598 		memset(&info, 0, sizeof(info));
    599 		info.rti_info[RTAX_DST] = dst;
    600 		rt_missmsg(RTM_MISS, &info, 0, 0);
    601 	}
    602 	splx(s);
    603 	return NULL;
    604 }
    605 
    606 struct rtentry *
    607 rtalloc1(const struct sockaddr *dst, int report)
    608 {
    609 	struct rtentry *rt;
    610 
    611 	RT_RLOCK();
    612 	rt = rtalloc1_locked(dst, report, true, false);
    613 	RT_UNLOCK();
    614 
    615 	return rt;
    616 }
    617 
    618 static void
    619 rt_ref(struct rtentry *rt)
    620 {
    621 
    622 	KASSERTMSG(rt->rt_refcnt >= 0, "rt_refcnt=%d", rt->rt_refcnt);
    623 	atomic_inc_uint(&rt->rt_refcnt);
    624 }
    625 
    626 void
    627 rt_unref(struct rtentry *rt)
    628 {
    629 
    630 	KASSERT(rt != NULL);
    631 	KASSERTMSG(rt->rt_refcnt > 0, "refcnt=%d", rt->rt_refcnt);
    632 
    633 	atomic_dec_uint(&rt->rt_refcnt);
    634 	if (!ISSET(rt->rt_flags, RTF_UP) || ISSET(rt->rt_flags, RTF_UPDATING)) {
    635 		mutex_enter(&rt_free_global.lock);
    636 		cv_broadcast(&rt->rt_cv);
    637 		mutex_exit(&rt_free_global.lock);
    638 	}
    639 }
    640 
    641 static bool
    642 rt_wait_ok(void)
    643 {
    644 
    645 	KASSERT(!cpu_intr_p());
    646 	return !cpu_softintr_p();
    647 }
    648 
    649 void
    650 rt_wait_refcnt(const char *title, struct rtentry *rt, int cnt)
    651 {
    652 	mutex_enter(&rt_free_global.lock);
    653 	while (rt->rt_refcnt > cnt) {
    654 		dlog(LOG_DEBUG, "%s: %s waiting (refcnt=%d)\n",
    655 		    __func__, title, rt->rt_refcnt);
    656 		cv_wait(&rt->rt_cv, &rt_free_global.lock);
    657 		dlog(LOG_DEBUG, "%s: %s waited (refcnt=%d)\n",
    658 		    __func__, title, rt->rt_refcnt);
    659 	}
    660 	mutex_exit(&rt_free_global.lock);
    661 }
    662 
    663 void
    664 rt_wait_psref(struct rtentry *rt)
    665 {
    666 
    667 	psref_target_destroy(&rt->rt_psref, rt_psref_class);
    668 	psref_target_init(&rt->rt_psref, rt_psref_class);
    669 }
    670 
    671 static void
    672 _rt_free(struct rtentry *rt)
    673 {
    674 	struct ifaddr *ifa;
    675 
    676 	/*
    677 	 * Need to avoid a deadlock on rt_wait_refcnt of update
    678 	 * and a conflict on psref_target_destroy of update.
    679 	 */
    680 #ifdef NET_MPSAFE
    681 	rt_update_wait();
    682 #endif
    683 
    684 	RT_REFCNT_TRACE(rt);
    685 	KASSERTMSG(rt->rt_refcnt >= 0, "refcnt=%d", rt->rt_refcnt);
    686 	rt_wait_refcnt("free", rt, 0);
    687 #ifdef NET_MPSAFE
    688 	psref_target_destroy(&rt->rt_psref, rt_psref_class);
    689 #endif
    690 
    691 	rt_assert_inactive(rt);
    692 	rttrash--;
    693 	ifa = rt->rt_ifa;
    694 	rt->rt_ifa = NULL;
    695 	ifafree(ifa);
    696 	rt->rt_ifp = NULL;
    697 	cv_destroy(&rt->rt_cv);
    698 	rt_destroy(rt);
    699 	pool_put(&rtentry_pool, rt);
    700 }
    701 
    702 static void
    703 rt_free_work(struct work *wk, void *arg)
    704 {
    705 
    706 	for (;;) {
    707 		struct rtentry *rt;
    708 
    709 		mutex_enter(&rt_free_global.lock);
    710 		if ((rt = SLIST_FIRST(&rt_free_global.queue)) == NULL) {
    711 			rt_free_global.enqueued = false;
    712 			mutex_exit(&rt_free_global.lock);
    713 			return;
    714 		}
    715 		SLIST_REMOVE_HEAD(&rt_free_global.queue, rt_free);
    716 		mutex_exit(&rt_free_global.lock);
    717 		atomic_dec_uint(&rt->rt_refcnt);
    718 		_rt_free(rt);
    719 	}
    720 }
    721 
    722 void
    723 rt_free(struct rtentry *rt)
    724 {
    725 
    726 	KASSERTMSG(rt->rt_refcnt > 0, "rt_refcnt=%d", rt->rt_refcnt);
    727 	if (rt_wait_ok()) {
    728 		atomic_dec_uint(&rt->rt_refcnt);
    729 		_rt_free(rt);
    730 		return;
    731 	}
    732 
    733 	mutex_enter(&rt_free_global.lock);
    734 	/* No need to add a reference here. */
    735 	SLIST_INSERT_HEAD(&rt_free_global.queue, rt, rt_free);
    736 	if (!rt_free_global.enqueued) {
    737 		workqueue_enqueue(rt_free_global.wq, &rt_free_global.wk, NULL);
    738 		rt_free_global.enqueued = true;
    739 	}
    740 	mutex_exit(&rt_free_global.lock);
    741 }
    742 
    743 #ifdef NET_MPSAFE
    744 static void
    745 rt_update_wait(void)
    746 {
    747 
    748 	mutex_enter(&rt_update_global.lock);
    749 	while (rt_update_global.ongoing) {
    750 		dlog(LOG_DEBUG, "%s: waiting lwp=%p\n", __func__, curlwp);
    751 		cv_wait(&rt_update_global.cv, &rt_update_global.lock);
    752 		dlog(LOG_DEBUG, "%s: waited lwp=%p\n", __func__, curlwp);
    753 	}
    754 	mutex_exit(&rt_update_global.lock);
    755 }
    756 #endif
    757 
    758 int
    759 rt_update_prepare(struct rtentry *rt)
    760 {
    761 
    762 	dlog(LOG_DEBUG, "%s: updating rt=%p lwp=%p\n", __func__, rt, curlwp);
    763 
    764 	RT_WLOCK();
    765 	/* If the entry is being destroyed, don't proceed the update. */
    766 	if (!ISSET(rt->rt_flags, RTF_UP)) {
    767 		RT_UNLOCK();
    768 		return ESRCH;
    769 	}
    770 	rt->rt_flags |= RTF_UPDATING;
    771 	RT_UNLOCK();
    772 
    773 	mutex_enter(&rt_update_global.lock);
    774 	while (rt_update_global.ongoing) {
    775 		dlog(LOG_DEBUG, "%s: waiting ongoing updating rt=%p lwp=%p\n",
    776 		    __func__, rt, curlwp);
    777 		cv_wait(&rt_update_global.cv, &rt_update_global.lock);
    778 		dlog(LOG_DEBUG, "%s: waited ongoing updating rt=%p lwp=%p\n",
    779 		    __func__, rt, curlwp);
    780 	}
    781 	rt_update_global.ongoing = true;
    782 	/* XXX need it to avoid rt_update_wait by updater itself. */
    783 	rt_update_global.lwp = curlwp;
    784 	mutex_exit(&rt_update_global.lock);
    785 
    786 	rt_wait_refcnt("update", rt, 1);
    787 	rt_wait_psref(rt);
    788 
    789 	return 0;
    790 }
    791 
    792 void
    793 rt_update_finish(struct rtentry *rt)
    794 {
    795 
    796 	RT_WLOCK();
    797 	rt->rt_flags &= ~RTF_UPDATING;
    798 	RT_UNLOCK();
    799 
    800 	mutex_enter(&rt_update_global.lock);
    801 	rt_update_global.ongoing = false;
    802 	rt_update_global.lwp = NULL;
    803 	cv_broadcast(&rt_update_global.cv);
    804 	mutex_exit(&rt_update_global.lock);
    805 
    806 	dlog(LOG_DEBUG, "%s: updated rt=%p lwp=%p\n", __func__, rt, curlwp);
    807 }
    808 
    809 /*
    810  * Force a routing table entry to the specified
    811  * destination to go through the given gateway.
    812  * Normally called as a result of a routing redirect
    813  * message from the network layer.
    814  *
    815  * N.B.: must be called at splsoftnet
    816  */
    817 void
    818 rtredirect(const struct sockaddr *dst, const struct sockaddr *gateway,
    819 	const struct sockaddr *netmask, int flags, const struct sockaddr *src,
    820 	struct rtentry **rtp)
    821 {
    822 	struct rtentry *rt;
    823 	int error = 0;
    824 	uint64_t *stat = NULL;
    825 	struct rt_addrinfo info;
    826 	struct ifaddr *ifa;
    827 	struct psref psref;
    828 
    829 	/* verify the gateway is directly reachable */
    830 	if ((ifa = ifa_ifwithnet_psref(gateway, &psref)) == NULL) {
    831 		error = ENETUNREACH;
    832 		goto out;
    833 	}
    834 	rt = rtalloc1(dst, 0);
    835 	/*
    836 	 * If the redirect isn't from our current router for this dst,
    837 	 * it's either old or wrong.  If it redirects us to ourselves,
    838 	 * we have a routing loop, perhaps as a result of an interface
    839 	 * going down recently.
    840 	 */
    841 	if (!(flags & RTF_DONE) && rt &&
    842 	     (sockaddr_cmp(src, rt->rt_gateway) != 0 || rt->rt_ifa != ifa))
    843 		error = EINVAL;
    844 	else {
    845 		int s = pserialize_read_enter();
    846 		struct ifaddr *_ifa;
    847 
    848 		_ifa = ifa_ifwithaddr(gateway);
    849 		if (_ifa != NULL)
    850 			error = EHOSTUNREACH;
    851 		pserialize_read_exit(s);
    852 	}
    853 	if (error)
    854 		goto done;
    855 	/*
    856 	 * Create a new entry if we just got back a wildcard entry
    857 	 * or the lookup failed.  This is necessary for hosts
    858 	 * which use routing redirects generated by smart gateways
    859 	 * to dynamically build the routing tables.
    860 	 */
    861 	if (rt == NULL || (rt_mask(rt) && rt_mask(rt)->sa_len < 2))
    862 		goto create;
    863 	/*
    864 	 * Don't listen to the redirect if it's
    865 	 * for a route to an interface.
    866 	 */
    867 	if (rt->rt_flags & RTF_GATEWAY) {
    868 		if (((rt->rt_flags & RTF_HOST) == 0) && (flags & RTF_HOST)) {
    869 			/*
    870 			 * Changing from route to net => route to host.
    871 			 * Create new route, rather than smashing route to net.
    872 			 */
    873 		create:
    874 			if (rt != NULL)
    875 				rt_unref(rt);
    876 			flags |=  RTF_GATEWAY | RTF_DYNAMIC;
    877 			memset(&info, 0, sizeof(info));
    878 			info.rti_info[RTAX_DST] = dst;
    879 			info.rti_info[RTAX_GATEWAY] = gateway;
    880 			info.rti_info[RTAX_NETMASK] = netmask;
    881 			info.rti_ifa = ifa;
    882 			info.rti_flags = flags;
    883 			rt = NULL;
    884 			error = rtrequest1(RTM_ADD, &info, &rt);
    885 			if (rt != NULL)
    886 				flags = rt->rt_flags;
    887 			if (error == 0)
    888 				rt_newmsg_dynamic(RTM_ADD, rt);
    889 			stat = &rtstat.rts_dynamic;
    890 		} else {
    891 			/*
    892 			 * Smash the current notion of the gateway to
    893 			 * this destination.  Should check about netmask!!!
    894 			 */
    895 #ifdef NET_MPSAFE
    896 			KASSERT(!cpu_softintr_p());
    897 
    898 			error = rt_update_prepare(rt);
    899 			if (error == 0) {
    900 #endif
    901 				RT_WLOCK();
    902 				error = rt_setgate(rt, gateway);
    903 				if (error == 0) {
    904 					rt->rt_flags |= RTF_MODIFIED;
    905 					flags |= RTF_MODIFIED;
    906 				}
    907 				RT_UNLOCK();
    908 #ifdef NET_MPSAFE
    909 				rt_update_finish(rt);
    910 			} else {
    911 				/*
    912 				 * If error != 0, the rtentry is being
    913 				 * destroyed, so doing nothing doesn't
    914 				 * matter.
    915 				 */
    916 			}
    917 #endif
    918 			stat = &rtstat.rts_newgateway;
    919 		}
    920 	} else
    921 		error = EHOSTUNREACH;
    922 done:
    923 	if (rt) {
    924 		if (rtp != NULL && !error)
    925 			*rtp = rt;
    926 		else
    927 			rt_unref(rt);
    928 	}
    929 out:
    930 	if (error)
    931 		rtstat.rts_badredirect++;
    932 	else if (stat != NULL)
    933 		(*stat)++;
    934 	memset(&info, 0, sizeof(info));
    935 	info.rti_info[RTAX_DST] = dst;
    936 	info.rti_info[RTAX_GATEWAY] = gateway;
    937 	info.rti_info[RTAX_NETMASK] = netmask;
    938 	info.rti_info[RTAX_AUTHOR] = src;
    939 	rt_missmsg(RTM_REDIRECT, &info, flags, error);
    940 	ifa_release(ifa, &psref);
    941 }
    942 
    943 /*
    944  * Delete a route and generate a message.
    945  * It doesn't free a passed rt.
    946  */
    947 static int
    948 rtdeletemsg(struct rtentry *rt)
    949 {
    950 	int error;
    951 	struct rt_addrinfo info;
    952 	struct rtentry *retrt;
    953 
    954 	/*
    955 	 * Request the new route so that the entry is not actually
    956 	 * deleted.  That will allow the information being reported to
    957 	 * be accurate (and consistent with route_output()).
    958 	 */
    959 	memset(&info, 0, sizeof(info));
    960 	info.rti_info[RTAX_DST] = rt_getkey(rt);
    961 	info.rti_info[RTAX_NETMASK] = rt_mask(rt);
    962 	info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
    963 	info.rti_flags = rt->rt_flags;
    964 	error = rtrequest1(RTM_DELETE, &info, &retrt);
    965 
    966 	rt_missmsg(RTM_DELETE, &info, info.rti_flags, error);
    967 
    968 	return error;
    969 }
    970 
    971 static struct ifaddr *
    972 ifa_ifwithroute_psref(int flags, const struct sockaddr *dst,
    973     const struct sockaddr *gateway, struct psref *psref)
    974 {
    975 	struct ifaddr *ifa = NULL;
    976 
    977 	if ((flags & RTF_GATEWAY) == 0) {
    978 		/*
    979 		 * If we are adding a route to an interface,
    980 		 * and the interface is a pt to pt link
    981 		 * we should search for the destination
    982 		 * as our clue to the interface.  Otherwise
    983 		 * we can use the local address.
    984 		 */
    985 		if ((flags & RTF_HOST) && gateway->sa_family != AF_LINK)
    986 			ifa = ifa_ifwithdstaddr_psref(dst, psref);
    987 		if (ifa == NULL)
    988 			ifa = ifa_ifwithaddr_psref(gateway, psref);
    989 	} else {
    990 		/*
    991 		 * If we are adding a route to a remote net
    992 		 * or host, the gateway may still be on the
    993 		 * other end of a pt to pt link.
    994 		 */
    995 		ifa = ifa_ifwithdstaddr_psref(gateway, psref);
    996 	}
    997 	if (ifa == NULL)
    998 		ifa = ifa_ifwithnet_psref(gateway, psref);
    999 	if (ifa == NULL) {
   1000 		int s;
   1001 		struct rtentry *rt;
   1002 
   1003 		rt = rtalloc1_locked(gateway, 0, true, true);
   1004 		if (rt == NULL)
   1005 			return NULL;
   1006 		if (rt->rt_flags & RTF_GATEWAY) {
   1007 			rt_unref(rt);
   1008 			return NULL;
   1009 		}
   1010 		/*
   1011 		 * Just in case. May not need to do this workaround.
   1012 		 * Revisit when working on rtentry MP-ification.
   1013 		 */
   1014 		s = pserialize_read_enter();
   1015 		IFADDR_READER_FOREACH(ifa, rt->rt_ifp) {
   1016 			if (ifa == rt->rt_ifa)
   1017 				break;
   1018 		}
   1019 		if (ifa != NULL)
   1020 			ifa_acquire(ifa, psref);
   1021 		pserialize_read_exit(s);
   1022 		rt_unref(rt);
   1023 		if (ifa == NULL)
   1024 			return NULL;
   1025 	}
   1026 	if (ifa->ifa_addr->sa_family != dst->sa_family) {
   1027 		struct ifaddr *nifa;
   1028 		int s;
   1029 
   1030 		s = pserialize_read_enter();
   1031 		nifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
   1032 		if (nifa != NULL) {
   1033 			ifa_release(ifa, psref);
   1034 			ifa_acquire(nifa, psref);
   1035 			ifa = nifa;
   1036 		}
   1037 		pserialize_read_exit(s);
   1038 	}
   1039 	return ifa;
   1040 }
   1041 
   1042 /*
   1043  * If it suceeds and ret_nrt isn't NULL, refcnt of ret_nrt is incremented.
   1044  * The caller has to rtfree it by itself.
   1045  */
   1046 int
   1047 rtrequest(int req, const struct sockaddr *dst, const struct sockaddr *gateway,
   1048 	const struct sockaddr *netmask, int flags, struct rtentry **ret_nrt)
   1049 {
   1050 	struct rt_addrinfo info;
   1051 
   1052 	memset(&info, 0, sizeof(info));
   1053 	info.rti_flags = flags;
   1054 	info.rti_info[RTAX_DST] = dst;
   1055 	info.rti_info[RTAX_GATEWAY] = gateway;
   1056 	info.rti_info[RTAX_NETMASK] = netmask;
   1057 	return rtrequest1(req, &info, ret_nrt);
   1058 }
   1059 
   1060 static struct ifnet *
   1061 rt_getifp(struct rt_addrinfo *info, struct psref *psref)
   1062 {
   1063 	const struct sockaddr *ifpaddr = info->rti_info[RTAX_IFP];
   1064 
   1065 	if (info->rti_ifp != NULL)
   1066 		return NULL;
   1067 	/*
   1068 	 * ifp may be specified by sockaddr_dl when protocol address
   1069 	 * is ambiguous
   1070 	 */
   1071 	if (ifpaddr != NULL && ifpaddr->sa_family == AF_LINK) {
   1072 		struct ifaddr *ifa;
   1073 		int s = pserialize_read_enter();
   1074 
   1075 		ifa = ifa_ifwithnet(ifpaddr);
   1076 		if (ifa != NULL)
   1077 			info->rti_ifp = if_get_byindex(ifa->ifa_ifp->if_index,
   1078 			    psref);
   1079 		pserialize_read_exit(s);
   1080 	}
   1081 
   1082 	return info->rti_ifp;
   1083 }
   1084 
   1085 static struct ifaddr *
   1086 rt_getifa(struct rt_addrinfo *info, struct psref *psref)
   1087 {
   1088 	struct ifaddr *ifa = NULL;
   1089 	const struct sockaddr *dst = info->rti_info[RTAX_DST];
   1090 	const struct sockaddr *gateway = info->rti_info[RTAX_GATEWAY];
   1091 	const struct sockaddr *ifaaddr = info->rti_info[RTAX_IFA];
   1092 	int flags = info->rti_flags;
   1093 	const struct sockaddr *sa;
   1094 
   1095 	if (info->rti_ifa == NULL && ifaaddr != NULL) {
   1096 		ifa = ifa_ifwithaddr_psref(ifaaddr, psref);
   1097 		if (ifa != NULL)
   1098 			goto got;
   1099 	}
   1100 
   1101 	sa = ifaaddr != NULL ? ifaaddr :
   1102 	    (gateway != NULL ? gateway : dst);
   1103 	if (sa != NULL && info->rti_ifp != NULL)
   1104 		ifa = ifaof_ifpforaddr_psref(sa, info->rti_ifp, psref);
   1105 	else if (dst != NULL && gateway != NULL)
   1106 		ifa = ifa_ifwithroute_psref(flags, dst, gateway, psref);
   1107 	else if (sa != NULL)
   1108 		ifa = ifa_ifwithroute_psref(flags, sa, sa, psref);
   1109 	if (ifa == NULL)
   1110 		return NULL;
   1111 got:
   1112 	if (ifa->ifa_getifa != NULL) {
   1113 		/* FIXME ifa_getifa is NOMPSAFE */
   1114 		ifa = (*ifa->ifa_getifa)(ifa, dst);
   1115 		if (ifa == NULL)
   1116 			return NULL;
   1117 		ifa_acquire(ifa, psref);
   1118 	}
   1119 	info->rti_ifa = ifa;
   1120 	if (info->rti_ifp == NULL)
   1121 		info->rti_ifp = ifa->ifa_ifp;
   1122 	return ifa;
   1123 }
   1124 
   1125 /*
   1126  * If it suceeds and ret_nrt isn't NULL, refcnt of ret_nrt is incremented.
   1127  * The caller has to rtfree it by itself.
   1128  */
   1129 int
   1130 rtrequest1(int req, struct rt_addrinfo *info, struct rtentry **ret_nrt)
   1131 {
   1132 	int s = splsoftnet(), ss;
   1133 	int error = 0, rc;
   1134 	struct rtentry *rt;
   1135 	rtbl_t *rtbl;
   1136 	struct ifaddr *ifa = NULL;
   1137 	struct sockaddr_storage maskeddst;
   1138 	const struct sockaddr *dst = info->rti_info[RTAX_DST];
   1139 	const struct sockaddr *gateway = info->rti_info[RTAX_GATEWAY];
   1140 	const struct sockaddr *netmask = info->rti_info[RTAX_NETMASK];
   1141 	int flags = info->rti_flags;
   1142 	struct psref psref_ifp, psref_ifa;
   1143 	int bound = 0;
   1144 	struct ifnet *ifp = NULL;
   1145 	bool need_to_release_ifa = true;
   1146 	bool need_unlock = true;
   1147 #define senderr(x) { error = x ; goto bad; }
   1148 
   1149 	RT_WLOCK();
   1150 
   1151 	bound = curlwp_bind();
   1152 	if ((rtbl = rt_gettable(dst->sa_family)) == NULL)
   1153 		senderr(ESRCH);
   1154 	if (flags & RTF_HOST)
   1155 		netmask = NULL;
   1156 	switch (req) {
   1157 	case RTM_DELETE:
   1158 		if (netmask) {
   1159 			rt_maskedcopy(dst, (struct sockaddr *)&maskeddst,
   1160 			    netmask);
   1161 			dst = (struct sockaddr *)&maskeddst;
   1162 		}
   1163 		if ((rt = rt_lookup(rtbl, dst, netmask)) == NULL)
   1164 			senderr(ESRCH);
   1165 		if ((rt = rt_deladdr(rtbl, dst, netmask)) == NULL)
   1166 			senderr(ESRCH);
   1167 		rt->rt_flags &= ~RTF_UP;
   1168 		ifa = rt->rt_ifa;
   1169 		if (ifa->ifa_flags & IFA_ROUTE &&
   1170 		    rt_ifa_connected(rt, ifa)) {
   1171 			RT_DPRINTF("rt->_rt_key = %p, ifa = %p, "
   1172 			    "deleted IFA_ROUTE\n",
   1173 			    (void *)rt->_rt_key, (void *)ifa);
   1174 			ifa->ifa_flags &= ~IFA_ROUTE;
   1175 		}
   1176 		if (ifa->ifa_rtrequest)
   1177 			ifa->ifa_rtrequest(RTM_DELETE, rt, info);
   1178 		ifa = NULL;
   1179 		rttrash++;
   1180 		if (ret_nrt) {
   1181 			*ret_nrt = rt;
   1182 			rt_ref(rt);
   1183 			RT_REFCNT_TRACE(rt);
   1184 		}
   1185 		rtcache_invalidate();
   1186 		RT_UNLOCK();
   1187 		need_unlock = false;
   1188 		rt_timer_remove_all(rt);
   1189 #if defined(INET) || defined(INET6)
   1190 		if (netmask != NULL)
   1191 			lltable_prefix_free(dst->sa_family, dst, netmask, 0);
   1192 #endif
   1193 		if (ret_nrt == NULL) {
   1194 			/* Adjust the refcount */
   1195 			rt_ref(rt);
   1196 			RT_REFCNT_TRACE(rt);
   1197 			rt_free(rt);
   1198 		}
   1199 		break;
   1200 
   1201 	case RTM_ADD:
   1202 		if (info->rti_ifa == NULL) {
   1203 			ifp = rt_getifp(info, &psref_ifp);
   1204 			ifa = rt_getifa(info, &psref_ifa);
   1205 			if (ifa == NULL)
   1206 				senderr(ENETUNREACH);
   1207 		} else {
   1208 			/* Caller should have a reference of ifa */
   1209 			ifa = info->rti_ifa;
   1210 			need_to_release_ifa = false;
   1211 		}
   1212 		rt = pool_get(&rtentry_pool, PR_NOWAIT);
   1213 		if (rt == NULL)
   1214 			senderr(ENOBUFS);
   1215 		memset(rt, 0, sizeof(*rt));
   1216 		rt->rt_flags = RTF_UP | (flags & ~RTF_DONTCHANGEIFA);
   1217 		LIST_INIT(&rt->rt_timer);
   1218 
   1219 		RT_DPRINTF("rt->_rt_key = %p\n", (void *)rt->_rt_key);
   1220 		if (netmask) {
   1221 			rt_maskedcopy(dst, (struct sockaddr *)&maskeddst,
   1222 			    netmask);
   1223 			rt_setkey(rt, (struct sockaddr *)&maskeddst, M_NOWAIT);
   1224 		} else {
   1225 			rt_setkey(rt, dst, M_NOWAIT);
   1226 		}
   1227 		RT_DPRINTF("rt->_rt_key = %p\n", (void *)rt->_rt_key);
   1228 		if (rt_getkey(rt) == NULL ||
   1229 		    rt_setgate(rt, gateway) != 0) {
   1230 			pool_put(&rtentry_pool, rt);
   1231 			senderr(ENOBUFS);
   1232 		}
   1233 
   1234 		rt_set_ifa(rt, ifa);
   1235 		if (info->rti_info[RTAX_TAG] != NULL) {
   1236 			const struct sockaddr *tag;
   1237 			tag = rt_settag(rt, info->rti_info[RTAX_TAG]);
   1238 			if (tag == NULL)
   1239 				senderr(ENOBUFS);
   1240 		}
   1241 		RT_DPRINTF("rt->_rt_key = %p\n", (void *)rt->_rt_key);
   1242 
   1243 		ss = pserialize_read_enter();
   1244 		if (info->rti_info[RTAX_IFP] != NULL) {
   1245 			struct ifaddr *ifa2;
   1246 			ifa2 = ifa_ifwithnet(info->rti_info[RTAX_IFP]);
   1247 			if (ifa2 != NULL)
   1248 				rt->rt_ifp = ifa2->ifa_ifp;
   1249 			else
   1250 				rt->rt_ifp = ifa->ifa_ifp;
   1251 		} else
   1252 			rt->rt_ifp = ifa->ifa_ifp;
   1253 		pserialize_read_exit(ss);
   1254 		cv_init(&rt->rt_cv, "rtentry");
   1255 		psref_target_init(&rt->rt_psref, rt_psref_class);
   1256 
   1257 		RT_DPRINTF("rt->_rt_key = %p\n", (void *)rt->_rt_key);
   1258 		rc = rt_addaddr(rtbl, rt, netmask);
   1259 		RT_DPRINTF("rt->_rt_key = %p\n", (void *)rt->_rt_key);
   1260 		if (rc != 0) {
   1261 			ifafree(ifa); /* for rt_set_ifa above */
   1262 			cv_destroy(&rt->rt_cv);
   1263 			rt_destroy(rt);
   1264 			pool_put(&rtentry_pool, rt);
   1265 			senderr(rc);
   1266 		}
   1267 		RT_DPRINTF("rt->_rt_key = %p\n", (void *)rt->_rt_key);
   1268 		if (ifa->ifa_rtrequest)
   1269 			ifa->ifa_rtrequest(req, rt, info);
   1270 		if (need_to_release_ifa)
   1271 			ifa_release(ifa, &psref_ifa);
   1272 		ifa = NULL;
   1273 		if_put(ifp, &psref_ifp);
   1274 		ifp = NULL;
   1275 		RT_DPRINTF("rt->_rt_key = %p\n", (void *)rt->_rt_key);
   1276 		if (ret_nrt) {
   1277 			*ret_nrt = rt;
   1278 			rt_ref(rt);
   1279 			RT_REFCNT_TRACE(rt);
   1280 		}
   1281 		rtcache_invalidate();
   1282 		RT_UNLOCK();
   1283 		need_unlock = false;
   1284 		break;
   1285 	case RTM_GET:
   1286 		if (netmask != NULL) {
   1287 			rt_maskedcopy(dst, (struct sockaddr *)&maskeddst,
   1288 			    netmask);
   1289 			dst = (struct sockaddr *)&maskeddst;
   1290 		}
   1291 		if ((rt = rt_lookup(rtbl, dst, netmask)) == NULL)
   1292 			senderr(ESRCH);
   1293 		if (ret_nrt != NULL) {
   1294 			*ret_nrt = rt;
   1295 			rt_ref(rt);
   1296 			RT_REFCNT_TRACE(rt);
   1297 		}
   1298 		break;
   1299 	}
   1300 bad:
   1301 	if (need_to_release_ifa)
   1302 		ifa_release(ifa, &psref_ifa);
   1303 	if_put(ifp, &psref_ifp);
   1304 	curlwp_bindx(bound);
   1305 	if (need_unlock)
   1306 		RT_UNLOCK();
   1307 	splx(s);
   1308 	return error;
   1309 }
   1310 
   1311 int
   1312 rt_setgate(struct rtentry *rt, const struct sockaddr *gate)
   1313 {
   1314 	struct sockaddr *new, *old;
   1315 
   1316 	KASSERT(RT_WLOCKED());
   1317 	KASSERT(rt->_rt_key != NULL);
   1318 	RT_DPRINTF("rt->_rt_key = %p\n", (void *)rt->_rt_key);
   1319 
   1320 	new = sockaddr_dup(gate, M_ZERO | M_NOWAIT);
   1321 	if (new == NULL)
   1322 		return ENOMEM;
   1323 
   1324 	old = rt->rt_gateway;
   1325 	rt->rt_gateway = new;
   1326 	if (old != NULL)
   1327 		sockaddr_free(old);
   1328 
   1329 	KASSERT(rt->_rt_key != NULL);
   1330 	RT_DPRINTF("rt->_rt_key = %p\n", (void *)rt->_rt_key);
   1331 
   1332 	if (rt->rt_flags & RTF_GATEWAY) {
   1333 		struct rtentry *gwrt;
   1334 
   1335 		gwrt = rtalloc1_locked(gate, 1, false, true);
   1336 		/*
   1337 		 * If we switched gateways, grab the MTU from the new
   1338 		 * gateway route if the current MTU, if the current MTU is
   1339 		 * greater than the MTU of gateway.
   1340 		 * Note that, if the MTU of gateway is 0, we will reset the
   1341 		 * MTU of the route to run PMTUD again from scratch. XXX
   1342 		 */
   1343 		if (gwrt != NULL) {
   1344 			KASSERT(gwrt->_rt_key != NULL);
   1345 			RT_DPRINTF("gwrt->_rt_key = %p\n", gwrt->_rt_key);
   1346 			if ((rt->rt_rmx.rmx_locks & RTV_MTU) == 0 &&
   1347 			    rt->rt_rmx.rmx_mtu &&
   1348 			    rt->rt_rmx.rmx_mtu > gwrt->rt_rmx.rmx_mtu) {
   1349 				rt->rt_rmx.rmx_mtu = gwrt->rt_rmx.rmx_mtu;
   1350 			}
   1351 			rt_unref(gwrt);
   1352 		}
   1353 	}
   1354 	KASSERT(rt->_rt_key != NULL);
   1355 	RT_DPRINTF("rt->_rt_key = %p\n", (void *)rt->_rt_key);
   1356 	return 0;
   1357 }
   1358 
   1359 static struct ifaddr *
   1360 rt_update_get_ifa(const struct rt_addrinfo *info, const struct rtentry *rt,
   1361     struct ifnet **ifp, struct psref *psref_ifp, struct psref *psref)
   1362 {
   1363 	struct ifaddr *ifa = NULL;
   1364 
   1365 	*ifp = NULL;
   1366 	if (info->rti_info[RTAX_IFP] != NULL) {
   1367 		ifa = ifa_ifwithnet_psref(info->rti_info[RTAX_IFP], psref);
   1368 		if (ifa == NULL)
   1369 			goto next;
   1370 		if (ifa->ifa_ifp->if_flags & IFF_UNNUMBERED) {
   1371 			ifa_release(ifa, psref);
   1372 			ifa = NULL;
   1373 			goto next;
   1374 		}
   1375 		*ifp = ifa->ifa_ifp;
   1376 		if_acquire(*ifp, psref_ifp);
   1377 		if (info->rti_info[RTAX_IFA] == NULL &&
   1378 		    info->rti_info[RTAX_GATEWAY] == NULL)
   1379 			goto out;
   1380 		ifa_release(ifa, psref);
   1381 		if (info->rti_info[RTAX_IFA] == NULL) {
   1382 			/* route change <dst> <gw> -ifp <if> */
   1383 			ifa = ifaof_ifpforaddr_psref(
   1384 			    info->rti_info[RTAX_GATEWAY], *ifp, psref);
   1385 		} else {
   1386 			/* route change <dst> -ifp <if> -ifa <addr> */
   1387 			ifa = ifa_ifwithaddr_psref(info->rti_info[RTAX_IFA],
   1388 			    psref);
   1389 			if (ifa != NULL)
   1390 				goto out;
   1391 			ifa = ifaof_ifpforaddr_psref(info->rti_info[RTAX_IFA],
   1392 			    *ifp, psref);
   1393 		}
   1394 		goto out;
   1395 	}
   1396 next:
   1397 	if (info->rti_info[RTAX_IFA] != NULL) {
   1398 		/* route change <dst> <gw> -ifa <addr> */
   1399 		ifa = ifa_ifwithaddr_psref(info->rti_info[RTAX_IFA], psref);
   1400 		if (ifa != NULL)
   1401 			goto out;
   1402 	}
   1403 	if (info->rti_info[RTAX_GATEWAY] != NULL) {
   1404 		/* route change <dst> <gw> */
   1405 		ifa = ifa_ifwithroute_psref(rt->rt_flags, rt_getkey(rt),
   1406 		    info->rti_info[RTAX_GATEWAY], psref);
   1407 	}
   1408 out:
   1409 	if (ifa != NULL && *ifp == NULL) {
   1410 		*ifp = ifa->ifa_ifp;
   1411 		if_acquire(*ifp, psref_ifp);
   1412 	}
   1413 	if (ifa == NULL && *ifp != NULL) {
   1414 		if_put(*ifp, psref_ifp);
   1415 		*ifp = NULL;
   1416 	}
   1417 	return ifa;
   1418 }
   1419 
   1420 int
   1421 rt_update(struct rtentry *rt, struct rt_addrinfo *info, void *rtm)
   1422 {
   1423 	int error = 0;
   1424 	struct ifnet *ifp = NULL, *new_ifp = NULL;
   1425 	struct ifaddr *ifa = NULL, *new_ifa;
   1426 	struct psref psref_ifa, psref_new_ifa, psref_ifp, psref_new_ifp;
   1427 	bool newgw, ifp_changed = false;
   1428 
   1429 	RT_WLOCK();
   1430 	/*
   1431 	 * New gateway could require new ifaddr, ifp;
   1432 	 * flags may also be different; ifp may be specified
   1433 	 * by ll sockaddr when protocol address is ambiguous
   1434 	 */
   1435 	newgw = info->rti_info[RTAX_GATEWAY] != NULL &&
   1436 	    sockaddr_cmp(info->rti_info[RTAX_GATEWAY], rt->rt_gateway) != 0;
   1437 
   1438 	if (newgw || info->rti_info[RTAX_IFP] != NULL ||
   1439 	    info->rti_info[RTAX_IFA] != NULL) {
   1440 		ifp = rt_getifp(info, &psref_ifp);
   1441 		/* info refers ifp so we need to keep a reference */
   1442 		ifa = rt_getifa(info, &psref_ifa);
   1443 		if (ifa == NULL) {
   1444 			error = ENETUNREACH;
   1445 			goto out;
   1446 		}
   1447 	}
   1448 	if (newgw) {
   1449 		error = rt_setgate(rt, info->rti_info[RTAX_GATEWAY]);
   1450 		if (error != 0)
   1451 			goto out;
   1452 	}
   1453 	if (info->rti_info[RTAX_TAG]) {
   1454 		const struct sockaddr *tag;
   1455 		tag = rt_settag(rt, info->rti_info[RTAX_TAG]);
   1456 		if (tag == NULL) {
   1457 			error = ENOBUFS;
   1458 			goto out;
   1459 		}
   1460 	}
   1461 	/*
   1462 	 * New gateway could require new ifaddr, ifp;
   1463 	 * flags may also be different; ifp may be specified
   1464 	 * by ll sockaddr when protocol address is ambiguous
   1465 	 */
   1466 	new_ifa = rt_update_get_ifa(info, rt, &new_ifp, &psref_new_ifp,
   1467 	    &psref_new_ifa);
   1468 	if (new_ifa != NULL) {
   1469 		ifa_release(ifa, &psref_ifa);
   1470 		ifa = new_ifa;
   1471 	}
   1472 	if (ifa) {
   1473 		struct ifaddr *oifa = rt->rt_ifa;
   1474 		if (oifa != ifa && !ifa_is_destroying(ifa) &&
   1475 		    new_ifp != NULL && !if_is_deactivated(new_ifp)) {
   1476 			if (oifa && oifa->ifa_rtrequest)
   1477 				oifa->ifa_rtrequest(RTM_DELETE, rt, info);
   1478 			rt_replace_ifa(rt, ifa);
   1479 			rt->rt_ifp = new_ifp;
   1480 			ifp_changed = true;
   1481 		}
   1482 		if (new_ifa == NULL)
   1483 			ifa_release(ifa, &psref_ifa);
   1484 		/* To avoid ifa_release below */
   1485 		ifa = NULL;
   1486 	}
   1487 	ifa_release(new_ifa, &psref_new_ifa);
   1488 	if (new_ifp && rt->rt_ifp != new_ifp && !if_is_deactivated(new_ifp)) {
   1489 		rt->rt_ifp = new_ifp;
   1490 		ifp_changed = true;
   1491 	}
   1492 	rt_setmetrics(rtm, rt);
   1493 	if (rt->rt_flags != info->rti_flags) {
   1494 		rt->rt_flags = (info->rti_flags & ~PRESERVED_RTF) |
   1495 		    (rt->rt_flags & PRESERVED_RTF);
   1496 	}
   1497 	if (rt->rt_ifa->ifa_rtrequest)
   1498 		rt->rt_ifa->ifa_rtrequest(RTM_ADD, rt, info);
   1499 #if defined(INET) || defined(INET6)
   1500 	if (ifp_changed && rt_mask(rt) != NULL)
   1501 		lltable_prefix_free(rt_getkey(rt)->sa_family, rt_getkey(rt),
   1502 		    rt_mask(rt), 0);
   1503 #else
   1504 	(void)ifp_changed; /* XXX gcc */
   1505 #endif
   1506 out:
   1507 	ifa_release(ifa, &psref_ifa);
   1508 	if_put(new_ifp, &psref_new_ifp);
   1509 	if_put(ifp, &psref_ifp);
   1510 
   1511 	RT_UNLOCK();
   1512 
   1513 	return error;
   1514 }
   1515 
   1516 static void
   1517 rt_maskedcopy(const struct sockaddr *src, struct sockaddr *dst,
   1518 	const struct sockaddr *netmask)
   1519 {
   1520 	const char *netmaskp = &netmask->sa_data[0],
   1521 	           *srcp = &src->sa_data[0];
   1522 	char *dstp = &dst->sa_data[0];
   1523 	const char *maskend = (char *)dst + MIN(netmask->sa_len, src->sa_len);
   1524 	const char *srcend = (char *)dst + src->sa_len;
   1525 
   1526 	dst->sa_len = src->sa_len;
   1527 	dst->sa_family = src->sa_family;
   1528 
   1529 	while (dstp < maskend)
   1530 		*dstp++ = *srcp++ & *netmaskp++;
   1531 	if (dstp < srcend)
   1532 		memset(dstp, 0, (size_t)(srcend - dstp));
   1533 }
   1534 
   1535 /*
   1536  * Inform the routing socket of a route change.
   1537  */
   1538 void
   1539 rt_newmsg(const int cmd, const struct rtentry *rt)
   1540 {
   1541 	struct rt_addrinfo info;
   1542 
   1543 	memset((void *)&info, 0, sizeof(info));
   1544 	info.rti_info[RTAX_DST] = rt_getkey(rt);
   1545 	info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
   1546 	info.rti_info[RTAX_NETMASK] = rt_mask(rt);
   1547 	if (rt->rt_ifp) {
   1548 		info.rti_info[RTAX_IFP] = rt->rt_ifp->if_dl->ifa_addr;
   1549 		info.rti_info[RTAX_IFA] = rt->rt_ifa->ifa_addr;
   1550 	}
   1551 
   1552 	rt_missmsg(cmd, &info, rt->rt_flags, 0);
   1553 }
   1554 
   1555 /*
   1556  * Inform the routing socket of a route change for RTF_DYNAMIC.
   1557  */
   1558 void
   1559 rt_newmsg_dynamic(const int cmd, const struct rtentry *rt)
   1560 {
   1561 	struct rt_addrinfo info;
   1562 	struct sockaddr *gateway = rt->rt_gateway;
   1563 
   1564 	if (gateway == NULL)
   1565 		return;
   1566 
   1567 	switch(gateway->sa_family) {
   1568 #ifdef INET
   1569 	case AF_INET: {
   1570 		extern bool icmp_dynamic_rt_msg;
   1571 		if (!icmp_dynamic_rt_msg)
   1572 			return;
   1573 		break;
   1574 	}
   1575 #endif
   1576 #ifdef INET6
   1577 	case AF_INET6: {
   1578 		extern bool icmp6_dynamic_rt_msg;
   1579 		if (!icmp6_dynamic_rt_msg)
   1580 			return;
   1581 		break;
   1582 	}
   1583 #endif
   1584 	default:
   1585 		return;
   1586 	}
   1587 
   1588 	memset((void *)&info, 0, sizeof(info));
   1589 	info.rti_info[RTAX_DST] = rt_getkey(rt);
   1590 	info.rti_info[RTAX_GATEWAY] = gateway;
   1591 	info.rti_info[RTAX_NETMASK] = rt_mask(rt);
   1592 	if (rt->rt_ifp) {
   1593 		info.rti_info[RTAX_IFP] = rt->rt_ifp->if_dl->ifa_addr;
   1594 		info.rti_info[RTAX_IFA] = rt->rt_ifa->ifa_addr;
   1595 	}
   1596 
   1597 	rt_missmsg(cmd, &info, rt->rt_flags, 0);
   1598 }
   1599 
   1600 /*
   1601  * Set up or tear down a routing table entry, normally
   1602  * for an interface.
   1603  */
   1604 int
   1605 rtinit(struct ifaddr *ifa, int cmd, int flags)
   1606 {
   1607 	struct rtentry *rt;
   1608 	struct sockaddr *dst, *odst;
   1609 	struct sockaddr_storage maskeddst;
   1610 	struct rtentry *nrt = NULL;
   1611 	int error;
   1612 	struct rt_addrinfo info;
   1613 
   1614 	dst = flags & RTF_HOST ? ifa->ifa_dstaddr : ifa->ifa_addr;
   1615 	if (cmd == RTM_DELETE) {
   1616 		if ((flags & RTF_HOST) == 0 && ifa->ifa_netmask) {
   1617 			/* Delete subnet route for this interface */
   1618 			odst = dst;
   1619 			dst = (struct sockaddr *)&maskeddst;
   1620 			rt_maskedcopy(odst, dst, ifa->ifa_netmask);
   1621 		}
   1622 		if ((rt = rtalloc1(dst, 0)) != NULL) {
   1623 			if (rt->rt_ifa != ifa) {
   1624 				rt_unref(rt);
   1625 				return (flags & RTF_HOST) ? EHOSTUNREACH
   1626 							: ENETUNREACH;
   1627 			}
   1628 			rt_unref(rt);
   1629 		}
   1630 	}
   1631 	memset(&info, 0, sizeof(info));
   1632 	info.rti_ifa = ifa;
   1633 	info.rti_flags = flags | ifa->ifa_flags | RTF_DONTCHANGEIFA;
   1634 	info.rti_info[RTAX_DST] = dst;
   1635 	info.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
   1636 
   1637 	/*
   1638 	 * XXX here, it seems that we are assuming that ifa_netmask is NULL
   1639 	 * for RTF_HOST.  bsdi4 passes NULL explicitly (via intermediate
   1640 	 * variable) when RTF_HOST is 1.  still not sure if i can safely
   1641 	 * change it to meet bsdi4 behavior.
   1642 	 */
   1643 	if (cmd != RTM_LLINFO_UPD)
   1644 		info.rti_info[RTAX_NETMASK] = ifa->ifa_netmask;
   1645 	error = rtrequest1((cmd == RTM_LLINFO_UPD) ? RTM_GET : cmd, &info,
   1646 	    &nrt);
   1647 	if (error != 0)
   1648 		return error;
   1649 
   1650 	rt = nrt;
   1651 	RT_REFCNT_TRACE(rt);
   1652 	switch (cmd) {
   1653 	case RTM_DELETE:
   1654 		rt_newmsg(cmd, rt);
   1655 		rt_free(rt);
   1656 		break;
   1657 	case RTM_LLINFO_UPD:
   1658 		if (cmd == RTM_LLINFO_UPD && ifa->ifa_rtrequest != NULL)
   1659 			ifa->ifa_rtrequest(RTM_LLINFO_UPD, rt, &info);
   1660 		rt_newmsg(RTM_CHANGE, rt);
   1661 		rt_unref(rt);
   1662 		break;
   1663 	case RTM_ADD:
   1664 		KASSERT(rt->rt_ifa == ifa);
   1665 		rt_newmsg(cmd, rt);
   1666 		rt_unref(rt);
   1667 		RT_REFCNT_TRACE(rt);
   1668 		break;
   1669 	}
   1670 	return error;
   1671 }
   1672 
   1673 /*
   1674  * Create a local route entry for the address.
   1675  * Announce the addition of the address and the route to the routing socket.
   1676  */
   1677 int
   1678 rt_ifa_addlocal(struct ifaddr *ifa)
   1679 {
   1680 	struct rtentry *rt;
   1681 	int e;
   1682 
   1683 	/* If there is no loopback entry, allocate one. */
   1684 	rt = rtalloc1(ifa->ifa_addr, 0);
   1685 #ifdef RT_DEBUG
   1686 	if (rt != NULL)
   1687 		dump_rt(rt);
   1688 #endif
   1689 	if (rt == NULL || (rt->rt_flags & RTF_HOST) == 0 ||
   1690 	    (rt->rt_ifp->if_flags & IFF_LOOPBACK) == 0)
   1691 	{
   1692 		struct rt_addrinfo info;
   1693 		struct rtentry *nrt;
   1694 
   1695 		memset(&info, 0, sizeof(info));
   1696 		info.rti_flags = RTF_HOST | RTF_LOCAL | RTF_DONTCHANGEIFA;
   1697 		info.rti_info[RTAX_DST] = ifa->ifa_addr;
   1698 		info.rti_info[RTAX_GATEWAY] =
   1699 		    (const struct sockaddr *)ifa->ifa_ifp->if_sadl;
   1700 		info.rti_ifa = ifa;
   1701 		nrt = NULL;
   1702 		e = rtrequest1(RTM_ADD, &info, &nrt);
   1703 		rt_addrmsg_rt(RTM_ADD, ifa, e, nrt);
   1704 		if (nrt != NULL) {
   1705 			KASSERT(nrt->rt_ifa == ifa);
   1706 #ifdef RT_DEBUG
   1707 			dump_rt(nrt);
   1708 #endif
   1709 			rt_unref(nrt);
   1710 			RT_REFCNT_TRACE(nrt);
   1711 		}
   1712 	} else {
   1713 		e = 0;
   1714 		rt_addrmsg(RTM_NEWADDR, ifa);
   1715 	}
   1716 	if (rt != NULL)
   1717 		rt_unref(rt);
   1718 	return e;
   1719 }
   1720 
   1721 /*
   1722  * Remove the local route entry for the address.
   1723  * Announce the removal of the address and the route to the routing socket.
   1724  */
   1725 int
   1726 rt_ifa_remlocal(struct ifaddr *ifa, struct ifaddr *alt_ifa)
   1727 {
   1728 	struct rtentry *rt;
   1729 	int e = 0;
   1730 
   1731 	rt = rtalloc1(ifa->ifa_addr, 0);
   1732 
   1733 	/*
   1734 	 * Before deleting, check if a corresponding loopbacked
   1735 	 * host route surely exists.  With this check, we can avoid
   1736 	 * deleting an interface direct route whose destination is
   1737 	 * the same as the address being removed.  This can happen
   1738 	 * when removing a subnet-router anycast address on an
   1739 	 * interface attached to a shared medium.
   1740 	 */
   1741 	if (rt != NULL &&
   1742 	    (rt->rt_flags & RTF_HOST) &&
   1743 	    (rt->rt_ifp->if_flags & IFF_LOOPBACK))
   1744 	{
   1745 		/* If we cannot replace the route's ifaddr with the equivalent
   1746 		 * ifaddr of another interface, I believe it is safest to
   1747 		 * delete the route.
   1748 		 */
   1749 		if (alt_ifa == NULL) {
   1750 			e = rtdeletemsg(rt);
   1751 			if (e == 0) {
   1752 				rt_unref(rt);
   1753 				rt_free(rt);
   1754 				rt = NULL;
   1755 			}
   1756 			rt_addrmsg(RTM_DELADDR, ifa);
   1757 		} else {
   1758 #ifdef NET_MPSAFE
   1759 			int error = rt_update_prepare(rt);
   1760 			if (error == 0) {
   1761 				rt_replace_ifa(rt, alt_ifa);
   1762 				rt_update_finish(rt);
   1763 			} else {
   1764 				/*
   1765 				 * If error != 0, the rtentry is being
   1766 				 * destroyed, so doing nothing doesn't
   1767 				 * matter.
   1768 				 */
   1769 			}
   1770 #else
   1771 			rt_replace_ifa(rt, alt_ifa);
   1772 #endif
   1773 			rt_newmsg(RTM_CHANGE, rt);
   1774 		}
   1775 	} else
   1776 		rt_addrmsg(RTM_DELADDR, ifa);
   1777 	if (rt != NULL)
   1778 		rt_unref(rt);
   1779 	return e;
   1780 }
   1781 
   1782 /*
   1783  * Route timer routines.  These routes allow functions to be called
   1784  * for various routes at any time.  This is useful in supporting
   1785  * path MTU discovery and redirect route deletion.
   1786  *
   1787  * This is similar to some BSDI internal functions, but it provides
   1788  * for multiple queues for efficiency's sake...
   1789  */
   1790 
   1791 LIST_HEAD(, rttimer_queue) rttimer_queue_head;
   1792 static int rt_init_done = 0;
   1793 
   1794 /*
   1795  * Some subtle order problems with domain initialization mean that
   1796  * we cannot count on this being run from rt_init before various
   1797  * protocol initializations are done.  Therefore, we make sure
   1798  * that this is run when the first queue is added...
   1799  */
   1800 
   1801 static void rt_timer_work(struct work *, void *);
   1802 
   1803 static void
   1804 rt_timer_init(void)
   1805 {
   1806 	int error;
   1807 
   1808 	assert(rt_init_done == 0);
   1809 
   1810 	/* XXX should be in rt_init */
   1811 	rw_init(&rt_lock);
   1812 
   1813 	LIST_INIT(&rttimer_queue_head);
   1814 	callout_init(&rt_timer_ch, CALLOUT_MPSAFE);
   1815 	error = workqueue_create(&rt_timer_wq, "rt_timer",
   1816 	    rt_timer_work, NULL, PRI_SOFTNET, IPL_SOFTNET, WQ_MPSAFE);
   1817 	if (error)
   1818 		panic("%s: workqueue_create failed (%d)\n", __func__, error);
   1819 	callout_reset(&rt_timer_ch, hz, rt_timer_timer, NULL);
   1820 	rt_init_done = 1;
   1821 }
   1822 
   1823 struct rttimer_queue *
   1824 rt_timer_queue_create(u_int timeout)
   1825 {
   1826 	struct rttimer_queue *rtq;
   1827 
   1828 	if (rt_init_done == 0)
   1829 		rt_timer_init();
   1830 
   1831 	R_Malloc(rtq, struct rttimer_queue *, sizeof *rtq);
   1832 	if (rtq == NULL)
   1833 		return NULL;
   1834 	memset(rtq, 0, sizeof(*rtq));
   1835 
   1836 	rtq->rtq_timeout = timeout;
   1837 	TAILQ_INIT(&rtq->rtq_head);
   1838 	RT_WLOCK();
   1839 	LIST_INSERT_HEAD(&rttimer_queue_head, rtq, rtq_link);
   1840 	RT_UNLOCK();
   1841 
   1842 	return rtq;
   1843 }
   1844 
   1845 void
   1846 rt_timer_queue_change(struct rttimer_queue *rtq, long timeout)
   1847 {
   1848 
   1849 	rtq->rtq_timeout = timeout;
   1850 }
   1851 
   1852 static void
   1853 rt_timer_queue_remove_all(struct rttimer_queue *rtq)
   1854 {
   1855 	struct rttimer *r;
   1856 
   1857 	RT_ASSERT_WLOCK();
   1858 
   1859 	while ((r = TAILQ_FIRST(&rtq->rtq_head)) != NULL) {
   1860 		LIST_REMOVE(r, rtt_link);
   1861 		TAILQ_REMOVE(&rtq->rtq_head, r, rtt_next);
   1862 		rt_ref(r->rtt_rt); /* XXX */
   1863 		RT_REFCNT_TRACE(r->rtt_rt);
   1864 		RT_UNLOCK();
   1865 		(*r->rtt_func)(r->rtt_rt, r);
   1866 		pool_put(&rttimer_pool, r);
   1867 		RT_WLOCK();
   1868 		if (rtq->rtq_count > 0)
   1869 			rtq->rtq_count--;
   1870 		else
   1871 			printf("rt_timer_queue_remove_all: "
   1872 			    "rtq_count reached 0\n");
   1873 	}
   1874 }
   1875 
   1876 void
   1877 rt_timer_queue_destroy(struct rttimer_queue *rtq)
   1878 {
   1879 
   1880 	RT_WLOCK();
   1881 	rt_timer_queue_remove_all(rtq);
   1882 	LIST_REMOVE(rtq, rtq_link);
   1883 	RT_UNLOCK();
   1884 
   1885 	/*
   1886 	 * Caller is responsible for freeing the rttimer_queue structure.
   1887 	 */
   1888 }
   1889 
   1890 unsigned long
   1891 rt_timer_count(struct rttimer_queue *rtq)
   1892 {
   1893 	return rtq->rtq_count;
   1894 }
   1895 
   1896 static void
   1897 rt_timer_remove_all(struct rtentry *rt)
   1898 {
   1899 	struct rttimer *r;
   1900 
   1901 	RT_WLOCK();
   1902 	while ((r = LIST_FIRST(&rt->rt_timer)) != NULL) {
   1903 		LIST_REMOVE(r, rtt_link);
   1904 		TAILQ_REMOVE(&r->rtt_queue->rtq_head, r, rtt_next);
   1905 		if (r->rtt_queue->rtq_count > 0)
   1906 			r->rtt_queue->rtq_count--;
   1907 		else
   1908 			printf("rt_timer_remove_all: rtq_count reached 0\n");
   1909 		pool_put(&rttimer_pool, r);
   1910 	}
   1911 	RT_UNLOCK();
   1912 }
   1913 
   1914 int
   1915 rt_timer_add(struct rtentry *rt,
   1916 	void (*func)(struct rtentry *, struct rttimer *),
   1917 	struct rttimer_queue *queue)
   1918 {
   1919 	struct rttimer *r;
   1920 
   1921 	KASSERT(func != NULL);
   1922 	RT_WLOCK();
   1923 	/*
   1924 	 * If there's already a timer with this action, destroy it before
   1925 	 * we add a new one.
   1926 	 */
   1927 	LIST_FOREACH(r, &rt->rt_timer, rtt_link) {
   1928 		if (r->rtt_func == func)
   1929 			break;
   1930 	}
   1931 	if (r != NULL) {
   1932 		LIST_REMOVE(r, rtt_link);
   1933 		TAILQ_REMOVE(&r->rtt_queue->rtq_head, r, rtt_next);
   1934 		if (r->rtt_queue->rtq_count > 0)
   1935 			r->rtt_queue->rtq_count--;
   1936 		else
   1937 			printf("rt_timer_add: rtq_count reached 0\n");
   1938 	} else {
   1939 		r = pool_get(&rttimer_pool, PR_NOWAIT);
   1940 		if (r == NULL) {
   1941 			RT_UNLOCK();
   1942 			return ENOBUFS;
   1943 		}
   1944 	}
   1945 
   1946 	memset(r, 0, sizeof(*r));
   1947 
   1948 	r->rtt_rt = rt;
   1949 	r->rtt_time = time_uptime;
   1950 	r->rtt_func = func;
   1951 	r->rtt_queue = queue;
   1952 	LIST_INSERT_HEAD(&rt->rt_timer, r, rtt_link);
   1953 	TAILQ_INSERT_TAIL(&queue->rtq_head, r, rtt_next);
   1954 	r->rtt_queue->rtq_count++;
   1955 
   1956 	RT_UNLOCK();
   1957 
   1958 	return 0;
   1959 }
   1960 
   1961 static void
   1962 rt_timer_work(struct work *wk, void *arg)
   1963 {
   1964 	struct rttimer_queue *rtq;
   1965 	struct rttimer *r;
   1966 
   1967 	RT_WLOCK();
   1968 	LIST_FOREACH(rtq, &rttimer_queue_head, rtq_link) {
   1969 		while ((r = TAILQ_FIRST(&rtq->rtq_head)) != NULL &&
   1970 		    (r->rtt_time + rtq->rtq_timeout) < time_uptime) {
   1971 			LIST_REMOVE(r, rtt_link);
   1972 			TAILQ_REMOVE(&rtq->rtq_head, r, rtt_next);
   1973 			/*
   1974 			 * Take a reference to avoid the rtentry is freed
   1975 			 * accidentally after RT_UNLOCK.  The callback
   1976 			 * (rtt_func) must rt_unref it by itself.
   1977 			 */
   1978 			rt_ref(r->rtt_rt);
   1979 			RT_REFCNT_TRACE(r->rtt_rt);
   1980 			RT_UNLOCK();
   1981 			(*r->rtt_func)(r->rtt_rt, r);
   1982 			pool_put(&rttimer_pool, r);
   1983 			RT_WLOCK();
   1984 			if (rtq->rtq_count > 0)
   1985 				rtq->rtq_count--;
   1986 			else
   1987 				printf("rt_timer_timer: rtq_count reached 0\n");
   1988 		}
   1989 	}
   1990 	RT_UNLOCK();
   1991 
   1992 	callout_reset(&rt_timer_ch, hz, rt_timer_timer, NULL);
   1993 }
   1994 
   1995 static void
   1996 rt_timer_timer(void *arg)
   1997 {
   1998 
   1999 	workqueue_enqueue(rt_timer_wq, &rt_timer_wk, NULL);
   2000 }
   2001 
   2002 static struct rtentry *
   2003 _rtcache_init(struct route *ro, int flag)
   2004 {
   2005 	struct rtentry *rt;
   2006 
   2007 	rtcache_invariants(ro);
   2008 	KASSERT(ro->_ro_rt == NULL);
   2009 
   2010 	if (rtcache_getdst(ro) == NULL)
   2011 		return NULL;
   2012 	rt = rtalloc1(rtcache_getdst(ro), flag);
   2013 	if (rt != NULL) {
   2014 		RT_RLOCK();
   2015 		if (ISSET(rt->rt_flags, RTF_UP)) {
   2016 			ro->_ro_rt = rt;
   2017 			ro->ro_rtcache_generation = rtcache_generation;
   2018 			rtcache_ref(rt, ro);
   2019 		}
   2020 		RT_UNLOCK();
   2021 		rt_unref(rt);
   2022 	}
   2023 
   2024 	rtcache_invariants(ro);
   2025 	return ro->_ro_rt;
   2026 }
   2027 
   2028 struct rtentry *
   2029 rtcache_init(struct route *ro)
   2030 {
   2031 
   2032 	return _rtcache_init(ro, 1);
   2033 }
   2034 
   2035 struct rtentry *
   2036 rtcache_init_noclone(struct route *ro)
   2037 {
   2038 
   2039 	return _rtcache_init(ro, 0);
   2040 }
   2041 
   2042 struct rtentry *
   2043 rtcache_update(struct route *ro, int clone)
   2044 {
   2045 
   2046 	ro->_ro_rt = NULL;
   2047 	return _rtcache_init(ro, clone);
   2048 }
   2049 
   2050 void
   2051 rtcache_copy(struct route *new_ro, struct route *old_ro)
   2052 {
   2053 	struct rtentry *rt;
   2054 	int ret;
   2055 
   2056 	KASSERT(new_ro != old_ro);
   2057 	rtcache_invariants(new_ro);
   2058 	rtcache_invariants(old_ro);
   2059 
   2060 	rt = rtcache_validate(old_ro);
   2061 
   2062 	if (rtcache_getdst(old_ro) == NULL)
   2063 		goto out;
   2064 	ret = rtcache_setdst(new_ro, rtcache_getdst(old_ro));
   2065 	if (ret != 0)
   2066 		goto out;
   2067 
   2068 	RT_RLOCK();
   2069 	new_ro->_ro_rt = rt;
   2070 	new_ro->ro_rtcache_generation = rtcache_generation;
   2071 	RT_UNLOCK();
   2072 	rtcache_invariants(new_ro);
   2073 out:
   2074 	rtcache_unref(rt, old_ro);
   2075 	return;
   2076 }
   2077 
   2078 #if defined(RT_DEBUG) && defined(NET_MPSAFE)
   2079 static void
   2080 rtcache_trace(const char *func, struct rtentry *rt, struct route *ro)
   2081 {
   2082 	char dst[64];
   2083 
   2084 	sockaddr_format(ro->ro_sa, dst, 64);
   2085 	printf("trace: %s:\tdst=%s cpu=%d lwp=%p psref=%p target=%p\n", func, dst,
   2086 	    cpu_index(curcpu()), curlwp, &ro->ro_psref, &rt->rt_psref);
   2087 }
   2088 #define RTCACHE_PSREF_TRACE(rt, ro)	rtcache_trace(__func__, (rt), (ro))
   2089 #else
   2090 #define RTCACHE_PSREF_TRACE(rt, ro)	do {} while (0)
   2091 #endif
   2092 
   2093 static void
   2094 rtcache_ref(struct rtentry *rt, struct route *ro)
   2095 {
   2096 
   2097 	KASSERT(rt != NULL);
   2098 
   2099 #ifdef NET_MPSAFE
   2100 	RTCACHE_PSREF_TRACE(rt, ro);
   2101 	ro->ro_bound = curlwp_bind();
   2102 	/* XXX Use a real caller's address */
   2103 	PSREF_DEBUG_FILL_RETURN_ADDRESS(&ro->ro_psref);
   2104 	psref_acquire(&ro->ro_psref, &rt->rt_psref, rt_psref_class);
   2105 #endif
   2106 }
   2107 
   2108 void
   2109 rtcache_unref(struct rtentry *rt, struct route *ro)
   2110 {
   2111 
   2112 	if (rt == NULL)
   2113 		return;
   2114 
   2115 #ifdef NET_MPSAFE
   2116 	psref_release(&ro->ro_psref, &rt->rt_psref, rt_psref_class);
   2117 	curlwp_bindx(ro->ro_bound);
   2118 	RTCACHE_PSREF_TRACE(rt, ro);
   2119 #endif
   2120 }
   2121 
   2122 struct rtentry *
   2123 rtcache_validate(struct route *ro)
   2124 {
   2125 	struct rtentry *rt = NULL;
   2126 
   2127 #ifdef NET_MPSAFE
   2128 retry:
   2129 #endif
   2130 	rtcache_invariants(ro);
   2131 	RT_RLOCK();
   2132 	if (ro->ro_rtcache_generation != rtcache_generation) {
   2133 		/* The cache is invalidated */
   2134 		rt = NULL;
   2135 		goto out;
   2136 	}
   2137 
   2138 	rt = ro->_ro_rt;
   2139 	if (rt == NULL)
   2140 		goto out;
   2141 
   2142 	if ((rt->rt_flags & RTF_UP) == 0) {
   2143 		rt = NULL;
   2144 		goto out;
   2145 	}
   2146 #ifdef NET_MPSAFE
   2147 	if (ISSET(rt->rt_flags, RTF_UPDATING)) {
   2148 		if (rt_wait_ok()) {
   2149 			RT_UNLOCK();
   2150 
   2151 			/* We can wait until the update is complete */
   2152 			rt_update_wait();
   2153 			goto retry;
   2154 		} else {
   2155 			rt = NULL;
   2156 		}
   2157 	} else
   2158 #endif
   2159 		rtcache_ref(rt, ro);
   2160 out:
   2161 	RT_UNLOCK();
   2162 	return rt;
   2163 }
   2164 
   2165 struct rtentry *
   2166 rtcache_lookup2(struct route *ro, const struct sockaddr *dst,
   2167     int clone, int *hitp)
   2168 {
   2169 	const struct sockaddr *odst;
   2170 	struct rtentry *rt = NULL;
   2171 
   2172 	odst = rtcache_getdst(ro);
   2173 	if (odst == NULL)
   2174 		goto miss;
   2175 
   2176 	if (sockaddr_cmp(odst, dst) != 0) {
   2177 		rtcache_free(ro);
   2178 		goto miss;
   2179 	}
   2180 
   2181 	rt = rtcache_validate(ro);
   2182 	if (rt == NULL) {
   2183 		ro->_ro_rt = NULL;
   2184 		goto miss;
   2185 	}
   2186 
   2187 	rtcache_invariants(ro);
   2188 
   2189 	if (hitp != NULL)
   2190 		*hitp = 1;
   2191 	return rt;
   2192 miss:
   2193 	if (hitp != NULL)
   2194 		*hitp = 0;
   2195 	if (rtcache_setdst(ro, dst) == 0)
   2196 		rt = _rtcache_init(ro, clone);
   2197 
   2198 	rtcache_invariants(ro);
   2199 
   2200 	return rt;
   2201 }
   2202 
   2203 void
   2204 rtcache_free(struct route *ro)
   2205 {
   2206 
   2207 	ro->_ro_rt = NULL;
   2208 	if (ro->ro_sa != NULL) {
   2209 		sockaddr_free(ro->ro_sa);
   2210 		ro->ro_sa = NULL;
   2211 	}
   2212 	rtcache_invariants(ro);
   2213 }
   2214 
   2215 int
   2216 rtcache_setdst(struct route *ro, const struct sockaddr *sa)
   2217 {
   2218 	KASSERT(sa != NULL);
   2219 
   2220 	rtcache_invariants(ro);
   2221 	if (ro->ro_sa != NULL) {
   2222 		if (ro->ro_sa->sa_family == sa->sa_family) {
   2223 			ro->_ro_rt = NULL;
   2224 			sockaddr_copy(ro->ro_sa, ro->ro_sa->sa_len, sa);
   2225 			rtcache_invariants(ro);
   2226 			return 0;
   2227 		}
   2228 		/* free ro_sa, wrong family */
   2229 		rtcache_free(ro);
   2230 	}
   2231 
   2232 	KASSERT(ro->_ro_rt == NULL);
   2233 
   2234 	if ((ro->ro_sa = sockaddr_dup(sa, M_ZERO | M_NOWAIT)) == NULL) {
   2235 		rtcache_invariants(ro);
   2236 		return ENOMEM;
   2237 	}
   2238 	rtcache_invariants(ro);
   2239 	return 0;
   2240 }
   2241 
   2242 static void
   2243 rtcache_percpu_init_cpu(void *p, void *arg __unused, struct cpu_info *ci __unused)
   2244 {
   2245 	struct route **rop = p;
   2246 
   2247 	/*
   2248 	 * We can't have struct route as percpu data because it can be destroyed
   2249 	 * over a memory enlargement processing of percpu.
   2250 	 */
   2251 	*rop = kmem_zalloc(sizeof(**rop), KM_SLEEP);
   2252 }
   2253 
   2254 percpu_t *
   2255 rtcache_percpu_alloc(void)
   2256 {
   2257 
   2258 	return percpu_create(sizeof(struct route *),
   2259 	    rtcache_percpu_init_cpu, NULL, NULL);
   2260 }
   2261 
   2262 const struct sockaddr *
   2263 rt_settag(struct rtentry *rt, const struct sockaddr *tag)
   2264 {
   2265 	if (rt->rt_tag != tag) {
   2266 		if (rt->rt_tag != NULL)
   2267 			sockaddr_free(rt->rt_tag);
   2268 		rt->rt_tag = sockaddr_dup(tag, M_ZERO | M_NOWAIT);
   2269 	}
   2270 	return rt->rt_tag;
   2271 }
   2272 
   2273 struct sockaddr *
   2274 rt_gettag(const struct rtentry *rt)
   2275 {
   2276 	return rt->rt_tag;
   2277 }
   2278 
   2279 int
   2280 rt_check_reject_route(const struct rtentry *rt, const struct ifnet *ifp)
   2281 {
   2282 
   2283 	if ((rt->rt_flags & RTF_REJECT) != 0) {
   2284 		/* Mimic looutput */
   2285 		if (ifp->if_flags & IFF_LOOPBACK)
   2286 			return (rt->rt_flags & RTF_HOST) ?
   2287 			    EHOSTUNREACH : ENETUNREACH;
   2288 		else if (rt->rt_rmx.rmx_expire == 0 ||
   2289 		    time_uptime < rt->rt_rmx.rmx_expire)
   2290 			return (rt->rt_flags & RTF_GATEWAY) ?
   2291 			    EHOSTUNREACH : EHOSTDOWN;
   2292 	}
   2293 
   2294 	return 0;
   2295 }
   2296 
   2297 void
   2298 rt_delete_matched_entries(sa_family_t family, int (*f)(struct rtentry *, void *),
   2299     void *v, bool notify)
   2300 {
   2301 
   2302 	for (;;) {
   2303 		int s;
   2304 		int error;
   2305 		struct rtentry *rt, *retrt = NULL;
   2306 
   2307 		RT_RLOCK();
   2308 		s = splsoftnet();
   2309 		rt = rtbl_search_matched_entry(family, f, v);
   2310 		if (rt == NULL) {
   2311 			splx(s);
   2312 			RT_UNLOCK();
   2313 			return;
   2314 		}
   2315 		rt_ref(rt);
   2316 		RT_REFCNT_TRACE(rt);
   2317 		splx(s);
   2318 		RT_UNLOCK();
   2319 
   2320 		error = rtrequest(RTM_DELETE, rt_getkey(rt), rt->rt_gateway,
   2321 		    rt_mask(rt), rt->rt_flags, &retrt);
   2322 		if (error == 0) {
   2323 			KASSERT(retrt == rt);
   2324 			KASSERT((retrt->rt_flags & RTF_UP) == 0);
   2325 			if (notify)
   2326 				rt_newmsg(RTM_DELETE, retrt);
   2327 			retrt->rt_ifp = NULL;
   2328 			rt_unref(rt);
   2329 			RT_REFCNT_TRACE(rt);
   2330 			rt_free(retrt);
   2331 		} else if (error == ESRCH) {
   2332 			/* Someone deleted the entry already. */
   2333 			rt_unref(rt);
   2334 			RT_REFCNT_TRACE(rt);
   2335 		} else {
   2336 			log(LOG_ERR, "%s: unable to delete rtentry @ %p, "
   2337 			    "error = %d\n", rt->rt_ifp->if_xname, rt, error);
   2338 			/* XXX how to treat this case? */
   2339 		}
   2340 	}
   2341 }
   2342 
   2343 static int
   2344 rt_walktree_locked(sa_family_t family, int (*f)(struct rtentry *, void *),
   2345     void *v)
   2346 {
   2347 
   2348 	return rtbl_walktree(family, f, v);
   2349 }
   2350 
   2351 void
   2352 rt_replace_ifa_matched_entries(sa_family_t family,
   2353     int (*f)(struct rtentry *, void *), void *v, struct ifaddr *ifa)
   2354 {
   2355 
   2356 	for (;;) {
   2357 		int s;
   2358 #ifdef NET_MPSAFE
   2359 		int error;
   2360 #endif
   2361 		struct rtentry *rt;
   2362 
   2363 		RT_RLOCK();
   2364 		s = splsoftnet();
   2365 		rt = rtbl_search_matched_entry(family, f, v);
   2366 		if (rt == NULL) {
   2367 			splx(s);
   2368 			RT_UNLOCK();
   2369 			return;
   2370 		}
   2371 		rt_ref(rt);
   2372 		RT_REFCNT_TRACE(rt);
   2373 		splx(s);
   2374 		RT_UNLOCK();
   2375 
   2376 #ifdef NET_MPSAFE
   2377 		error = rt_update_prepare(rt);
   2378 		if (error == 0) {
   2379 			rt_replace_ifa(rt, ifa);
   2380 			rt_update_finish(rt);
   2381 			rt_newmsg(RTM_CHANGE, rt);
   2382 		} else {
   2383 			/*
   2384 			 * If error != 0, the rtentry is being
   2385 			 * destroyed, so doing nothing doesn't
   2386 			 * matter.
   2387 			 */
   2388 		}
   2389 #else
   2390 		rt_replace_ifa(rt, ifa);
   2391 		rt_newmsg(RTM_CHANGE, rt);
   2392 #endif
   2393 		rt_unref(rt);
   2394 		RT_REFCNT_TRACE(rt);
   2395 	}
   2396 }
   2397 
   2398 int
   2399 rt_walktree(sa_family_t family, int (*f)(struct rtentry *, void *), void *v)
   2400 {
   2401 	int error;
   2402 
   2403 	RT_RLOCK();
   2404 	error = rt_walktree_locked(family, f, v);
   2405 	RT_UNLOCK();
   2406 
   2407 	return error;
   2408 }
   2409 
   2410 #ifdef DDB
   2411 
   2412 #include <machine/db_machdep.h>
   2413 #include <ddb/db_interface.h>
   2414 #include <ddb/db_output.h>
   2415 
   2416 #define	rt_expire rt_rmx.rmx_expire
   2417 
   2418 static void
   2419 db_print_sa(const struct sockaddr *sa)
   2420 {
   2421 	int len;
   2422 	const u_char *p;
   2423 
   2424 	if (sa == NULL) {
   2425 		db_printf("[NULL]");
   2426 		return;
   2427 	}
   2428 
   2429 	p = (const u_char *)sa;
   2430 	len = sa->sa_len;
   2431 	db_printf("[");
   2432 	while (len > 0) {
   2433 		db_printf("%d", *p);
   2434 		p++; len--;
   2435 		if (len) db_printf(",");
   2436 	}
   2437 	db_printf("]\n");
   2438 }
   2439 
   2440 static void
   2441 db_print_ifa(struct ifaddr *ifa)
   2442 {
   2443 	if (ifa == NULL)
   2444 		return;
   2445 	db_printf("  ifa_addr=");
   2446 	db_print_sa(ifa->ifa_addr);
   2447 	db_printf("  ifa_dsta=");
   2448 	db_print_sa(ifa->ifa_dstaddr);
   2449 	db_printf("  ifa_mask=");
   2450 	db_print_sa(ifa->ifa_netmask);
   2451 	db_printf("  flags=0x%x,refcnt=%d,metric=%d\n",
   2452 			  ifa->ifa_flags,
   2453 			  ifa->ifa_refcnt,
   2454 			  ifa->ifa_metric);
   2455 }
   2456 
   2457 /*
   2458  * Function to pass to rt_walktree().
   2459  * Return non-zero error to abort walk.
   2460  */
   2461 static int
   2462 db_show_rtentry(struct rtentry *rt, void *w)
   2463 {
   2464 	db_printf("rtentry=%p", rt);
   2465 
   2466 	db_printf(" flags=0x%x refcnt=%d use=%"PRId64" expire=%"PRId64"\n",
   2467 			  rt->rt_flags, rt->rt_refcnt,
   2468 			  rt->rt_use, (uint64_t)rt->rt_expire);
   2469 
   2470 	db_printf(" key="); db_print_sa(rt_getkey(rt));
   2471 	db_printf(" mask="); db_print_sa(rt_mask(rt));
   2472 	db_printf(" gw="); db_print_sa(rt->rt_gateway);
   2473 
   2474 	db_printf(" ifp=%p ", rt->rt_ifp);
   2475 	if (rt->rt_ifp)
   2476 		db_printf("(%s)", rt->rt_ifp->if_xname);
   2477 	else
   2478 		db_printf("(NULL)");
   2479 
   2480 	db_printf(" ifa=%p\n", rt->rt_ifa);
   2481 	db_print_ifa(rt->rt_ifa);
   2482 
   2483 	db_printf(" gwroute=%p llinfo=%p\n",
   2484 			  rt->rt_gwroute, rt->rt_llinfo);
   2485 
   2486 	return 0;
   2487 }
   2488 
   2489 /*
   2490  * Function to print all the route trees.
   2491  * Use this from ddb:  "show routes"
   2492  */
   2493 void
   2494 db_show_routes(db_expr_t addr, bool have_addr,
   2495     db_expr_t count, const char *modif)
   2496 {
   2497 
   2498 	/* Taking RT_LOCK will fail if LOCKDEBUG is enabled. */
   2499 	rt_walktree_locked(AF_INET, db_show_rtentry, NULL);
   2500 }
   2501 #endif
   2502