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