xref: /openbsd-src/sys/net/rtable.c (revision c1a45aed656e7d5627c30c92421893a76f370ccb)
1 /*	$OpenBSD: rtable.c,v 1.77 2022/04/19 15:44:56 bluhm Exp $ */
2 
3 /*
4  * Copyright (c) 2014-2016 Martin Pieuchot
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #ifndef _KERNEL
20 #include "kern_compat.h"
21 #else
22 #include <sys/param.h>
23 #include <sys/systm.h>
24 #include <sys/socket.h>
25 #include <sys/malloc.h>
26 #include <sys/queue.h>
27 #include <sys/domain.h>
28 #include <sys/srp.h>
29 #endif
30 
31 #include <net/rtable.h>
32 #include <net/route.h>
33 
34 /*
35  * Structures used by rtable_get() to retrieve the corresponding
36  * routing table for a given pair of ``af'' and ``rtableid''.
37  *
38  * Note that once allocated routing table heads are never freed.
39  * This way we do not need to reference count them.
40  *
41  *	afmap		    rtmap/dommp
42  *   -----------          ---------     -----
43  *   |   0     |--------> | 0 | 0 | ... | 0 |	Array mapping rtableid (=index)
44  *   -----------          ---------     -----   to rdomain/loopback (=value).
45  *   | AF_INET |.
46  *   ----------- `.       .---------.     .---------.
47  *       ...	   `----> | rtable0 | ... | rtableN |	Array of pointers for
48  *   -----------          '---------'     '---------'	IPv4 routing tables
49  *   | AF_MPLS |					indexed by ``rtableid''.
50  *   -----------
51  */
52 struct srp	  *afmap;
53 uint8_t		   af2idx[AF_MAX+1];	/* To only allocate supported AF */
54 uint8_t		   af2idx_max;
55 
56 /* Array of routing table pointers. */
57 struct rtmap {
58 	unsigned int	   limit;
59 	void		 **tbl;
60 };
61 
62 /*
63  * Array of rtableid -> rdomain mapping.
64  *
65  * Only used for the first index as described above.
66  */
67 struct dommp {
68 	unsigned int	   limit;
69 	/*
70 	 * Array to get the routing domain and loopback interface related to
71 	 * a routing table. Format:
72 	 *
73 	 * 8 unused bits | 16 bits for loopback index | 8 bits for rdomain
74 	 */
75 	unsigned int	  *value;
76 };
77 
78 unsigned int	   rtmap_limit = 0;
79 
80 void		   rtmap_init(void);
81 void		   rtmap_grow(unsigned int, sa_family_t);
82 void		   rtmap_dtor(void *, void *);
83 
84 struct srp_gc	   rtmap_gc = SRP_GC_INITIALIZER(rtmap_dtor, NULL);
85 
86 void		   rtable_init_backend(void);
87 void		  *rtable_alloc(unsigned int, unsigned int, unsigned int);
88 void		  *rtable_get(unsigned int, sa_family_t);
89 
90 void
91 rtmap_init(void)
92 {
93 	const struct domain	*dp;
94 	int			 i;
95 
96 	/* Start with a single table for every domain that requires it. */
97 	for (i = 0; (dp = domains[i]) != NULL; i++) {
98 		if (dp->dom_rtoffset == 0)
99 			continue;
100 
101 		rtmap_grow(1, dp->dom_family);
102 	}
103 
104 	/* Initialize the rtableid->rdomain mapping table. */
105 	rtmap_grow(1, 0);
106 
107 	rtmap_limit = 1;
108 }
109 
110 /*
111  * Grow the size of the array of routing table for AF ``af'' to ``nlimit''.
112  */
113 void
114 rtmap_grow(unsigned int nlimit, sa_family_t af)
115 {
116 	struct rtmap	*map, *nmap;
117 	int		 i;
118 
119 	KERNEL_ASSERT_LOCKED();
120 
121 	KASSERT(nlimit > rtmap_limit);
122 
123 	nmap = malloc(sizeof(*nmap), M_RTABLE, M_WAITOK);
124 	nmap->limit = nlimit;
125 	nmap->tbl = mallocarray(nlimit, sizeof(*nmap[0].tbl), M_RTABLE,
126 	    M_WAITOK|M_ZERO);
127 
128 	map = srp_get_locked(&afmap[af2idx[af]]);
129 	if (map != NULL) {
130 		KASSERT(map->limit == rtmap_limit);
131 
132 		for (i = 0; i < map->limit; i++)
133 			nmap->tbl[i] = map->tbl[i];
134 	}
135 
136 	srp_update_locked(&rtmap_gc, &afmap[af2idx[af]], nmap);
137 }
138 
139 void
140 rtmap_dtor(void *null, void *xmap)
141 {
142 	struct rtmap	*map = xmap;
143 
144 	/*
145 	 * doesn't need to be serialized since this is the last reference
146 	 * to this map. there's nothing to race against.
147 	 */
148 	free(map->tbl, M_RTABLE, map->limit * sizeof(*map[0].tbl));
149 	free(map, M_RTABLE, sizeof(*map));
150 }
151 
152 void
153 rtable_init(void)
154 {
155 	const struct domain	*dp;
156 	int			 i;
157 
158 	KASSERT(sizeof(struct rtmap) == sizeof(struct dommp));
159 
160 	/* We use index 0 for the rtable/rdomain map. */
161 	af2idx_max = 1;
162 	memset(af2idx, 0, sizeof(af2idx));
163 
164 	/*
165 	 * Compute the maximum supported key length in case the routing
166 	 * table backend needs it.
167 	 */
168 	for (i = 0; (dp = domains[i]) != NULL; i++) {
169 		if (dp->dom_rtoffset == 0)
170 			continue;
171 
172 		af2idx[dp->dom_family] = af2idx_max++;
173 	}
174 	rtable_init_backend();
175 
176 	/*
177 	 * Allocate AF-to-id table now that we now how many AFs this
178 	 * kernel supports.
179 	 */
180 	afmap = mallocarray(af2idx_max + 1, sizeof(*afmap), M_RTABLE,
181 	    M_WAITOK|M_ZERO);
182 
183 	rtmap_init();
184 
185 	if (rtable_add(0) != 0)
186 		panic("unable to create default routing table");
187 
188 	rt_timer_init();
189 }
190 
191 int
192 rtable_add(unsigned int id)
193 {
194 	const struct domain	*dp;
195 	void			*tbl;
196 	struct rtmap		*map;
197 	struct dommp		*dmm;
198 	sa_family_t		 af;
199 	unsigned int		 off, alen;
200 	int			 i, error = 0;
201 
202 	if (id > RT_TABLEID_MAX)
203 		return (EINVAL);
204 
205 	KERNEL_LOCK();
206 
207 	if (rtable_exists(id))
208 		goto out;
209 
210 	for (i = 0; (dp = domains[i]) != NULL; i++) {
211 		if (dp->dom_rtoffset == 0)
212 			continue;
213 
214 		af = dp->dom_family;
215 		off = dp->dom_rtoffset;
216 		alen = dp->dom_maxplen;
217 
218 		if (id >= rtmap_limit)
219 			rtmap_grow(id + 1, af);
220 
221 		tbl = rtable_alloc(id, alen, off);
222 		if (tbl == NULL) {
223 			error = ENOMEM;
224 			goto out;
225 		}
226 
227 		map = srp_get_locked(&afmap[af2idx[af]]);
228 		map->tbl[id] = tbl;
229 	}
230 
231 	/* Reflect possible growth. */
232 	if (id >= rtmap_limit) {
233 		rtmap_grow(id + 1, 0);
234 		rtmap_limit = id + 1;
235 	}
236 
237 	/* Use main rtable/rdomain by default. */
238 	dmm = srp_get_locked(&afmap[0]);
239 	dmm->value[id] = 0;
240 out:
241 	KERNEL_UNLOCK();
242 
243 	return (error);
244 }
245 
246 void *
247 rtable_get(unsigned int rtableid, sa_family_t af)
248 {
249 	struct rtmap	*map;
250 	void		*tbl = NULL;
251 	struct srp_ref	 sr;
252 
253 	if (af >= nitems(af2idx) || af2idx[af] == 0)
254 		return (NULL);
255 
256 	map = srp_enter(&sr, &afmap[af2idx[af]]);
257 	if (rtableid < map->limit)
258 		tbl = map->tbl[rtableid];
259 	srp_leave(&sr);
260 
261 	return (tbl);
262 }
263 
264 int
265 rtable_exists(unsigned int rtableid)
266 {
267 	const struct domain	*dp;
268 	void			*tbl;
269 	int			 i;
270 
271 	for (i = 0; (dp = domains[i]) != NULL; i++) {
272 		if (dp->dom_rtoffset == 0)
273 			continue;
274 
275 		tbl = rtable_get(rtableid, dp->dom_family);
276 		if (tbl != NULL)
277 			return (1);
278 	}
279 
280 	return (0);
281 }
282 
283 int
284 rtable_empty(unsigned int rtableid)
285 {
286 	const struct domain	*dp;
287 	int			 i;
288 	struct art_root		*tbl;
289 
290 	for (i = 0; (dp = domains[i]) != NULL; i++) {
291 		if (dp->dom_rtoffset == 0)
292 			continue;
293 
294 		tbl = rtable_get(rtableid, dp->dom_family);
295 		if (tbl == NULL)
296 			continue;
297 		if (tbl->ar_root.ref != NULL)
298 			return (0);
299 	}
300 
301 	return (1);
302 }
303 
304 unsigned int
305 rtable_l2(unsigned int rtableid)
306 {
307 	struct dommp	*dmm;
308 	unsigned int	 rdomain = 0;
309 	struct srp_ref	 sr;
310 
311 	dmm = srp_enter(&sr, &afmap[0]);
312 	if (rtableid < dmm->limit)
313 		rdomain = (dmm->value[rtableid] & RT_TABLEID_MASK);
314 	srp_leave(&sr);
315 
316 	return (rdomain);
317 }
318 
319 unsigned int
320 rtable_loindex(unsigned int rtableid)
321 {
322 	struct dommp	*dmm;
323 	unsigned int	 loifidx = 0;
324 	struct srp_ref	 sr;
325 
326 	dmm = srp_enter(&sr, &afmap[0]);
327 	if (rtableid < dmm->limit)
328 		loifidx = (dmm->value[rtableid] >> RT_TABLEID_BITS);
329 	srp_leave(&sr);
330 
331 	return (loifidx);
332 }
333 
334 void
335 rtable_l2set(unsigned int rtableid, unsigned int rdomain, unsigned int loifidx)
336 {
337 	struct dommp	*dmm;
338 	unsigned int	 value;
339 
340 	KERNEL_ASSERT_LOCKED();
341 
342 	if (!rtable_exists(rtableid) || !rtable_exists(rdomain))
343 		return;
344 
345 	value = (rdomain & RT_TABLEID_MASK) | (loifidx << RT_TABLEID_BITS);
346 
347 	dmm = srp_get_locked(&afmap[0]);
348 	dmm->value[rtableid] = value;
349 }
350 
351 
352 static inline uint8_t	*satoaddr(struct art_root *, struct sockaddr *);
353 
354 int	an_match(struct art_node *, struct sockaddr *, int);
355 void	rtentry_ref(void *, void *);
356 void	rtentry_unref(void *, void *);
357 
358 void	rtable_mpath_insert(struct art_node *, struct rtentry *);
359 
360 struct srpl_rc rt_rc = SRPL_RC_INITIALIZER(rtentry_ref, rtentry_unref, NULL);
361 
362 void
363 rtable_init_backend(void)
364 {
365 	art_init();
366 }
367 
368 void *
369 rtable_alloc(unsigned int rtableid, unsigned int alen, unsigned int off)
370 {
371 	return (art_alloc(rtableid, alen, off));
372 }
373 
374 int
375 rtable_setsource(unsigned int rtableid, int af, struct sockaddr *src)
376 {
377 	struct art_root		*ar;
378 
379 	if ((ar = rtable_get(rtableid, af)) == NULL)
380 		return (EAFNOSUPPORT);
381 
382 	ar->source = src;
383 
384 	return (0);
385 }
386 
387 struct sockaddr *
388 rtable_getsource(unsigned int rtableid, int af)
389 {
390 	struct art_root		*ar;
391 
392 	ar = rtable_get(rtableid, af);
393 	if (ar == NULL)
394 		return (NULL);
395 
396 	return (ar->source);
397 }
398 
399 void
400 rtable_clearsource(unsigned int rtableid, struct sockaddr *src)
401 {
402 	struct sockaddr	*addr;
403 
404 	addr = rtable_getsource(rtableid, src->sa_family);
405 	if (addr && (addr->sa_len == src->sa_len)) {
406 		if (memcmp(src, addr, addr->sa_len) == 0) {
407 			rtable_setsource(rtableid, src->sa_family, NULL);
408 		}
409 	}
410 }
411 
412 struct rtentry *
413 rtable_lookup(unsigned int rtableid, struct sockaddr *dst,
414     struct sockaddr *mask, struct sockaddr *gateway, uint8_t prio)
415 {
416 	struct art_root			*ar;
417 	struct art_node			*an;
418 	struct rtentry			*rt = NULL;
419 	struct srp_ref			 sr, nsr;
420 	uint8_t				*addr;
421 	int				 plen;
422 
423 	ar = rtable_get(rtableid, dst->sa_family);
424 	if (ar == NULL)
425 		return (NULL);
426 
427 	addr = satoaddr(ar, dst);
428 
429 	/* No need for a perfect match. */
430 	if (mask == NULL) {
431 		an = art_match(ar, addr, &nsr);
432 		if (an == NULL)
433 			goto out;
434 	} else {
435 		plen = rtable_satoplen(dst->sa_family, mask);
436 		if (plen == -1)
437 			return (NULL);
438 
439 		an = art_lookup(ar, addr, plen, &nsr);
440 
441 		/* Make sure we've got a perfect match. */
442 		if (!an_match(an, dst, plen))
443 			goto out;
444 	}
445 
446 	SRPL_FOREACH(rt, &sr, &an->an_rtlist, rt_next) {
447 		if (prio != RTP_ANY &&
448 		    (rt->rt_priority & RTP_MASK) != (prio & RTP_MASK))
449 			continue;
450 
451 		if (gateway == NULL)
452 			break;
453 
454 		if (rt->rt_gateway->sa_len == gateway->sa_len &&
455 		    memcmp(rt->rt_gateway, gateway, gateway->sa_len) == 0)
456 			break;
457 	}
458 	if (rt != NULL)
459 		rtref(rt);
460 
461 	SRPL_LEAVE(&sr);
462 out:
463 	srp_leave(&nsr);
464 
465 	return (rt);
466 }
467 
468 struct rtentry *
469 rtable_match(unsigned int rtableid, struct sockaddr *dst, uint32_t *src)
470 {
471 	struct art_root			*ar;
472 	struct art_node			*an;
473 	struct rtentry			*rt = NULL;
474 	struct srp_ref			 sr, nsr;
475 	uint8_t				*addr;
476 	int				 hash;
477 
478 	ar = rtable_get(rtableid, dst->sa_family);
479 	if (ar == NULL)
480 		return (NULL);
481 
482 	addr = satoaddr(ar, dst);
483 
484 	an = art_match(ar, addr, &nsr);
485 	if (an == NULL)
486 		goto out;
487 
488 	rt = SRPL_FIRST(&sr, &an->an_rtlist);
489 	rtref(rt);
490 	SRPL_LEAVE(&sr);
491 
492 	/* Gateway selection by Hash-Threshold (RFC 2992) */
493 	if ((hash = rt_hash(rt, dst, src)) != -1) {
494 		struct rtentry		*mrt;
495 		int			 threshold, npaths = 0;
496 
497 		KASSERT(hash <= 0xffff);
498 
499 		SRPL_FOREACH(mrt, &sr, &an->an_rtlist, rt_next) {
500 			/* Only count nexthops with the same priority. */
501 			if (mrt->rt_priority == rt->rt_priority)
502 				npaths++;
503 		}
504 		SRPL_LEAVE(&sr);
505 
506 		threshold = (0xffff / npaths) + 1;
507 
508 		/*
509 		 * we have no protection against concurrent modification of the
510 		 * route list attached to the node, so we won't necessarily
511 		 * have the same number of routes.  for most modifications,
512 		 * we'll pick a route that we wouldn't have if we only saw the
513 		 * list before or after the change.  if we were going to use
514 		 * the last available route, but it got removed, we'll hit
515 		 * the end of the list and then pick the first route.
516 		 */
517 
518 		mrt = SRPL_FIRST(&sr, &an->an_rtlist);
519 		while (hash > threshold && mrt != NULL) {
520 			if (mrt->rt_priority == rt->rt_priority)
521 				hash -= threshold;
522 			mrt = SRPL_FOLLOW(&sr, mrt, rt_next);
523 		}
524 
525 		if (mrt != NULL) {
526 			rtref(mrt);
527 			rtfree(rt);
528 			rt = mrt;
529 		}
530 		SRPL_LEAVE(&sr);
531 	}
532 out:
533 	srp_leave(&nsr);
534 	return (rt);
535 }
536 
537 int
538 rtable_insert(unsigned int rtableid, struct sockaddr *dst,
539     struct sockaddr *mask, struct sockaddr *gateway, uint8_t prio,
540     struct rtentry *rt)
541 {
542 	struct rtentry			*mrt;
543 	struct srp_ref			 sr;
544 	struct art_root			*ar;
545 	struct art_node			*an, *prev;
546 	uint8_t				*addr;
547 	int				 plen;
548 	unsigned int			 rt_flags;
549 	int				 error = 0;
550 
551 	ar = rtable_get(rtableid, dst->sa_family);
552 	if (ar == NULL)
553 		return (EAFNOSUPPORT);
554 
555 	addr = satoaddr(ar, dst);
556 	plen = rtable_satoplen(dst->sa_family, mask);
557 	if (plen == -1)
558 		return (EINVAL);
559 
560 	rtref(rt); /* guarantee rtfree won't do anything during insert */
561 	rw_enter_write(&ar->ar_lock);
562 
563 	/* Do not permit exactly the same dst/mask/gw pair. */
564 	an = art_lookup(ar, addr, plen, &sr);
565 	srp_leave(&sr); /* an can't go away while we have the lock */
566 	if (an_match(an, dst, plen)) {
567 		struct rtentry  *mrt;
568 		int		 mpathok = ISSET(rt->rt_flags, RTF_MPATH);
569 
570 		SRPL_FOREACH_LOCKED(mrt, &an->an_rtlist, rt_next) {
571 			if (prio != RTP_ANY &&
572 			    (mrt->rt_priority & RTP_MASK) != (prio & RTP_MASK))
573 				continue;
574 
575 			if (!mpathok ||
576 			    (mrt->rt_gateway->sa_len == gateway->sa_len &&
577 			    !memcmp(mrt->rt_gateway, gateway, gateway->sa_len))){
578 				error = EEXIST;
579 				goto leave;
580 			}
581 		}
582 	}
583 
584 	an = art_get(dst, plen);
585 	if (an == NULL) {
586 		error = ENOBUFS;
587 		goto leave;
588 	}
589 
590 	/* prepare for immediate operation if insert succeeds */
591 	rt_flags = rt->rt_flags;
592 	rt->rt_flags &= ~RTF_MPATH;
593 	rt->rt_dest = dst;
594 	rt->rt_plen = plen;
595 	SRPL_INSERT_HEAD_LOCKED(&rt_rc, &an->an_rtlist, rt, rt_next);
596 
597 	prev = art_insert(ar, an, addr, plen);
598 	if (prev != an) {
599 		SRPL_REMOVE_LOCKED(&rt_rc, &an->an_rtlist, rt, rtentry,
600 		    rt_next);
601 		rt->rt_flags = rt_flags;
602 		art_put(an);
603 
604 		if (prev == NULL) {
605 			error = ESRCH;
606 			goto leave;
607 		}
608 
609 		an = prev;
610 
611 		mrt = SRPL_FIRST_LOCKED(&an->an_rtlist);
612 		KASSERT(mrt != NULL);
613 		KASSERT((rt->rt_flags & RTF_MPATH) || mrt->rt_priority != prio);
614 
615 		/*
616 		 * An ART node with the same destination/netmask already
617 		 * exists, MPATH conflict must have been already checked.
618 		 */
619 		if (rt->rt_flags & RTF_MPATH) {
620 			/*
621 			 * Only keep the RTF_MPATH flag if two routes have
622 			 * the same gateway.
623 			 */
624 			rt->rt_flags &= ~RTF_MPATH;
625 			SRPL_FOREACH_LOCKED(mrt, &an->an_rtlist, rt_next) {
626 				if (mrt->rt_priority == prio) {
627 					mrt->rt_flags |= RTF_MPATH;
628 					rt->rt_flags |= RTF_MPATH;
629 				}
630 			}
631 		}
632 
633 		/* Put newly inserted entry at the right place. */
634 		rtable_mpath_insert(an, rt);
635 	}
636 leave:
637 	rw_exit_write(&ar->ar_lock);
638 	rtfree(rt);
639 	return (error);
640 }
641 
642 int
643 rtable_delete(unsigned int rtableid, struct sockaddr *dst,
644     struct sockaddr *mask, struct rtentry *rt)
645 {
646 	struct art_root			*ar;
647 	struct art_node			*an;
648 	struct srp_ref			 sr;
649 	uint8_t				*addr;
650 	int				 plen;
651 	struct rtentry			*mrt;
652 	int				 npaths = 0;
653 	int				 error = 0;
654 
655 	ar = rtable_get(rtableid, dst->sa_family);
656 	if (ar == NULL)
657 		return (EAFNOSUPPORT);
658 
659 	addr = satoaddr(ar, dst);
660 	plen = rtable_satoplen(dst->sa_family, mask);
661 	if (plen == -1)
662 		return (EINVAL);
663 
664 	rtref(rt); /* guarantee rtfree won't do anything under ar_lock */
665 	rw_enter_write(&ar->ar_lock);
666 	an = art_lookup(ar, addr, plen, &sr);
667 	srp_leave(&sr); /* an can't go away while we have the lock */
668 
669 	/* Make sure we've got a perfect match. */
670 	if (!an_match(an, dst, plen)) {
671 		error = ESRCH;
672 		goto leave;
673 	}
674 
675 	/*
676 	 * If other multipath route entries are still attached to
677 	 * this ART node we only have to unlink it.
678 	 */
679 	SRPL_FOREACH_LOCKED(mrt, &an->an_rtlist, rt_next)
680 		npaths++;
681 
682 	if (npaths > 1) {
683 		KASSERT(rt->rt_refcnt >= 1);
684 		SRPL_REMOVE_LOCKED(&rt_rc, &an->an_rtlist, rt, rtentry,
685 		    rt_next);
686 
687 		mrt = SRPL_FIRST_LOCKED(&an->an_rtlist);
688 		if (npaths == 2)
689 			mrt->rt_flags &= ~RTF_MPATH;
690 
691 		goto leave;
692 	}
693 
694 	if (art_delete(ar, an, addr, plen) == NULL)
695 		panic("art_delete failed to find node %p", an);
696 
697 	KASSERT(rt->rt_refcnt >= 1);
698 	SRPL_REMOVE_LOCKED(&rt_rc, &an->an_rtlist, rt, rtentry, rt_next);
699 	art_put(an);
700 
701 leave:
702 	rw_exit_write(&ar->ar_lock);
703 	rtfree(rt);
704 
705 	return (error);
706 }
707 
708 struct rtable_walk_cookie {
709 	int		(*rwc_func)(struct rtentry *, void *, unsigned int);
710 	void		 *rwc_arg;
711 	struct rtentry	**rwc_prt;
712 	unsigned int	  rwc_rid;
713 };
714 
715 /*
716  * Helper for rtable_walk to keep the ART code free from any "struct rtentry".
717  */
718 int
719 rtable_walk_helper(struct art_node *an, void *xrwc)
720 {
721 	struct srp_ref			 sr;
722 	struct rtable_walk_cookie	*rwc = xrwc;
723 	struct rtentry			*rt;
724 	int				 error = 0;
725 
726 	SRPL_FOREACH(rt, &sr, &an->an_rtlist, rt_next) {
727 		error = (*rwc->rwc_func)(rt, rwc->rwc_arg, rwc->rwc_rid);
728 		if (error != 0)
729 			break;
730 	}
731 	if (rwc->rwc_prt != NULL && rt != NULL) {
732 		rtref(rt);
733 		*rwc->rwc_prt = rt;
734 	}
735 	SRPL_LEAVE(&sr);
736 
737 	return (error);
738 }
739 
740 int
741 rtable_walk(unsigned int rtableid, sa_family_t af, struct rtentry **prt,
742     int (*func)(struct rtentry *, void *, unsigned int), void *arg)
743 {
744 	struct art_root			*ar;
745 	struct rtable_walk_cookie	 rwc;
746 	int				 error;
747 
748 	ar = rtable_get(rtableid, af);
749 	if (ar == NULL)
750 		return (EAFNOSUPPORT);
751 
752 	rwc.rwc_func = func;
753 	rwc.rwc_arg = arg;
754 	rwc.rwc_prt = prt;
755 	rwc.rwc_rid = rtableid;
756 
757 	error = art_walk(ar, rtable_walk_helper, &rwc);
758 
759 	return (error);
760 }
761 
762 struct rtentry *
763 rtable_iterate(struct rtentry *rt0)
764 {
765 	struct rtentry *rt = NULL;
766 	struct srp_ref sr;
767 
768 	rt = SRPL_NEXT(&sr, rt0, rt_next);
769 	if (rt != NULL)
770 		rtref(rt);
771 	SRPL_LEAVE(&sr);
772 	rtfree(rt0);
773 	return (rt);
774 }
775 
776 int
777 rtable_mpath_capable(unsigned int rtableid, sa_family_t af)
778 {
779 	return (1);
780 }
781 
782 int
783 rtable_mpath_reprio(unsigned int rtableid, struct sockaddr *dst,
784     int plen, uint8_t prio, struct rtentry *rt)
785 {
786 	struct art_root			*ar;
787 	struct art_node			*an;
788 	struct srp_ref			 sr;
789 	uint8_t				*addr;
790 	int				 error = 0;
791 
792 	ar = rtable_get(rtableid, dst->sa_family);
793 	if (ar == NULL)
794 		return (EAFNOSUPPORT);
795 
796 	addr = satoaddr(ar, dst);
797 
798 	rw_enter_write(&ar->ar_lock);
799 	an = art_lookup(ar, addr, plen, &sr);
800 	srp_leave(&sr); /* an can't go away while we have the lock */
801 
802 	/* Make sure we've got a perfect match. */
803 	if (!an_match(an, dst, plen)) {
804 		error = ESRCH;
805 	} else if (SRPL_FIRST_LOCKED(&an->an_rtlist) == rt &&
806 		SRPL_NEXT_LOCKED(rt, rt_next) == NULL) {
807 		/*
808 		 * If there's only one entry on the list do not go
809 		 * through an insert/remove cycle.  This is done to
810 		 * guarantee that ``an->an_rtlist''  is never empty
811 		 * when a node is in the tree.
812 		 */
813 		rt->rt_priority = prio;
814 	} else {
815 		rtref(rt); /* keep rt alive in between remove and insert */
816 		SRPL_REMOVE_LOCKED(&rt_rc, &an->an_rtlist,
817 		    rt, rtentry, rt_next);
818 		rt->rt_priority = prio;
819 		rtable_mpath_insert(an, rt);
820 		rtfree(rt);
821 		error = EAGAIN;
822 	}
823 	rw_exit_write(&ar->ar_lock);
824 
825 	return (error);
826 }
827 
828 void
829 rtable_mpath_insert(struct art_node *an, struct rtentry *rt)
830 {
831 	struct rtentry			*mrt, *prt = NULL;
832 	uint8_t				 prio = rt->rt_priority;
833 
834 	if ((mrt = SRPL_FIRST_LOCKED(&an->an_rtlist)) == NULL) {
835 		SRPL_INSERT_HEAD_LOCKED(&rt_rc, &an->an_rtlist, rt, rt_next);
836 		return;
837 	}
838 
839 	/* Iterate until we find the route to be placed after ``rt''. */
840 	while (mrt->rt_priority <= prio && SRPL_NEXT_LOCKED(mrt, rt_next)) {
841 		prt = mrt;
842 		mrt = SRPL_NEXT_LOCKED(mrt, rt_next);
843 	}
844 
845 	if (mrt->rt_priority <= prio) {
846 		SRPL_INSERT_AFTER_LOCKED(&rt_rc, mrt, rt, rt_next);
847 	} else if (prt != NULL) {
848 		SRPL_INSERT_AFTER_LOCKED(&rt_rc, prt, rt, rt_next);
849 	} else {
850 		SRPL_INSERT_HEAD_LOCKED(&rt_rc, &an->an_rtlist, rt, rt_next);
851 	}
852 }
853 
854 /*
855  * Returns 1 if ``an'' perfectly matches (``dst'', ``plen''), 0 otherwise.
856  */
857 int
858 an_match(struct art_node *an, struct sockaddr *dst, int plen)
859 {
860 	struct rtentry			*rt;
861 	struct srp_ref			 sr;
862 	int				 match;
863 
864 	if (an == NULL || an->an_plen != plen)
865 		return (0);
866 
867 	rt = SRPL_FIRST(&sr, &an->an_rtlist);
868 	match = (memcmp(rt->rt_dest, dst, dst->sa_len) == 0);
869 	SRPL_LEAVE(&sr);
870 
871 	return (match);
872 }
873 
874 void
875 rtentry_ref(void *null, void *xrt)
876 {
877 	struct rtentry *rt = xrt;
878 
879 	rtref(rt);
880 }
881 
882 void
883 rtentry_unref(void *null, void *xrt)
884 {
885 	struct rtentry *rt = xrt;
886 
887 	rtfree(rt);
888 }
889 
890 /*
891  * Return a pointer to the address (key).  This is an heritage from the
892  * BSD radix tree needed to skip the non-address fields from the flavor
893  * of "struct sockaddr" used by this routing table.
894  */
895 static inline uint8_t *
896 satoaddr(struct art_root *at, struct sockaddr *sa)
897 {
898 	return (((uint8_t *)sa) + at->ar_off);
899 }
900 
901 /*
902  * Return the prefix length of a mask.
903  */
904 int
905 rtable_satoplen(sa_family_t af, struct sockaddr *mask)
906 {
907 	const struct domain	*dp;
908 	uint8_t			*ap, *ep;
909 	int			 mlen, plen = 0;
910 	int			 i;
911 
912 	for (i = 0; (dp = domains[i]) != NULL; i++) {
913 		if (dp->dom_rtoffset == 0)
914 			continue;
915 
916 		if (af == dp->dom_family)
917 			break;
918 	}
919 	if (dp == NULL)
920 		return (-1);
921 
922 	/* Host route */
923 	if (mask == NULL)
924 		return (dp->dom_maxplen);
925 
926 	mlen = mask->sa_len;
927 
928 	/* Default route */
929 	if (mlen == 0)
930 		return (0);
931 
932 	ap = (uint8_t *)((uint8_t *)mask) + dp->dom_rtoffset;
933 	ep = (uint8_t *)((uint8_t *)mask) + mlen;
934 	if (ap > ep)
935 		return (-1);
936 
937 	/* Trim trailing zeroes. */
938 	while (ap < ep && ep[-1] == 0)
939 		ep--;
940 
941 	if (ap == ep)
942 		return (0);
943 
944 	/* "Beauty" adapted from sbin/route/show.c ... */
945 	while (ap < ep) {
946 		switch (*ap++) {
947 		case 0xff:
948 			plen += 8;
949 			break;
950 		case 0xfe:
951 			plen += 7;
952 			goto out;
953 		case 0xfc:
954 			plen += 6;
955 			goto out;
956 		case 0xf8:
957 			plen += 5;
958 			goto out;
959 		case 0xf0:
960 			plen += 4;
961 			goto out;
962 		case 0xe0:
963 			plen += 3;
964 			goto out;
965 		case 0xc0:
966 			plen += 2;
967 			goto out;
968 		case 0x80:
969 			plen += 1;
970 			goto out;
971 		default:
972 			/* Non contiguous mask. */
973 			return (-1);
974 		}
975 	}
976 
977 out:
978 	if (plen > dp->dom_maxplen || ap != ep)
979 		return -1;
980 
981 	return (plen);
982 }
983