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