xref: /linux/net/ipv6/ip6_fib.c (revision c0ef1446959101d23fdf1b1bdefc6613a83dba03)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *	Linux INET6 implementation
4  *	Forwarding Information Database
5  *
6  *	Authors:
7  *	Pedro Roque		<roque@di.fc.ul.pt>
8  *
9  *	Changes:
10  *	Yuji SEKIYA @USAGI:	Support default route on router node;
11  *				remove ip6_null_entry from the top of
12  *				routing table.
13  *	Ville Nuorvala:		Fixed routing subtrees.
14  */
15 
16 #define pr_fmt(fmt) "IPv6: " fmt
17 
18 #include <linux/bpf.h>
19 #include <linux/errno.h>
20 #include <linux/types.h>
21 #include <linux/net.h>
22 #include <linux/route.h>
23 #include <linux/netdevice.h>
24 #include <linux/in6.h>
25 #include <linux/init.h>
26 #include <linux/list.h>
27 #include <linux/slab.h>
28 
29 #include <net/ip.h>
30 #include <net/ipv6.h>
31 #include <net/ndisc.h>
32 #include <net/addrconf.h>
33 #include <net/lwtunnel.h>
34 #include <net/fib_notifier.h>
35 
36 #include <net/ip_fib.h>
37 #include <net/ip6_fib.h>
38 #include <net/ip6_route.h>
39 
40 static struct kmem_cache *fib6_node_kmem __read_mostly;
41 
42 struct fib6_cleaner {
43 	struct fib6_walker w;
44 	struct net *net;
45 	int (*func)(struct fib6_info *, void *arg);
46 	int sernum;
47 	void *arg;
48 	bool skip_notify;
49 };
50 
51 #ifdef CONFIG_IPV6_SUBTREES
52 #define FWS_INIT FWS_S
53 #else
54 #define FWS_INIT FWS_L
55 #endif
56 
57 static struct fib6_info *fib6_find_prefix(struct net *net,
58 					 struct fib6_table *table,
59 					 struct fib6_node *fn);
60 static struct fib6_node *fib6_repair_tree(struct net *net,
61 					  struct fib6_table *table,
62 					  struct fib6_node *fn);
63 static int fib6_walk(struct net *net, struct fib6_walker *w);
64 static int fib6_walk_continue(struct fib6_walker *w);
65 
66 /*
67  *	A routing update causes an increase of the serial number on the
68  *	affected subtree. This allows for cached routes to be asynchronously
69  *	tested when modifications are made to the destination cache as a
70  *	result of redirects, path MTU changes, etc.
71  */
72 
73 static void fib6_gc_timer_cb(struct timer_list *t);
74 
75 #define FOR_WALKERS(net, w) \
76 	list_for_each_entry(w, &(net)->ipv6.fib6_walkers, lh)
77 
78 static void fib6_walker_link(struct net *net, struct fib6_walker *w)
79 {
80 	write_lock_bh(&net->ipv6.fib6_walker_lock);
81 	list_add(&w->lh, &net->ipv6.fib6_walkers);
82 	write_unlock_bh(&net->ipv6.fib6_walker_lock);
83 }
84 
85 static void fib6_walker_unlink(struct net *net, struct fib6_walker *w)
86 {
87 	write_lock_bh(&net->ipv6.fib6_walker_lock);
88 	list_del(&w->lh);
89 	write_unlock_bh(&net->ipv6.fib6_walker_lock);
90 }
91 
92 static int fib6_new_sernum(struct net *net)
93 {
94 	int new, old = atomic_read(&net->ipv6.fib6_sernum);
95 
96 	do {
97 		new = old < INT_MAX ? old + 1 : 1;
98 	} while (!atomic_try_cmpxchg(&net->ipv6.fib6_sernum, &old, new));
99 
100 	return new;
101 }
102 
103 enum {
104 	FIB6_NO_SERNUM_CHANGE = 0,
105 };
106 
107 void fib6_update_sernum(struct net *net, struct fib6_info *f6i)
108 {
109 	struct fib6_node *fn;
110 
111 	fn = rcu_dereference_protected(f6i->fib6_node,
112 			lockdep_is_held(&f6i->fib6_table->tb6_lock));
113 	if (fn)
114 		WRITE_ONCE(fn->fn_sernum, fib6_new_sernum(net));
115 }
116 
117 /*
118  *	Auxiliary address test functions for the radix tree.
119  *
120  *	These assume a 32bit processor (although it will work on
121  *	64bit processors)
122  */
123 
124 /*
125  *	test bit
126  */
127 #if defined(__LITTLE_ENDIAN)
128 # define BITOP_BE32_SWIZZLE	(0x1F & ~7)
129 #else
130 # define BITOP_BE32_SWIZZLE	0
131 #endif
132 
133 static __be32 addr_bit_set(const void *token, int fn_bit)
134 {
135 	const __be32 *addr = token;
136 	/*
137 	 * Here,
138 	 *	1 << ((~fn_bit ^ BITOP_BE32_SWIZZLE) & 0x1f)
139 	 * is optimized version of
140 	 *	htonl(1 << ((~fn_bit)&0x1F))
141 	 * See include/asm-generic/bitops/le.h.
142 	 */
143 	return (__force __be32)(1 << ((~fn_bit ^ BITOP_BE32_SWIZZLE) & 0x1f)) &
144 	       addr[fn_bit >> 5];
145 }
146 
147 struct fib6_info *fib6_info_alloc(gfp_t gfp_flags, bool with_fib6_nh)
148 {
149 	struct fib6_info *f6i;
150 	size_t sz = sizeof(*f6i);
151 
152 	if (with_fib6_nh)
153 		sz += sizeof(struct fib6_nh);
154 
155 	f6i = kzalloc(sz, gfp_flags);
156 	if (!f6i)
157 		return NULL;
158 
159 	/* fib6_siblings is a union with nh_list, so this initializes both */
160 	INIT_LIST_HEAD(&f6i->fib6_siblings);
161 	refcount_set(&f6i->fib6_ref, 1);
162 
163 	INIT_HLIST_NODE(&f6i->gc_link);
164 
165 	return f6i;
166 }
167 
168 void fib6_info_destroy_rcu(struct rcu_head *head)
169 {
170 	struct fib6_info *f6i = container_of(head, struct fib6_info, rcu);
171 
172 	WARN_ON(f6i->fib6_node);
173 
174 	if (f6i->nh)
175 		nexthop_put(f6i->nh);
176 	else
177 		fib6_nh_release(f6i->fib6_nh);
178 
179 	ip_fib_metrics_put(f6i->fib6_metrics);
180 	kfree(f6i);
181 }
182 EXPORT_SYMBOL_GPL(fib6_info_destroy_rcu);
183 
184 static struct fib6_node *node_alloc(struct net *net)
185 {
186 	struct fib6_node *fn;
187 
188 	fn = kmem_cache_zalloc(fib6_node_kmem, GFP_ATOMIC);
189 	if (fn)
190 		net->ipv6.rt6_stats->fib_nodes++;
191 
192 	return fn;
193 }
194 
195 static void node_free_immediate(struct net *net, struct fib6_node *fn)
196 {
197 	kmem_cache_free(fib6_node_kmem, fn);
198 	net->ipv6.rt6_stats->fib_nodes--;
199 }
200 
201 static void node_free(struct net *net, struct fib6_node *fn)
202 {
203 	kfree_rcu(fn, rcu);
204 	net->ipv6.rt6_stats->fib_nodes--;
205 }
206 
207 static void fib6_free_table(struct fib6_table *table)
208 {
209 	inetpeer_invalidate_tree(&table->tb6_peers);
210 	kfree(table);
211 }
212 
213 static void fib6_link_table(struct net *net, struct fib6_table *tb)
214 {
215 	unsigned int h;
216 
217 	/*
218 	 * Initialize table lock at a single place to give lockdep a key,
219 	 * tables aren't visible prior to being linked to the list.
220 	 */
221 	spin_lock_init(&tb->tb6_lock);
222 	h = tb->tb6_id & (FIB6_TABLE_HASHSZ - 1);
223 
224 	/*
225 	 * No protection necessary, this is the only list mutatation
226 	 * operation, tables never disappear once they exist.
227 	 */
228 	hlist_add_head_rcu(&tb->tb6_hlist, &net->ipv6.fib_table_hash[h]);
229 }
230 
231 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
232 
233 static struct fib6_table *fib6_alloc_table(struct net *net, u32 id)
234 {
235 	struct fib6_table *table;
236 
237 	table = kzalloc(sizeof(*table), GFP_ATOMIC);
238 	if (table) {
239 		table->tb6_id = id;
240 		rcu_assign_pointer(table->tb6_root.leaf,
241 				   net->ipv6.fib6_null_entry);
242 		table->tb6_root.fn_flags = RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO;
243 		inet_peer_base_init(&table->tb6_peers);
244 		INIT_HLIST_HEAD(&table->tb6_gc_hlist);
245 	}
246 
247 	return table;
248 }
249 
250 struct fib6_table *fib6_new_table(struct net *net, u32 id)
251 {
252 	struct fib6_table *tb, *new_tb;
253 
254 	if (id == 0)
255 		id = RT6_TABLE_MAIN;
256 
257 	tb = fib6_get_table(net, id);
258 	if (tb)
259 		return tb;
260 
261 	new_tb = fib6_alloc_table(net, id);
262 	if (!new_tb)
263 		return NULL;
264 
265 	spin_lock_bh(&net->ipv6.fib_table_hash_lock);
266 
267 	tb = fib6_get_table(net, id);
268 	if (unlikely(tb)) {
269 		spin_unlock_bh(&net->ipv6.fib_table_hash_lock);
270 		kfree(new_tb);
271 		return tb;
272 	}
273 
274 	fib6_link_table(net, new_tb);
275 
276 	spin_unlock_bh(&net->ipv6.fib_table_hash_lock);
277 
278 	return new_tb;
279 }
280 EXPORT_SYMBOL_GPL(fib6_new_table);
281 
282 struct fib6_table *fib6_get_table(struct net *net, u32 id)
283 {
284 	struct hlist_head *head;
285 	struct fib6_table *tb;
286 
287 	if (!id)
288 		id = RT6_TABLE_MAIN;
289 
290 	head = &net->ipv6.fib_table_hash[id & (FIB6_TABLE_HASHSZ - 1)];
291 
292 	/* See comment in fib6_link_table().  RCU is not required,
293 	 * but rcu_dereference_raw() is used to avoid data-race.
294 	 */
295 	hlist_for_each_entry_rcu(tb, head, tb6_hlist, true)
296 		if (tb->tb6_id == id)
297 			return tb;
298 
299 	return NULL;
300 }
301 EXPORT_SYMBOL_GPL(fib6_get_table);
302 
303 static void __net_init fib6_tables_init(struct net *net)
304 {
305 	fib6_link_table(net, net->ipv6.fib6_main_tbl);
306 	fib6_link_table(net, net->ipv6.fib6_local_tbl);
307 }
308 #else
309 
310 struct fib6_table *fib6_new_table(struct net *net, u32 id)
311 {
312 	return fib6_get_table(net, id);
313 }
314 
315 struct fib6_table *fib6_get_table(struct net *net, u32 id)
316 {
317 	  return net->ipv6.fib6_main_tbl;
318 }
319 
320 struct dst_entry *fib6_rule_lookup(struct net *net, struct flowi6 *fl6,
321 				   const struct sk_buff *skb,
322 				   int flags, pol_lookup_t lookup)
323 {
324 	struct rt6_info *rt;
325 
326 	rt = pol_lookup_func(lookup,
327 			net, net->ipv6.fib6_main_tbl, fl6, skb, flags);
328 	if (rt->dst.error == -EAGAIN) {
329 		ip6_rt_put_flags(rt, flags);
330 		rt = net->ipv6.ip6_null_entry;
331 		if (!(flags & RT6_LOOKUP_F_DST_NOREF))
332 			dst_hold(&rt->dst);
333 	}
334 
335 	return &rt->dst;
336 }
337 
338 /* called with rcu lock held; no reference taken on fib6_info */
339 int fib6_lookup(struct net *net, int oif, struct flowi6 *fl6,
340 		struct fib6_result *res, int flags)
341 {
342 	return fib6_table_lookup(net, net->ipv6.fib6_main_tbl, oif, fl6,
343 				 res, flags);
344 }
345 
346 static void __net_init fib6_tables_init(struct net *net)
347 {
348 	fib6_link_table(net, net->ipv6.fib6_main_tbl);
349 }
350 
351 #endif
352 
353 unsigned int fib6_tables_seq_read(const struct net *net)
354 {
355 	unsigned int h, fib_seq = 0;
356 
357 	rcu_read_lock();
358 	for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
359 		const struct hlist_head *head = &net->ipv6.fib_table_hash[h];
360 		const struct fib6_table *tb;
361 
362 		hlist_for_each_entry_rcu(tb, head, tb6_hlist)
363 			fib_seq += READ_ONCE(tb->fib_seq);
364 	}
365 	rcu_read_unlock();
366 
367 	return fib_seq;
368 }
369 
370 static int call_fib6_entry_notifier(struct notifier_block *nb,
371 				    enum fib_event_type event_type,
372 				    struct fib6_info *rt,
373 				    struct netlink_ext_ack *extack)
374 {
375 	struct fib6_entry_notifier_info info = {
376 		.info.extack = extack,
377 		.rt = rt,
378 	};
379 
380 	return call_fib6_notifier(nb, event_type, &info.info);
381 }
382 
383 static int call_fib6_multipath_entry_notifier(struct notifier_block *nb,
384 					      enum fib_event_type event_type,
385 					      struct fib6_info *rt,
386 					      unsigned int nsiblings,
387 					      struct netlink_ext_ack *extack)
388 {
389 	struct fib6_entry_notifier_info info = {
390 		.info.extack = extack,
391 		.rt = rt,
392 		.nsiblings = nsiblings,
393 	};
394 
395 	return call_fib6_notifier(nb, event_type, &info.info);
396 }
397 
398 int call_fib6_entry_notifiers(struct net *net,
399 			      enum fib_event_type event_type,
400 			      struct fib6_info *rt,
401 			      struct netlink_ext_ack *extack)
402 {
403 	struct fib6_entry_notifier_info info = {
404 		.info.extack = extack,
405 		.rt = rt,
406 	};
407 
408 	WRITE_ONCE(rt->fib6_table->fib_seq, rt->fib6_table->fib_seq + 1);
409 	return call_fib6_notifiers(net, event_type, &info.info);
410 }
411 
412 int call_fib6_multipath_entry_notifiers(struct net *net,
413 					enum fib_event_type event_type,
414 					struct fib6_info *rt,
415 					unsigned int nsiblings,
416 					struct netlink_ext_ack *extack)
417 {
418 	struct fib6_entry_notifier_info info = {
419 		.info.extack = extack,
420 		.rt = rt,
421 		.nsiblings = nsiblings,
422 	};
423 
424 	WRITE_ONCE(rt->fib6_table->fib_seq, rt->fib6_table->fib_seq + 1);
425 	return call_fib6_notifiers(net, event_type, &info.info);
426 }
427 
428 int call_fib6_entry_notifiers_replace(struct net *net, struct fib6_info *rt)
429 {
430 	struct fib6_entry_notifier_info info = {
431 		.rt = rt,
432 		.nsiblings = rt->fib6_nsiblings,
433 	};
434 
435 	WRITE_ONCE(rt->fib6_table->fib_seq, rt->fib6_table->fib_seq + 1);
436 	return call_fib6_notifiers(net, FIB_EVENT_ENTRY_REPLACE, &info.info);
437 }
438 
439 struct fib6_dump_arg {
440 	struct net *net;
441 	struct notifier_block *nb;
442 	struct netlink_ext_ack *extack;
443 };
444 
445 static int fib6_rt_dump(struct fib6_info *rt, struct fib6_dump_arg *arg)
446 {
447 	enum fib_event_type fib_event = FIB_EVENT_ENTRY_REPLACE;
448 	int err;
449 
450 	if (!rt || rt == arg->net->ipv6.fib6_null_entry)
451 		return 0;
452 
453 	if (rt->fib6_nsiblings)
454 		err = call_fib6_multipath_entry_notifier(arg->nb, fib_event,
455 							 rt,
456 							 rt->fib6_nsiblings,
457 							 arg->extack);
458 	else
459 		err = call_fib6_entry_notifier(arg->nb, fib_event, rt,
460 					       arg->extack);
461 
462 	return err;
463 }
464 
465 static int fib6_node_dump(struct fib6_walker *w)
466 {
467 	int err;
468 
469 	err = fib6_rt_dump(w->leaf, w->args);
470 	w->leaf = NULL;
471 	return err;
472 }
473 
474 static int fib6_table_dump(struct net *net, struct fib6_table *tb,
475 			   struct fib6_walker *w)
476 {
477 	int err;
478 
479 	w->root = &tb->tb6_root;
480 	spin_lock_bh(&tb->tb6_lock);
481 	err = fib6_walk(net, w);
482 	spin_unlock_bh(&tb->tb6_lock);
483 	return err;
484 }
485 
486 /* Called with rcu_read_lock() */
487 int fib6_tables_dump(struct net *net, struct notifier_block *nb,
488 		     struct netlink_ext_ack *extack)
489 {
490 	struct fib6_dump_arg arg;
491 	struct fib6_walker *w;
492 	unsigned int h;
493 	int err = 0;
494 
495 	w = kzalloc(sizeof(*w), GFP_ATOMIC);
496 	if (!w)
497 		return -ENOMEM;
498 
499 	w->func = fib6_node_dump;
500 	arg.net = net;
501 	arg.nb = nb;
502 	arg.extack = extack;
503 	w->args = &arg;
504 
505 	for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
506 		struct hlist_head *head = &net->ipv6.fib_table_hash[h];
507 		struct fib6_table *tb;
508 
509 		hlist_for_each_entry_rcu(tb, head, tb6_hlist) {
510 			err = fib6_table_dump(net, tb, w);
511 			if (err)
512 				goto out;
513 		}
514 	}
515 
516 out:
517 	kfree(w);
518 
519 	/* The tree traversal function should never return a positive value. */
520 	return err > 0 ? -EINVAL : err;
521 }
522 
523 static int fib6_dump_node(struct fib6_walker *w)
524 {
525 	int res;
526 	struct fib6_info *rt;
527 
528 	for_each_fib6_walker_rt(w) {
529 		res = rt6_dump_route(rt, w->args, w->skip_in_node);
530 		if (res >= 0) {
531 			/* Frame is full, suspend walking */
532 			w->leaf = rt;
533 
534 			/* We'll restart from this node, so if some routes were
535 			 * already dumped, skip them next time.
536 			 */
537 			w->skip_in_node += res;
538 
539 			return 1;
540 		}
541 		w->skip_in_node = 0;
542 
543 		/* Multipath routes are dumped in one route with the
544 		 * RTA_MULTIPATH attribute. Jump 'rt' to point to the
545 		 * last sibling of this route (no need to dump the
546 		 * sibling routes again)
547 		 */
548 		if (rt->fib6_nsiblings)
549 			rt = list_last_entry(&rt->fib6_siblings,
550 					     struct fib6_info,
551 					     fib6_siblings);
552 	}
553 	w->leaf = NULL;
554 	return 0;
555 }
556 
557 static void fib6_dump_end(struct netlink_callback *cb)
558 {
559 	struct net *net = sock_net(cb->skb->sk);
560 	struct fib6_walker *w = (void *)cb->args[2];
561 
562 	if (w) {
563 		if (cb->args[4]) {
564 			cb->args[4] = 0;
565 			fib6_walker_unlink(net, w);
566 		}
567 		cb->args[2] = 0;
568 		kfree(w);
569 	}
570 	cb->done = (void *)cb->args[3];
571 	cb->args[1] = 3;
572 }
573 
574 static int fib6_dump_done(struct netlink_callback *cb)
575 {
576 	fib6_dump_end(cb);
577 	return cb->done ? cb->done(cb) : 0;
578 }
579 
580 static int fib6_dump_table(struct fib6_table *table, struct sk_buff *skb,
581 			   struct netlink_callback *cb)
582 {
583 	struct net *net = sock_net(skb->sk);
584 	struct fib6_walker *w;
585 	int res;
586 
587 	w = (void *)cb->args[2];
588 	w->root = &table->tb6_root;
589 
590 	if (cb->args[4] == 0) {
591 		w->count = 0;
592 		w->skip = 0;
593 		w->skip_in_node = 0;
594 
595 		spin_lock_bh(&table->tb6_lock);
596 		res = fib6_walk(net, w);
597 		spin_unlock_bh(&table->tb6_lock);
598 		if (res > 0) {
599 			cb->args[4] = 1;
600 			cb->args[5] = READ_ONCE(w->root->fn_sernum);
601 		}
602 	} else {
603 		int sernum = READ_ONCE(w->root->fn_sernum);
604 		if (cb->args[5] != sernum) {
605 			/* Begin at the root if the tree changed */
606 			cb->args[5] = sernum;
607 			w->state = FWS_INIT;
608 			w->node = w->root;
609 			w->skip = w->count;
610 			w->skip_in_node = 0;
611 		} else
612 			w->skip = 0;
613 
614 		spin_lock_bh(&table->tb6_lock);
615 		res = fib6_walk_continue(w);
616 		spin_unlock_bh(&table->tb6_lock);
617 		if (res <= 0) {
618 			fib6_walker_unlink(net, w);
619 			cb->args[4] = 0;
620 		}
621 	}
622 
623 	return res;
624 }
625 
626 static int inet6_dump_fib(struct sk_buff *skb, struct netlink_callback *cb)
627 {
628 	struct rt6_rtnl_dump_arg arg = {
629 		.filter.dump_exceptions = true,
630 		.filter.dump_routes = true,
631 		.filter.rtnl_held = false,
632 	};
633 	const struct nlmsghdr *nlh = cb->nlh;
634 	struct net *net = sock_net(skb->sk);
635 	unsigned int e = 0, s_e;
636 	struct hlist_head *head;
637 	struct fib6_walker *w;
638 	struct fib6_table *tb;
639 	unsigned int h, s_h;
640 	int err = 0;
641 
642 	rcu_read_lock();
643 	if (cb->strict_check) {
644 		err = ip_valid_fib_dump_req(net, nlh, &arg.filter, cb);
645 		if (err < 0)
646 			goto unlock;
647 	} else if (nlmsg_len(nlh) >= sizeof(struct rtmsg)) {
648 		struct rtmsg *rtm = nlmsg_data(nlh);
649 
650 		if (rtm->rtm_flags & RTM_F_PREFIX)
651 			arg.filter.flags = RTM_F_PREFIX;
652 	}
653 
654 	w = (void *)cb->args[2];
655 	if (!w) {
656 		/* New dump:
657 		 *
658 		 * 1. allocate and initialize walker.
659 		 */
660 		w = kzalloc(sizeof(*w), GFP_ATOMIC);
661 		if (!w) {
662 			err = -ENOMEM;
663 			goto unlock;
664 		}
665 		w->func = fib6_dump_node;
666 		cb->args[2] = (long)w;
667 
668 		/* 2. hook callback destructor.
669 		 */
670 		cb->args[3] = (long)cb->done;
671 		cb->done = fib6_dump_done;
672 
673 	}
674 
675 	arg.skb = skb;
676 	arg.cb = cb;
677 	arg.net = net;
678 	w->args = &arg;
679 
680 	if (arg.filter.table_id) {
681 		tb = fib6_get_table(net, arg.filter.table_id);
682 		if (!tb) {
683 			if (rtnl_msg_family(cb->nlh) != PF_INET6)
684 				goto unlock;
685 
686 			NL_SET_ERR_MSG_MOD(cb->extack, "FIB table does not exist");
687 			err = -ENOENT;
688 			goto unlock;
689 		}
690 
691 		if (!cb->args[0]) {
692 			err = fib6_dump_table(tb, skb, cb);
693 			if (!err)
694 				cb->args[0] = 1;
695 		}
696 		goto unlock;
697 	}
698 
699 	s_h = cb->args[0];
700 	s_e = cb->args[1];
701 
702 	for (h = s_h; h < FIB6_TABLE_HASHSZ; h++, s_e = 0) {
703 		e = 0;
704 		head = &net->ipv6.fib_table_hash[h];
705 		hlist_for_each_entry_rcu(tb, head, tb6_hlist) {
706 			if (e < s_e)
707 				goto next;
708 			err = fib6_dump_table(tb, skb, cb);
709 			if (err != 0)
710 				goto out;
711 next:
712 			e++;
713 		}
714 	}
715 out:
716 	cb->args[1] = e;
717 	cb->args[0] = h;
718 
719 unlock:
720 	rcu_read_unlock();
721 	if (err <= 0)
722 		fib6_dump_end(cb);
723 	return err;
724 }
725 
726 void fib6_metric_set(struct fib6_info *f6i, int metric, u32 val)
727 {
728 	if (!f6i)
729 		return;
730 
731 	if (f6i->fib6_metrics == &dst_default_metrics) {
732 		struct dst_metrics *p = kzalloc(sizeof(*p), GFP_ATOMIC);
733 
734 		if (!p)
735 			return;
736 
737 		refcount_set(&p->refcnt, 1);
738 		f6i->fib6_metrics = p;
739 	}
740 
741 	f6i->fib6_metrics->metrics[metric - 1] = val;
742 }
743 
744 /*
745  *	Routing Table
746  *
747  *	return the appropriate node for a routing tree "add" operation
748  *	by either creating and inserting or by returning an existing
749  *	node.
750  */
751 
752 static struct fib6_node *fib6_add_1(struct net *net,
753 				    struct fib6_table *table,
754 				    struct fib6_node *root,
755 				    struct in6_addr *addr, int plen,
756 				    int offset, int allow_create,
757 				    int replace_required,
758 				    struct netlink_ext_ack *extack)
759 {
760 	struct fib6_node *fn, *in, *ln;
761 	struct fib6_node *pn = NULL;
762 	struct rt6key *key;
763 	int	bit;
764 	__be32	dir = 0;
765 
766 	/* insert node in tree */
767 
768 	fn = root;
769 
770 	do {
771 		struct fib6_info *leaf = rcu_dereference_protected(fn->leaf,
772 					    lockdep_is_held(&table->tb6_lock));
773 		key = (struct rt6key *)((u8 *)leaf + offset);
774 
775 		/*
776 		 *	Prefix match
777 		 */
778 		if (plen < fn->fn_bit ||
779 		    !ipv6_prefix_equal(&key->addr, addr, fn->fn_bit)) {
780 			if (!allow_create) {
781 				if (replace_required) {
782 					NL_SET_ERR_MSG(extack,
783 						       "Can not replace route - no match found");
784 					pr_warn("Can't replace route, no match found\n");
785 					return ERR_PTR(-ENOENT);
786 				}
787 				pr_warn("NLM_F_CREATE should be set when creating new route\n");
788 			}
789 			goto insert_above;
790 		}
791 
792 		/*
793 		 *	Exact match ?
794 		 */
795 
796 		if (plen == fn->fn_bit) {
797 			/* clean up an intermediate node */
798 			if (!(fn->fn_flags & RTN_RTINFO)) {
799 				RCU_INIT_POINTER(fn->leaf, NULL);
800 				fib6_info_release(leaf);
801 			/* remove null_entry in the root node */
802 			} else if (fn->fn_flags & RTN_TL_ROOT &&
803 				   rcu_access_pointer(fn->leaf) ==
804 				   net->ipv6.fib6_null_entry) {
805 				RCU_INIT_POINTER(fn->leaf, NULL);
806 			}
807 
808 			return fn;
809 		}
810 
811 		/*
812 		 *	We have more bits to go
813 		 */
814 
815 		/* Try to walk down on tree. */
816 		dir = addr_bit_set(addr, fn->fn_bit);
817 		pn = fn;
818 		fn = dir ?
819 		     rcu_dereference_protected(fn->right,
820 					lockdep_is_held(&table->tb6_lock)) :
821 		     rcu_dereference_protected(fn->left,
822 					lockdep_is_held(&table->tb6_lock));
823 	} while (fn);
824 
825 	if (!allow_create) {
826 		/* We should not create new node because
827 		 * NLM_F_REPLACE was specified without NLM_F_CREATE
828 		 * I assume it is safe to require NLM_F_CREATE when
829 		 * REPLACE flag is used! Later we may want to remove the
830 		 * check for replace_required, because according
831 		 * to netlink specification, NLM_F_CREATE
832 		 * MUST be specified if new route is created.
833 		 * That would keep IPv6 consistent with IPv4
834 		 */
835 		if (replace_required) {
836 			NL_SET_ERR_MSG(extack,
837 				       "Can not replace route - no match found");
838 			pr_warn("Can't replace route, no match found\n");
839 			return ERR_PTR(-ENOENT);
840 		}
841 		pr_warn("NLM_F_CREATE should be set when creating new route\n");
842 	}
843 	/*
844 	 *	We walked to the bottom of tree.
845 	 *	Create new leaf node without children.
846 	 */
847 
848 	ln = node_alloc(net);
849 
850 	if (!ln)
851 		return ERR_PTR(-ENOMEM);
852 	ln->fn_bit = plen;
853 	RCU_INIT_POINTER(ln->parent, pn);
854 
855 	if (dir)
856 		rcu_assign_pointer(pn->right, ln);
857 	else
858 		rcu_assign_pointer(pn->left, ln);
859 
860 	return ln;
861 
862 
863 insert_above:
864 	/*
865 	 * split since we don't have a common prefix anymore or
866 	 * we have a less significant route.
867 	 * we've to insert an intermediate node on the list
868 	 * this new node will point to the one we need to create
869 	 * and the current
870 	 */
871 
872 	pn = rcu_dereference_protected(fn->parent,
873 				       lockdep_is_held(&table->tb6_lock));
874 
875 	/* find 1st bit in difference between the 2 addrs.
876 
877 	   See comment in __ipv6_addr_diff: bit may be an invalid value,
878 	   but if it is >= plen, the value is ignored in any case.
879 	 */
880 
881 	bit = __ipv6_addr_diff(addr, &key->addr, sizeof(*addr));
882 
883 	/*
884 	 *		(intermediate)[in]
885 	 *	          /	   \
886 	 *	(new leaf node)[ln] (old node)[fn]
887 	 */
888 	if (plen > bit) {
889 		in = node_alloc(net);
890 		ln = node_alloc(net);
891 
892 		if (!in || !ln) {
893 			if (in)
894 				node_free_immediate(net, in);
895 			if (ln)
896 				node_free_immediate(net, ln);
897 			return ERR_PTR(-ENOMEM);
898 		}
899 
900 		/*
901 		 * new intermediate node.
902 		 * RTN_RTINFO will
903 		 * be off since that an address that chooses one of
904 		 * the branches would not match less specific routes
905 		 * in the other branch
906 		 */
907 
908 		in->fn_bit = bit;
909 
910 		RCU_INIT_POINTER(in->parent, pn);
911 		in->leaf = fn->leaf;
912 		fib6_info_hold(rcu_dereference_protected(in->leaf,
913 				lockdep_is_held(&table->tb6_lock)));
914 
915 		/* update parent pointer */
916 		if (dir)
917 			rcu_assign_pointer(pn->right, in);
918 		else
919 			rcu_assign_pointer(pn->left, in);
920 
921 		ln->fn_bit = plen;
922 
923 		RCU_INIT_POINTER(ln->parent, in);
924 		rcu_assign_pointer(fn->parent, in);
925 
926 		if (addr_bit_set(addr, bit)) {
927 			rcu_assign_pointer(in->right, ln);
928 			rcu_assign_pointer(in->left, fn);
929 		} else {
930 			rcu_assign_pointer(in->left, ln);
931 			rcu_assign_pointer(in->right, fn);
932 		}
933 	} else { /* plen <= bit */
934 
935 		/*
936 		 *		(new leaf node)[ln]
937 		 *	          /	   \
938 		 *	     (old node)[fn] NULL
939 		 */
940 
941 		ln = node_alloc(net);
942 
943 		if (!ln)
944 			return ERR_PTR(-ENOMEM);
945 
946 		ln->fn_bit = plen;
947 
948 		RCU_INIT_POINTER(ln->parent, pn);
949 
950 		if (addr_bit_set(&key->addr, plen))
951 			RCU_INIT_POINTER(ln->right, fn);
952 		else
953 			RCU_INIT_POINTER(ln->left, fn);
954 
955 		rcu_assign_pointer(fn->parent, ln);
956 
957 		if (dir)
958 			rcu_assign_pointer(pn->right, ln);
959 		else
960 			rcu_assign_pointer(pn->left, ln);
961 	}
962 	return ln;
963 }
964 
965 static void __fib6_drop_pcpu_from(struct fib6_nh *fib6_nh,
966 				  const struct fib6_info *match)
967 {
968 	int cpu;
969 
970 	if (!fib6_nh->rt6i_pcpu)
971 		return;
972 
973 	rcu_read_lock();
974 	/* release the reference to this fib entry from
975 	 * all of its cached pcpu routes
976 	 */
977 	for_each_possible_cpu(cpu) {
978 		struct rt6_info **ppcpu_rt;
979 		struct rt6_info *pcpu_rt;
980 
981 		ppcpu_rt = per_cpu_ptr(fib6_nh->rt6i_pcpu, cpu);
982 
983 		/* Paired with xchg() in rt6_get_pcpu_route() */
984 		pcpu_rt = READ_ONCE(*ppcpu_rt);
985 
986 		/* only dropping the 'from' reference if the cached route
987 		 * is using 'match'. The cached pcpu_rt->from only changes
988 		 * from a fib6_info to NULL (ip6_dst_destroy); it can never
989 		 * change from one fib6_info reference to another
990 		 */
991 		if (pcpu_rt && rcu_access_pointer(pcpu_rt->from) == match) {
992 			struct fib6_info *from;
993 
994 			from = unrcu_pointer(xchg(&pcpu_rt->from, NULL));
995 			fib6_info_release(from);
996 		}
997 	}
998 	rcu_read_unlock();
999 }
1000 
1001 static int fib6_nh_drop_pcpu_from(struct fib6_nh *nh, void *_arg)
1002 {
1003 	struct fib6_info *arg = _arg;
1004 
1005 	__fib6_drop_pcpu_from(nh, arg);
1006 	return 0;
1007 }
1008 
1009 static void fib6_drop_pcpu_from(struct fib6_info *f6i)
1010 {
1011 	/* Make sure rt6_make_pcpu_route() wont add other percpu routes
1012 	 * while we are cleaning them here.
1013 	 */
1014 	f6i->fib6_destroying = 1;
1015 	mb(); /* paired with the cmpxchg() in rt6_make_pcpu_route() */
1016 
1017 	if (f6i->nh) {
1018 		rcu_read_lock();
1019 		nexthop_for_each_fib6_nh(f6i->nh, fib6_nh_drop_pcpu_from, f6i);
1020 		rcu_read_unlock();
1021 	} else {
1022 		struct fib6_nh *fib6_nh;
1023 
1024 		fib6_nh = f6i->fib6_nh;
1025 		__fib6_drop_pcpu_from(fib6_nh, f6i);
1026 	}
1027 }
1028 
1029 static void fib6_purge_rt(struct fib6_info *rt, struct fib6_node *fn,
1030 			  struct net *net)
1031 {
1032 	struct fib6_table *table = rt->fib6_table;
1033 
1034 	/* Flush all cached dst in exception table */
1035 	rt6_flush_exceptions(rt);
1036 	fib6_drop_pcpu_from(rt);
1037 
1038 	if (rt->nh) {
1039 		spin_lock(&rt->nh->lock);
1040 
1041 		if (!list_empty(&rt->nh_list))
1042 			list_del_init(&rt->nh_list);
1043 
1044 		spin_unlock(&rt->nh->lock);
1045 	}
1046 
1047 	if (refcount_read(&rt->fib6_ref) != 1) {
1048 		/* This route is used as dummy address holder in some split
1049 		 * nodes. It is not leaked, but it still holds other resources,
1050 		 * which must be released in time. So, scan ascendant nodes
1051 		 * and replace dummy references to this route with references
1052 		 * to still alive ones.
1053 		 */
1054 		while (fn) {
1055 			struct fib6_info *leaf = rcu_dereference_protected(fn->leaf,
1056 					    lockdep_is_held(&table->tb6_lock));
1057 			struct fib6_info *new_leaf;
1058 			if (!(fn->fn_flags & RTN_RTINFO) && leaf == rt) {
1059 				new_leaf = fib6_find_prefix(net, table, fn);
1060 				fib6_info_hold(new_leaf);
1061 
1062 				rcu_assign_pointer(fn->leaf, new_leaf);
1063 				fib6_info_release(rt);
1064 			}
1065 			fn = rcu_dereference_protected(fn->parent,
1066 				    lockdep_is_held(&table->tb6_lock));
1067 		}
1068 	}
1069 
1070 	fib6_clean_expires(rt);
1071 	fib6_remove_gc_list(rt);
1072 }
1073 
1074 /*
1075  *	Insert routing information in a node.
1076  */
1077 
1078 static int fib6_add_rt2node(struct fib6_node *fn, struct fib6_info *rt,
1079 			    struct nl_info *info, struct netlink_ext_ack *extack,
1080 			    struct list_head *purge_list)
1081 {
1082 	struct fib6_info *leaf = rcu_dereference_protected(fn->leaf,
1083 				    lockdep_is_held(&rt->fib6_table->tb6_lock));
1084 	struct fib6_info *iter = NULL;
1085 	struct fib6_info __rcu **ins;
1086 	struct fib6_info __rcu **fallback_ins = NULL;
1087 	int replace = (info->nlh &&
1088 		       (info->nlh->nlmsg_flags & NLM_F_REPLACE));
1089 	int add = (!info->nlh ||
1090 		   (info->nlh->nlmsg_flags & NLM_F_CREATE));
1091 	int found = 0;
1092 	bool rt_can_ecmp = rt6_qualify_for_ecmp(rt);
1093 	bool notify_sibling_rt = false;
1094 	u16 nlflags = NLM_F_EXCL;
1095 	int err;
1096 
1097 	if (info->nlh && (info->nlh->nlmsg_flags & NLM_F_APPEND))
1098 		nlflags |= NLM_F_APPEND;
1099 
1100 	ins = &fn->leaf;
1101 
1102 	for (iter = leaf; iter;
1103 	     iter = rcu_dereference_protected(iter->fib6_next,
1104 				lockdep_is_held(&rt->fib6_table->tb6_lock))) {
1105 		/*
1106 		 *	Search for duplicates
1107 		 */
1108 
1109 		if (iter->fib6_metric == rt->fib6_metric) {
1110 			/*
1111 			 *	Same priority level
1112 			 */
1113 			if (info->nlh &&
1114 			    (info->nlh->nlmsg_flags & NLM_F_EXCL))
1115 				return -EEXIST;
1116 
1117 			nlflags &= ~NLM_F_EXCL;
1118 			if (replace) {
1119 				if (rt_can_ecmp == rt6_qualify_for_ecmp(iter)) {
1120 					found++;
1121 					break;
1122 				}
1123 				fallback_ins = fallback_ins ?: ins;
1124 				goto next_iter;
1125 			}
1126 
1127 			if (rt6_duplicate_nexthop(iter, rt)) {
1128 				if (rt->fib6_nsiblings)
1129 					rt->fib6_nsiblings = 0;
1130 				if (!(iter->fib6_flags & RTF_EXPIRES))
1131 					return -EEXIST;
1132 				if (!(rt->fib6_flags & RTF_EXPIRES)) {
1133 					fib6_clean_expires(iter);
1134 					fib6_remove_gc_list(iter);
1135 				} else {
1136 					fib6_set_expires(iter, rt->expires);
1137 					fib6_add_gc_list(iter);
1138 				}
1139 
1140 				if (rt->fib6_pmtu)
1141 					fib6_metric_set(iter, RTAX_MTU,
1142 							rt->fib6_pmtu);
1143 				return -EEXIST;
1144 			}
1145 			/* If we have the same destination and the same metric,
1146 			 * but not the same gateway, then the route we try to
1147 			 * add is sibling to this route, increment our counter
1148 			 * of siblings, and later we will add our route to the
1149 			 * list.
1150 			 * Only static routes (which don't have flag
1151 			 * RTF_EXPIRES) are used for ECMPv6.
1152 			 *
1153 			 * To avoid long list, we only had siblings if the
1154 			 * route have a gateway.
1155 			 */
1156 			if (rt_can_ecmp &&
1157 			    rt6_qualify_for_ecmp(iter))
1158 				rt->fib6_nsiblings++;
1159 		}
1160 
1161 		if (iter->fib6_metric > rt->fib6_metric)
1162 			break;
1163 
1164 next_iter:
1165 		ins = &iter->fib6_next;
1166 	}
1167 
1168 	if (fallback_ins && !found) {
1169 		/* No matching route with same ecmp-able-ness found, replace
1170 		 * first matching route
1171 		 */
1172 		ins = fallback_ins;
1173 		iter = rcu_dereference_protected(*ins,
1174 				    lockdep_is_held(&rt->fib6_table->tb6_lock));
1175 		found++;
1176 	}
1177 
1178 	/* Reset round-robin state, if necessary */
1179 	if (ins == &fn->leaf)
1180 		fn->rr_ptr = NULL;
1181 
1182 	/* Link this route to others same route. */
1183 	if (rt->fib6_nsiblings) {
1184 		unsigned int fib6_nsiblings;
1185 		struct fib6_info *sibling, *temp_sibling;
1186 
1187 		/* Find the first route that have the same metric */
1188 		sibling = leaf;
1189 		notify_sibling_rt = true;
1190 		while (sibling) {
1191 			if (sibling->fib6_metric == rt->fib6_metric &&
1192 			    rt6_qualify_for_ecmp(sibling)) {
1193 				list_add_tail_rcu(&rt->fib6_siblings,
1194 						  &sibling->fib6_siblings);
1195 				break;
1196 			}
1197 			sibling = rcu_dereference_protected(sibling->fib6_next,
1198 				    lockdep_is_held(&rt->fib6_table->tb6_lock));
1199 			notify_sibling_rt = false;
1200 		}
1201 		/* For each sibling in the list, increment the counter of
1202 		 * siblings. BUG() if counters does not match, list of siblings
1203 		 * is broken!
1204 		 */
1205 		fib6_nsiblings = 0;
1206 		list_for_each_entry_safe(sibling, temp_sibling,
1207 					 &rt->fib6_siblings, fib6_siblings) {
1208 			sibling->fib6_nsiblings++;
1209 			BUG_ON(sibling->fib6_nsiblings != rt->fib6_nsiblings);
1210 			fib6_nsiblings++;
1211 		}
1212 		BUG_ON(fib6_nsiblings != rt->fib6_nsiblings);
1213 		rcu_read_lock();
1214 		rt6_multipath_rebalance(temp_sibling);
1215 		rcu_read_unlock();
1216 	}
1217 
1218 	/*
1219 	 *	insert node
1220 	 */
1221 	if (!replace) {
1222 		if (!add)
1223 			pr_warn("NLM_F_CREATE should be set when creating new route\n");
1224 
1225 add:
1226 		nlflags |= NLM_F_CREATE;
1227 
1228 		/* The route should only be notified if it is the first
1229 		 * route in the node or if it is added as a sibling
1230 		 * route to the first route in the node.
1231 		 */
1232 		if (!info->skip_notify_kernel &&
1233 		    (notify_sibling_rt || ins == &fn->leaf)) {
1234 			enum fib_event_type fib_event;
1235 
1236 			if (notify_sibling_rt)
1237 				fib_event = FIB_EVENT_ENTRY_APPEND;
1238 			else
1239 				fib_event = FIB_EVENT_ENTRY_REPLACE;
1240 			err = call_fib6_entry_notifiers(info->nl_net,
1241 							fib_event, rt,
1242 							extack);
1243 			if (err) {
1244 				struct fib6_info *sibling, *next_sibling;
1245 
1246 				/* If the route has siblings, then it first
1247 				 * needs to be unlinked from them.
1248 				 */
1249 				if (!rt->fib6_nsiblings)
1250 					return err;
1251 
1252 				list_for_each_entry_safe(sibling, next_sibling,
1253 							 &rt->fib6_siblings,
1254 							 fib6_siblings)
1255 					sibling->fib6_nsiblings--;
1256 				rt->fib6_nsiblings = 0;
1257 				list_del_rcu(&rt->fib6_siblings);
1258 				rcu_read_lock();
1259 				rt6_multipath_rebalance(next_sibling);
1260 				rcu_read_unlock();
1261 				return err;
1262 			}
1263 		}
1264 
1265 		rcu_assign_pointer(rt->fib6_next, iter);
1266 		fib6_info_hold(rt);
1267 		rcu_assign_pointer(rt->fib6_node, fn);
1268 		rcu_assign_pointer(*ins, rt);
1269 		if (!info->skip_notify)
1270 			inet6_rt_notify(RTM_NEWROUTE, rt, info, nlflags);
1271 		info->nl_net->ipv6.rt6_stats->fib_rt_entries++;
1272 
1273 		if (!(fn->fn_flags & RTN_RTINFO)) {
1274 			info->nl_net->ipv6.rt6_stats->fib_route_nodes++;
1275 			fn->fn_flags |= RTN_RTINFO;
1276 		}
1277 
1278 	} else {
1279 		int nsiblings;
1280 
1281 		if (!found) {
1282 			if (add)
1283 				goto add;
1284 			pr_warn("NLM_F_REPLACE set, but no existing node found!\n");
1285 			return -ENOENT;
1286 		}
1287 
1288 		if (!info->skip_notify_kernel && ins == &fn->leaf) {
1289 			err = call_fib6_entry_notifiers(info->nl_net,
1290 							FIB_EVENT_ENTRY_REPLACE,
1291 							rt, extack);
1292 			if (err)
1293 				return err;
1294 		}
1295 
1296 		fib6_info_hold(rt);
1297 		rcu_assign_pointer(rt->fib6_node, fn);
1298 		rt->fib6_next = iter->fib6_next;
1299 		rcu_assign_pointer(*ins, rt);
1300 		if (!info->skip_notify)
1301 			inet6_rt_notify(RTM_NEWROUTE, rt, info, NLM_F_REPLACE);
1302 		if (!(fn->fn_flags & RTN_RTINFO)) {
1303 			info->nl_net->ipv6.rt6_stats->fib_route_nodes++;
1304 			fn->fn_flags |= RTN_RTINFO;
1305 		}
1306 		nsiblings = iter->fib6_nsiblings;
1307 		iter->fib6_node = NULL;
1308 		list_add(&iter->purge_link, purge_list);
1309 		if (rcu_access_pointer(fn->rr_ptr) == iter)
1310 			fn->rr_ptr = NULL;
1311 
1312 		if (nsiblings) {
1313 			/* Replacing an ECMP route, remove all siblings */
1314 			ins = &rt->fib6_next;
1315 			iter = rcu_dereference_protected(*ins,
1316 				    lockdep_is_held(&rt->fib6_table->tb6_lock));
1317 			while (iter) {
1318 				if (iter->fib6_metric > rt->fib6_metric)
1319 					break;
1320 				if (rt6_qualify_for_ecmp(iter)) {
1321 					*ins = iter->fib6_next;
1322 					iter->fib6_node = NULL;
1323 					list_add(&iter->purge_link, purge_list);
1324 					if (rcu_access_pointer(fn->rr_ptr) == iter)
1325 						fn->rr_ptr = NULL;
1326 					nsiblings--;
1327 					info->nl_net->ipv6.rt6_stats->fib_rt_entries--;
1328 				} else {
1329 					ins = &iter->fib6_next;
1330 				}
1331 				iter = rcu_dereference_protected(*ins,
1332 					lockdep_is_held(&rt->fib6_table->tb6_lock));
1333 			}
1334 			WARN_ON(nsiblings != 0);
1335 		}
1336 	}
1337 
1338 	return 0;
1339 }
1340 
1341 static int fib6_add_rt2node_nh(struct fib6_node *fn, struct fib6_info *rt,
1342 			       struct nl_info *info, struct netlink_ext_ack *extack,
1343 			       struct list_head *purge_list)
1344 {
1345 	int err;
1346 
1347 	spin_lock(&rt->nh->lock);
1348 
1349 	if (rt->nh->dead) {
1350 		NL_SET_ERR_MSG(extack, "Nexthop has been deleted");
1351 		err = -EINVAL;
1352 	} else {
1353 		err = fib6_add_rt2node(fn, rt, info, extack, purge_list);
1354 		if (!err)
1355 			list_add(&rt->nh_list, &rt->nh->f6i_list);
1356 	}
1357 
1358 	spin_unlock(&rt->nh->lock);
1359 
1360 	return err;
1361 }
1362 
1363 static void fib6_start_gc(struct net *net, struct fib6_info *rt)
1364 {
1365 	if (!timer_pending(&net->ipv6.ip6_fib_timer) &&
1366 	    (rt->fib6_flags & RTF_EXPIRES))
1367 		mod_timer(&net->ipv6.ip6_fib_timer,
1368 			  jiffies + net->ipv6.sysctl.ip6_rt_gc_interval);
1369 }
1370 
1371 void fib6_force_start_gc(struct net *net)
1372 {
1373 	if (!timer_pending(&net->ipv6.ip6_fib_timer))
1374 		mod_timer(&net->ipv6.ip6_fib_timer,
1375 			  jiffies + net->ipv6.sysctl.ip6_rt_gc_interval);
1376 }
1377 
1378 static void __fib6_update_sernum_upto_root(struct fib6_info *rt,
1379 					   int sernum)
1380 {
1381 	struct fib6_node *fn = rcu_dereference_protected(rt->fib6_node,
1382 				lockdep_is_held(&rt->fib6_table->tb6_lock));
1383 
1384 	/* paired with smp_rmb() in fib6_get_cookie_safe() */
1385 	smp_wmb();
1386 	while (fn) {
1387 		WRITE_ONCE(fn->fn_sernum, sernum);
1388 		fn = rcu_dereference_protected(fn->parent,
1389 				lockdep_is_held(&rt->fib6_table->tb6_lock));
1390 	}
1391 }
1392 
1393 void fib6_update_sernum_upto_root(struct net *net, struct fib6_info *rt)
1394 {
1395 	__fib6_update_sernum_upto_root(rt, fib6_new_sernum(net));
1396 }
1397 
1398 /* allow ipv4 to update sernum via ipv6_stub */
1399 void fib6_update_sernum_stub(struct net *net, struct fib6_info *f6i)
1400 {
1401 	spin_lock_bh(&f6i->fib6_table->tb6_lock);
1402 	fib6_update_sernum_upto_root(net, f6i);
1403 	spin_unlock_bh(&f6i->fib6_table->tb6_lock);
1404 }
1405 
1406 /*
1407  *	Add routing information to the routing tree.
1408  *	<destination addr>/<source addr>
1409  *	with source addr info in sub-trees
1410  *	Need to own table->tb6_lock
1411  */
1412 
1413 int fib6_add(struct fib6_node *root, struct fib6_info *rt,
1414 	     struct nl_info *info, struct netlink_ext_ack *extack)
1415 {
1416 	struct fib6_table *table = rt->fib6_table;
1417 	LIST_HEAD(purge_list);
1418 	struct fib6_node *fn;
1419 #ifdef CONFIG_IPV6_SUBTREES
1420 	struct fib6_node *pn = NULL;
1421 #endif
1422 	int err = -ENOMEM;
1423 	int allow_create = 1;
1424 	int replace_required = 0;
1425 
1426 	if (info->nlh) {
1427 		if (!(info->nlh->nlmsg_flags & NLM_F_CREATE))
1428 			allow_create = 0;
1429 		if (info->nlh->nlmsg_flags & NLM_F_REPLACE)
1430 			replace_required = 1;
1431 	}
1432 	if (!allow_create && !replace_required)
1433 		pr_warn("RTM_NEWROUTE with no NLM_F_CREATE or NLM_F_REPLACE\n");
1434 
1435 	fn = fib6_add_1(info->nl_net, table, root,
1436 			&rt->fib6_dst.addr, rt->fib6_dst.plen,
1437 			offsetof(struct fib6_info, fib6_dst), allow_create,
1438 			replace_required, extack);
1439 	if (IS_ERR(fn)) {
1440 		err = PTR_ERR(fn);
1441 		fn = NULL;
1442 		goto out;
1443 	}
1444 
1445 #ifdef CONFIG_IPV6_SUBTREES
1446 	pn = fn;
1447 
1448 	if (rt->fib6_src.plen) {
1449 		struct fib6_node *sn;
1450 
1451 		if (!rcu_access_pointer(fn->subtree)) {
1452 			struct fib6_node *sfn;
1453 
1454 			/*
1455 			 * Create subtree.
1456 			 *
1457 			 *		fn[main tree]
1458 			 *		|
1459 			 *		sfn[subtree root]
1460 			 *		   \
1461 			 *		    sn[new leaf node]
1462 			 */
1463 
1464 			/* Create subtree root node */
1465 			sfn = node_alloc(info->nl_net);
1466 			if (!sfn)
1467 				goto failure;
1468 
1469 			fib6_info_hold(info->nl_net->ipv6.fib6_null_entry);
1470 			rcu_assign_pointer(sfn->leaf,
1471 					   info->nl_net->ipv6.fib6_null_entry);
1472 			sfn->fn_flags = RTN_ROOT;
1473 
1474 			/* Now add the first leaf node to new subtree */
1475 
1476 			sn = fib6_add_1(info->nl_net, table, sfn,
1477 					&rt->fib6_src.addr, rt->fib6_src.plen,
1478 					offsetof(struct fib6_info, fib6_src),
1479 					allow_create, replace_required, extack);
1480 
1481 			if (IS_ERR(sn)) {
1482 				/* If it is failed, discard just allocated
1483 				   root, and then (in failure) stale node
1484 				   in main tree.
1485 				 */
1486 				node_free_immediate(info->nl_net, sfn);
1487 				err = PTR_ERR(sn);
1488 				goto failure;
1489 			}
1490 
1491 			/* Now link new subtree to main tree */
1492 			rcu_assign_pointer(sfn->parent, fn);
1493 			rcu_assign_pointer(fn->subtree, sfn);
1494 		} else {
1495 			sn = fib6_add_1(info->nl_net, table, FIB6_SUBTREE(fn),
1496 					&rt->fib6_src.addr, rt->fib6_src.plen,
1497 					offsetof(struct fib6_info, fib6_src),
1498 					allow_create, replace_required, extack);
1499 
1500 			if (IS_ERR(sn)) {
1501 				err = PTR_ERR(sn);
1502 				goto failure;
1503 			}
1504 		}
1505 
1506 		if (!rcu_access_pointer(fn->leaf)) {
1507 			if (fn->fn_flags & RTN_TL_ROOT) {
1508 				/* put back null_entry for root node */
1509 				rcu_assign_pointer(fn->leaf,
1510 					    info->nl_net->ipv6.fib6_null_entry);
1511 			} else {
1512 				fib6_info_hold(rt);
1513 				rcu_assign_pointer(fn->leaf, rt);
1514 			}
1515 		}
1516 		fn = sn;
1517 	}
1518 #endif
1519 
1520 	if (rt->nh)
1521 		err = fib6_add_rt2node_nh(fn, rt, info, extack, &purge_list);
1522 	else
1523 		err = fib6_add_rt2node(fn, rt, info, extack, &purge_list);
1524 	if (!err) {
1525 		struct fib6_info *iter, *next;
1526 
1527 		list_for_each_entry_safe(iter, next, &purge_list, purge_link) {
1528 			list_del(&iter->purge_link);
1529 			fib6_purge_rt(iter, fn, info->nl_net);
1530 			fib6_info_release(iter);
1531 		}
1532 
1533 		__fib6_update_sernum_upto_root(rt, fib6_new_sernum(info->nl_net));
1534 
1535 		if (rt->fib6_flags & RTF_EXPIRES)
1536 			fib6_add_gc_list(rt);
1537 
1538 		fib6_start_gc(info->nl_net, rt);
1539 	}
1540 
1541 out:
1542 	if (err) {
1543 #ifdef CONFIG_IPV6_SUBTREES
1544 		/*
1545 		 * If fib6_add_1 has cleared the old leaf pointer in the
1546 		 * super-tree leaf node we have to find a new one for it.
1547 		 */
1548 		if (pn != fn) {
1549 			struct fib6_info *pn_leaf =
1550 				rcu_dereference_protected(pn->leaf,
1551 				    lockdep_is_held(&table->tb6_lock));
1552 			if (pn_leaf == rt) {
1553 				pn_leaf = NULL;
1554 				RCU_INIT_POINTER(pn->leaf, NULL);
1555 				fib6_info_release(rt);
1556 			}
1557 			if (!pn_leaf && !(pn->fn_flags & RTN_RTINFO)) {
1558 				pn_leaf = fib6_find_prefix(info->nl_net, table,
1559 							   pn);
1560 				if (!pn_leaf)
1561 					pn_leaf =
1562 					    info->nl_net->ipv6.fib6_null_entry;
1563 				fib6_info_hold(pn_leaf);
1564 				rcu_assign_pointer(pn->leaf, pn_leaf);
1565 			}
1566 		}
1567 #endif
1568 		goto failure;
1569 	} else if (fib6_requires_src(rt)) {
1570 		fib6_routes_require_src_inc(info->nl_net);
1571 	}
1572 	return err;
1573 
1574 failure:
1575 	/* fn->leaf could be NULL and fib6_repair_tree() needs to be called if:
1576 	 * 1. fn is an intermediate node and we failed to add the new
1577 	 * route to it in both subtree creation failure and fib6_add_rt2node()
1578 	 * failure case.
1579 	 * 2. fn is the root node in the table and we fail to add the first
1580 	 * default route to it.
1581 	 */
1582 	if (fn &&
1583 	    (!(fn->fn_flags & (RTN_RTINFO|RTN_ROOT)) ||
1584 	     (fn->fn_flags & RTN_TL_ROOT &&
1585 	      !rcu_access_pointer(fn->leaf))))
1586 		fib6_repair_tree(info->nl_net, table, fn);
1587 	return err;
1588 }
1589 
1590 /*
1591  *	Routing tree lookup
1592  *
1593  */
1594 
1595 struct lookup_args {
1596 	int			offset;		/* key offset on fib6_info */
1597 	const struct in6_addr	*addr;		/* search key			*/
1598 };
1599 
1600 static struct fib6_node *fib6_node_lookup_1(struct fib6_node *root,
1601 					    struct lookup_args *args)
1602 {
1603 	struct fib6_node *fn;
1604 	__be32 dir;
1605 
1606 	if (unlikely(args->offset == 0))
1607 		return NULL;
1608 
1609 	/*
1610 	 *	Descend on a tree
1611 	 */
1612 
1613 	fn = root;
1614 
1615 	for (;;) {
1616 		struct fib6_node *next;
1617 
1618 		dir = addr_bit_set(args->addr, fn->fn_bit);
1619 
1620 		next = dir ? rcu_dereference(fn->right) :
1621 			     rcu_dereference(fn->left);
1622 
1623 		if (next) {
1624 			fn = next;
1625 			continue;
1626 		}
1627 		break;
1628 	}
1629 
1630 	while (fn) {
1631 		struct fib6_node *subtree = FIB6_SUBTREE(fn);
1632 
1633 		if (subtree || fn->fn_flags & RTN_RTINFO) {
1634 			struct fib6_info *leaf = rcu_dereference(fn->leaf);
1635 			struct rt6key *key;
1636 
1637 			if (!leaf)
1638 				goto backtrack;
1639 
1640 			key = (struct rt6key *) ((u8 *)leaf + args->offset);
1641 
1642 			if (ipv6_prefix_equal(&key->addr, args->addr, key->plen)) {
1643 #ifdef CONFIG_IPV6_SUBTREES
1644 				if (subtree) {
1645 					struct fib6_node *sfn;
1646 					sfn = fib6_node_lookup_1(subtree,
1647 								 args + 1);
1648 					if (!sfn)
1649 						goto backtrack;
1650 					fn = sfn;
1651 				}
1652 #endif
1653 				if (fn->fn_flags & RTN_RTINFO)
1654 					return fn;
1655 			}
1656 		}
1657 backtrack:
1658 		if (fn->fn_flags & RTN_ROOT)
1659 			break;
1660 
1661 		fn = rcu_dereference(fn->parent);
1662 	}
1663 
1664 	return NULL;
1665 }
1666 
1667 /* called with rcu_read_lock() held
1668  */
1669 struct fib6_node *fib6_node_lookup(struct fib6_node *root,
1670 				   const struct in6_addr *daddr,
1671 				   const struct in6_addr *saddr)
1672 {
1673 	struct fib6_node *fn;
1674 	struct lookup_args args[] = {
1675 		{
1676 			.offset = offsetof(struct fib6_info, fib6_dst),
1677 			.addr = daddr,
1678 		},
1679 #ifdef CONFIG_IPV6_SUBTREES
1680 		{
1681 			.offset = offsetof(struct fib6_info, fib6_src),
1682 			.addr = saddr,
1683 		},
1684 #endif
1685 		{
1686 			.offset = 0,	/* sentinel */
1687 		}
1688 	};
1689 
1690 	fn = fib6_node_lookup_1(root, daddr ? args : args + 1);
1691 	if (!fn || fn->fn_flags & RTN_TL_ROOT)
1692 		fn = root;
1693 
1694 	return fn;
1695 }
1696 
1697 /*
1698  *	Get node with specified destination prefix (and source prefix,
1699  *	if subtrees are used)
1700  *	exact_match == true means we try to find fn with exact match of
1701  *	the passed in prefix addr
1702  *	exact_match == false means we try to find fn with longest prefix
1703  *	match of the passed in prefix addr. This is useful for finding fn
1704  *	for cached route as it will be stored in the exception table under
1705  *	the node with longest prefix length.
1706  */
1707 
1708 
1709 static struct fib6_node *fib6_locate_1(struct fib6_node *root,
1710 				       const struct in6_addr *addr,
1711 				       int plen, int offset,
1712 				       bool exact_match)
1713 {
1714 	struct fib6_node *fn, *prev = NULL;
1715 
1716 	for (fn = root; fn ; ) {
1717 		struct fib6_info *leaf = rcu_dereference(fn->leaf);
1718 		struct rt6key *key;
1719 
1720 		/* This node is being deleted */
1721 		if (!leaf) {
1722 			if (plen <= fn->fn_bit)
1723 				goto out;
1724 			else
1725 				goto next;
1726 		}
1727 
1728 		key = (struct rt6key *)((u8 *)leaf + offset);
1729 
1730 		/*
1731 		 *	Prefix match
1732 		 */
1733 		if (plen < fn->fn_bit ||
1734 		    !ipv6_prefix_equal(&key->addr, addr, fn->fn_bit))
1735 			goto out;
1736 
1737 		if (plen == fn->fn_bit)
1738 			return fn;
1739 
1740 		if (fn->fn_flags & RTN_RTINFO)
1741 			prev = fn;
1742 
1743 next:
1744 		/*
1745 		 *	We have more bits to go
1746 		 */
1747 		if (addr_bit_set(addr, fn->fn_bit))
1748 			fn = rcu_dereference(fn->right);
1749 		else
1750 			fn = rcu_dereference(fn->left);
1751 	}
1752 out:
1753 	if (exact_match)
1754 		return NULL;
1755 	else
1756 		return prev;
1757 }
1758 
1759 struct fib6_node *fib6_locate(struct fib6_node *root,
1760 			      const struct in6_addr *daddr, int dst_len,
1761 			      const struct in6_addr *saddr, int src_len,
1762 			      bool exact_match)
1763 {
1764 	struct fib6_node *fn;
1765 
1766 	fn = fib6_locate_1(root, daddr, dst_len,
1767 			   offsetof(struct fib6_info, fib6_dst),
1768 			   exact_match);
1769 
1770 #ifdef CONFIG_IPV6_SUBTREES
1771 	if (src_len) {
1772 		WARN_ON(saddr == NULL);
1773 		if (fn) {
1774 			struct fib6_node *subtree = FIB6_SUBTREE(fn);
1775 
1776 			if (subtree) {
1777 				fn = fib6_locate_1(subtree, saddr, src_len,
1778 					   offsetof(struct fib6_info, fib6_src),
1779 					   exact_match);
1780 			}
1781 		}
1782 	}
1783 #endif
1784 
1785 	if (fn && fn->fn_flags & RTN_RTINFO)
1786 		return fn;
1787 
1788 	return NULL;
1789 }
1790 
1791 
1792 /*
1793  *	Deletion
1794  *
1795  */
1796 
1797 static struct fib6_info *fib6_find_prefix(struct net *net,
1798 					 struct fib6_table *table,
1799 					 struct fib6_node *fn)
1800 {
1801 	struct fib6_node *child_left, *child_right;
1802 
1803 	if (fn->fn_flags & RTN_ROOT)
1804 		return net->ipv6.fib6_null_entry;
1805 
1806 	while (fn) {
1807 		child_left = rcu_dereference_protected(fn->left,
1808 				    lockdep_is_held(&table->tb6_lock));
1809 		child_right = rcu_dereference_protected(fn->right,
1810 				    lockdep_is_held(&table->tb6_lock));
1811 		if (child_left)
1812 			return rcu_dereference_protected(child_left->leaf,
1813 					lockdep_is_held(&table->tb6_lock));
1814 		if (child_right)
1815 			return rcu_dereference_protected(child_right->leaf,
1816 					lockdep_is_held(&table->tb6_lock));
1817 
1818 		fn = FIB6_SUBTREE(fn);
1819 	}
1820 	return NULL;
1821 }
1822 
1823 /*
1824  *	Called to trim the tree of intermediate nodes when possible. "fn"
1825  *	is the node we want to try and remove.
1826  *	Need to own table->tb6_lock
1827  */
1828 
1829 static struct fib6_node *fib6_repair_tree(struct net *net,
1830 					  struct fib6_table *table,
1831 					  struct fib6_node *fn)
1832 {
1833 	int children;
1834 	int nstate;
1835 	struct fib6_node *child;
1836 	struct fib6_walker *w;
1837 	int iter = 0;
1838 
1839 	/* Set fn->leaf to null_entry for root node. */
1840 	if (fn->fn_flags & RTN_TL_ROOT) {
1841 		rcu_assign_pointer(fn->leaf, net->ipv6.fib6_null_entry);
1842 		return fn;
1843 	}
1844 
1845 	for (;;) {
1846 		struct fib6_node *fn_r = rcu_dereference_protected(fn->right,
1847 					    lockdep_is_held(&table->tb6_lock));
1848 		struct fib6_node *fn_l = rcu_dereference_protected(fn->left,
1849 					    lockdep_is_held(&table->tb6_lock));
1850 		struct fib6_node *pn = rcu_dereference_protected(fn->parent,
1851 					    lockdep_is_held(&table->tb6_lock));
1852 		struct fib6_node *pn_r = rcu_dereference_protected(pn->right,
1853 					    lockdep_is_held(&table->tb6_lock));
1854 		struct fib6_node *pn_l = rcu_dereference_protected(pn->left,
1855 					    lockdep_is_held(&table->tb6_lock));
1856 		struct fib6_info *fn_leaf = rcu_dereference_protected(fn->leaf,
1857 					    lockdep_is_held(&table->tb6_lock));
1858 		struct fib6_info *pn_leaf = rcu_dereference_protected(pn->leaf,
1859 					    lockdep_is_held(&table->tb6_lock));
1860 		struct fib6_info *new_fn_leaf;
1861 
1862 		pr_debug("fixing tree: plen=%d iter=%d\n", fn->fn_bit, iter);
1863 		iter++;
1864 
1865 		WARN_ON(fn->fn_flags & RTN_RTINFO);
1866 		WARN_ON(fn->fn_flags & RTN_TL_ROOT);
1867 		WARN_ON(fn_leaf);
1868 
1869 		children = 0;
1870 		child = NULL;
1871 		if (fn_r) {
1872 			child = fn_r;
1873 			children |= 1;
1874 		}
1875 		if (fn_l) {
1876 			child = fn_l;
1877 			children |= 2;
1878 		}
1879 
1880 		if (children == 3 || FIB6_SUBTREE(fn)
1881 #ifdef CONFIG_IPV6_SUBTREES
1882 		    /* Subtree root (i.e. fn) may have one child */
1883 		    || (children && fn->fn_flags & RTN_ROOT)
1884 #endif
1885 		    ) {
1886 			new_fn_leaf = fib6_find_prefix(net, table, fn);
1887 #if RT6_DEBUG >= 2
1888 			if (!new_fn_leaf) {
1889 				WARN_ON(!new_fn_leaf);
1890 				new_fn_leaf = net->ipv6.fib6_null_entry;
1891 			}
1892 #endif
1893 			fib6_info_hold(new_fn_leaf);
1894 			rcu_assign_pointer(fn->leaf, new_fn_leaf);
1895 			return pn;
1896 		}
1897 
1898 #ifdef CONFIG_IPV6_SUBTREES
1899 		if (FIB6_SUBTREE(pn) == fn) {
1900 			WARN_ON(!(fn->fn_flags & RTN_ROOT));
1901 			RCU_INIT_POINTER(pn->subtree, NULL);
1902 			nstate = FWS_L;
1903 		} else {
1904 			WARN_ON(fn->fn_flags & RTN_ROOT);
1905 #endif
1906 			if (pn_r == fn)
1907 				rcu_assign_pointer(pn->right, child);
1908 			else if (pn_l == fn)
1909 				rcu_assign_pointer(pn->left, child);
1910 #if RT6_DEBUG >= 2
1911 			else
1912 				WARN_ON(1);
1913 #endif
1914 			if (child)
1915 				rcu_assign_pointer(child->parent, pn);
1916 			nstate = FWS_R;
1917 #ifdef CONFIG_IPV6_SUBTREES
1918 		}
1919 #endif
1920 
1921 		read_lock(&net->ipv6.fib6_walker_lock);
1922 		FOR_WALKERS(net, w) {
1923 			if (!child) {
1924 				if (w->node == fn) {
1925 					pr_debug("W %p adjusted by delnode 1, s=%d/%d\n",
1926 						 w, w->state, nstate);
1927 					w->node = pn;
1928 					w->state = nstate;
1929 				}
1930 			} else {
1931 				if (w->node == fn) {
1932 					w->node = child;
1933 					if (children&2) {
1934 						pr_debug("W %p adjusted by delnode 2, s=%d\n",
1935 							 w, w->state);
1936 						w->state = w->state >= FWS_R ? FWS_U : FWS_INIT;
1937 					} else {
1938 						pr_debug("W %p adjusted by delnode 2, s=%d\n",
1939 							 w, w->state);
1940 						w->state = w->state >= FWS_C ? FWS_U : FWS_INIT;
1941 					}
1942 				}
1943 			}
1944 		}
1945 		read_unlock(&net->ipv6.fib6_walker_lock);
1946 
1947 		node_free(net, fn);
1948 		if (pn->fn_flags & RTN_RTINFO || FIB6_SUBTREE(pn))
1949 			return pn;
1950 
1951 		RCU_INIT_POINTER(pn->leaf, NULL);
1952 		fib6_info_release(pn_leaf);
1953 		fn = pn;
1954 	}
1955 }
1956 
1957 static void fib6_del_route(struct fib6_table *table, struct fib6_node *fn,
1958 			   struct fib6_info __rcu **rtp, struct nl_info *info)
1959 {
1960 	struct fib6_info *leaf, *replace_rt = NULL;
1961 	struct fib6_walker *w;
1962 	struct fib6_info *rt = rcu_dereference_protected(*rtp,
1963 				    lockdep_is_held(&table->tb6_lock));
1964 	struct net *net = info->nl_net;
1965 	bool notify_del = false;
1966 
1967 	/* If the deleted route is the first in the node and it is not part of
1968 	 * a multipath route, then we need to replace it with the next route
1969 	 * in the node, if exists.
1970 	 */
1971 	leaf = rcu_dereference_protected(fn->leaf,
1972 					 lockdep_is_held(&table->tb6_lock));
1973 	if (leaf == rt && !rt->fib6_nsiblings) {
1974 		if (rcu_access_pointer(rt->fib6_next))
1975 			replace_rt = rcu_dereference_protected(rt->fib6_next,
1976 					    lockdep_is_held(&table->tb6_lock));
1977 		else
1978 			notify_del = true;
1979 	}
1980 
1981 	/* Unlink it */
1982 	*rtp = rt->fib6_next;
1983 	rt->fib6_node = NULL;
1984 	net->ipv6.rt6_stats->fib_rt_entries--;
1985 	net->ipv6.rt6_stats->fib_discarded_routes++;
1986 
1987 	/* Reset round-robin state, if necessary */
1988 	if (rcu_access_pointer(fn->rr_ptr) == rt)
1989 		fn->rr_ptr = NULL;
1990 
1991 	/* Remove this entry from other siblings */
1992 	if (rt->fib6_nsiblings) {
1993 		struct fib6_info *sibling, *next_sibling;
1994 
1995 		/* The route is deleted from a multipath route. If this
1996 		 * multipath route is the first route in the node, then we need
1997 		 * to emit a delete notification. Otherwise, we need to skip
1998 		 * the notification.
1999 		 */
2000 		if (rt->fib6_metric == leaf->fib6_metric &&
2001 		    rt6_qualify_for_ecmp(leaf))
2002 			notify_del = true;
2003 		list_for_each_entry_safe(sibling, next_sibling,
2004 					 &rt->fib6_siblings, fib6_siblings)
2005 			sibling->fib6_nsiblings--;
2006 		rt->fib6_nsiblings = 0;
2007 		list_del_rcu(&rt->fib6_siblings);
2008 		rt6_multipath_rebalance(next_sibling);
2009 	}
2010 
2011 	/* Adjust walkers */
2012 	read_lock(&net->ipv6.fib6_walker_lock);
2013 	FOR_WALKERS(net, w) {
2014 		if (w->state == FWS_C && w->leaf == rt) {
2015 			pr_debug("walker %p adjusted by delroute\n", w);
2016 			w->leaf = rcu_dereference_protected(rt->fib6_next,
2017 					    lockdep_is_held(&table->tb6_lock));
2018 			if (!w->leaf)
2019 				w->state = FWS_U;
2020 		}
2021 	}
2022 	read_unlock(&net->ipv6.fib6_walker_lock);
2023 
2024 	/* If it was last route, call fib6_repair_tree() to:
2025 	 * 1. For root node, put back null_entry as how the table was created.
2026 	 * 2. For other nodes, expunge its radix tree node.
2027 	 */
2028 	if (!rcu_access_pointer(fn->leaf)) {
2029 		if (!(fn->fn_flags & RTN_TL_ROOT)) {
2030 			fn->fn_flags &= ~RTN_RTINFO;
2031 			net->ipv6.rt6_stats->fib_route_nodes--;
2032 		}
2033 		fn = fib6_repair_tree(net, table, fn);
2034 	}
2035 
2036 	fib6_purge_rt(rt, fn, net);
2037 
2038 	if (!info->skip_notify_kernel) {
2039 		if (notify_del)
2040 			call_fib6_entry_notifiers(net, FIB_EVENT_ENTRY_DEL,
2041 						  rt, NULL);
2042 		else if (replace_rt)
2043 			call_fib6_entry_notifiers_replace(net, replace_rt);
2044 	}
2045 	if (!info->skip_notify)
2046 		inet6_rt_notify(RTM_DELROUTE, rt, info, 0);
2047 
2048 	fib6_info_release(rt);
2049 }
2050 
2051 /* Need to own table->tb6_lock */
2052 int fib6_del(struct fib6_info *rt, struct nl_info *info)
2053 {
2054 	struct net *net = info->nl_net;
2055 	struct fib6_info __rcu **rtp;
2056 	struct fib6_info __rcu **rtp_next;
2057 	struct fib6_table *table;
2058 	struct fib6_node *fn;
2059 
2060 	if (rt == net->ipv6.fib6_null_entry)
2061 		return -ENOENT;
2062 
2063 	table = rt->fib6_table;
2064 	fn = rcu_dereference_protected(rt->fib6_node,
2065 				       lockdep_is_held(&table->tb6_lock));
2066 	if (!fn)
2067 		return -ENOENT;
2068 
2069 	WARN_ON(!(fn->fn_flags & RTN_RTINFO));
2070 
2071 	/*
2072 	 *	Walk the leaf entries looking for ourself
2073 	 */
2074 
2075 	for (rtp = &fn->leaf; *rtp; rtp = rtp_next) {
2076 		struct fib6_info *cur = rcu_dereference_protected(*rtp,
2077 					lockdep_is_held(&table->tb6_lock));
2078 		if (rt == cur) {
2079 			if (fib6_requires_src(cur))
2080 				fib6_routes_require_src_dec(info->nl_net);
2081 			fib6_del_route(table, fn, rtp, info);
2082 			return 0;
2083 		}
2084 		rtp_next = &cur->fib6_next;
2085 	}
2086 	return -ENOENT;
2087 }
2088 
2089 /*
2090  *	Tree traversal function.
2091  *
2092  *	Certainly, it is not interrupt safe.
2093  *	However, it is internally reenterable wrt itself and fib6_add/fib6_del.
2094  *	It means, that we can modify tree during walking
2095  *	and use this function for garbage collection, clone pruning,
2096  *	cleaning tree when a device goes down etc. etc.
2097  *
2098  *	It guarantees that every node will be traversed,
2099  *	and that it will be traversed only once.
2100  *
2101  *	Callback function w->func may return:
2102  *	0 -> continue walking.
2103  *	positive value -> walking is suspended (used by tree dumps,
2104  *	and probably by gc, if it will be split to several slices)
2105  *	negative value -> terminate walking.
2106  *
2107  *	The function itself returns:
2108  *	0   -> walk is complete.
2109  *	>0  -> walk is incomplete (i.e. suspended)
2110  *	<0  -> walk is terminated by an error.
2111  *
2112  *	This function is called with tb6_lock held.
2113  */
2114 
2115 static int fib6_walk_continue(struct fib6_walker *w)
2116 {
2117 	struct fib6_node *fn, *pn, *left, *right;
2118 
2119 	/* w->root should always be table->tb6_root */
2120 	WARN_ON_ONCE(!(w->root->fn_flags & RTN_TL_ROOT));
2121 
2122 	for (;;) {
2123 		fn = w->node;
2124 		if (!fn)
2125 			return 0;
2126 
2127 		switch (w->state) {
2128 #ifdef CONFIG_IPV6_SUBTREES
2129 		case FWS_S:
2130 			if (FIB6_SUBTREE(fn)) {
2131 				w->node = FIB6_SUBTREE(fn);
2132 				continue;
2133 			}
2134 			w->state = FWS_L;
2135 			fallthrough;
2136 #endif
2137 		case FWS_L:
2138 			left = rcu_dereference_protected(fn->left, 1);
2139 			if (left) {
2140 				w->node = left;
2141 				w->state = FWS_INIT;
2142 				continue;
2143 			}
2144 			w->state = FWS_R;
2145 			fallthrough;
2146 		case FWS_R:
2147 			right = rcu_dereference_protected(fn->right, 1);
2148 			if (right) {
2149 				w->node = right;
2150 				w->state = FWS_INIT;
2151 				continue;
2152 			}
2153 			w->state = FWS_C;
2154 			w->leaf = rcu_dereference_protected(fn->leaf, 1);
2155 			fallthrough;
2156 		case FWS_C:
2157 			if (w->leaf && fn->fn_flags & RTN_RTINFO) {
2158 				int err;
2159 
2160 				if (w->skip) {
2161 					w->skip--;
2162 					goto skip;
2163 				}
2164 
2165 				err = w->func(w);
2166 				if (err)
2167 					return err;
2168 
2169 				w->count++;
2170 				continue;
2171 			}
2172 skip:
2173 			w->state = FWS_U;
2174 			fallthrough;
2175 		case FWS_U:
2176 			if (fn == w->root)
2177 				return 0;
2178 			pn = rcu_dereference_protected(fn->parent, 1);
2179 			left = rcu_dereference_protected(pn->left, 1);
2180 			right = rcu_dereference_protected(pn->right, 1);
2181 			w->node = pn;
2182 #ifdef CONFIG_IPV6_SUBTREES
2183 			if (FIB6_SUBTREE(pn) == fn) {
2184 				WARN_ON(!(fn->fn_flags & RTN_ROOT));
2185 				w->state = FWS_L;
2186 				continue;
2187 			}
2188 #endif
2189 			if (left == fn) {
2190 				w->state = FWS_R;
2191 				continue;
2192 			}
2193 			if (right == fn) {
2194 				w->state = FWS_C;
2195 				w->leaf = rcu_dereference_protected(w->node->leaf, 1);
2196 				continue;
2197 			}
2198 #if RT6_DEBUG >= 2
2199 			WARN_ON(1);
2200 #endif
2201 		}
2202 	}
2203 }
2204 
2205 static int fib6_walk(struct net *net, struct fib6_walker *w)
2206 {
2207 	int res;
2208 
2209 	w->state = FWS_INIT;
2210 	w->node = w->root;
2211 
2212 	fib6_walker_link(net, w);
2213 	res = fib6_walk_continue(w);
2214 	if (res <= 0)
2215 		fib6_walker_unlink(net, w);
2216 	return res;
2217 }
2218 
2219 static int fib6_clean_node(struct fib6_walker *w)
2220 {
2221 	int res;
2222 	struct fib6_info *rt;
2223 	struct fib6_cleaner *c = container_of(w, struct fib6_cleaner, w);
2224 	struct nl_info info = {
2225 		.nl_net = c->net,
2226 		.skip_notify = c->skip_notify,
2227 	};
2228 
2229 	if (c->sernum != FIB6_NO_SERNUM_CHANGE &&
2230 	    READ_ONCE(w->node->fn_sernum) != c->sernum)
2231 		WRITE_ONCE(w->node->fn_sernum, c->sernum);
2232 
2233 	if (!c->func) {
2234 		WARN_ON_ONCE(c->sernum == FIB6_NO_SERNUM_CHANGE);
2235 		w->leaf = NULL;
2236 		return 0;
2237 	}
2238 
2239 	for_each_fib6_walker_rt(w) {
2240 		res = c->func(rt, c->arg);
2241 		if (res == -1) {
2242 			w->leaf = rt;
2243 			res = fib6_del(rt, &info);
2244 			if (res) {
2245 #if RT6_DEBUG >= 2
2246 				pr_debug("%s: del failed: rt=%p@%p err=%d\n",
2247 					 __func__, rt,
2248 					 rcu_access_pointer(rt->fib6_node),
2249 					 res);
2250 #endif
2251 				continue;
2252 			}
2253 			return 0;
2254 		} else if (res == -2) {
2255 			if (WARN_ON(!rt->fib6_nsiblings))
2256 				continue;
2257 			rt = list_last_entry(&rt->fib6_siblings,
2258 					     struct fib6_info, fib6_siblings);
2259 			continue;
2260 		}
2261 		WARN_ON(res != 0);
2262 	}
2263 	w->leaf = rt;
2264 	return 0;
2265 }
2266 
2267 /*
2268  *	Convenient frontend to tree walker.
2269  *
2270  *	func is called on each route.
2271  *		It may return -2 -> skip multipath route.
2272  *			      -1 -> delete this route.
2273  *		              0  -> continue walking
2274  */
2275 
2276 static void fib6_clean_tree(struct net *net, struct fib6_node *root,
2277 			    int (*func)(struct fib6_info *, void *arg),
2278 			    int sernum, void *arg, bool skip_notify)
2279 {
2280 	struct fib6_cleaner c;
2281 
2282 	c.w.root = root;
2283 	c.w.func = fib6_clean_node;
2284 	c.w.count = 0;
2285 	c.w.skip = 0;
2286 	c.w.skip_in_node = 0;
2287 	c.func = func;
2288 	c.sernum = sernum;
2289 	c.arg = arg;
2290 	c.net = net;
2291 	c.skip_notify = skip_notify;
2292 
2293 	fib6_walk(net, &c.w);
2294 }
2295 
2296 static void __fib6_clean_all(struct net *net,
2297 			     int (*func)(struct fib6_info *, void *),
2298 			     int sernum, void *arg, bool skip_notify)
2299 {
2300 	struct fib6_table *table;
2301 	struct hlist_head *head;
2302 	unsigned int h;
2303 
2304 	rcu_read_lock();
2305 	for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
2306 		head = &net->ipv6.fib_table_hash[h];
2307 		hlist_for_each_entry_rcu(table, head, tb6_hlist) {
2308 			spin_lock_bh(&table->tb6_lock);
2309 			fib6_clean_tree(net, &table->tb6_root,
2310 					func, sernum, arg, skip_notify);
2311 			spin_unlock_bh(&table->tb6_lock);
2312 		}
2313 	}
2314 	rcu_read_unlock();
2315 }
2316 
2317 void fib6_clean_all(struct net *net, int (*func)(struct fib6_info *, void *),
2318 		    void *arg)
2319 {
2320 	__fib6_clean_all(net, func, FIB6_NO_SERNUM_CHANGE, arg, false);
2321 }
2322 
2323 void fib6_clean_all_skip_notify(struct net *net,
2324 				int (*func)(struct fib6_info *, void *),
2325 				void *arg)
2326 {
2327 	__fib6_clean_all(net, func, FIB6_NO_SERNUM_CHANGE, arg, true);
2328 }
2329 
2330 static void fib6_flush_trees(struct net *net)
2331 {
2332 	int new_sernum = fib6_new_sernum(net);
2333 
2334 	__fib6_clean_all(net, NULL, new_sernum, NULL, false);
2335 }
2336 
2337 /*
2338  *	Garbage collection
2339  */
2340 
2341 static int fib6_age(struct fib6_info *rt, struct fib6_gc_args *gc_args)
2342 {
2343 	unsigned long now = jiffies;
2344 
2345 	/*
2346 	 *	check addrconf expiration here.
2347 	 *	Routes are expired even if they are in use.
2348 	 */
2349 
2350 	if (rt->fib6_flags & RTF_EXPIRES && rt->expires) {
2351 		if (time_after(now, rt->expires)) {
2352 			pr_debug("expiring %p\n", rt);
2353 			return -1;
2354 		}
2355 		gc_args->more++;
2356 	}
2357 
2358 	/*	Also age clones in the exception table.
2359 	 *	Note, that clones are aged out
2360 	 *	only if they are not in use now.
2361 	 */
2362 	rt6_age_exceptions(rt, gc_args, now);
2363 
2364 	return 0;
2365 }
2366 
2367 static void fib6_gc_table(struct net *net,
2368 			  struct fib6_table *tb6,
2369 			  struct fib6_gc_args *gc_args)
2370 {
2371 	struct fib6_info *rt;
2372 	struct hlist_node *n;
2373 	struct nl_info info = {
2374 		.nl_net = net,
2375 		.skip_notify = false,
2376 	};
2377 
2378 	hlist_for_each_entry_safe(rt, n, &tb6->tb6_gc_hlist, gc_link)
2379 		if (fib6_age(rt, gc_args) == -1)
2380 			fib6_del(rt, &info);
2381 }
2382 
2383 static void fib6_gc_all(struct net *net, struct fib6_gc_args *gc_args)
2384 {
2385 	struct fib6_table *table;
2386 	struct hlist_head *head;
2387 	unsigned int h;
2388 
2389 	rcu_read_lock();
2390 	for (h = 0; h < FIB6_TABLE_HASHSZ; h++) {
2391 		head = &net->ipv6.fib_table_hash[h];
2392 		hlist_for_each_entry_rcu(table, head, tb6_hlist) {
2393 			spin_lock_bh(&table->tb6_lock);
2394 
2395 			fib6_gc_table(net, table, gc_args);
2396 
2397 			spin_unlock_bh(&table->tb6_lock);
2398 		}
2399 	}
2400 	rcu_read_unlock();
2401 }
2402 
2403 void fib6_run_gc(unsigned long expires, struct net *net, bool force)
2404 {
2405 	struct fib6_gc_args gc_args;
2406 	unsigned long now;
2407 
2408 	if (force) {
2409 		spin_lock_bh(&net->ipv6.fib6_gc_lock);
2410 	} else if (!spin_trylock_bh(&net->ipv6.fib6_gc_lock)) {
2411 		mod_timer(&net->ipv6.ip6_fib_timer, jiffies + HZ);
2412 		return;
2413 	}
2414 	gc_args.timeout = expires ? (int)expires :
2415 			  net->ipv6.sysctl.ip6_rt_gc_interval;
2416 	gc_args.more = 0;
2417 
2418 	fib6_gc_all(net, &gc_args);
2419 	now = jiffies;
2420 	net->ipv6.ip6_rt_last_gc = now;
2421 
2422 	if (gc_args.more)
2423 		mod_timer(&net->ipv6.ip6_fib_timer,
2424 			  round_jiffies(now
2425 					+ net->ipv6.sysctl.ip6_rt_gc_interval));
2426 	else
2427 		timer_delete(&net->ipv6.ip6_fib_timer);
2428 	spin_unlock_bh(&net->ipv6.fib6_gc_lock);
2429 }
2430 
2431 static void fib6_gc_timer_cb(struct timer_list *t)
2432 {
2433 	struct net *arg = timer_container_of(arg, t, ipv6.ip6_fib_timer);
2434 
2435 	fib6_run_gc(0, arg, true);
2436 }
2437 
2438 static int __net_init fib6_net_init(struct net *net)
2439 {
2440 	size_t size = sizeof(struct hlist_head) * FIB6_TABLE_HASHSZ;
2441 	int err;
2442 
2443 	err = fib6_notifier_init(net);
2444 	if (err)
2445 		return err;
2446 
2447 	/* Default to 3-tuple */
2448 	net->ipv6.sysctl.multipath_hash_fields =
2449 		FIB_MULTIPATH_HASH_FIELD_DEFAULT_MASK;
2450 
2451 	spin_lock_init(&net->ipv6.fib6_gc_lock);
2452 	rwlock_init(&net->ipv6.fib6_walker_lock);
2453 	INIT_LIST_HEAD(&net->ipv6.fib6_walkers);
2454 	timer_setup(&net->ipv6.ip6_fib_timer, fib6_gc_timer_cb, 0);
2455 
2456 	net->ipv6.rt6_stats = kzalloc(sizeof(*net->ipv6.rt6_stats), GFP_KERNEL);
2457 	if (!net->ipv6.rt6_stats)
2458 		goto out_notifier;
2459 
2460 	/* Avoid false sharing : Use at least a full cache line */
2461 	size = max_t(size_t, size, L1_CACHE_BYTES);
2462 
2463 	net->ipv6.fib_table_hash = kzalloc(size, GFP_KERNEL);
2464 	if (!net->ipv6.fib_table_hash)
2465 		goto out_rt6_stats;
2466 
2467 	spin_lock_init(&net->ipv6.fib_table_hash_lock);
2468 
2469 	net->ipv6.fib6_main_tbl = kzalloc(sizeof(*net->ipv6.fib6_main_tbl),
2470 					  GFP_KERNEL);
2471 	if (!net->ipv6.fib6_main_tbl)
2472 		goto out_fib_table_hash;
2473 
2474 	net->ipv6.fib6_main_tbl->tb6_id = RT6_TABLE_MAIN;
2475 	rcu_assign_pointer(net->ipv6.fib6_main_tbl->tb6_root.leaf,
2476 			   net->ipv6.fib6_null_entry);
2477 	net->ipv6.fib6_main_tbl->tb6_root.fn_flags =
2478 		RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO;
2479 	inet_peer_base_init(&net->ipv6.fib6_main_tbl->tb6_peers);
2480 	INIT_HLIST_HEAD(&net->ipv6.fib6_main_tbl->tb6_gc_hlist);
2481 
2482 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
2483 	net->ipv6.fib6_local_tbl = kzalloc(sizeof(*net->ipv6.fib6_local_tbl),
2484 					   GFP_KERNEL);
2485 	if (!net->ipv6.fib6_local_tbl)
2486 		goto out_fib6_main_tbl;
2487 	net->ipv6.fib6_local_tbl->tb6_id = RT6_TABLE_LOCAL;
2488 	rcu_assign_pointer(net->ipv6.fib6_local_tbl->tb6_root.leaf,
2489 			   net->ipv6.fib6_null_entry);
2490 	net->ipv6.fib6_local_tbl->tb6_root.fn_flags =
2491 		RTN_ROOT | RTN_TL_ROOT | RTN_RTINFO;
2492 	inet_peer_base_init(&net->ipv6.fib6_local_tbl->tb6_peers);
2493 	INIT_HLIST_HEAD(&net->ipv6.fib6_local_tbl->tb6_gc_hlist);
2494 #endif
2495 	fib6_tables_init(net);
2496 
2497 	return 0;
2498 
2499 #ifdef CONFIG_IPV6_MULTIPLE_TABLES
2500 out_fib6_main_tbl:
2501 	kfree(net->ipv6.fib6_main_tbl);
2502 #endif
2503 out_fib_table_hash:
2504 	kfree(net->ipv6.fib_table_hash);
2505 out_rt6_stats:
2506 	kfree(net->ipv6.rt6_stats);
2507 out_notifier:
2508 	fib6_notifier_exit(net);
2509 	return -ENOMEM;
2510 }
2511 
2512 static void fib6_net_exit(struct net *net)
2513 {
2514 	unsigned int i;
2515 
2516 	timer_delete_sync(&net->ipv6.ip6_fib_timer);
2517 
2518 	for (i = 0; i < FIB6_TABLE_HASHSZ; i++) {
2519 		struct hlist_head *head = &net->ipv6.fib_table_hash[i];
2520 		struct hlist_node *tmp;
2521 		struct fib6_table *tb;
2522 
2523 		hlist_for_each_entry_safe(tb, tmp, head, tb6_hlist) {
2524 			hlist_del(&tb->tb6_hlist);
2525 			fib6_free_table(tb);
2526 		}
2527 	}
2528 
2529 	kfree(net->ipv6.fib_table_hash);
2530 	kfree(net->ipv6.rt6_stats);
2531 	fib6_notifier_exit(net);
2532 }
2533 
2534 static struct pernet_operations fib6_net_ops = {
2535 	.init = fib6_net_init,
2536 	.exit = fib6_net_exit,
2537 };
2538 
2539 static const struct rtnl_msg_handler fib6_rtnl_msg_handlers[] __initconst_or_module = {
2540 	{.owner = THIS_MODULE, .protocol = PF_INET6, .msgtype = RTM_GETROUTE,
2541 	 .dumpit = inet6_dump_fib,
2542 	 .flags = RTNL_FLAG_DUMP_UNLOCKED | RTNL_FLAG_DUMP_SPLIT_NLM_DONE},
2543 };
2544 
2545 int __init fib6_init(void)
2546 {
2547 	int ret = -ENOMEM;
2548 
2549 	fib6_node_kmem = KMEM_CACHE(fib6_node,
2550 				    SLAB_HWCACHE_ALIGN | SLAB_ACCOUNT);
2551 	if (!fib6_node_kmem)
2552 		goto out;
2553 
2554 	ret = register_pernet_subsys(&fib6_net_ops);
2555 	if (ret)
2556 		goto out_kmem_cache_create;
2557 
2558 	ret = rtnl_register_many(fib6_rtnl_msg_handlers);
2559 	if (ret)
2560 		goto out_unregister_subsys;
2561 
2562 	__fib6_flush_trees = fib6_flush_trees;
2563 out:
2564 	return ret;
2565 
2566 out_unregister_subsys:
2567 	unregister_pernet_subsys(&fib6_net_ops);
2568 out_kmem_cache_create:
2569 	kmem_cache_destroy(fib6_node_kmem);
2570 	goto out;
2571 }
2572 
2573 void fib6_gc_cleanup(void)
2574 {
2575 	unregister_pernet_subsys(&fib6_net_ops);
2576 	kmem_cache_destroy(fib6_node_kmem);
2577 }
2578 
2579 #ifdef CONFIG_PROC_FS
2580 static int ipv6_route_native_seq_show(struct seq_file *seq, void *v)
2581 {
2582 	struct fib6_info *rt = v;
2583 	struct ipv6_route_iter *iter = seq->private;
2584 	struct fib6_nh *fib6_nh = rt->fib6_nh;
2585 	unsigned int flags = rt->fib6_flags;
2586 	const struct net_device *dev;
2587 
2588 	if (rt->nh)
2589 		fib6_nh = nexthop_fib6_nh(rt->nh);
2590 
2591 	seq_printf(seq, "%pi6 %02x ", &rt->fib6_dst.addr, rt->fib6_dst.plen);
2592 
2593 #ifdef CONFIG_IPV6_SUBTREES
2594 	seq_printf(seq, "%pi6 %02x ", &rt->fib6_src.addr, rt->fib6_src.plen);
2595 #else
2596 	seq_puts(seq, "00000000000000000000000000000000 00 ");
2597 #endif
2598 	if (fib6_nh->fib_nh_gw_family) {
2599 		flags |= RTF_GATEWAY;
2600 		seq_printf(seq, "%pi6", &fib6_nh->fib_nh_gw6);
2601 	} else {
2602 		seq_puts(seq, "00000000000000000000000000000000");
2603 	}
2604 
2605 	dev = fib6_nh->fib_nh_dev;
2606 	seq_printf(seq, " %08x %08x %08x %08x %8s\n",
2607 		   rt->fib6_metric, refcount_read(&rt->fib6_ref), 0,
2608 		   flags, dev ? dev->name : "");
2609 	iter->w.leaf = NULL;
2610 	return 0;
2611 }
2612 
2613 static int ipv6_route_yield(struct fib6_walker *w)
2614 {
2615 	struct ipv6_route_iter *iter = w->args;
2616 
2617 	if (!iter->skip)
2618 		return 1;
2619 
2620 	do {
2621 		iter->w.leaf = rcu_dereference_protected(
2622 				iter->w.leaf->fib6_next,
2623 				lockdep_is_held(&iter->tbl->tb6_lock));
2624 		iter->skip--;
2625 		if (!iter->skip && iter->w.leaf)
2626 			return 1;
2627 	} while (iter->w.leaf);
2628 
2629 	return 0;
2630 }
2631 
2632 static void ipv6_route_seq_setup_walk(struct ipv6_route_iter *iter,
2633 				      struct net *net)
2634 {
2635 	memset(&iter->w, 0, sizeof(iter->w));
2636 	iter->w.func = ipv6_route_yield;
2637 	iter->w.root = &iter->tbl->tb6_root;
2638 	iter->w.state = FWS_INIT;
2639 	iter->w.node = iter->w.root;
2640 	iter->w.args = iter;
2641 	iter->sernum = READ_ONCE(iter->w.root->fn_sernum);
2642 	INIT_LIST_HEAD(&iter->w.lh);
2643 	fib6_walker_link(net, &iter->w);
2644 }
2645 
2646 static struct fib6_table *ipv6_route_seq_next_table(struct fib6_table *tbl,
2647 						    struct net *net)
2648 {
2649 	unsigned int h;
2650 	struct hlist_node *node;
2651 
2652 	if (tbl) {
2653 		h = (tbl->tb6_id & (FIB6_TABLE_HASHSZ - 1)) + 1;
2654 		node = rcu_dereference(hlist_next_rcu(&tbl->tb6_hlist));
2655 	} else {
2656 		h = 0;
2657 		node = NULL;
2658 	}
2659 
2660 	while (!node && h < FIB6_TABLE_HASHSZ) {
2661 		node = rcu_dereference(
2662 			hlist_first_rcu(&net->ipv6.fib_table_hash[h++]));
2663 	}
2664 	return hlist_entry_safe(node, struct fib6_table, tb6_hlist);
2665 }
2666 
2667 static void ipv6_route_check_sernum(struct ipv6_route_iter *iter)
2668 {
2669 	int sernum = READ_ONCE(iter->w.root->fn_sernum);
2670 
2671 	if (iter->sernum != sernum) {
2672 		iter->sernum = sernum;
2673 		iter->w.state = FWS_INIT;
2674 		iter->w.node = iter->w.root;
2675 		WARN_ON(iter->w.skip);
2676 		iter->w.skip = iter->w.count;
2677 	}
2678 }
2679 
2680 static void *ipv6_route_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2681 {
2682 	int r;
2683 	struct fib6_info *n;
2684 	struct net *net = seq_file_net(seq);
2685 	struct ipv6_route_iter *iter = seq->private;
2686 
2687 	++(*pos);
2688 	if (!v)
2689 		goto iter_table;
2690 
2691 	n = rcu_dereference(((struct fib6_info *)v)->fib6_next);
2692 	if (n)
2693 		return n;
2694 
2695 iter_table:
2696 	ipv6_route_check_sernum(iter);
2697 	spin_lock_bh(&iter->tbl->tb6_lock);
2698 	r = fib6_walk_continue(&iter->w);
2699 	spin_unlock_bh(&iter->tbl->tb6_lock);
2700 	if (r > 0) {
2701 		return iter->w.leaf;
2702 	} else if (r < 0) {
2703 		fib6_walker_unlink(net, &iter->w);
2704 		return NULL;
2705 	}
2706 	fib6_walker_unlink(net, &iter->w);
2707 
2708 	iter->tbl = ipv6_route_seq_next_table(iter->tbl, net);
2709 	if (!iter->tbl)
2710 		return NULL;
2711 
2712 	ipv6_route_seq_setup_walk(iter, net);
2713 	goto iter_table;
2714 }
2715 
2716 static void *ipv6_route_seq_start(struct seq_file *seq, loff_t *pos)
2717 	__acquires(RCU)
2718 {
2719 	struct net *net = seq_file_net(seq);
2720 	struct ipv6_route_iter *iter = seq->private;
2721 
2722 	rcu_read_lock();
2723 	iter->tbl = ipv6_route_seq_next_table(NULL, net);
2724 	iter->skip = *pos;
2725 
2726 	if (iter->tbl) {
2727 		loff_t p = 0;
2728 
2729 		ipv6_route_seq_setup_walk(iter, net);
2730 		return ipv6_route_seq_next(seq, NULL, &p);
2731 	} else {
2732 		return NULL;
2733 	}
2734 }
2735 
2736 static bool ipv6_route_iter_active(struct ipv6_route_iter *iter)
2737 {
2738 	struct fib6_walker *w = &iter->w;
2739 	return w->node && !(w->state == FWS_U && w->node == w->root);
2740 }
2741 
2742 static void ipv6_route_native_seq_stop(struct seq_file *seq, void *v)
2743 	__releases(RCU)
2744 {
2745 	struct net *net = seq_file_net(seq);
2746 	struct ipv6_route_iter *iter = seq->private;
2747 
2748 	if (ipv6_route_iter_active(iter))
2749 		fib6_walker_unlink(net, &iter->w);
2750 
2751 	rcu_read_unlock();
2752 }
2753 
2754 #if IS_BUILTIN(CONFIG_IPV6) && defined(CONFIG_BPF_SYSCALL)
2755 static int ipv6_route_prog_seq_show(struct bpf_prog *prog,
2756 				    struct bpf_iter_meta *meta,
2757 				    void *v)
2758 {
2759 	struct bpf_iter__ipv6_route ctx;
2760 
2761 	ctx.meta = meta;
2762 	ctx.rt = v;
2763 	return bpf_iter_run_prog(prog, &ctx);
2764 }
2765 
2766 static int ipv6_route_seq_show(struct seq_file *seq, void *v)
2767 {
2768 	struct ipv6_route_iter *iter = seq->private;
2769 	struct bpf_iter_meta meta;
2770 	struct bpf_prog *prog;
2771 	int ret;
2772 
2773 	meta.seq = seq;
2774 	prog = bpf_iter_get_info(&meta, false);
2775 	if (!prog)
2776 		return ipv6_route_native_seq_show(seq, v);
2777 
2778 	ret = ipv6_route_prog_seq_show(prog, &meta, v);
2779 	iter->w.leaf = NULL;
2780 
2781 	return ret;
2782 }
2783 
2784 static void ipv6_route_seq_stop(struct seq_file *seq, void *v)
2785 {
2786 	struct bpf_iter_meta meta;
2787 	struct bpf_prog *prog;
2788 
2789 	if (!v) {
2790 		meta.seq = seq;
2791 		prog = bpf_iter_get_info(&meta, true);
2792 		if (prog)
2793 			(void)ipv6_route_prog_seq_show(prog, &meta, v);
2794 	}
2795 
2796 	ipv6_route_native_seq_stop(seq, v);
2797 }
2798 #else
2799 static int ipv6_route_seq_show(struct seq_file *seq, void *v)
2800 {
2801 	return ipv6_route_native_seq_show(seq, v);
2802 }
2803 
2804 static void ipv6_route_seq_stop(struct seq_file *seq, void *v)
2805 {
2806 	ipv6_route_native_seq_stop(seq, v);
2807 }
2808 #endif
2809 
2810 const struct seq_operations ipv6_route_seq_ops = {
2811 	.start	= ipv6_route_seq_start,
2812 	.next	= ipv6_route_seq_next,
2813 	.stop	= ipv6_route_seq_stop,
2814 	.show	= ipv6_route_seq_show
2815 };
2816 #endif /* CONFIG_PROC_FS */
2817