xref: /freebsd/sys/net/route/nhop_ctl.c (revision 5c4aa6257210502c93ad65882a8a4842d984bae2)
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_inet6.h"
32 #include "opt_route.h"
33 
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/lock.h>
37 #include <sys/rwlock.h>
38 #include <sys/malloc.h>
39 #include <sys/socket.h>
40 #include <sys/sysctl.h>
41 #include <sys/kernel.h>
42 #include <sys/epoch.h>
43 
44 #include <net/if.h>
45 #include <net/if_var.h>
46 #include <net/if_dl.h>
47 #include <net/route.h>
48 #include <net/route/route_ctl.h>
49 #include <net/route/route_var.h>
50 #include <net/route/nhop_utils.h>
51 #include <net/route/nhop.h>
52 #include <net/route/nhop_var.h>
53 #include <net/vnet.h>
54 
55 #define	DEBUG_MOD_NAME	nhop_ctl
56 #define	DEBUG_MAX_LEVEL	LOG_DEBUG
57 #include <net/route/route_debug.h>
58 _DECLARE_DEBUG(LOG_INFO);
59 
60 /*
61  * This file contains core functionality for the nexthop ("nhop") route subsystem.
62  * The business logic needed to create nexhop objects is implemented here.
63  *
64  * Nexthops in the original sense are the objects containing all the necessary
65  * information to forward the packet to the selected destination.
66  * In particular, nexthop is defined by a combination of
67  *  ifp, ifa, aifp, mtu, gw addr(if set), nh_type, nh_upper_family, mask of rt_flags and
68  *    NHF_DEFAULT
69  *
70  * Additionally, each nexthop gets assigned its unique index (nexthop index).
71  * It serves two purposes: first one is to ease the ability of userland programs to
72  *  reference nexthops by their index. The second one allows lookup algorithms to
73  *  to store index instead of pointer (2 bytes vs 8) as a lookup result.
74  * All nexthops are stored in the resizable hash table.
75  *
76  * Basically, this file revolves around supporting 3 functions:
77  * 1) nhop_create_from_info / nhop_create_from_nhop, which contains all
78  *  business logic on filling the nexthop fields based on the provided request.
79  * 2) nhop_get(), which gets a usable referenced nexthops.
80  *
81  * Conventions:
82  * 1) non-exported functions start with verb
83  * 2) exported function starts with the subsystem prefix: "nhop"
84  */
85 
86 static int dump_nhop_entry(struct rib_head *rh, struct nhop_object *nh, struct sysctl_req *w);
87 
88 static struct nhop_priv *alloc_nhop_structure(void);
89 static int get_nhop(struct rib_head *rnh, struct rt_addrinfo *info,
90     struct nhop_priv **pnh_priv);
91 static int finalize_nhop(struct nh_control *ctl, struct rt_addrinfo *info,
92     struct nhop_priv *nh_priv);
93 static struct ifnet *get_aifp(const struct nhop_object *nh);
94 static void fill_sdl_from_ifp(struct sockaddr_dl_short *sdl, const struct ifnet *ifp);
95 
96 static void destroy_nhop_epoch(epoch_context_t ctx);
97 static void destroy_nhop(struct nhop_priv *nh_priv);
98 
99 _Static_assert(__offsetof(struct nhop_object, nh_ifp) == 32,
100     "nhop_object: wrong nh_ifp offset");
101 _Static_assert(sizeof(struct nhop_object) <= 128,
102     "nhop_object: size exceeds 128 bytes");
103 
104 static uma_zone_t nhops_zone;	/* Global zone for each and every nexthop */
105 
106 #define	NHOP_OBJECT_ALIGNED_SIZE	roundup2(sizeof(struct nhop_object), \
107 							2 * CACHE_LINE_SIZE)
108 #define	NHOP_PRIV_ALIGNED_SIZE		roundup2(sizeof(struct nhop_priv), \
109 							2 * CACHE_LINE_SIZE)
110 void
111 nhops_init(void)
112 {
113 
114 	nhops_zone = uma_zcreate("routing nhops",
115 	    NHOP_OBJECT_ALIGNED_SIZE + NHOP_PRIV_ALIGNED_SIZE,
116 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
117 }
118 
119 /*
120  * Fetches the interface of source address used by the route.
121  * In all cases except interface-address-route it would be the
122  * same as the transmit interfaces.
123  * However, for the interface address this function will return
124  * this interface ifp instead of loopback. This is needed to support
125  * link-local IPv6 loopback communications.
126  *
127  * Returns found ifp.
128  */
129 static struct ifnet *
130 get_aifp(const struct nhop_object *nh)
131 {
132 	struct ifnet *aifp = NULL;
133 
134 	/*
135 	 * Adjust the "outgoing" interface.  If we're going to loop
136 	 * the packet back to ourselves, the ifp would be the loopback
137 	 * interface. However, we'd rather know the interface associated
138 	 * to the destination address (which should probably be one of
139 	 * our own addresses).
140 	 */
141 	if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) &&
142 			nh->gw_sa.sa_family == AF_LINK) {
143 		aifp = ifnet_byindex(nh->gwl_sa.sdl_index);
144 		if (aifp == NULL) {
145 			FIB_NH_LOG(LOG_WARNING, nh, "unable to get aifp for %s index %d",
146 				if_name(nh->nh_ifp), nh->gwl_sa.sdl_index);
147 		}
148 	}
149 
150 	if (aifp == NULL)
151 		aifp = nh->nh_ifp;
152 
153 	return (aifp);
154 }
155 
156 int
157 cmp_priv(const struct nhop_priv *_one, const struct nhop_priv *_two)
158 {
159 
160 	if (memcmp(_one->nh, _two->nh, NHOP_END_CMP) != 0)
161 		return (0);
162 
163 	if (memcmp(_one, _two, NH_PRIV_END_CMP) != 0)
164 		return (0);
165 
166 	return (1);
167 }
168 
169 /*
170  * Conditionally sets @nh mtu data based on the @info data.
171  */
172 static void
173 set_nhop_mtu_from_info(struct nhop_object *nh, const struct rt_addrinfo *info)
174 {
175 
176 	if (info->rti_mflags & RTV_MTU) {
177 		if (info->rti_rmx->rmx_mtu != 0) {
178 			/*
179 			 * MTU was explicitly provided by user.
180 			 * Keep it.
181 			 */
182 
183 			nh->nh_priv->rt_flags |= RTF_FIXEDMTU;
184 		} else {
185 			/*
186 			 * User explicitly sets MTU to 0.
187 			 * Assume rollback to default.
188 			 */
189 			nh->nh_priv->rt_flags &= ~RTF_FIXEDMTU;
190 		}
191 		nh->nh_mtu = info->rti_rmx->rmx_mtu;
192 	}
193 }
194 
195 /*
196  * Fills in shorted link-level sockadd version suitable to be stored inside the
197  *  nexthop gateway buffer.
198  */
199 static void
200 fill_sdl_from_ifp(struct sockaddr_dl_short *sdl, const struct ifnet *ifp)
201 {
202 
203 	bzero(sdl, sizeof(struct sockaddr_dl_short));
204 	sdl->sdl_family = AF_LINK;
205 	sdl->sdl_len = sizeof(struct sockaddr_dl_short);
206 	sdl->sdl_index = ifp->if_index;
207 	sdl->sdl_type = ifp->if_type;
208 }
209 
210 static int
211 set_nhop_gw_from_info(struct nhop_object *nh, struct rt_addrinfo *info)
212 {
213 	struct sockaddr *gw;
214 
215 	gw = info->rti_info[RTAX_GATEWAY];
216 	KASSERT(gw != NULL, ("gw is NULL"));
217 
218 	if ((gw->sa_family == AF_LINK) && !(info->rti_flags & RTF_GATEWAY)) {
219 
220 		/*
221 		 * Interface route with interface specified by the interface
222 		 * index in sockadd_dl structure. It is used in the IPv6 loopback
223 		 * output code, where we need to preserve the original interface
224 		 * to maintain proper scoping.
225 		 * Despite the fact that nexthop code stores original interface
226 		 * in the separate field (nh_aifp, see below), write AF_LINK
227 		 * compatible sa with shorter total length.
228 		 */
229 		struct sockaddr_dl *sdl = (struct sockaddr_dl *)gw;
230 		struct ifnet *ifp = ifnet_byindex(sdl->sdl_index);
231 		if (ifp == NULL) {
232 			FIB_NH_LOG(LOG_WARNING, nh, "invalid ifindex %d", sdl->sdl_index);
233 			return (EINVAL);
234 		}
235 		fill_sdl_from_ifp(&nh->gwl_sa, ifp);
236 	} else {
237 
238 		/*
239 		 * Multiple options here:
240 		 *
241 		 * 1) RTF_GATEWAY with IPv4/IPv6 gateway data
242 		 * 2) Interface route with IPv4/IPv6 address of the
243 		 *   matching interface. Some routing daemons do that
244 		 *   instead of specifying ifindex in AF_LINK.
245 		 *
246 		 * In both cases, save the original nexthop to make the callers
247 		 *   happy.
248 		 */
249 		if (gw->sa_len > sizeof(struct sockaddr_in6)) {
250 			FIB_NH_LOG(LOG_WARNING, nh, "nhop SA size too big: AF %d len %u",
251 			    gw->sa_family, gw->sa_len);
252 			return (ENOMEM);
253 		}
254 		memcpy(&nh->gw_sa, gw, gw->sa_len);
255 	}
256 	return (0);
257 }
258 
259 static uint16_t
260 convert_rt_to_nh_flags(int rt_flags)
261 {
262 	uint16_t res;
263 
264 	res = (rt_flags & RTF_REJECT) ? NHF_REJECT : 0;
265 	res |= (rt_flags & RTF_HOST) ? NHF_HOST : 0;
266 	res |= (rt_flags & RTF_BLACKHOLE) ? NHF_BLACKHOLE : 0;
267 	res |= (rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) ? NHF_REDIRECT : 0;
268 	res |= (rt_flags & RTF_BROADCAST) ? NHF_BROADCAST : 0;
269 	res |= (rt_flags & RTF_GATEWAY) ? NHF_GATEWAY : 0;
270 
271 	return (res);
272 }
273 
274 static int
275 fill_nhop_from_info(struct nhop_priv *nh_priv, struct rt_addrinfo *info)
276 {
277 	int error, rt_flags;
278 	struct nhop_object *nh;
279 
280 	nh = nh_priv->nh;
281 
282 	rt_flags = info->rti_flags & NHOP_RT_FLAG_MASK;
283 
284 	nh->nh_priv->rt_flags = rt_flags;
285 	nh_priv->nh_upper_family = info->rti_info[RTAX_DST]->sa_family;
286 	nh_priv->nh_type = 0; // hook responsibility to set nhop type
287 	nh->nh_flags = convert_rt_to_nh_flags(rt_flags);
288 
289 	set_nhop_mtu_from_info(nh, info);
290 	if ((error = set_nhop_gw_from_info(nh, info)) != 0)
291 		return (error);
292 	if (nh->gw_sa.sa_family == AF_LINK)
293 		nh_priv->nh_neigh_family = nh_priv->nh_upper_family;
294 	else
295 		nh_priv->nh_neigh_family = nh->gw_sa.sa_family;
296 
297 	nh->nh_ifp = (info->rti_ifp != NULL) ? info->rti_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);
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 nhop_priv *nh_priv = nh->nh_priv;
413 	struct sockaddr *info_gw;
414 	int error;
415 
416 	/* Update MTU if set in the request*/
417 	set_nhop_mtu_from_info(nh, info);
418 
419 	/* XXX: allow only one of BLACKHOLE,REJECT,GATEWAY */
420 
421 	/* Allow some flags (FLAG1,STATIC,BLACKHOLE,REJECT) to be toggled on change. */
422 	nh_priv->rt_flags &= ~RTF_FMASK;
423 	nh_priv->rt_flags |= info->rti_flags & RTF_FMASK;
424 
425 	/* Consider gateway change */
426 	info_gw = info->rti_info[RTAX_GATEWAY];
427 	if (info_gw != NULL) {
428 		error = set_nhop_gw_from_info(nh, info);
429 		if (error != 0)
430 			return (error);
431 		if (nh->gw_sa.sa_family == AF_LINK)
432 			nh_priv->nh_neigh_family = nh_priv->nh_upper_family;
433 		else
434 			nh_priv->nh_neigh_family = nh->gw_sa.sa_family;
435 		/* Update RTF_GATEWAY flag status */
436 		nh_priv->rt_flags &= ~RTF_GATEWAY;
437 		nh_priv->rt_flags |= (RTF_GATEWAY & info->rti_flags);
438 	}
439 	/* Update datapath flags */
440 	nh->nh_flags = convert_rt_to_nh_flags(nh_priv->rt_flags);
441 
442 	if (info->rti_ifa != NULL)
443 		nh->nh_ifa = info->rti_ifa;
444 	if (info->rti_ifp != NULL)
445 		nh->nh_ifp = info->rti_ifp;
446 	nh->nh_aifp = get_aifp(nh);
447 
448 	return (0);
449 }
450 
451 /*
452  * Creates new nexthop based on @nh_orig and augmentation data from @info.
453  * Helper function used in the route changes, please see
454  *   alter_nhop_from_info() comments for more details.
455  *
456  * Returns:
457  * 0 on success, filling @nh_ret with the desired nexthop object
458  * errno otherwise
459  */
460 int
461 nhop_create_from_nhop(struct rib_head *rnh, const struct nhop_object *nh_orig,
462     struct rt_addrinfo *info, struct nhop_object **pnh)
463 {
464 	struct nhop_priv *nh_priv;
465 	struct nhop_object *nh;
466 	int error;
467 
468 	NET_EPOCH_ASSERT();
469 
470 	nh_priv = alloc_nhop_structure();
471 	nh = nh_priv->nh;
472 
473 	/* Start with copying data from original nexthop */
474 	nh_priv->nh_upper_family = nh_orig->nh_priv->nh_upper_family;
475 	nh_priv->nh_neigh_family = nh_orig->nh_priv->nh_neigh_family;
476 	nh_priv->rt_flags = nh_orig->nh_priv->rt_flags;
477 	nh_priv->nh_type = nh_orig->nh_priv->nh_type;
478 	nh_priv->nh_fibnum = nh_orig->nh_priv->nh_fibnum;
479 
480 	nh->nh_ifp = nh_orig->nh_ifp;
481 	nh->nh_ifa = nh_orig->nh_ifa;
482 	nh->nh_aifp = nh_orig->nh_aifp;
483 	nh->nh_mtu = nh_orig->nh_mtu;
484 	nh->nh_flags = nh_orig->nh_flags;
485 	memcpy(&nh->gw_sa, &nh_orig->gw_sa, nh_orig->gw_sa.sa_len);
486 
487 	error = alter_nhop_from_info(nh, info);
488 	if (error != 0) {
489 		uma_zfree(nhops_zone, nh_priv->nh);
490 		return (error);
491 	}
492 
493 	error = get_nhop(rnh, info, &nh_priv);
494 	if (error == 0)
495 		*pnh = nh_priv->nh;
496 
497 	return (error);
498 }
499 
500 /*
501  * Allocates memory for public/private nexthop structures.
502  *
503  * Returns pointer to nhop_priv or NULL.
504  */
505 static struct nhop_priv *
506 alloc_nhop_structure()
507 {
508 	struct nhop_object *nh;
509 	struct nhop_priv *nh_priv;
510 
511 	nh = (struct nhop_object *)uma_zalloc(nhops_zone, M_NOWAIT | M_ZERO);
512 	if (nh == NULL)
513 		return (NULL);
514 	nh_priv = (struct nhop_priv *)((char *)nh + NHOP_OBJECT_ALIGNED_SIZE);
515 
516 	nh->nh_priv = nh_priv;
517 	nh_priv->nh = nh;
518 
519 	return (nh_priv);
520 }
521 
522 static bool
523 reference_nhop_deps(struct nhop_object *nh)
524 {
525 	if (!ifa_try_ref(nh->nh_ifa))
526 		return (false);
527 	nh->nh_aifp = get_aifp(nh);
528 	if (!if_try_ref(nh->nh_aifp)) {
529 		ifa_free(nh->nh_ifa);
530 		return (false);
531 	}
532 	FIB_NH_LOG(LOG_DEBUG, nh, "AIFP: %p nh_ifp %p", nh->nh_aifp, nh->nh_ifp);
533 	if (!if_try_ref(nh->nh_ifp)) {
534 		ifa_free(nh->nh_ifa);
535 		if_rele(nh->nh_aifp);
536 		return (false);
537 	}
538 
539 	return (true);
540 }
541 
542 /*
543  * Alocates/references the remaining bits of nexthop data and links
544  *  it to the hash table.
545  * Returns 0 if successful,
546  *  errno otherwise. @nh_priv is freed in case of error.
547  */
548 static int
549 finalize_nhop(struct nh_control *ctl, struct rt_addrinfo *info,
550     struct nhop_priv *nh_priv)
551 {
552 	struct nhop_object *nh = nh_priv->nh;
553 
554 	/* Allocate per-cpu packet counter */
555 	nh->nh_pksent = counter_u64_alloc(M_NOWAIT);
556 	if (nh->nh_pksent == NULL) {
557 		uma_zfree(nhops_zone, nh);
558 		RTSTAT_INC(rts_nh_alloc_failure);
559 		FIB_NH_LOG(LOG_WARNING, nh, "counter_u64_alloc() failed");
560 		return (ENOMEM);
561 	}
562 
563 	if (!reference_nhop_deps(nh)) {
564 		counter_u64_free(nh->nh_pksent);
565 		uma_zfree(nhops_zone, nh);
566 		RTSTAT_INC(rts_nh_alloc_failure);
567 		FIB_NH_LOG(LOG_WARNING, nh, "interface reference failed");
568 		return (EAGAIN);
569 	}
570 
571 	/* Save vnet to ease destruction */
572 	nh_priv->nh_vnet = curvnet;
573 
574 	refcount_init(&nh_priv->nh_refcnt, 1);
575 
576 	/* Please see nhop_free() comments on the initial value */
577 	refcount_init(&nh_priv->nh_linked, 2);
578 
579 	nh_priv->nh_fibnum = ctl->ctl_rh->rib_fibnum;
580 
581 	if (link_nhop(ctl, nh_priv) == 0) {
582 		/*
583 		 * Adding nexthop to the datastructures
584 		 *  failed. Call destructor w/o waiting for
585 		 *  the epoch end, as nexthop is not used
586 		 *  and return.
587 		 */
588 		char nhbuf[48];
589 		FIB_NH_LOG(LOG_WARNING, nh, "failed to link %s",
590 		    nhop_print_buf(nh, nhbuf, sizeof(nhbuf)));
591 		destroy_nhop(nh_priv);
592 
593 		return (ENOBUFS);
594 	}
595 
596 #if DEBUG_MAX_LEVEL >= LOG_DEBUG
597 	char nhbuf[48];
598 	FIB_NH_LOG(LOG_DEBUG, nh, "finalized: %s", nhop_print_buf(nh, nhbuf, sizeof(nhbuf)));
599 #endif
600 
601 	return (0);
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 	if_rele(nh->nh_ifp);
612 	if_rele(nh->nh_aifp);
613 	ifa_free(nh->nh_ifa);
614 	counter_u64_free(nh->nh_pksent);
615 
616 	uma_zfree(nhops_zone, nh);
617 }
618 
619 /*
620  * Epoch callback indicating nhop is safe to destroy
621  */
622 static void
623 destroy_nhop_epoch(epoch_context_t ctx)
624 {
625 	struct nhop_priv *nh_priv;
626 
627 	nh_priv = __containerof(ctx, struct nhop_priv, nh_epoch_ctx);
628 
629 	destroy_nhop(nh_priv);
630 }
631 
632 void
633 nhop_ref_object(struct nhop_object *nh)
634 {
635 	u_int old;
636 
637 	old = refcount_acquire(&nh->nh_priv->nh_refcnt);
638 	KASSERT(old > 0, ("%s: nhop object %p has 0 refs", __func__, nh));
639 }
640 
641 int
642 nhop_try_ref_object(struct nhop_object *nh)
643 {
644 
645 	return (refcount_acquire_if_not_zero(&nh->nh_priv->nh_refcnt));
646 }
647 
648 void
649 nhop_free(struct nhop_object *nh)
650 {
651 	struct nh_control *ctl;
652 	struct nhop_priv *nh_priv = nh->nh_priv;
653 	struct epoch_tracker et;
654 
655 	if (!refcount_release(&nh_priv->nh_refcnt))
656 		return;
657 
658 #if DEBUG_MAX_LEVEL >= LOG_DEBUG
659 	char nhbuf[48];
660 	FIB_NH_LOG(LOG_DEBUG, nh, "deleting %s", nhop_print_buf(nh, nhbuf, sizeof(nhbuf)));
661 #endif
662 
663 	/*
664 	 * There are only 2 places, where nh_linked can be decreased:
665 	 *  rib destroy (nhops_destroy_rib) and this function.
666 	 * nh_link can never be increased.
667 	 *
668 	 * Hence, use initial value of 2 to make use of
669 	 *  refcount_release_if_not_last().
670 	 *
671 	 * There can be two scenarious when calling this function:
672 	 *
673 	 * 1) nh_linked value is 2. This means that either
674 	 *  nhops_destroy_rib() has not been called OR it is running,
675 	 *  but we are guaranteed that nh_control won't be freed in
676 	 *  this epoch. Hence, nexthop can be safely unlinked.
677 	 *
678 	 * 2) nh_linked value is 1. In that case, nhops_destroy_rib()
679 	 *  has been called and nhop unlink can be skipped.
680 	 */
681 
682 	NET_EPOCH_ENTER(et);
683 	if (refcount_release_if_not_last(&nh_priv->nh_linked)) {
684 		ctl = nh_priv->nh_control;
685 		if (unlink_nhop(ctl, nh_priv) == NULL) {
686 			/* Do not try to reclaim */
687 			char nhbuf[48];
688 			FIB_NH_LOG(LOG_WARNING, nh, "failed to unlink %s",
689 			    nhop_print_buf(nh, nhbuf, sizeof(nhbuf)));
690 			NET_EPOCH_EXIT(et);
691 			return;
692 		}
693 	}
694 	NET_EPOCH_EXIT(et);
695 
696 	epoch_call(net_epoch_preempt, destroy_nhop_epoch,
697 	    &nh_priv->nh_epoch_ctx);
698 }
699 
700 void
701 nhop_ref_any(struct nhop_object *nh)
702 {
703 #ifdef ROUTE_MPATH
704 	if (!NH_IS_NHGRP(nh))
705 		nhop_ref_object(nh);
706 	else
707 		nhgrp_ref_object((struct nhgrp_object *)nh);
708 #else
709 	nhop_ref_object(nh);
710 #endif
711 }
712 
713 void
714 nhop_free_any(struct nhop_object *nh)
715 {
716 
717 #ifdef ROUTE_MPATH
718 	if (!NH_IS_NHGRP(nh))
719 		nhop_free(nh);
720 	else
721 		nhgrp_free((struct nhgrp_object *)nh);
722 #else
723 	nhop_free(nh);
724 #endif
725 }
726 
727 /* Helper functions */
728 
729 uint32_t
730 nhop_get_idx(const struct nhop_object *nh)
731 {
732 
733 	return (nh->nh_priv->nh_idx);
734 }
735 
736 enum nhop_type
737 nhop_get_type(const struct nhop_object *nh)
738 {
739 
740 	return (nh->nh_priv->nh_type);
741 }
742 
743 void
744 nhop_set_type(struct nhop_object *nh, enum nhop_type nh_type)
745 {
746 
747 	nh->nh_priv->nh_type = nh_type;
748 }
749 
750 int
751 nhop_get_rtflags(const struct nhop_object *nh)
752 {
753 
754 	return (nh->nh_priv->rt_flags);
755 }
756 
757 void
758 nhop_set_rtflags(struct nhop_object *nh, int rt_flags)
759 {
760 
761 	nh->nh_priv->rt_flags = rt_flags;
762 }
763 
764 struct vnet *
765 nhop_get_vnet(const struct nhop_object *nh)
766 {
767 
768 	return (nh->nh_priv->nh_vnet);
769 }
770 
771 struct nhop_object *
772 nhop_select_func(struct nhop_object *nh, uint32_t flowid)
773 {
774 
775 	return (nhop_select(nh, flowid));
776 }
777 
778 /*
779  * Returns address family of the traffic uses the nexthop.
780  */
781 int
782 nhop_get_upper_family(const struct nhop_object *nh)
783 {
784 	return (nh->nh_priv->nh_upper_family);
785 }
786 
787 /*
788  * Returns address family of the LLE or gateway that is used
789  * to forward the traffic to.
790  */
791 int
792 nhop_get_neigh_family(const struct nhop_object *nh)
793 {
794 	return (nh->nh_priv->nh_neigh_family);
795 }
796 
797 uint32_t
798 nhop_get_fibnum(const struct nhop_object *nh)
799 {
800 	return (nh->nh_priv->nh_fibnum);
801 }
802 
803 void
804 nhops_update_ifmtu(struct rib_head *rh, struct ifnet *ifp, uint32_t mtu)
805 {
806 	struct nh_control *ctl;
807 	struct nhop_priv *nh_priv;
808 	struct nhop_object *nh;
809 
810 	ctl = rh->nh_control;
811 
812 	NHOPS_WLOCK(ctl);
813 	CHT_SLIST_FOREACH(&ctl->nh_head, nhops, nh_priv) {
814 		nh = nh_priv->nh;
815 		if (nh->nh_ifp == ifp) {
816 			if ((nh_priv->rt_flags & RTF_FIXEDMTU) == 0 ||
817 			    nh->nh_mtu > mtu) {
818 				/* Update MTU directly */
819 				nh->nh_mtu = mtu;
820 			}
821 		}
822 	} CHT_SLIST_FOREACH_END;
823 	NHOPS_WUNLOCK(ctl);
824 
825 }
826 
827 /*
828  * Prints nexthop @nh data in the provided @buf.
829  * Example: nh#33/inet/em0/192.168.0.1
830  */
831 char *
832 nhop_print_buf(const struct nhop_object *nh, char *buf, size_t bufsize)
833 {
834 #if defined(INET) || defined(INET6)
835 	char abuf[INET6_ADDRSTRLEN];
836 #endif
837 	struct nhop_priv *nh_priv = nh->nh_priv;
838 	const char *upper_str = rib_print_family(nh->nh_priv->nh_upper_family);
839 
840 	switch (nh->gw_sa.sa_family) {
841 #ifdef INET
842 	case AF_INET:
843 		inet_ntop(AF_INET, &nh->gw4_sa.sin_addr, abuf, sizeof(abuf));
844 		snprintf(buf, bufsize, "nh#%d/%s/%s/%s", nh_priv->nh_idx, upper_str,
845 		    if_name(nh->nh_ifp), abuf);
846 		break;
847 #endif
848 #ifdef INET6
849 	case AF_INET6:
850 		inet_ntop(AF_INET6, &nh->gw6_sa.sin6_addr, abuf, sizeof(abuf));
851 		snprintf(buf, bufsize, "nh#%d/%s/%s/%s", nh_priv->nh_idx, upper_str,
852 		    if_name(nh->nh_ifp), abuf);
853 		break;
854 #endif
855 	case AF_LINK:
856 		snprintf(buf, bufsize, "nh#%d/%s/%s/resolve", nh_priv->nh_idx, upper_str,
857 		    if_name(nh->nh_ifp));
858 		break;
859 	default:
860 		snprintf(buf, bufsize, "nh#%d/%s/%s/????", nh_priv->nh_idx, upper_str,
861 		    if_name(nh->nh_ifp));
862 		break;
863 	}
864 
865 	return (buf);
866 }
867 
868 /*
869  * Dumps a single entry to sysctl buffer.
870  *
871  * Layout:
872  *  rt_msghdr - generic RTM header to allow users to skip non-understood messages
873  *  nhop_external - nexhop description structure (with length)
874  *  nhop_addrs - structure encapsulating GW/SRC sockaddrs
875  */
876 static int
877 dump_nhop_entry(struct rib_head *rh, struct nhop_object *nh, struct sysctl_req *w)
878 {
879 	struct {
880 		struct rt_msghdr	rtm;
881 		struct nhop_external	nhe;
882 		struct nhop_addrs	na;
883 	} arpc;
884 	struct nhop_external *pnhe;
885 	struct sockaddr *gw_sa, *src_sa;
886 	struct sockaddr_storage ss;
887 	size_t addrs_len;
888 	int error;
889 
890 	memset(&arpc, 0, sizeof(arpc));
891 
892 	arpc.rtm.rtm_msglen = sizeof(arpc);
893 	arpc.rtm.rtm_version = RTM_VERSION;
894 	arpc.rtm.rtm_type = RTM_GET;
895 	//arpc.rtm.rtm_flags = RTF_UP;
896 	arpc.rtm.rtm_flags = nh->nh_priv->rt_flags;
897 
898 	/* nhop_external */
899 	pnhe = &arpc.nhe;
900 	pnhe->nh_len = sizeof(struct nhop_external);
901 	pnhe->nh_idx = nh->nh_priv->nh_idx;
902 	pnhe->nh_fib = rh->rib_fibnum;
903 	pnhe->ifindex = nh->nh_ifp->if_index;
904 	pnhe->aifindex = nh->nh_aifp->if_index;
905 	pnhe->nh_family = nh->nh_priv->nh_upper_family;
906 	pnhe->nh_type = nh->nh_priv->nh_type;
907 	pnhe->nh_mtu = nh->nh_mtu;
908 	pnhe->nh_flags = nh->nh_flags;
909 
910 	memcpy(pnhe->nh_prepend, nh->nh_prepend, sizeof(nh->nh_prepend));
911 	pnhe->prepend_len = nh->nh_prepend_len;
912 	pnhe->nh_refcount = nh->nh_priv->nh_refcnt;
913 	pnhe->nh_pksent = counter_u64_fetch(nh->nh_pksent);
914 
915 	/* sockaddr container */
916 	addrs_len = sizeof(struct nhop_addrs);
917 	arpc.na.gw_sa_off = addrs_len;
918 	gw_sa = (struct sockaddr *)&nh->gw4_sa;
919 	addrs_len += gw_sa->sa_len;
920 
921 	src_sa = nh->nh_ifa->ifa_addr;
922 	if (src_sa->sa_family == AF_LINK) {
923 		/* Shorten structure */
924 		memset(&ss, 0, sizeof(struct sockaddr_storage));
925 		fill_sdl_from_ifp((struct sockaddr_dl_short *)&ss,
926 		    nh->nh_ifa->ifa_ifp);
927 		src_sa = (struct sockaddr *)&ss;
928 	}
929 	arpc.na.src_sa_off = addrs_len;
930 	addrs_len += src_sa->sa_len;
931 
932 	/* Write total container length */
933 	arpc.na.na_len = addrs_len;
934 
935 	arpc.rtm.rtm_msglen += arpc.na.na_len - sizeof(struct nhop_addrs);
936 
937 	error = SYSCTL_OUT(w, &arpc, sizeof(arpc));
938 	if (error == 0)
939 		error = SYSCTL_OUT(w, gw_sa, gw_sa->sa_len);
940 	if (error == 0)
941 		error = SYSCTL_OUT(w, src_sa, src_sa->sa_len);
942 
943 	return (error);
944 }
945 
946 uint32_t
947 nhops_get_count(struct rib_head *rh)
948 {
949 	struct nh_control *ctl;
950 	uint32_t count;
951 
952 	ctl = rh->nh_control;
953 
954 	NHOPS_RLOCK(ctl);
955 	count = ctl->nh_head.items_count;
956 	NHOPS_RUNLOCK(ctl);
957 
958 	return (count);
959 }
960 
961 int
962 nhops_dump_sysctl(struct rib_head *rh, struct sysctl_req *w)
963 {
964 	struct nh_control *ctl;
965 	struct nhop_priv *nh_priv;
966 	int error;
967 
968 	ctl = rh->nh_control;
969 
970 	NHOPS_RLOCK(ctl);
971 #if DEBUG_MAX_LEVEL >= LOG_DEBUG
972 	FIB_LOG(LOG_DEBUG, rh->rib_fibnum, rh->rib_family, "dump %u items",
973 	    ctl->nh_head.items_count);
974 #endif
975 	CHT_SLIST_FOREACH(&ctl->nh_head, nhops, nh_priv) {
976 		error = dump_nhop_entry(rh, nh_priv->nh, w);
977 		if (error != 0) {
978 			NHOPS_RUNLOCK(ctl);
979 			return (error);
980 		}
981 	} CHT_SLIST_FOREACH_END;
982 	NHOPS_RUNLOCK(ctl);
983 
984 	return (0);
985 }
986