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