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