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