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