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