xref: /linux/net/core/net_namespace.c (revision 7c6c4ed80b874f721bc7c2c937e098c56e37d2f0)
1 // SPDX-License-Identifier: GPL-2.0-only
2 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
3 
4 #include <linux/workqueue.h>
5 #include <linux/rtnetlink.h>
6 #include <linux/cache.h>
7 #include <linux/slab.h>
8 #include <linux/list.h>
9 #include <linux/delay.h>
10 #include <linux/sched.h>
11 #include <linux/idr.h>
12 #include <linux/rculist.h>
13 #include <linux/nsproxy.h>
14 #include <linux/fs.h>
15 #include <linux/proc_ns.h>
16 #include <linux/file.h>
17 #include <linux/export.h>
18 #include <linux/user_namespace.h>
19 #include <linux/net_namespace.h>
20 #include <linux/sched/task.h>
21 #include <linux/uidgid.h>
22 #include <linux/proc_fs.h>
23 #include <linux/nstree.h>
24 
25 #include <net/aligned_data.h>
26 #include <net/sock.h>
27 #include <net/netlink.h>
28 #include <net/net_namespace.h>
29 #include <net/netns/generic.h>
30 
31 /*
32  *	Our network namespace constructor/destructor lists
33  */
34 
35 static LIST_HEAD(pernet_list);
36 static struct list_head *first_device = &pernet_list;
37 
38 LIST_HEAD(net_namespace_list);
39 EXPORT_SYMBOL_GPL(net_namespace_list);
40 
41 /* Protects net_namespace_list. Nests iside rtnl_lock() */
42 DECLARE_RWSEM(net_rwsem);
43 EXPORT_SYMBOL_GPL(net_rwsem);
44 
45 #ifdef CONFIG_KEYS
46 static struct key_tag init_net_key_domain = { .usage = REFCOUNT_INIT(1) };
47 #endif
48 
49 struct net init_net;
50 EXPORT_SYMBOL(init_net);
51 
52 static bool init_net_initialized;
53 /*
54  * pernet_ops_rwsem: protects: pernet_list, net_generic_ids,
55  * init_net_initialized and first_device pointer.
56  * This is internal net namespace object. Please, don't use it
57  * outside.
58  */
59 DECLARE_RWSEM(pernet_ops_rwsem);
60 
61 #define MIN_PERNET_OPS_ID	\
62 	((sizeof(struct net_generic) + sizeof(void *) - 1) / sizeof(void *))
63 
64 #define INITIAL_NET_GEN_PTRS	13 /* +1 for len +2 for rcu_head */
65 
66 static unsigned int max_gen_ptrs = INITIAL_NET_GEN_PTRS;
67 
net_alloc_generic(void)68 static struct net_generic *net_alloc_generic(void)
69 {
70 	unsigned int gen_ptrs = READ_ONCE(max_gen_ptrs);
71 	unsigned int generic_size;
72 	struct net_generic *ng;
73 
74 	generic_size = offsetof(struct net_generic, ptr[gen_ptrs]);
75 
76 	ng = kzalloc(generic_size, GFP_KERNEL);
77 	if (ng)
78 		ng->s.len = gen_ptrs;
79 
80 	return ng;
81 }
82 
net_assign_generic(struct net * net,unsigned int id,void * data)83 static int net_assign_generic(struct net *net, unsigned int id, void *data)
84 {
85 	struct net_generic *ng, *old_ng;
86 
87 	BUG_ON(id < MIN_PERNET_OPS_ID);
88 
89 	old_ng = rcu_dereference_protected(net->gen,
90 					   lockdep_is_held(&pernet_ops_rwsem));
91 	if (old_ng->s.len > id) {
92 		old_ng->ptr[id] = data;
93 		return 0;
94 	}
95 
96 	ng = net_alloc_generic();
97 	if (!ng)
98 		return -ENOMEM;
99 
100 	/*
101 	 * Some synchronisation notes:
102 	 *
103 	 * The net_generic explores the net->gen array inside rcu
104 	 * read section. Besides once set the net->gen->ptr[x]
105 	 * pointer never changes (see rules in netns/generic.h).
106 	 *
107 	 * That said, we simply duplicate this array and schedule
108 	 * the old copy for kfree after a grace period.
109 	 */
110 
111 	memcpy(&ng->ptr[MIN_PERNET_OPS_ID], &old_ng->ptr[MIN_PERNET_OPS_ID],
112 	       (old_ng->s.len - MIN_PERNET_OPS_ID) * sizeof(void *));
113 	ng->ptr[id] = data;
114 
115 	rcu_assign_pointer(net->gen, ng);
116 	kfree_rcu(old_ng, s.rcu);
117 	return 0;
118 }
119 
ops_init(const struct pernet_operations * ops,struct net * net)120 static int ops_init(const struct pernet_operations *ops, struct net *net)
121 {
122 	struct net_generic *ng;
123 	int err = -ENOMEM;
124 	void *data = NULL;
125 
126 	if (ops->id) {
127 		data = kzalloc(ops->size, GFP_KERNEL);
128 		if (!data)
129 			goto out;
130 
131 		err = net_assign_generic(net, *ops->id, data);
132 		if (err)
133 			goto cleanup;
134 	}
135 	err = 0;
136 	if (ops->init)
137 		err = ops->init(net);
138 	if (!err)
139 		return 0;
140 
141 	if (ops->id) {
142 		ng = rcu_dereference_protected(net->gen,
143 					       lockdep_is_held(&pernet_ops_rwsem));
144 		ng->ptr[*ops->id] = NULL;
145 	}
146 
147 cleanup:
148 	kfree(data);
149 
150 out:
151 	return err;
152 }
153 
ops_pre_exit_list(const struct pernet_operations * ops,struct list_head * net_exit_list)154 static void ops_pre_exit_list(const struct pernet_operations *ops,
155 			      struct list_head *net_exit_list)
156 {
157 	struct net *net;
158 
159 	if (ops->pre_exit) {
160 		list_for_each_entry(net, net_exit_list, exit_list)
161 			ops->pre_exit(net);
162 	}
163 }
164 
ops_exit_rtnl_list(const struct list_head * ops_list,const struct pernet_operations * ops,struct list_head * net_exit_list)165 static void ops_exit_rtnl_list(const struct list_head *ops_list,
166 			       const struct pernet_operations *ops,
167 			       struct list_head *net_exit_list)
168 {
169 	const struct pernet_operations *saved_ops = ops;
170 	LIST_HEAD(dev_kill_list);
171 	struct net *net;
172 
173 	rtnl_lock();
174 
175 	list_for_each_entry(net, net_exit_list, exit_list) {
176 		__rtnl_net_lock(net);
177 
178 		ops = saved_ops;
179 		list_for_each_entry_continue_reverse(ops, ops_list, list) {
180 			if (ops->exit_rtnl)
181 				ops->exit_rtnl(net, &dev_kill_list);
182 		}
183 
184 		__rtnl_net_unlock(net);
185 	}
186 
187 	unregister_netdevice_many(&dev_kill_list);
188 
189 	rtnl_unlock();
190 }
191 
ops_exit_list(const struct pernet_operations * ops,struct list_head * net_exit_list)192 static void ops_exit_list(const struct pernet_operations *ops,
193 			  struct list_head *net_exit_list)
194 {
195 	if (ops->exit) {
196 		struct net *net;
197 
198 		list_for_each_entry(net, net_exit_list, exit_list) {
199 			ops->exit(net);
200 			cond_resched();
201 		}
202 	}
203 
204 	if (ops->exit_batch)
205 		ops->exit_batch(net_exit_list);
206 }
207 
ops_free_list(const struct pernet_operations * ops,struct list_head * net_exit_list)208 static void ops_free_list(const struct pernet_operations *ops,
209 			  struct list_head *net_exit_list)
210 {
211 	struct net *net;
212 
213 	if (ops->id) {
214 		list_for_each_entry(net, net_exit_list, exit_list)
215 			kfree(net_generic(net, *ops->id));
216 	}
217 }
218 
ops_undo_list(const struct list_head * ops_list,const struct pernet_operations * ops,struct list_head * net_exit_list,bool expedite_rcu)219 static void ops_undo_list(const struct list_head *ops_list,
220 			  const struct pernet_operations *ops,
221 			  struct list_head *net_exit_list,
222 			  bool expedite_rcu)
223 {
224 	const struct pernet_operations *saved_ops;
225 	bool hold_rtnl = false;
226 
227 	if (!ops)
228 		ops = list_entry(ops_list, typeof(*ops), list);
229 
230 	saved_ops = ops;
231 
232 	list_for_each_entry_continue_reverse(ops, ops_list, list) {
233 		hold_rtnl |= !!ops->exit_rtnl;
234 		ops_pre_exit_list(ops, net_exit_list);
235 	}
236 
237 	/* Another CPU might be rcu-iterating the list, wait for it.
238 	 * This needs to be before calling the exit() notifiers, so the
239 	 * rcu_barrier() after ops_undo_list() isn't sufficient alone.
240 	 * Also the pre_exit() and exit() methods need this barrier.
241 	 */
242 	if (expedite_rcu)
243 		synchronize_rcu_expedited();
244 	else
245 		synchronize_rcu();
246 
247 	if (hold_rtnl)
248 		ops_exit_rtnl_list(ops_list, saved_ops, net_exit_list);
249 
250 	ops = saved_ops;
251 	list_for_each_entry_continue_reverse(ops, ops_list, list)
252 		ops_exit_list(ops, net_exit_list);
253 
254 	ops = saved_ops;
255 	list_for_each_entry_continue_reverse(ops, ops_list, list)
256 		ops_free_list(ops, net_exit_list);
257 }
258 
ops_undo_single(struct pernet_operations * ops,struct list_head * net_exit_list)259 static void ops_undo_single(struct pernet_operations *ops,
260 			    struct list_head *net_exit_list)
261 {
262 	LIST_HEAD(ops_list);
263 
264 	list_add(&ops->list, &ops_list);
265 	ops_undo_list(&ops_list, NULL, net_exit_list, false);
266 	list_del(&ops->list);
267 }
268 
269 /* should be called with nsid_lock held */
alloc_netid(struct net * net,struct net * peer,int reqid)270 static int alloc_netid(struct net *net, struct net *peer, int reqid)
271 {
272 	int min = 0, max = 0;
273 
274 	if (reqid >= 0) {
275 		min = reqid;
276 		max = reqid + 1;
277 	}
278 
279 	return idr_alloc(&net->netns_ids, peer, min, max, GFP_ATOMIC);
280 }
281 
282 /* This function is used by idr_for_each(). If net is equal to peer, the
283  * function returns the id so that idr_for_each() stops. Because we cannot
284  * returns the id 0 (idr_for_each() will not stop), we return the magic value
285  * NET_ID_ZERO (-1) for it.
286  */
287 #define NET_ID_ZERO -1
net_eq_idr(int id,void * net,void * peer)288 static int net_eq_idr(int id, void *net, void *peer)
289 {
290 	if (net_eq(net, peer))
291 		return id ? : NET_ID_ZERO;
292 	return 0;
293 }
294 
295 /* Must be called from RCU-critical section or with nsid_lock held */
__peernet2id(const struct net * net,struct net * peer)296 static int __peernet2id(const struct net *net, struct net *peer)
297 {
298 	int id = idr_for_each(&net->netns_ids, net_eq_idr, peer);
299 
300 	/* Magic value for id 0. */
301 	if (id == NET_ID_ZERO)
302 		return 0;
303 	if (id > 0)
304 		return id;
305 
306 	return NETNSA_NSID_NOT_ASSIGNED;
307 }
308 
309 static void rtnl_net_notifyid(struct net *net, int cmd, int id, u32 portid,
310 			      struct nlmsghdr *nlh, gfp_t gfp);
311 /* This function returns the id of a peer netns. If no id is assigned, one will
312  * be allocated and returned.
313  */
peernet2id_alloc(struct net * net,struct net * peer,gfp_t gfp)314 int peernet2id_alloc(struct net *net, struct net *peer, gfp_t gfp)
315 {
316 	int id;
317 
318 	if (!check_net(net))
319 		return NETNSA_NSID_NOT_ASSIGNED;
320 
321 	spin_lock(&net->nsid_lock);
322 	id = __peernet2id(net, peer);
323 	if (id >= 0) {
324 		spin_unlock(&net->nsid_lock);
325 		return id;
326 	}
327 
328 	/* When peer is obtained from RCU lists, we may race with
329 	 * its cleanup. Check whether it's alive, and this guarantees
330 	 * we never hash a peer back to net->netns_ids, after it has
331 	 * just been idr_remove()'d from there in cleanup_net().
332 	 */
333 	if (!maybe_get_net(peer)) {
334 		spin_unlock(&net->nsid_lock);
335 		return NETNSA_NSID_NOT_ASSIGNED;
336 	}
337 
338 	id = alloc_netid(net, peer, -1);
339 	spin_unlock(&net->nsid_lock);
340 
341 	put_net(peer);
342 	if (id < 0)
343 		return NETNSA_NSID_NOT_ASSIGNED;
344 
345 	rtnl_net_notifyid(net, RTM_NEWNSID, id, 0, NULL, gfp);
346 
347 	return id;
348 }
349 EXPORT_SYMBOL_GPL(peernet2id_alloc);
350 
351 /* This function returns, if assigned, the id of a peer netns. */
peernet2id(const struct net * net,struct net * peer)352 int peernet2id(const struct net *net, struct net *peer)
353 {
354 	int id;
355 
356 	rcu_read_lock();
357 	id = __peernet2id(net, peer);
358 	rcu_read_unlock();
359 
360 	return id;
361 }
362 EXPORT_SYMBOL(peernet2id);
363 
364 /* This function returns true is the peer netns has an id assigned into the
365  * current netns.
366  */
peernet_has_id(const struct net * net,struct net * peer)367 bool peernet_has_id(const struct net *net, struct net *peer)
368 {
369 	return peernet2id(net, peer) >= 0;
370 }
371 
get_net_ns_by_id(const struct net * net,int id)372 struct net *get_net_ns_by_id(const struct net *net, int id)
373 {
374 	struct net *peer;
375 
376 	if (id < 0)
377 		return NULL;
378 
379 	rcu_read_lock();
380 	peer = idr_find(&net->netns_ids, id);
381 	if (peer)
382 		peer = maybe_get_net(peer);
383 	rcu_read_unlock();
384 
385 	return peer;
386 }
387 EXPORT_SYMBOL_GPL(get_net_ns_by_id);
388 
preinit_net_sysctl(struct net * net)389 static __net_init void preinit_net_sysctl(struct net *net)
390 {
391 	net->core.sysctl_somaxconn = SOMAXCONN;
392 	/* Limits per socket sk_omem_alloc usage.
393 	 * TCP zerocopy regular usage needs 128 KB.
394 	 */
395 	net->core.sysctl_optmem_max = 128 * 1024;
396 	net->core.sysctl_txrehash = SOCK_TXREHASH_ENABLED;
397 	net->core.sysctl_tstamp_allow_data = 1;
398 	net->core.sysctl_txq_reselection = msecs_to_jiffies(1000);
399 }
400 
401 /* init code that must occur even if setup_net() is not called. */
preinit_net(struct net * net,struct user_namespace * user_ns)402 static __net_init int preinit_net(struct net *net, struct user_namespace *user_ns)
403 {
404 	int ret;
405 
406 	ret = ns_common_init(net);
407 	if (ret)
408 		return ret;
409 
410 	refcount_set(&net->passive, 1);
411 	ref_tracker_dir_init(&net->refcnt_tracker, 128, "net_refcnt");
412 	ref_tracker_dir_init(&net->notrefcnt_tracker, 128, "net_notrefcnt");
413 
414 	get_random_bytes(&net->hash_mix, sizeof(u32));
415 	net->dev_base_seq = 1;
416 	net->user_ns = user_ns;
417 
418 	idr_init(&net->netns_ids);
419 	spin_lock_init(&net->nsid_lock);
420 	mutex_init(&net->ipv4.ra_mutex);
421 
422 #ifdef CONFIG_DEBUG_NET_SMALL_RTNL
423 	mutex_init(&net->rtnl_mutex);
424 	lock_set_cmp_fn(&net->rtnl_mutex, rtnl_net_lock_cmp_fn, NULL);
425 #endif
426 
427 	INIT_LIST_HEAD(&net->ptype_all);
428 	INIT_LIST_HEAD(&net->ptype_specific);
429 	preinit_net_sysctl(net);
430 	return 0;
431 }
432 
433 /*
434  * setup_net runs the initializers for the network namespace object.
435  */
setup_net(struct net * net)436 static __net_init int setup_net(struct net *net)
437 {
438 	/* Must be called with pernet_ops_rwsem held */
439 	const struct pernet_operations *ops;
440 	LIST_HEAD(net_exit_list);
441 	int error = 0;
442 
443 	net->net_cookie = ns_tree_gen_id(net);
444 
445 	list_for_each_entry(ops, &pernet_list, list) {
446 		error = ops_init(ops, net);
447 		if (error < 0)
448 			goto out_undo;
449 	}
450 	down_write(&net_rwsem);
451 	list_add_tail_rcu(&net->list, &net_namespace_list);
452 	up_write(&net_rwsem);
453 	ns_tree_add_raw(net);
454 out:
455 	return error;
456 
457 out_undo:
458 	/* Walk through the list backwards calling the exit functions
459 	 * for the pernet modules whose init functions did not fail.
460 	 */
461 	list_add(&net->exit_list, &net_exit_list);
462 	ops_undo_list(&pernet_list, ops, &net_exit_list, false);
463 	rcu_barrier();
464 	goto out;
465 }
466 
467 #ifdef CONFIG_NET_NS
inc_net_namespaces(struct user_namespace * ns)468 static struct ucounts *inc_net_namespaces(struct user_namespace *ns)
469 {
470 	return inc_ucount(ns, current_euid(), UCOUNT_NET_NAMESPACES);
471 }
472 
dec_net_namespaces(struct ucounts * ucounts)473 static void dec_net_namespaces(struct ucounts *ucounts)
474 {
475 	dec_ucount(ucounts, UCOUNT_NET_NAMESPACES);
476 }
477 
478 static struct kmem_cache *net_cachep __ro_after_init;
479 static struct workqueue_struct *netns_wq;
480 
net_alloc(void)481 static struct net *net_alloc(void)
482 {
483 	struct net *net = NULL;
484 	struct net_generic *ng;
485 
486 	ng = net_alloc_generic();
487 	if (!ng)
488 		goto out;
489 
490 	net = kmem_cache_zalloc(net_cachep, GFP_KERNEL);
491 	if (!net)
492 		goto out_free;
493 
494 #ifdef CONFIG_KEYS
495 	net->key_domain = kzalloc_obj(struct key_tag);
496 	if (!net->key_domain)
497 		goto out_free_2;
498 	refcount_set(&net->key_domain->usage, 1);
499 #endif
500 
501 	rcu_assign_pointer(net->gen, ng);
502 out:
503 	return net;
504 
505 #ifdef CONFIG_KEYS
506 out_free_2:
507 	kmem_cache_free(net_cachep, net);
508 	net = NULL;
509 #endif
510 out_free:
511 	kfree(ng);
512 	goto out;
513 }
514 
515 static LLIST_HEAD(defer_free_list);
516 
net_complete_free(void)517 static void net_complete_free(void)
518 {
519 	struct llist_node *kill_list;
520 	struct net *net, *next;
521 
522 	/* Get the list of namespaces to free from last round. */
523 	kill_list = llist_del_all(&defer_free_list);
524 
525 	llist_for_each_entry_safe(net, next, kill_list, defer_free_list)
526 		kmem_cache_free(net_cachep, net);
527 
528 }
529 
net_passive_dec(struct net * net)530 void net_passive_dec(struct net *net)
531 {
532 	if (refcount_dec_and_test(&net->passive)) {
533 		kfree(rcu_access_pointer(net->gen));
534 
535 		/* There should not be any trackers left there. */
536 		ref_tracker_dir_exit(&net->notrefcnt_tracker);
537 
538 		/* Wait for an extra rcu_barrier() before final free. */
539 		llist_add(&net->defer_free_list, &defer_free_list);
540 	}
541 }
542 
net_drop_ns(struct ns_common * ns)543 void net_drop_ns(struct ns_common *ns)
544 {
545 	if (ns)
546 		net_passive_dec(to_net_ns(ns));
547 }
548 
copy_net_ns(u64 flags,struct user_namespace * user_ns,struct net * old_net)549 struct net *copy_net_ns(u64 flags,
550 			struct user_namespace *user_ns, struct net *old_net)
551 {
552 	struct ucounts *ucounts;
553 	struct net *net;
554 	int rv;
555 
556 	if (!(flags & CLONE_NEWNET))
557 		return get_net(old_net);
558 
559 	ucounts = inc_net_namespaces(user_ns);
560 	if (!ucounts)
561 		return ERR_PTR(-ENOSPC);
562 
563 	net = net_alloc();
564 	if (!net) {
565 		rv = -ENOMEM;
566 		goto dec_ucounts;
567 	}
568 
569 	rv = preinit_net(net, user_ns);
570 	if (rv < 0)
571 		goto dec_ucounts;
572 	net->ucounts = ucounts;
573 	get_user_ns(user_ns);
574 
575 	rv = down_read_killable(&pernet_ops_rwsem);
576 	if (rv < 0)
577 		goto put_userns;
578 
579 	rv = setup_net(net);
580 
581 	up_read(&pernet_ops_rwsem);
582 
583 	if (rv < 0) {
584 put_userns:
585 		ns_common_free(net);
586 #ifdef CONFIG_KEYS
587 		key_remove_domain(net->key_domain);
588 #endif
589 		put_user_ns(user_ns);
590 		net_passive_dec(net);
591 dec_ucounts:
592 		dec_net_namespaces(ucounts);
593 		return ERR_PTR(rv);
594 	}
595 	return net;
596 }
597 
598 /**
599  * net_ns_get_ownership - get sysfs ownership data for @net
600  * @net: network namespace in question (can be NULL)
601  * @uid: kernel user ID for sysfs objects
602  * @gid: kernel group ID for sysfs objects
603  *
604  * Returns the uid/gid pair of root in the user namespace associated with the
605  * given network namespace.
606  */
net_ns_get_ownership(const struct net * net,kuid_t * uid,kgid_t * gid)607 void net_ns_get_ownership(const struct net *net, kuid_t *uid, kgid_t *gid)
608 {
609 	if (net) {
610 		kuid_t ns_root_uid = make_kuid(net->user_ns, 0);
611 		kgid_t ns_root_gid = make_kgid(net->user_ns, 0);
612 
613 		if (uid_valid(ns_root_uid))
614 			*uid = ns_root_uid;
615 
616 		if (gid_valid(ns_root_gid))
617 			*gid = ns_root_gid;
618 	} else {
619 		*uid = GLOBAL_ROOT_UID;
620 		*gid = GLOBAL_ROOT_GID;
621 	}
622 }
623 EXPORT_SYMBOL_GPL(net_ns_get_ownership);
624 
unhash_nsid(struct net * last)625 static void unhash_nsid(struct net *last)
626 {
627 	struct net *tmp, *peer;
628 
629 	/* This function is only called from cleanup_net() work,
630 	 * and this work is the only process, that may delete
631 	 * a net from net_namespace_list. So, when the below
632 	 * is executing, the list may only grow. Thus, we do not
633 	 * use for_each_net_rcu() or net_rwsem.
634 	 */
635 	for_each_net(tmp) {
636 		int id = 0;
637 
638 		spin_lock(&tmp->nsid_lock);
639 		while ((peer = idr_get_next(&tmp->netns_ids, &id))) {
640 			int curr_id = id;
641 
642 			id++;
643 			if (!peer->is_dying)
644 				continue;
645 
646 			idr_remove(&tmp->netns_ids, curr_id);
647 			spin_unlock(&tmp->nsid_lock);
648 			rtnl_net_notifyid(tmp, RTM_DELNSID, curr_id, 0, NULL,
649 					  GFP_KERNEL);
650 			spin_lock(&tmp->nsid_lock);
651 		}
652 		spin_unlock(&tmp->nsid_lock);
653 		if (tmp == last)
654 			break;
655 	}
656 }
657 
658 static LLIST_HEAD(cleanup_list);
659 
660 struct task_struct *cleanup_net_task;
661 
cleanup_net(struct work_struct * work)662 static void cleanup_net(struct work_struct *work)
663 {
664 	struct llist_node *net_kill_list;
665 	struct net *net, *tmp, *last;
666 	LIST_HEAD(net_exit_list);
667 
668 	WRITE_ONCE(cleanup_net_task, current);
669 
670 	/* Atomically snapshot the list of namespaces to cleanup */
671 	net_kill_list = llist_del_all(&cleanup_list);
672 
673 	down_read(&pernet_ops_rwsem);
674 
675 	/* Don't let anyone else find us. */
676 	down_write(&net_rwsem);
677 	llist_for_each_entry(net, net_kill_list, cleanup_list) {
678 		ns_tree_remove(net);
679 		list_del_rcu(&net->list);
680 		net->is_dying = true;
681 	}
682 	/* Cache last net. After we unlock rtnl, no one new net
683 	 * added to net_namespace_list can assign nsid pointer
684 	 * to a net from net_kill_list (see peernet2id_alloc()).
685 	 * So, we skip them in unhash_nsid().
686 	 *
687 	 * Note, that unhash_nsid() does not delete nsid links
688 	 * between net_kill_list's nets, as they've already
689 	 * deleted from net_namespace_list. But, this would be
690 	 * useless anyway, as netns_ids are destroyed there.
691 	 */
692 	last = list_last_entry(&net_namespace_list, struct net, list);
693 	up_write(&net_rwsem);
694 
695 	unhash_nsid(last);
696 
697 	llist_for_each_entry(net, net_kill_list, cleanup_list) {
698 		idr_destroy(&net->netns_ids);
699 		list_add_tail(&net->exit_list, &net_exit_list);
700 	}
701 
702 	ops_undo_list(&pernet_list, NULL, &net_exit_list, true);
703 
704 	up_read(&pernet_ops_rwsem);
705 
706 	/* Ensure there are no outstanding rcu callbacks using this
707 	 * network namespace.
708 	 */
709 	rcu_barrier();
710 
711 	net_complete_free();
712 
713 	/* Finally it is safe to free my network namespace structure */
714 	list_for_each_entry_safe(net, tmp, &net_exit_list, exit_list) {
715 		list_del_init(&net->exit_list);
716 		ns_common_free(net);
717 		dec_net_namespaces(net->ucounts);
718 #ifdef CONFIG_KEYS
719 		key_remove_domain(net->key_domain);
720 #endif
721 		put_user_ns(net->user_ns);
722 		net_passive_dec(net);
723 	}
724 	WRITE_ONCE(cleanup_net_task, NULL);
725 }
726 
727 /**
728  * net_ns_barrier - wait until concurrent net_cleanup_work is done
729  *
730  * cleanup_net runs from work queue and will first remove namespaces
731  * from the global list, then run net exit functions.
732  *
733  * Call this in module exit path to make sure that all netns
734  * ->exit ops have been invoked before the function is removed.
735  */
net_ns_barrier(void)736 void net_ns_barrier(void)
737 {
738 	down_write(&pernet_ops_rwsem);
739 	up_write(&pernet_ops_rwsem);
740 }
741 EXPORT_SYMBOL(net_ns_barrier);
742 
743 static DECLARE_WORK(net_cleanup_work, cleanup_net);
744 
__put_net(struct net * net)745 void __put_net(struct net *net)
746 {
747 	ref_tracker_dir_exit(&net->refcnt_tracker);
748 	/* Cleanup the network namespace in process context */
749 	if (llist_add(&net->cleanup_list, &cleanup_list))
750 		queue_work(netns_wq, &net_cleanup_work);
751 }
752 EXPORT_SYMBOL_GPL(__put_net);
753 
754 /**
755  * get_net_ns - increment the refcount of the network namespace
756  * @ns: common namespace (net)
757  *
758  * Returns the net's common namespace or ERR_PTR() if ref is zero.
759  */
get_net_ns(struct ns_common * ns)760 struct ns_common *get_net_ns(struct ns_common *ns)
761 {
762 	struct net *net;
763 
764 	net = maybe_get_net(container_of(ns, struct net, ns));
765 	if (net)
766 		return &net->ns;
767 	return ERR_PTR(-EINVAL);
768 }
769 EXPORT_SYMBOL_GPL(get_net_ns);
770 
get_net_ns_by_fd(int fd)771 struct net *get_net_ns_by_fd(int fd)
772 {
773 	CLASS(fd, f)(fd);
774 
775 	if (fd_empty(f))
776 		return ERR_PTR(-EBADF);
777 
778 	if (proc_ns_file(fd_file(f))) {
779 		struct ns_common *ns = get_proc_ns(file_inode(fd_file(f)));
780 		if (ns->ops == &netns_operations)
781 			return get_net(container_of(ns, struct net, ns));
782 	}
783 
784 	return ERR_PTR(-EINVAL);
785 }
786 EXPORT_SYMBOL_GPL(get_net_ns_by_fd);
787 #endif
788 
get_net_ns_by_pid(pid_t pid)789 struct net *get_net_ns_by_pid(pid_t pid)
790 {
791 	struct task_struct *tsk;
792 	struct net *net;
793 
794 	/* Lookup the network namespace */
795 	net = ERR_PTR(-ESRCH);
796 	rcu_read_lock();
797 	tsk = find_task_by_vpid(pid);
798 	if (tsk) {
799 		struct nsproxy *nsproxy;
800 		task_lock(tsk);
801 		nsproxy = tsk->nsproxy;
802 		if (nsproxy)
803 			net = get_net(nsproxy->net_ns);
804 		task_unlock(tsk);
805 	}
806 	rcu_read_unlock();
807 	return net;
808 }
809 EXPORT_SYMBOL_GPL(get_net_ns_by_pid);
810 
811 #ifdef CONFIG_NET_NS_REFCNT_TRACKER
net_ns_net_debugfs(struct net * net)812 static void net_ns_net_debugfs(struct net *net)
813 {
814 	ref_tracker_dir_symlink(&net->refcnt_tracker, "netns-%llx-%u-refcnt",
815 				net->net_cookie, net->ns.inum);
816 	ref_tracker_dir_symlink(&net->notrefcnt_tracker, "netns-%llx-%u-notrefcnt",
817 				net->net_cookie, net->ns.inum);
818 }
819 
init_net_debugfs(void)820 static int __init init_net_debugfs(void)
821 {
822 	ref_tracker_dir_debugfs(&init_net.refcnt_tracker);
823 	ref_tracker_dir_debugfs(&init_net.notrefcnt_tracker);
824 	net_ns_net_debugfs(&init_net);
825 	return 0;
826 }
827 late_initcall(init_net_debugfs);
828 #else
net_ns_net_debugfs(struct net * net)829 static void net_ns_net_debugfs(struct net *net)
830 {
831 }
832 #endif
833 
net_ns_net_init(struct net * net)834 static __net_init int net_ns_net_init(struct net *net)
835 {
836 	net_ns_net_debugfs(net);
837 	return 0;
838 }
839 
840 static struct pernet_operations __net_initdata net_ns_ops = {
841 	.init = net_ns_net_init,
842 };
843 
844 static const struct nla_policy rtnl_net_policy[NETNSA_MAX + 1] = {
845 	[NETNSA_NONE]		= { .type = NLA_UNSPEC },
846 	[NETNSA_NSID]		= { .type = NLA_S32 },
847 	[NETNSA_PID]		= { .type = NLA_U32 },
848 	[NETNSA_FD]		= { .type = NLA_U32 },
849 	[NETNSA_TARGET_NSID]	= { .type = NLA_S32 },
850 };
851 
rtnl_net_newid(struct sk_buff * skb,struct nlmsghdr * nlh,struct netlink_ext_ack * extack)852 static int rtnl_net_newid(struct sk_buff *skb, struct nlmsghdr *nlh,
853 			  struct netlink_ext_ack *extack)
854 {
855 	struct net *net = sock_net(skb->sk);
856 	struct nlattr *tb[NETNSA_MAX + 1];
857 	struct nlattr *nla;
858 	struct net *peer;
859 	int nsid, err;
860 
861 	err = nlmsg_parse_deprecated(nlh, sizeof(struct rtgenmsg), tb,
862 				     NETNSA_MAX, rtnl_net_policy, extack);
863 	if (err < 0)
864 		return err;
865 	if (!tb[NETNSA_NSID]) {
866 		NL_SET_ERR_MSG(extack, "nsid is missing");
867 		return -EINVAL;
868 	}
869 	nsid = nla_get_s32(tb[NETNSA_NSID]);
870 
871 	if (tb[NETNSA_PID]) {
872 		peer = get_net_ns_by_pid(nla_get_u32(tb[NETNSA_PID]));
873 		nla = tb[NETNSA_PID];
874 	} else if (tb[NETNSA_FD]) {
875 		peer = get_net_ns_by_fd(nla_get_u32(tb[NETNSA_FD]));
876 		nla = tb[NETNSA_FD];
877 	} else {
878 		NL_SET_ERR_MSG(extack, "Peer netns reference is missing");
879 		return -EINVAL;
880 	}
881 	if (IS_ERR(peer)) {
882 		NL_SET_BAD_ATTR(extack, nla);
883 		NL_SET_ERR_MSG(extack, "Peer netns reference is invalid");
884 		return PTR_ERR(peer);
885 	}
886 
887 	spin_lock(&net->nsid_lock);
888 	if (__peernet2id(net, peer) >= 0) {
889 		spin_unlock(&net->nsid_lock);
890 		err = -EEXIST;
891 		NL_SET_BAD_ATTR(extack, nla);
892 		NL_SET_ERR_MSG(extack,
893 			       "Peer netns already has a nsid assigned");
894 		goto out;
895 	}
896 
897 	err = alloc_netid(net, peer, nsid);
898 	spin_unlock(&net->nsid_lock);
899 	if (err >= 0) {
900 		rtnl_net_notifyid(net, RTM_NEWNSID, err, NETLINK_CB(skb).portid,
901 				  nlh, GFP_KERNEL);
902 		err = 0;
903 	} else if (err == -ENOSPC && nsid >= 0) {
904 		err = -EEXIST;
905 		NL_SET_BAD_ATTR(extack, tb[NETNSA_NSID]);
906 		NL_SET_ERR_MSG(extack, "The specified nsid is already used");
907 	}
908 out:
909 	put_net(peer);
910 	return err;
911 }
912 
rtnl_net_get_size(void)913 static int rtnl_net_get_size(void)
914 {
915 	return NLMSG_ALIGN(sizeof(struct rtgenmsg))
916 	       + nla_total_size(sizeof(s32)) /* NETNSA_NSID */
917 	       + nla_total_size(sizeof(s32)) /* NETNSA_CURRENT_NSID */
918 	       ;
919 }
920 
921 struct net_fill_args {
922 	u32 portid;
923 	u32 seq;
924 	int flags;
925 	int cmd;
926 	int nsid;
927 	bool add_ref;
928 	int ref_nsid;
929 };
930 
rtnl_net_fill(struct sk_buff * skb,struct net_fill_args * args)931 static int rtnl_net_fill(struct sk_buff *skb, struct net_fill_args *args)
932 {
933 	struct nlmsghdr *nlh;
934 	struct rtgenmsg *rth;
935 
936 	nlh = nlmsg_put(skb, args->portid, args->seq, args->cmd, sizeof(*rth),
937 			args->flags);
938 	if (!nlh)
939 		return -EMSGSIZE;
940 
941 	rth = nlmsg_data(nlh);
942 	rth->rtgen_family = AF_UNSPEC;
943 
944 	if (nla_put_s32(skb, NETNSA_NSID, args->nsid))
945 		goto nla_put_failure;
946 
947 	if (args->add_ref &&
948 	    nla_put_s32(skb, NETNSA_CURRENT_NSID, args->ref_nsid))
949 		goto nla_put_failure;
950 
951 	nlmsg_end(skb, nlh);
952 	return 0;
953 
954 nla_put_failure:
955 	nlmsg_cancel(skb, nlh);
956 	return -EMSGSIZE;
957 }
958 
rtnl_net_valid_getid_req(struct sk_buff * skb,const struct nlmsghdr * nlh,struct nlattr ** tb,struct netlink_ext_ack * extack)959 static int rtnl_net_valid_getid_req(struct sk_buff *skb,
960 				    const struct nlmsghdr *nlh,
961 				    struct nlattr **tb,
962 				    struct netlink_ext_ack *extack)
963 {
964 	int i, err;
965 
966 	if (!netlink_strict_get_check(skb))
967 		return nlmsg_parse_deprecated(nlh, sizeof(struct rtgenmsg),
968 					      tb, NETNSA_MAX, rtnl_net_policy,
969 					      extack);
970 
971 	err = nlmsg_parse_deprecated_strict(nlh, sizeof(struct rtgenmsg), tb,
972 					    NETNSA_MAX, rtnl_net_policy,
973 					    extack);
974 	if (err)
975 		return err;
976 
977 	for (i = 0; i <= NETNSA_MAX; i++) {
978 		if (!tb[i])
979 			continue;
980 
981 		switch (i) {
982 		case NETNSA_PID:
983 		case NETNSA_FD:
984 		case NETNSA_NSID:
985 		case NETNSA_TARGET_NSID:
986 			break;
987 		default:
988 			NL_SET_ERR_MSG(extack, "Unsupported attribute in peer netns getid request");
989 			return -EINVAL;
990 		}
991 	}
992 
993 	return 0;
994 }
995 
rtnl_net_getid(struct sk_buff * skb,struct nlmsghdr * nlh,struct netlink_ext_ack * extack)996 static int rtnl_net_getid(struct sk_buff *skb, struct nlmsghdr *nlh,
997 			  struct netlink_ext_ack *extack)
998 {
999 	struct net *net = sock_net(skb->sk);
1000 	struct nlattr *tb[NETNSA_MAX + 1];
1001 	struct net_fill_args fillargs = {
1002 		.portid = NETLINK_CB(skb).portid,
1003 		.seq = nlh->nlmsg_seq,
1004 		.cmd = RTM_NEWNSID,
1005 	};
1006 	struct net *peer, *target = net;
1007 	struct nlattr *nla;
1008 	struct sk_buff *msg;
1009 	int err;
1010 
1011 	err = rtnl_net_valid_getid_req(skb, nlh, tb, extack);
1012 	if (err < 0)
1013 		return err;
1014 	if (tb[NETNSA_PID]) {
1015 		peer = get_net_ns_by_pid(nla_get_u32(tb[NETNSA_PID]));
1016 		nla = tb[NETNSA_PID];
1017 	} else if (tb[NETNSA_FD]) {
1018 		peer = get_net_ns_by_fd(nla_get_u32(tb[NETNSA_FD]));
1019 		nla = tb[NETNSA_FD];
1020 	} else if (tb[NETNSA_NSID]) {
1021 		peer = get_net_ns_by_id(net, nla_get_s32(tb[NETNSA_NSID]));
1022 		if (!peer)
1023 			peer = ERR_PTR(-ENOENT);
1024 		nla = tb[NETNSA_NSID];
1025 	} else {
1026 		NL_SET_ERR_MSG(extack, "Peer netns reference is missing");
1027 		return -EINVAL;
1028 	}
1029 
1030 	if (IS_ERR(peer)) {
1031 		NL_SET_BAD_ATTR(extack, nla);
1032 		NL_SET_ERR_MSG(extack, "Peer netns reference is invalid");
1033 		return PTR_ERR(peer);
1034 	}
1035 
1036 	if (tb[NETNSA_TARGET_NSID]) {
1037 		int id = nla_get_s32(tb[NETNSA_TARGET_NSID]);
1038 
1039 		target = rtnl_get_net_ns_capable(NETLINK_CB(skb).sk, id);
1040 		if (IS_ERR(target)) {
1041 			NL_SET_BAD_ATTR(extack, tb[NETNSA_TARGET_NSID]);
1042 			NL_SET_ERR_MSG(extack,
1043 				       "Target netns reference is invalid");
1044 			err = PTR_ERR(target);
1045 			goto out;
1046 		}
1047 		fillargs.add_ref = true;
1048 		fillargs.ref_nsid = peernet2id(net, peer);
1049 	}
1050 
1051 	msg = nlmsg_new(rtnl_net_get_size(), GFP_KERNEL);
1052 	if (!msg) {
1053 		err = -ENOMEM;
1054 		goto out;
1055 	}
1056 
1057 	fillargs.nsid = peernet2id(target, peer);
1058 	err = rtnl_net_fill(msg, &fillargs);
1059 	if (err < 0)
1060 		goto err_out;
1061 
1062 	err = rtnl_unicast(msg, net, NETLINK_CB(skb).portid);
1063 	goto out;
1064 
1065 err_out:
1066 	nlmsg_free(msg);
1067 out:
1068 	if (fillargs.add_ref)
1069 		put_net(target);
1070 	put_net(peer);
1071 	return err;
1072 }
1073 
1074 struct rtnl_net_dump_cb {
1075 	struct net *tgt_net;
1076 	struct net *ref_net;
1077 	struct sk_buff *skb;
1078 	struct net_fill_args fillargs;
1079 	int idx;
1080 	int s_idx;
1081 };
1082 
1083 /* Runs in RCU-critical section. */
rtnl_net_dumpid_one(int id,void * peer,void * data)1084 static int rtnl_net_dumpid_one(int id, void *peer, void *data)
1085 {
1086 	struct rtnl_net_dump_cb *net_cb = (struct rtnl_net_dump_cb *)data;
1087 	int ret;
1088 
1089 	if (net_cb->idx < net_cb->s_idx)
1090 		goto cont;
1091 
1092 	net_cb->fillargs.nsid = id;
1093 	if (net_cb->fillargs.add_ref)
1094 		net_cb->fillargs.ref_nsid = __peernet2id(net_cb->ref_net, peer);
1095 	ret = rtnl_net_fill(net_cb->skb, &net_cb->fillargs);
1096 	if (ret < 0)
1097 		return ret;
1098 
1099 cont:
1100 	net_cb->idx++;
1101 	return 0;
1102 }
1103 
rtnl_valid_dump_net_req(const struct nlmsghdr * nlh,struct sock * sk,struct rtnl_net_dump_cb * net_cb,struct netlink_callback * cb)1104 static int rtnl_valid_dump_net_req(const struct nlmsghdr *nlh, struct sock *sk,
1105 				   struct rtnl_net_dump_cb *net_cb,
1106 				   struct netlink_callback *cb)
1107 {
1108 	struct netlink_ext_ack *extack = cb->extack;
1109 	struct nlattr *tb[NETNSA_MAX + 1];
1110 	int err, i;
1111 
1112 	err = nlmsg_parse_deprecated_strict(nlh, sizeof(struct rtgenmsg), tb,
1113 					    NETNSA_MAX, rtnl_net_policy,
1114 					    extack);
1115 	if (err < 0)
1116 		return err;
1117 
1118 	for (i = 0; i <= NETNSA_MAX; i++) {
1119 		if (!tb[i])
1120 			continue;
1121 
1122 		if (i == NETNSA_TARGET_NSID) {
1123 			struct net *net;
1124 
1125 			net = rtnl_get_net_ns_capable(sk, nla_get_s32(tb[i]));
1126 			if (IS_ERR(net)) {
1127 				NL_SET_BAD_ATTR(extack, tb[i]);
1128 				NL_SET_ERR_MSG(extack,
1129 					       "Invalid target network namespace id");
1130 				return PTR_ERR(net);
1131 			}
1132 			net_cb->fillargs.add_ref = true;
1133 			net_cb->ref_net = net_cb->tgt_net;
1134 			net_cb->tgt_net = net;
1135 		} else {
1136 			NL_SET_BAD_ATTR(extack, tb[i]);
1137 			NL_SET_ERR_MSG(extack,
1138 				       "Unsupported attribute in dump request");
1139 			return -EINVAL;
1140 		}
1141 	}
1142 
1143 	return 0;
1144 }
1145 
rtnl_net_dumpid(struct sk_buff * skb,struct netlink_callback * cb)1146 static int rtnl_net_dumpid(struct sk_buff *skb, struct netlink_callback *cb)
1147 {
1148 	struct rtnl_net_dump_cb net_cb = {
1149 		.tgt_net = sock_net(skb->sk),
1150 		.skb = skb,
1151 		.fillargs = {
1152 			.portid = NETLINK_CB(cb->skb).portid,
1153 			.seq = cb->nlh->nlmsg_seq,
1154 			.flags = NLM_F_MULTI,
1155 			.cmd = RTM_NEWNSID,
1156 		},
1157 		.idx = 0,
1158 		.s_idx = cb->args[0],
1159 	};
1160 	int err = 0;
1161 
1162 	if (cb->strict_check) {
1163 		err = rtnl_valid_dump_net_req(cb->nlh, skb->sk, &net_cb, cb);
1164 		if (err < 0)
1165 			goto end;
1166 	}
1167 
1168 	rcu_read_lock();
1169 	idr_for_each(&net_cb.tgt_net->netns_ids, rtnl_net_dumpid_one, &net_cb);
1170 	rcu_read_unlock();
1171 
1172 	cb->args[0] = net_cb.idx;
1173 end:
1174 	if (net_cb.fillargs.add_ref)
1175 		put_net(net_cb.tgt_net);
1176 	return err;
1177 }
1178 
rtnl_net_notifyid(struct net * net,int cmd,int id,u32 portid,struct nlmsghdr * nlh,gfp_t gfp)1179 static void rtnl_net_notifyid(struct net *net, int cmd, int id, u32 portid,
1180 			      struct nlmsghdr *nlh, gfp_t gfp)
1181 {
1182 	struct net_fill_args fillargs = {
1183 		.portid = portid,
1184 		.seq = nlh ? nlh->nlmsg_seq : 0,
1185 		.cmd = cmd,
1186 		.nsid = id,
1187 	};
1188 	struct sk_buff *msg;
1189 	int err = -ENOMEM;
1190 
1191 	msg = nlmsg_new(rtnl_net_get_size(), gfp);
1192 	if (!msg)
1193 		goto out;
1194 
1195 	err = rtnl_net_fill(msg, &fillargs);
1196 	if (err < 0)
1197 		goto err_out;
1198 
1199 	rtnl_notify(msg, net, portid, RTNLGRP_NSID, nlh, gfp);
1200 	return;
1201 
1202 err_out:
1203 	nlmsg_free(msg);
1204 out:
1205 	rtnl_set_sk_err(net, RTNLGRP_NSID, err);
1206 }
1207 
1208 #ifdef CONFIG_NET_NS
netns_ipv4_struct_check(void)1209 static void __init netns_ipv4_struct_check(void)
1210 {
1211 	/* TX readonly hotpath cache lines */
1212 	CACHELINE_ASSERT_GROUP_MEMBER(struct netns_ipv4, netns_ipv4_read_tx,
1213 				      sysctl_tcp_early_retrans);
1214 	CACHELINE_ASSERT_GROUP_MEMBER(struct netns_ipv4, netns_ipv4_read_tx,
1215 				      sysctl_tcp_tso_win_divisor);
1216 	CACHELINE_ASSERT_GROUP_MEMBER(struct netns_ipv4, netns_ipv4_read_tx,
1217 				      sysctl_tcp_tso_rtt_log);
1218 	CACHELINE_ASSERT_GROUP_MEMBER(struct netns_ipv4, netns_ipv4_read_tx,
1219 				      sysctl_tcp_autocorking);
1220 	CACHELINE_ASSERT_GROUP_MEMBER(struct netns_ipv4, netns_ipv4_read_tx,
1221 				      sysctl_tcp_min_snd_mss);
1222 	CACHELINE_ASSERT_GROUP_MEMBER(struct netns_ipv4, netns_ipv4_read_tx,
1223 				      sysctl_tcp_notsent_lowat);
1224 	CACHELINE_ASSERT_GROUP_MEMBER(struct netns_ipv4, netns_ipv4_read_tx,
1225 				      sysctl_tcp_limit_output_bytes);
1226 	CACHELINE_ASSERT_GROUP_MEMBER(struct netns_ipv4, netns_ipv4_read_tx,
1227 				      sysctl_tcp_min_rtt_wlen);
1228 	CACHELINE_ASSERT_GROUP_MEMBER(struct netns_ipv4, netns_ipv4_read_tx,
1229 				      sysctl_tcp_wmem);
1230 	CACHELINE_ASSERT_GROUP_MEMBER(struct netns_ipv4, netns_ipv4_read_tx,
1231 				      sysctl_ip_fwd_use_pmtu);
1232 
1233 	/* RX readonly hotpath cache line */
1234 	CACHELINE_ASSERT_GROUP_MEMBER(struct netns_ipv4, netns_ipv4_read_rx,
1235 				      sysctl_tcp_moderate_rcvbuf);
1236 	CACHELINE_ASSERT_GROUP_MEMBER(struct netns_ipv4, netns_ipv4_read_rx,
1237 				      sysctl_tcp_rcvbuf_low_rtt);
1238 	CACHELINE_ASSERT_GROUP_MEMBER(struct netns_ipv4, netns_ipv4_read_rx,
1239 				      sysctl_ip_early_demux);
1240 	CACHELINE_ASSERT_GROUP_MEMBER(struct netns_ipv4, netns_ipv4_read_rx,
1241 				      sysctl_tcp_early_demux);
1242 	CACHELINE_ASSERT_GROUP_MEMBER(struct netns_ipv4, netns_ipv4_read_rx,
1243 				      sysctl_tcp_l3mdev_accept);
1244 	CACHELINE_ASSERT_GROUP_MEMBER(struct netns_ipv4, netns_ipv4_read_rx,
1245 				      sysctl_tcp_reordering);
1246 	CACHELINE_ASSERT_GROUP_MEMBER(struct netns_ipv4, netns_ipv4_read_rx,
1247 				      sysctl_tcp_rmem);
1248 }
1249 #endif
1250 
1251 static const struct rtnl_msg_handler net_ns_rtnl_msg_handlers[] __initconst = {
1252 	{.msgtype = RTM_NEWNSID, .doit = rtnl_net_newid,
1253 	 .flags = RTNL_FLAG_DOIT_UNLOCKED},
1254 	{.msgtype = RTM_GETNSID, .doit = rtnl_net_getid,
1255 	 .dumpit = rtnl_net_dumpid,
1256 	 .flags = RTNL_FLAG_DOIT_UNLOCKED | RTNL_FLAG_DUMP_UNLOCKED},
1257 };
1258 
net_ns_init(void)1259 void __init net_ns_init(void)
1260 {
1261 	struct net_generic *ng;
1262 
1263 #ifdef CONFIG_NET_NS
1264 	netns_ipv4_struct_check();
1265 	net_cachep = kmem_cache_create("net_namespace", sizeof(struct net),
1266 					SMP_CACHE_BYTES,
1267 					SLAB_PANIC|SLAB_ACCOUNT, NULL);
1268 
1269 	/* Create workqueue for cleanup */
1270 	netns_wq = create_singlethread_workqueue("netns");
1271 	if (!netns_wq)
1272 		panic("Could not create netns workq");
1273 #endif
1274 
1275 	ng = net_alloc_generic();
1276 	if (!ng)
1277 		panic("Could not allocate generic netns");
1278 
1279 	rcu_assign_pointer(init_net.gen, ng);
1280 
1281 #ifdef CONFIG_KEYS
1282 	init_net.key_domain = &init_net_key_domain;
1283 #endif
1284 	/*
1285 	 * This currently cannot fail as the initial network namespace
1286 	 * has a static inode number.
1287 	 */
1288 	if (preinit_net(&init_net, &init_user_ns))
1289 		panic("Could not preinitialize the initial network namespace");
1290 
1291 	down_write(&pernet_ops_rwsem);
1292 	if (setup_net(&init_net))
1293 		panic("Could not setup the initial network namespace");
1294 
1295 	init_net_initialized = true;
1296 	up_write(&pernet_ops_rwsem);
1297 
1298 	if (register_pernet_subsys(&net_ns_ops))
1299 		panic("Could not register network namespace subsystems");
1300 
1301 	rtnl_register_many(net_ns_rtnl_msg_handlers);
1302 }
1303 
1304 #ifdef CONFIG_NET_NS
__register_pernet_operations(struct list_head * list,struct pernet_operations * ops)1305 static int __register_pernet_operations(struct list_head *list,
1306 					struct pernet_operations *ops)
1307 {
1308 	LIST_HEAD(net_exit_list);
1309 	struct net *net;
1310 	int error;
1311 
1312 	list_add_tail(&ops->list, list);
1313 	if (ops->init || ops->id) {
1314 		/* We held write locked pernet_ops_rwsem, and parallel
1315 		 * setup_net() and cleanup_net() are not possible.
1316 		 */
1317 		for_each_net(net) {
1318 			error = ops_init(ops, net);
1319 			if (error)
1320 				goto out_undo;
1321 			list_add_tail(&net->exit_list, &net_exit_list);
1322 		}
1323 	}
1324 	return 0;
1325 
1326 out_undo:
1327 	/* If I have an error cleanup all namespaces I initialized */
1328 	list_del(&ops->list);
1329 	ops_undo_single(ops, &net_exit_list);
1330 	return error;
1331 }
1332 
__unregister_pernet_operations(struct pernet_operations * ops)1333 static void __unregister_pernet_operations(struct pernet_operations *ops)
1334 {
1335 	LIST_HEAD(net_exit_list);
1336 	struct net *net;
1337 
1338 	/* See comment in __register_pernet_operations() */
1339 	for_each_net(net)
1340 		list_add_tail(&net->exit_list, &net_exit_list);
1341 
1342 	list_del(&ops->list);
1343 	ops_undo_single(ops, &net_exit_list);
1344 }
1345 
1346 #else
1347 
__register_pernet_operations(struct list_head * list,struct pernet_operations * ops)1348 static int __register_pernet_operations(struct list_head *list,
1349 					struct pernet_operations *ops)
1350 {
1351 	if (!init_net_initialized) {
1352 		list_add_tail(&ops->list, list);
1353 		return 0;
1354 	}
1355 
1356 	return ops_init(ops, &init_net);
1357 }
1358 
__unregister_pernet_operations(struct pernet_operations * ops)1359 static void __unregister_pernet_operations(struct pernet_operations *ops)
1360 {
1361 	if (!init_net_initialized) {
1362 		list_del(&ops->list);
1363 	} else {
1364 		LIST_HEAD(net_exit_list);
1365 
1366 		list_add(&init_net.exit_list, &net_exit_list);
1367 		ops_undo_single(ops, &net_exit_list);
1368 	}
1369 }
1370 
1371 #endif /* CONFIG_NET_NS */
1372 
1373 static DEFINE_IDA(net_generic_ids);
1374 
register_pernet_operations(struct list_head * list,struct pernet_operations * ops)1375 static int register_pernet_operations(struct list_head *list,
1376 				      struct pernet_operations *ops)
1377 {
1378 	int error;
1379 
1380 	if (WARN_ON(!!ops->id ^ !!ops->size))
1381 		return -EINVAL;
1382 
1383 	if (ops->id) {
1384 		error = ida_alloc_min(&net_generic_ids, MIN_PERNET_OPS_ID,
1385 				GFP_KERNEL);
1386 		if (error < 0)
1387 			return error;
1388 		*ops->id = error;
1389 		/* This does not require READ_ONCE as writers already hold
1390 		 * pernet_ops_rwsem. But WRITE_ONCE is needed to protect
1391 		 * net_alloc_generic.
1392 		 */
1393 		WRITE_ONCE(max_gen_ptrs, max(max_gen_ptrs, *ops->id + 1));
1394 	}
1395 	error = __register_pernet_operations(list, ops);
1396 	if (error) {
1397 		rcu_barrier();
1398 		if (ops->id)
1399 			ida_free(&net_generic_ids, *ops->id);
1400 	}
1401 
1402 	return error;
1403 }
1404 
unregister_pernet_operations(struct pernet_operations * ops)1405 static void unregister_pernet_operations(struct pernet_operations *ops)
1406 {
1407 	__unregister_pernet_operations(ops);
1408 	rcu_barrier();
1409 	if (ops->id)
1410 		ida_free(&net_generic_ids, *ops->id);
1411 }
1412 
1413 /**
1414  *      register_pernet_subsys - register a network namespace subsystem
1415  *	@ops:  pernet operations structure for the subsystem
1416  *
1417  *	Register a subsystem which has init and exit functions
1418  *	that are called when network namespaces are created and
1419  *	destroyed respectively.
1420  *
1421  *	When registered all network namespace init functions are
1422  *	called for every existing network namespace.  Allowing kernel
1423  *	modules to have a race free view of the set of network namespaces.
1424  *
1425  *	When a new network namespace is created all of the init
1426  *	methods are called in the order in which they were registered.
1427  *
1428  *	When a network namespace is destroyed all of the exit methods
1429  *	are called in the reverse of the order with which they were
1430  *	registered.
1431  */
register_pernet_subsys(struct pernet_operations * ops)1432 int register_pernet_subsys(struct pernet_operations *ops)
1433 {
1434 	int error;
1435 	down_write(&pernet_ops_rwsem);
1436 	error =  register_pernet_operations(first_device, ops);
1437 	up_write(&pernet_ops_rwsem);
1438 	return error;
1439 }
1440 EXPORT_SYMBOL_GPL(register_pernet_subsys);
1441 
1442 /**
1443  *      unregister_pernet_subsys - unregister a network namespace subsystem
1444  *	@ops: pernet operations structure to manipulate
1445  *
1446  *	Remove the pernet operations structure from the list to be
1447  *	used when network namespaces are created or destroyed.  In
1448  *	addition run the exit method for all existing network
1449  *	namespaces.
1450  */
unregister_pernet_subsys(struct pernet_operations * ops)1451 void unregister_pernet_subsys(struct pernet_operations *ops)
1452 {
1453 	down_write(&pernet_ops_rwsem);
1454 	unregister_pernet_operations(ops);
1455 	up_write(&pernet_ops_rwsem);
1456 }
1457 EXPORT_SYMBOL_GPL(unregister_pernet_subsys);
1458 
1459 /**
1460  *      register_pernet_device - register a network namespace device
1461  *	@ops:  pernet operations structure for the subsystem
1462  *
1463  *	Register a device which has init and exit functions
1464  *	that are called when network namespaces are created and
1465  *	destroyed respectively.
1466  *
1467  *	When registered all network namespace init functions are
1468  *	called for every existing network namespace.  Allowing kernel
1469  *	modules to have a race free view of the set of network namespaces.
1470  *
1471  *	When a new network namespace is created all of the init
1472  *	methods are called in the order in which they were registered.
1473  *
1474  *	When a network namespace is destroyed all of the exit methods
1475  *	are called in the reverse of the order with which they were
1476  *	registered.
1477  */
register_pernet_device(struct pernet_operations * ops)1478 int register_pernet_device(struct pernet_operations *ops)
1479 {
1480 	int error;
1481 	down_write(&pernet_ops_rwsem);
1482 	error = register_pernet_operations(&pernet_list, ops);
1483 	if (!error && (first_device == &pernet_list))
1484 		first_device = &ops->list;
1485 	up_write(&pernet_ops_rwsem);
1486 	return error;
1487 }
1488 EXPORT_SYMBOL_GPL(register_pernet_device);
1489 
1490 /**
1491  *      unregister_pernet_device - unregister a network namespace netdevice
1492  *	@ops: pernet operations structure to manipulate
1493  *
1494  *	Remove the pernet operations structure from the list to be
1495  *	used when network namespaces are created or destroyed.  In
1496  *	addition run the exit method for all existing network
1497  *	namespaces.
1498  */
unregister_pernet_device(struct pernet_operations * ops)1499 void unregister_pernet_device(struct pernet_operations *ops)
1500 {
1501 	down_write(&pernet_ops_rwsem);
1502 	if (&ops->list == first_device)
1503 		first_device = first_device->next;
1504 	unregister_pernet_operations(ops);
1505 	up_write(&pernet_ops_rwsem);
1506 }
1507 EXPORT_SYMBOL_GPL(unregister_pernet_device);
1508 
1509 #ifdef CONFIG_NET_NS
netns_get(struct task_struct * task)1510 static struct ns_common *netns_get(struct task_struct *task)
1511 {
1512 	struct net *net = NULL;
1513 	struct nsproxy *nsproxy;
1514 
1515 	task_lock(task);
1516 	nsproxy = task->nsproxy;
1517 	if (nsproxy)
1518 		net = get_net(nsproxy->net_ns);
1519 	task_unlock(task);
1520 
1521 	return net ? &net->ns : NULL;
1522 }
1523 
netns_put(struct ns_common * ns)1524 static void netns_put(struct ns_common *ns)
1525 {
1526 	put_net(to_net_ns(ns));
1527 }
1528 
netns_install(struct nsset * nsset,struct ns_common * ns)1529 static int netns_install(struct nsset *nsset, struct ns_common *ns)
1530 {
1531 	struct nsproxy *nsproxy = nsset->nsproxy;
1532 	struct net *net = to_net_ns(ns);
1533 
1534 	if (!ns_capable(net->user_ns, CAP_SYS_ADMIN) ||
1535 	    !ns_capable(nsset->cred->user_ns, CAP_SYS_ADMIN))
1536 		return -EPERM;
1537 
1538 	put_net(nsproxy->net_ns);
1539 	nsproxy->net_ns = get_net(net);
1540 	return 0;
1541 }
1542 
netns_owner(struct ns_common * ns)1543 static struct user_namespace *netns_owner(struct ns_common *ns)
1544 {
1545 	return to_net_ns(ns)->user_ns;
1546 }
1547 
1548 const struct proc_ns_operations netns_operations = {
1549 	.name		= "net",
1550 	.get		= netns_get,
1551 	.put		= netns_put,
1552 	.install	= netns_install,
1553 	.owner		= netns_owner,
1554 };
1555 #endif
1556