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