xref: /freebsd/sys/net/route/nhop_ctl.c (revision f15e18a642cb3f7ebc747f8e9cdf11274140107d)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2020 Alexander V. Chernikov
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 #include "opt_inet.h"
31 #include "opt_route.h"
32 
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/lock.h>
36 #include <sys/rwlock.h>
37 #include <sys/malloc.h>
38 #include <sys/socket.h>
39 #include <sys/sysctl.h>
40 #include <sys/kernel.h>
41 #include <sys/epoch.h>
42 
43 #include <net/if.h>
44 #include <net/if_var.h>
45 #include <net/if_dl.h>
46 #include <net/route.h>
47 #include <net/route/route_ctl.h>
48 #include <net/route/route_var.h>
49 #include <net/route/nhop_utils.h>
50 #include <net/route/nhop.h>
51 #include <net/route/nhop_var.h>
52 #include <net/vnet.h>
53 
54 /*
55  * This file contains core functionality for the nexthop ("nhop") route subsystem.
56  * The business logic needed to create nexhop objects is implemented here.
57  *
58  * Nexthops in the original sense are the objects containing all the necessary
59  * information to forward the packet to the selected destination.
60  * In particular, nexthop is defined by a combination of
61  *  ifp, ifa, aifp, mtu, gw addr(if set), nh_type, nh_family, mask of rt_flags and
62  *    NHF_DEFAULT
63  *
64  * Additionally, each nexthop gets assigned its unique index (nexthop index).
65  * It serves two purposes: first one is to ease the ability of userland programs to
66  *  reference nexthops by their index. The second one allows lookup algorithms to
67  *  to store index instead of pointer (2 bytes vs 8) as a lookup result.
68  * All nexthops are stored in the resizable hash table.
69  *
70  * Basically, this file revolves around supporting 3 functions:
71  * 1) nhop_create_from_info / nhop_create_from_nhop, which contains all
72  *  business logic on filling the nexthop fields based on the provided request.
73  * 2) nhop_get(), which gets a usable referenced nexthops.
74  *
75  * Conventions:
76  * 1) non-exported functions start with verb
77  * 2) exported function starts with the subsystem prefix: "nhop"
78  */
79 
80 static int dump_nhop_entry(struct rib_head *rh, struct nhop_object *nh, struct sysctl_req *w);
81 
82 static struct nhop_priv *alloc_nhop_structure(void);
83 static int get_nhop(struct rib_head *rnh, struct rt_addrinfo *info,
84     struct nhop_priv **pnh_priv);
85 static int finalize_nhop(struct nh_control *ctl, struct rt_addrinfo *info,
86     struct nhop_priv *nh_priv);
87 static struct ifnet *get_aifp(const struct nhop_object *nh, int reference);
88 static void fill_sdl_from_ifp(struct sockaddr_dl_short *sdl, const struct ifnet *ifp);
89 
90 static void destroy_nhop_epoch(epoch_context_t ctx);
91 static void destroy_nhop(struct nhop_priv *nh_priv);
92 
93 static void print_nhop(const char *prefix, const struct nhop_object *nh);
94 
95 _Static_assert(__offsetof(struct nhop_object, nh_ifp) == 32,
96     "nhop_object: wrong nh_ifp offset");
97 _Static_assert(sizeof(struct nhop_object) <= 128,
98     "nhop_object: size exceeds 128 bytes");
99 
100 static uma_zone_t nhops_zone;	/* Global zone for each and every nexthop */
101 
102 #define	NHOP_OBJECT_ALIGNED_SIZE	roundup2(sizeof(struct nhop_object), \
103 							2 * CACHE_LINE_SIZE)
104 #define	NHOP_PRIV_ALIGNED_SIZE		roundup2(sizeof(struct nhop_priv), \
105 							2 * CACHE_LINE_SIZE)
106 void
107 nhops_init(void)
108 {
109 
110 	nhops_zone = uma_zcreate("routing nhops",
111 	    NHOP_OBJECT_ALIGNED_SIZE + NHOP_PRIV_ALIGNED_SIZE,
112 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
113 }
114 
115 /*
116  * Fetches the interface of source address used by the route.
117  * In all cases except interface-address-route it would be the
118  * same as the transmit interfaces.
119  * However, for the interface address this function will return
120  * this interface ifp instead of loopback. This is needed to support
121  * link-local IPv6 loopback communications.
122  *
123  * If @reference is non-zero, found ifp is referenced.
124  *
125  * Returns found ifp.
126  */
127 static struct ifnet *
128 get_aifp(const struct nhop_object *nh, int reference)
129 {
130 	struct ifnet *aifp = NULL;
131 
132 	/*
133 	 * Adjust the "outgoing" interface.  If we're going to loop
134 	 * the packet back to ourselves, the ifp would be the loopback
135 	 * interface. However, we'd rather know the interface associated
136 	 * to the destination address (which should probably be one of
137 	 * our own addresses).
138 	 */
139 	if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) &&
140 			nh->gw_sa.sa_family == AF_LINK) {
141 		if (reference)
142 			aifp = ifnet_byindex_ref(nh->gwl_sa.sdl_index);
143 		else
144 			aifp = ifnet_byindex(nh->gwl_sa.sdl_index);
145 		if (aifp == NULL) {
146 			DPRINTF("unable to get aifp for %s index %d",
147 				if_name(nh->nh_ifp), nh->gwl_sa.sdl_index);
148 		}
149 	}
150 
151 	if (aifp == NULL) {
152 		aifp = nh->nh_ifp;
153 		if (reference)
154 			if_ref(aifp);
155 	}
156 
157 	return (aifp);
158 }
159 
160 int
161 cmp_priv(const struct nhop_priv *_one, const struct nhop_priv *_two)
162 {
163 
164 	if (memcmp(_one->nh, _two->nh, NHOP_END_CMP) != 0)
165 		return (0);
166 
167 	if (memcmp(_one, _two, NH_PRIV_END_CMP) != 0)
168 		return (0);
169 
170 	return (1);
171 }
172 
173 /*
174  * Conditionally sets @nh mtu data based on the @info data.
175  */
176 static void
177 set_nhop_mtu_from_info(struct nhop_object *nh, const struct rt_addrinfo *info)
178 {
179 
180 	if (info->rti_mflags & RTV_MTU) {
181 		if (info->rti_rmx->rmx_mtu != 0) {
182 			/*
183 			 * MTU was explicitly provided by user.
184 			 * Keep it.
185 			 */
186 
187 			nh->nh_priv->rt_flags |= RTF_FIXEDMTU;
188 		} else {
189 			/*
190 			 * User explicitly sets MTU to 0.
191 			 * Assume rollback to default.
192 			 */
193 			nh->nh_priv->rt_flags &= ~RTF_FIXEDMTU;
194 		}
195 		nh->nh_mtu = info->rti_rmx->rmx_mtu;
196 	}
197 }
198 
199 /*
200  * Fills in shorted link-level sockadd version suitable to be stored inside the
201  *  nexthop gateway buffer.
202  */
203 static void
204 fill_sdl_from_ifp(struct sockaddr_dl_short *sdl, const struct ifnet *ifp)
205 {
206 
207 	bzero(sdl, sizeof(struct sockaddr_dl_short));
208 	sdl->sdl_family = AF_LINK;
209 	sdl->sdl_len = sizeof(struct sockaddr_dl_short);
210 	sdl->sdl_index = ifp->if_index;
211 	sdl->sdl_type = ifp->if_type;
212 }
213 
214 static int
215 set_nhop_gw_from_info(struct nhop_object *nh, struct rt_addrinfo *info)
216 {
217 	struct sockaddr *gw;
218 
219 	gw = info->rti_info[RTAX_GATEWAY];
220 	KASSERT(gw != NULL, ("gw is NULL"));
221 
222 	if ((gw->sa_family == AF_LINK) && !(info->rti_flags & RTF_GATEWAY)) {
223 
224 		/*
225 		 * Interface route with interface specified by the interface
226 		 * index in sockadd_dl structure. It is used in the IPv6 loopback
227 		 * output code, where we need to preserve the original interface
228 		 * to maintain proper scoping.
229 		 * Despite the fact that nexthop code stores original interface
230 		 * in the separate field (nh_aifp, see below), write AF_LINK
231 		 * compatible sa with shorter total length.
232 		 */
233 		struct sockaddr_dl *sdl = (struct sockaddr_dl *)gw;
234 		struct ifnet *ifp = ifnet_byindex(sdl->sdl_index);
235 		if (ifp == NULL) {
236 			DPRINTF("invalid ifindex %d", sdl->sdl_index);
237 			return (EINVAL);
238 		}
239 		fill_sdl_from_ifp(&nh->gwl_sa, ifp);
240 	} else {
241 
242 		/*
243 		 * Multiple options here:
244 		 *
245 		 * 1) RTF_GATEWAY with IPv4/IPv6 gateway data
246 		 * 2) Interface route with IPv4/IPv6 address of the
247 		 *   matching interface. Some routing daemons do that
248 		 *   instead of specifying ifindex in AF_LINK.
249 		 *
250 		 * In both cases, save the original nexthop to make the callers
251 		 *   happy.
252 		 */
253 		if (gw->sa_len > sizeof(struct sockaddr_in6)) {
254 			DPRINTF("nhop SA size too big: AF %d len %u",
255 			    gw->sa_family, gw->sa_len);
256 			return (ENOMEM);
257 		}
258 		memcpy(&nh->gw_sa, gw, gw->sa_len);
259 	}
260 	return (0);
261 }
262 
263 static uint16_t
264 convert_rt_to_nh_flags(int rt_flags)
265 {
266 	uint16_t res;
267 
268 	res = (rt_flags & RTF_REJECT) ? NHF_REJECT : 0;
269 	res |= (rt_flags & RTF_HOST) ? NHF_HOST : 0;
270 	res |= (rt_flags & RTF_BLACKHOLE) ? NHF_BLACKHOLE : 0;
271 	res |= (rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) ? NHF_REDIRECT : 0;
272 	res |= (rt_flags & RTF_BROADCAST) ? NHF_BROADCAST : 0;
273 	res |= (rt_flags & RTF_GATEWAY) ? NHF_GATEWAY : 0;
274 
275 	return (res);
276 }
277 
278 static int
279 fill_nhop_from_info(struct nhop_priv *nh_priv, struct rt_addrinfo *info)
280 {
281 	int error, rt_flags;
282 	struct nhop_object *nh;
283 
284 	nh = nh_priv->nh;
285 
286 	rt_flags = info->rti_flags & NHOP_RT_FLAG_MASK;
287 
288 	nh->nh_priv->rt_flags = rt_flags;
289 	nh_priv->nh_family = info->rti_info[RTAX_DST]->sa_family;
290 	nh_priv->nh_type = 0; // hook responsibility to set nhop type
291 
292 	nh->nh_flags = convert_rt_to_nh_flags(rt_flags);
293 	set_nhop_mtu_from_info(nh, info);
294 	if ((error = set_nhop_gw_from_info(nh, info)) != 0)
295 		return (error);
296 
297 	nh->nh_ifp = info->rti_ifa->ifa_ifp;
298 	nh->nh_ifa = info->rti_ifa;
299 	/* depends on the gateway */
300 	nh->nh_aifp = get_aifp(nh, 0);
301 
302 	/*
303 	 * Note some of the remaining data is set by the
304 	 * per-address-family pre-add hook.
305 	 */
306 
307 	return (0);
308 }
309 
310 /*
311  * Creates a new nexthop based on the information in @info.
312  *
313  * Returns:
314  * 0 on success, filling @nh_ret with the desired nexthop object ptr
315  * errno otherwise
316  */
317 int
318 nhop_create_from_info(struct rib_head *rnh, struct rt_addrinfo *info,
319     struct nhop_object **nh_ret)
320 {
321 	struct nhop_priv *nh_priv;
322 	int error;
323 
324 	NET_EPOCH_ASSERT();
325 
326 	if (info->rti_info[RTAX_GATEWAY] == NULL)
327 		return (EINVAL);
328 
329 	nh_priv = alloc_nhop_structure();
330 
331 	error = fill_nhop_from_info(nh_priv, info);
332 	if (error != 0) {
333 		uma_zfree(nhops_zone, nh_priv->nh);
334 		return (error);
335 	}
336 
337 	error = get_nhop(rnh, info, &nh_priv);
338 	if (error == 0)
339 		*nh_ret = nh_priv->nh;
340 
341 	return (error);
342 }
343 
344 /*
345  * Gets linked nhop using the provided @pnh_priv nexhop data.
346  * If linked nhop is found, returns it, freeing the provided one.
347  * If there is no such nexthop, attaches the remaining data to the
348  *  provided nexthop and links it.
349  *
350  * Returns 0 on success, storing referenced nexthop in @pnh_priv.
351  * Otherwise, errno is returned.
352  */
353 static int
354 get_nhop(struct rib_head *rnh, struct rt_addrinfo *info,
355     struct nhop_priv **pnh_priv)
356 {
357 	const struct sockaddr *dst, *gateway, *netmask;
358 	struct nhop_priv *nh_priv, *tmp_priv;
359 	int error;
360 
361 	nh_priv = *pnh_priv;
362 
363 	/* Give the protocols chance to augment the request data */
364 	dst = info->rti_info[RTAX_DST];
365 	netmask = info->rti_info[RTAX_NETMASK];
366 	gateway = info->rti_info[RTAX_GATEWAY];
367 
368 	error = rnh->rnh_preadd(rnh->rib_fibnum, dst, netmask, nh_priv->nh);
369 	if (error != 0) {
370 		uma_zfree(nhops_zone, nh_priv->nh);
371 		return (error);
372 	}
373 
374 	tmp_priv = find_nhop(rnh->nh_control, nh_priv);
375 	if (tmp_priv != NULL) {
376 		uma_zfree(nhops_zone, nh_priv->nh);
377 		*pnh_priv = tmp_priv;
378 		return (0);
379 	}
380 
381 	/*
382 	 * Existing nexthop not found, need to create new one.
383 	 * Note: multiple simultaneous get_nhop() requests
384 	 *  can result in multiple equal nexhops existing in the
385 	 *  nexthop table. This is not a not a problem until the
386 	 *  relative number of such nexthops is significant, which
387 	 *  is extremely unlikely.
388 	 */
389 
390 	error = finalize_nhop(rnh->nh_control, info, nh_priv);
391 	if (error != 0)
392 		return (error);
393 
394 	return (0);
395 }
396 
397 /*
398  * Update @nh with data supplied in @info.
399  * This is a helper function to support route changes.
400  *
401  * It limits the changes that can be done to the route to the following:
402  * 1) all combination of gateway changes (gw, interface, blackhole/reject)
403  * 2) route flags (FLAG[123],STATIC,BLACKHOLE,REJECT)
404  * 3) route MTU
405  *
406  * Returns:
407  * 0 on success
408  */
409 static int
410 alter_nhop_from_info(struct nhop_object *nh, struct rt_addrinfo *info)
411 {
412 	struct sockaddr *info_gw;
413 	int error;
414 
415 	/* Update MTU if set in the request*/
416 	set_nhop_mtu_from_info(nh, info);
417 
418 	/* XXX: allow only one of BLACKHOLE,REJECT,GATEWAY */
419 
420 	/* Allow some flags (FLAG1,STATIC,BLACKHOLE,REJECT) to be toggled on change. */
421 	nh->nh_priv->rt_flags &= ~RTF_FMASK;
422 	nh->nh_priv->rt_flags |= info->rti_flags & RTF_FMASK;
423 
424 	/* Consider gateway change */
425 	info_gw = info->rti_info[RTAX_GATEWAY];
426 	if (info_gw != NULL) {
427 		error = set_nhop_gw_from_info(nh, info);
428 		if (error != 0)
429 			return (error);
430 		/* Update RTF_GATEWAY flag status */
431 		nh->nh_priv->rt_flags &= ~RTF_GATEWAY;
432 		nh->nh_priv->rt_flags |= (RTF_GATEWAY & info->rti_flags);
433 	}
434 	/* Update datapath flags */
435 	nh->nh_flags = convert_rt_to_nh_flags(nh->nh_priv->rt_flags);
436 
437 	if (info->rti_ifa != NULL)
438 		nh->nh_ifa = info->rti_ifa;
439 	if (info->rti_ifp != NULL)
440 		nh->nh_ifp = info->rti_ifp;
441 	nh->nh_aifp = get_aifp(nh, 0);
442 
443 	return (0);
444 }
445 
446 /*
447  * Creates new nexthop based on @nh_orig and augmentation data from @info.
448  * Helper function used in the route changes, please see
449  *   alter_nhop_from_info() comments for more details.
450  *
451  * Returns:
452  * 0 on success, filling @nh_ret with the desired nexthop object
453  * errno otherwise
454  */
455 int
456 nhop_create_from_nhop(struct rib_head *rnh, const struct nhop_object *nh_orig,
457     struct rt_addrinfo *info, struct nhop_object **pnh)
458 {
459 	struct nhop_priv *nh_priv;
460 	struct nhop_object *nh;
461 	int error;
462 
463 	NET_EPOCH_ASSERT();
464 
465 	nh_priv = alloc_nhop_structure();
466 	nh = nh_priv->nh;
467 
468 	/* Start with copying data from original nexthop */
469 	nh_priv->nh_family = nh_orig->nh_priv->nh_family;
470 	nh_priv->rt_flags = nh_orig->nh_priv->rt_flags;
471 	nh_priv->nh_type = nh_orig->nh_priv->nh_type;
472 
473 	nh->nh_ifp = nh_orig->nh_ifp;
474 	nh->nh_ifa = nh_orig->nh_ifa;
475 	nh->nh_aifp = nh_orig->nh_aifp;
476 	nh->nh_mtu = nh_orig->nh_mtu;
477 	nh->nh_flags = nh_orig->nh_flags;
478 	memcpy(&nh->gw_sa, &nh_orig->gw_sa, nh_orig->gw_sa.sa_len);
479 
480 	error = alter_nhop_from_info(nh, info);
481 	if (error != 0) {
482 		uma_zfree(nhops_zone, nh_priv->nh);
483 		return (error);
484 	}
485 
486 	error = get_nhop(rnh, info, &nh_priv);
487 	if (error == 0)
488 		*pnh = nh_priv->nh;
489 
490 	return (error);
491 }
492 
493 /*
494  * Allocates memory for public/private nexthop structures.
495  *
496  * Returns pointer to nhop_priv or NULL.
497  */
498 static struct nhop_priv *
499 alloc_nhop_structure()
500 {
501 	struct nhop_object *nh;
502 	struct nhop_priv *nh_priv;
503 
504 	nh = (struct nhop_object *)uma_zalloc(nhops_zone, M_NOWAIT | M_ZERO);
505 	if (nh == NULL)
506 		return (NULL);
507 	nh_priv = (struct nhop_priv *)((char *)nh + NHOP_OBJECT_ALIGNED_SIZE);
508 
509 	nh->nh_priv = nh_priv;
510 	nh_priv->nh = nh;
511 
512 	return (nh_priv);
513 }
514 
515 /*
516  * Alocates/references the remaining bits of nexthop data and links
517  *  it to the hash table.
518  * Returns 0 if successful,
519  *  errno otherwise. @nh_priv is freed in case of error.
520  */
521 static int
522 finalize_nhop(struct nh_control *ctl, struct rt_addrinfo *info,
523     struct nhop_priv *nh_priv)
524 {
525 	struct nhop_object *nh;
526 
527 	nh = nh_priv->nh;
528 
529 	/* Allocate per-cpu packet counter */
530 	nh->nh_pksent = counter_u64_alloc(M_NOWAIT);
531 	if (nh->nh_pksent == NULL) {
532 		uma_zfree(nhops_zone, nh);
533 		RTSTAT_INC(rts_nh_alloc_failure);
534 		DPRINTF("nh_alloc_finalize failed");
535 		return (ENOMEM);
536 	}
537 
538 	/* Save vnet to ease destruction */
539 	nh_priv->nh_vnet = curvnet;
540 
541 	/* Reference external objects and calculate (referenced) ifa */
542 	if_ref(nh->nh_ifp);
543 	ifa_ref(nh->nh_ifa);
544 	nh->nh_aifp = get_aifp(nh, 1);
545 	DPRINTF("AIFP: %p nh_ifp %p", nh->nh_aifp, nh->nh_ifp);
546 
547 	refcount_init(&nh_priv->nh_refcnt, 1);
548 
549 	/* Please see nhop_free() comments on the initial value */
550 	refcount_init(&nh_priv->nh_linked, 2);
551 
552 	print_nhop("FINALIZE", nh);
553 
554 	if (link_nhop(ctl, nh_priv) == 0) {
555 		/*
556 		 * Adding nexthop to the datastructures
557 		 *  failed. Call destructor w/o waiting for
558 		 *  the epoch end, as nexthop is not used
559 		 *  and return.
560 		 */
561 		DPRINTF("link_nhop failed!");
562 		destroy_nhop(nh_priv);
563 
564 		return (ENOBUFS);
565 	}
566 
567 	return (0);
568 }
569 
570 static void
571 print_nhop_sa(char *buf, size_t buflen, const struct sockaddr *sa)
572 {
573 
574 	if (sa->sa_family == AF_INET) {
575 		const struct sockaddr_in *sin4;
576 		sin4 = (const struct sockaddr_in *)sa;
577 		inet_ntop(AF_INET, &sin4->sin_addr, buf, buflen);
578 	} else if (sa->sa_family == AF_INET6) {
579 		const struct sockaddr_in6 *sin6;
580 		sin6 = (const struct sockaddr_in6 *)sa;
581 		inet_ntop(AF_INET6, &sin6->sin6_addr, buf, buflen);
582 	} else if (sa->sa_family == AF_LINK) {
583 		const struct sockaddr_dl *sdl;
584 		sdl = (const struct sockaddr_dl *)sa;
585 		snprintf(buf, buflen, "if#%d", sdl->sdl_index);
586 	} else
587 		snprintf(buf, buflen, "af:%d", sa->sa_family);
588 }
589 
590 static void
591 print_nhop(const char *prefix, const struct nhop_object *nh)
592 {
593 	char src_buf[INET6_ADDRSTRLEN], addr_buf[INET6_ADDRSTRLEN];
594 
595 	print_nhop_sa(src_buf, sizeof(src_buf), nh->nh_ifa->ifa_addr);
596 	print_nhop_sa(addr_buf, sizeof(addr_buf), &nh->gw_sa);
597 
598 	DPRINTF("%s nhop priv %p: AF %d ifp %p %s addr %s src %p %s aifp %p %s mtu %d nh_flags %X",
599 	    prefix, nh->nh_priv, nh->nh_priv->nh_family, nh->nh_ifp,
600 	    if_name(nh->nh_ifp), addr_buf, nh->nh_ifa, src_buf, nh->nh_aifp,
601 	    if_name(nh->nh_aifp), nh->nh_mtu, nh->nh_flags);
602 }
603 
604 static void
605 destroy_nhop(struct nhop_priv *nh_priv)
606 {
607 	struct nhop_object *nh;
608 
609 	nh = nh_priv->nh;
610 
611 	print_nhop("DEL", nh);
612 
613 	if_rele(nh->nh_ifp);
614 	if_rele(nh->nh_aifp);
615 	ifa_free(nh->nh_ifa);
616 	counter_u64_free(nh->nh_pksent);
617 
618 	uma_zfree(nhops_zone, nh);
619 }
620 
621 /*
622  * Epoch callback indicating nhop is safe to destroy
623  */
624 static void
625 destroy_nhop_epoch(epoch_context_t ctx)
626 {
627 	struct nhop_priv *nh_priv;
628 
629 	nh_priv = __containerof(ctx, struct nhop_priv, nh_epoch_ctx);
630 
631 	destroy_nhop(nh_priv);
632 }
633 
634 void
635 nhop_ref_object(struct nhop_object *nh)
636 {
637 	u_int old;
638 
639 	old = refcount_acquire(&nh->nh_priv->nh_refcnt);
640 	KASSERT(old > 0, ("%s: nhop object %p has 0 refs", __func__, nh));
641 }
642 
643 int
644 nhop_try_ref_object(struct nhop_object *nh)
645 {
646 
647 	return (refcount_acquire_if_not_zero(&nh->nh_priv->nh_refcnt));
648 }
649 
650 void
651 nhop_free(struct nhop_object *nh)
652 {
653 	struct nh_control *ctl;
654 	struct nhop_priv *nh_priv = nh->nh_priv;
655 	struct epoch_tracker et;
656 
657 	if (!refcount_release(&nh_priv->nh_refcnt))
658 		return;
659 
660 	/*
661 	 * There are only 2 places, where nh_linked can be decreased:
662 	 *  rib destroy (nhops_destroy_rib) and this function.
663 	 * nh_link can never be increased.
664 	 *
665 	 * Hence, use initial value of 2 to make use of
666 	 *  refcount_release_if_not_last().
667 	 *
668 	 * There can be two scenarious when calling this function:
669 	 *
670 	 * 1) nh_linked value is 2. This means that either
671 	 *  nhops_destroy_rib() has not been called OR it is running,
672 	 *  but we are guaranteed that nh_control won't be freed in
673 	 *  this epoch. Hence, nexthop can be safely unlinked.
674 	 *
675 	 * 2) nh_linked value is 1. In that case, nhops_destroy_rib()
676 	 *  has been called and nhop unlink can be skipped.
677 	 */
678 
679 	NET_EPOCH_ENTER(et);
680 	if (refcount_release_if_not_last(&nh_priv->nh_linked)) {
681 		ctl = nh_priv->nh_control;
682 		if (unlink_nhop(ctl, nh_priv) == NULL) {
683 			/* Do not try to reclaim */
684 			DPRINTF("Failed to unlink nexhop %p", nh_priv);
685 			NET_EPOCH_EXIT(et);
686 			return;
687 		}
688 	}
689 	NET_EPOCH_EXIT(et);
690 
691 	epoch_call(net_epoch_preempt, destroy_nhop_epoch,
692 	    &nh_priv->nh_epoch_ctx);
693 }
694 
695 void
696 nhop_ref_any(struct nhop_object *nh)
697 {
698 #ifdef ROUTE_MPATH
699 	if (!NH_IS_NHGRP(nh))
700 		nhop_ref_object(nh);
701 	else
702 		nhgrp_ref_object((struct nhgrp_object *)nh);
703 #else
704 	nhop_ref_object(nh);
705 #endif
706 }
707 
708 void
709 nhop_free_any(struct nhop_object *nh)
710 {
711 
712 #ifdef ROUTE_MPATH
713 	if (!NH_IS_NHGRP(nh))
714 		nhop_free(nh);
715 	else
716 		nhgrp_free((struct nhgrp_object *)nh);
717 #else
718 	nhop_free(nh);
719 #endif
720 }
721 
722 /* Helper functions */
723 
724 uint32_t
725 nhop_get_idx(const struct nhop_object *nh)
726 {
727 
728 	return (nh->nh_priv->nh_idx);
729 }
730 
731 enum nhop_type
732 nhop_get_type(const struct nhop_object *nh)
733 {
734 
735 	return (nh->nh_priv->nh_type);
736 }
737 
738 void
739 nhop_set_type(struct nhop_object *nh, enum nhop_type nh_type)
740 {
741 
742 	nh->nh_priv->nh_type = nh_type;
743 }
744 
745 int
746 nhop_get_rtflags(const struct nhop_object *nh)
747 {
748 
749 	return (nh->nh_priv->rt_flags);
750 }
751 
752 void
753 nhop_set_rtflags(struct nhop_object *nh, int rt_flags)
754 {
755 
756 	nh->nh_priv->rt_flags = rt_flags;
757 }
758 
759 struct vnet *
760 nhop_get_vnet(const struct nhop_object *nh)
761 {
762 
763 	return (nh->nh_priv->nh_vnet);
764 }
765 
766 struct nhop_object *
767 nhop_select_func(struct nhop_object *nh, uint32_t flowid)
768 {
769 
770 	return (nhop_select(nh, flowid));
771 }
772 
773 void
774 nhops_update_ifmtu(struct rib_head *rh, struct ifnet *ifp, uint32_t mtu)
775 {
776 	struct nh_control *ctl;
777 	struct nhop_priv *nh_priv;
778 	struct nhop_object *nh;
779 
780 	ctl = rh->nh_control;
781 
782 	NHOPS_WLOCK(ctl);
783 	CHT_SLIST_FOREACH(&ctl->nh_head, nhops, nh_priv) {
784 		nh = nh_priv->nh;
785 		if (nh->nh_ifp == ifp) {
786 			if ((nh_priv->rt_flags & RTF_FIXEDMTU) == 0 ||
787 			    nh->nh_mtu > mtu) {
788 				/* Update MTU directly */
789 				nh->nh_mtu = mtu;
790 			}
791 		}
792 	} CHT_SLIST_FOREACH_END;
793 	NHOPS_WUNLOCK(ctl);
794 
795 }
796 
797 /*
798  * Dumps a single entry to sysctl buffer.
799  *
800  * Layout:
801  *  rt_msghdr - generic RTM header to allow users to skip non-understood messages
802  *  nhop_external - nexhop description structure (with length)
803  *  nhop_addrs - structure encapsulating GW/SRC sockaddrs
804  */
805 static int
806 dump_nhop_entry(struct rib_head *rh, struct nhop_object *nh, struct sysctl_req *w)
807 {
808 	struct {
809 		struct rt_msghdr	rtm;
810 		struct nhop_external	nhe;
811 		struct nhop_addrs	na;
812 	} arpc;
813 	struct nhop_external *pnhe;
814 	struct sockaddr *gw_sa, *src_sa;
815 	struct sockaddr_storage ss;
816 	size_t addrs_len;
817 	int error;
818 
819 	//DPRINTF("Dumping: head %p nh %p flags %X req %p\n", rh, nh, nh->nh_flags, w);
820 
821 	memset(&arpc, 0, sizeof(arpc));
822 
823 	arpc.rtm.rtm_msglen = sizeof(arpc);
824 	arpc.rtm.rtm_version = RTM_VERSION;
825 	arpc.rtm.rtm_type = RTM_GET;
826 	//arpc.rtm.rtm_flags = RTF_UP;
827 	arpc.rtm.rtm_flags = nh->nh_priv->rt_flags;
828 
829 	/* nhop_external */
830 	pnhe = &arpc.nhe;
831 	pnhe->nh_len = sizeof(struct nhop_external);
832 	pnhe->nh_idx = nh->nh_priv->nh_idx;
833 	pnhe->nh_fib = rh->rib_fibnum;
834 	pnhe->ifindex = nh->nh_ifp->if_index;
835 	pnhe->aifindex = nh->nh_aifp->if_index;
836 	pnhe->nh_family = nh->nh_priv->nh_family;
837 	pnhe->nh_type = nh->nh_priv->nh_type;
838 	pnhe->nh_mtu = nh->nh_mtu;
839 	pnhe->nh_flags = nh->nh_flags;
840 
841 	memcpy(pnhe->nh_prepend, nh->nh_prepend, sizeof(nh->nh_prepend));
842 	pnhe->prepend_len = nh->nh_prepend_len;
843 	pnhe->nh_refcount = nh->nh_priv->nh_refcnt;
844 	pnhe->nh_pksent = counter_u64_fetch(nh->nh_pksent);
845 
846 	/* sockaddr container */
847 	addrs_len = sizeof(struct nhop_addrs);
848 	arpc.na.gw_sa_off = addrs_len;
849 	gw_sa = (struct sockaddr *)&nh->gw4_sa;
850 	addrs_len += gw_sa->sa_len;
851 
852 	src_sa = nh->nh_ifa->ifa_addr;
853 	if (src_sa->sa_family == AF_LINK) {
854 		/* Shorten structure */
855 		memset(&ss, 0, sizeof(struct sockaddr_storage));
856 		fill_sdl_from_ifp((struct sockaddr_dl_short *)&ss,
857 		    nh->nh_ifa->ifa_ifp);
858 		src_sa = (struct sockaddr *)&ss;
859 	}
860 	arpc.na.src_sa_off = addrs_len;
861 	addrs_len += src_sa->sa_len;
862 
863 	/* Write total container length */
864 	arpc.na.na_len = addrs_len;
865 
866 	arpc.rtm.rtm_msglen += arpc.na.na_len - sizeof(struct nhop_addrs);
867 
868 	error = SYSCTL_OUT(w, &arpc, sizeof(arpc));
869 	if (error == 0)
870 		error = SYSCTL_OUT(w, gw_sa, gw_sa->sa_len);
871 	if (error == 0)
872 		error = SYSCTL_OUT(w, src_sa, src_sa->sa_len);
873 
874 	return (error);
875 }
876 
877 uint32_t
878 nhops_get_count(struct rib_head *rh)
879 {
880 	struct nh_control *ctl;
881 	uint32_t count;
882 
883 	ctl = rh->nh_control;
884 
885 	NHOPS_RLOCK(ctl);
886 	count = ctl->nh_head.items_count;
887 	NHOPS_RUNLOCK(ctl);
888 
889 	return (count);
890 }
891 
892 int
893 nhops_dump_sysctl(struct rib_head *rh, struct sysctl_req *w)
894 {
895 	struct nh_control *ctl;
896 	struct nhop_priv *nh_priv;
897 	int error;
898 
899 	ctl = rh->nh_control;
900 
901 	NHOPS_RLOCK(ctl);
902 	DPRINTF("NHDUMP: count=%u", ctl->nh_head.items_count);
903 	CHT_SLIST_FOREACH(&ctl->nh_head, nhops, nh_priv) {
904 		error = dump_nhop_entry(rh, nh_priv->nh, w);
905 		if (error != 0) {
906 			NHOPS_RUNLOCK(ctl);
907 			return (error);
908 		}
909 	} CHT_SLIST_FOREACH_END;
910 	NHOPS_RUNLOCK(ctl);
911 
912 	return (0);
913 }
914