xref: /linux/fs/super.c (revision 3ef975893041b9f826475298c802b5c046d0ba16)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  linux/fs/super.c
4  *
5  *  Copyright (C) 1991, 1992  Linus Torvalds
6  *
7  *  super.c contains code to handle: - mount structures
8  *                                   - super-block tables
9  *                                   - filesystem drivers list
10  *                                   - mount system call
11  *                                   - umount system call
12  *                                   - ustat system call
13  *
14  * GK 2/5/95  -  Changed to support mounting the root fs via NFS
15  *
16  *  Added kerneld support: Jacques Gelinas and Bjorn Ekwall
17  *  Added change_root: Werner Almesberger & Hans Lermen, Feb '96
18  *  Added options to /proc/mounts:
19  *    Torbjörn Lindh (torbjorn.lindh@gopta.se), April 14, 1996.
20  *  Added devfs support: Richard Gooch <rgooch@atnf.csiro.au>, 13-JAN-1998
21  *  Heavily rewritten for 'one fs - one tree' dcache architecture. AV, Mar 2000
22  */
23 
24 #include <linux/export.h>
25 #include <linux/slab.h>
26 #include <linux/blkdev.h>
27 #include <linux/mount.h>
28 #include <linux/security.h>
29 #include <linux/writeback.h>		/* for the emergency remount stuff */
30 #include <linux/idr.h>
31 #include <linux/mutex.h>
32 #include <linux/backing-dev.h>
33 #include <linux/rculist_bl.h>
34 #include <linux/fscrypt.h>
35 #include <linux/fsnotify.h>
36 #include <linux/lockdep.h>
37 #include <linux/user_namespace.h>
38 #include <linux/fs_context.h>
39 #include <linux/fserror.h>
40 #include <uapi/linux/mount.h>
41 #include "internal.h"
42 
43 static int thaw_super_locked(struct super_block *sb, enum freeze_holder who,
44 			     const void *freeze_owner);
45 
46 static LIST_HEAD(super_blocks);
47 static DEFINE_SPINLOCK(sb_lock);
48 
49 static char *sb_writers_name[SB_FREEZE_LEVELS] = {
50 	"sb_writers",
51 	"sb_pagefaults",
52 	"sb_internal",
53 };
54 
55 static inline void __super_lock(struct super_block *sb, bool excl)
56 {
57 	if (excl)
58 		down_write(&sb->s_umount);
59 	else
60 		down_read(&sb->s_umount);
61 }
62 
63 static inline void super_unlock(struct super_block *sb, bool excl)
64 {
65 	if (excl)
66 		up_write(&sb->s_umount);
67 	else
68 		up_read(&sb->s_umount);
69 }
70 
71 static inline void __super_lock_excl(struct super_block *sb)
72 {
73 	__super_lock(sb, true);
74 }
75 
76 static inline void super_unlock_excl(struct super_block *sb)
77 {
78 	super_unlock(sb, true);
79 }
80 
81 static inline void super_unlock_shared(struct super_block *sb)
82 {
83 	super_unlock(sb, false);
84 }
85 
86 static bool super_flags(const struct super_block *sb, unsigned int flags)
87 {
88 	/*
89 	 * Pairs with smp_store_release() in super_wake() and ensures
90 	 * that we see @flags after we're woken.
91 	 */
92 	return smp_load_acquire(&sb->s_flags) & flags;
93 }
94 
95 /**
96  * super_lock - wait for superblock to become ready and lock it
97  * @sb: superblock to wait for
98  * @excl: whether exclusive access is required
99  *
100  * If the superblock has neither passed through vfs_get_tree() or
101  * generic_shutdown_super() yet wait for it to happen. Either superblock
102  * creation will succeed and SB_BORN is set by vfs_get_tree() or we're
103  * woken and we'll see SB_DYING.
104  *
105  * The caller must have acquired a temporary reference on @sb->s_count.
106  *
107  * Return: The function returns true if SB_BORN was set and with
108  *         s_umount held. The function returns false if SB_DYING was
109  *         set and without s_umount held.
110  */
111 static __must_check bool super_lock(struct super_block *sb, bool excl)
112 {
113 	lockdep_assert_not_held(&sb->s_umount);
114 
115 	/* wait until the superblock is ready or dying */
116 	wait_var_event(&sb->s_flags, super_flags(sb, SB_BORN | SB_DYING));
117 
118 	/* Don't pointlessly acquire s_umount. */
119 	if (super_flags(sb, SB_DYING))
120 		return false;
121 
122 	__super_lock(sb, excl);
123 
124 	/*
125 	 * Has gone through generic_shutdown_super() in the meantime.
126 	 * @sb->s_root is NULL and @sb->s_active is 0. No one needs to
127 	 * grab a reference to this. Tell them so.
128 	 */
129 	if (sb->s_flags & SB_DYING) {
130 		super_unlock(sb, excl);
131 		return false;
132 	}
133 
134 	WARN_ON_ONCE(!(sb->s_flags & SB_BORN));
135 	return true;
136 }
137 
138 /* wait and try to acquire read-side of @sb->s_umount */
139 static inline bool super_lock_shared(struct super_block *sb)
140 {
141 	return super_lock(sb, false);
142 }
143 
144 /* wait and try to acquire write-side of @sb->s_umount */
145 static inline bool super_lock_excl(struct super_block *sb)
146 {
147 	return super_lock(sb, true);
148 }
149 
150 /* wake waiters */
151 #define SUPER_WAKE_FLAGS (SB_BORN | SB_DYING | SB_DEAD)
152 static void super_wake(struct super_block *sb, unsigned int flag)
153 {
154 	WARN_ON_ONCE((flag & ~SUPER_WAKE_FLAGS));
155 	WARN_ON_ONCE(hweight32(flag & SUPER_WAKE_FLAGS) > 1);
156 
157 	/*
158 	 * Pairs with smp_load_acquire() in super_lock() to make sure
159 	 * all initializations in the superblock are seen by the user
160 	 * seeing SB_BORN sent.
161 	 */
162 	smp_store_release(&sb->s_flags, sb->s_flags | flag);
163 	/*
164 	 * Pairs with the barrier in prepare_to_wait_event() to make sure
165 	 * ___wait_var_event() either sees SB_BORN set or
166 	 * waitqueue_active() check in wake_up_var() sees the waiter.
167 	 */
168 	smp_mb();
169 	wake_up_var(&sb->s_flags);
170 }
171 
172 /*
173  * One thing we have to be careful of with a per-sb shrinker is that we don't
174  * drop the last active reference to the superblock from within the shrinker.
175  * If that happens we could trigger unregistering the shrinker from within the
176  * shrinker path and that leads to deadlock on the shrinker_mutex. Hence we
177  * take a passive reference to the superblock to avoid this from occurring.
178  */
179 static unsigned long super_cache_scan(struct shrinker *shrink,
180 				      struct shrink_control *sc)
181 {
182 	struct super_block *sb;
183 	long	fs_objects = 0;
184 	long	total_objects;
185 	long	freed = 0;
186 	long	dentries;
187 	long	inodes;
188 
189 	sb = shrink->private_data;
190 
191 	/*
192 	 * Deadlock avoidance.  We may hold various FS locks, and we don't want
193 	 * to recurse into the FS that called us in clear_inode() and friends..
194 	 */
195 	if (!(sc->gfp_mask & __GFP_FS))
196 		return SHRINK_STOP;
197 
198 	if (!super_trylock_shared(sb))
199 		return SHRINK_STOP;
200 
201 	if (sb->s_op->nr_cached_objects)
202 		fs_objects = sb->s_op->nr_cached_objects(sb, sc);
203 
204 	inodes = list_lru_shrink_count(&sb->s_inode_lru, sc);
205 	dentries = list_lru_shrink_count(&sb->s_dentry_lru, sc);
206 	total_objects = dentries + inodes + fs_objects;
207 	if (!total_objects)
208 		total_objects = 1;
209 
210 	/* proportion the scan between the caches */
211 	dentries = mult_frac(sc->nr_to_scan, dentries, total_objects);
212 	inodes = mult_frac(sc->nr_to_scan, inodes, total_objects);
213 	fs_objects = mult_frac(sc->nr_to_scan, fs_objects, total_objects);
214 
215 	/*
216 	 * prune the dcache first as the icache is pinned by it, then
217 	 * prune the icache, followed by the filesystem specific caches
218 	 *
219 	 * Ensure that we always scan at least one object - memcg kmem
220 	 * accounting uses this to fully empty the caches.
221 	 */
222 	sc->nr_to_scan = dentries + 1;
223 	freed = prune_dcache_sb(sb, sc);
224 	sc->nr_to_scan = inodes + 1;
225 	freed += prune_icache_sb(sb, sc);
226 
227 	if (fs_objects) {
228 		sc->nr_to_scan = fs_objects + 1;
229 		freed += sb->s_op->free_cached_objects(sb, sc);
230 	}
231 
232 	super_unlock_shared(sb);
233 	return freed;
234 }
235 
236 static unsigned long super_cache_count(struct shrinker *shrink,
237 				       struct shrink_control *sc)
238 {
239 	struct super_block *sb;
240 	long	total_objects = 0;
241 
242 	sb = shrink->private_data;
243 
244 	/*
245 	 * We don't call super_trylock_shared() here as it is a scalability
246 	 * bottleneck, so we're exposed to partial setup state. The shrinker
247 	 * rwsem does not protect filesystem operations backing
248 	 * list_lru_shrink_count() or s_op->nr_cached_objects(). Counts can
249 	 * change between super_cache_count and super_cache_scan, so we really
250 	 * don't need locks here.
251 	 *
252 	 * However, if we are currently mounting the superblock, the underlying
253 	 * filesystem might be in a state of partial construction and hence it
254 	 * is dangerous to access it.  super_trylock_shared() uses a SB_BORN check
255 	 * to avoid this situation, so do the same here. The memory barrier is
256 	 * matched with the one in mount_fs() as we don't hold locks here.
257 	 */
258 	if (!(sb->s_flags & SB_BORN))
259 		return 0;
260 	smp_rmb();
261 
262 	if (sb->s_op && sb->s_op->nr_cached_objects)
263 		total_objects = sb->s_op->nr_cached_objects(sb, sc);
264 
265 	total_objects += list_lru_shrink_count(&sb->s_dentry_lru, sc);
266 	total_objects += list_lru_shrink_count(&sb->s_inode_lru, sc);
267 
268 	if (!total_objects)
269 		return SHRINK_EMPTY;
270 
271 	total_objects = vfs_pressure_ratio(total_objects);
272 	return total_objects;
273 }
274 
275 static void destroy_super_work(struct work_struct *work)
276 {
277 	struct super_block *s = container_of(work, struct super_block,
278 							destroy_work);
279 	fsnotify_sb_free(s);
280 	security_sb_free(s);
281 	put_user_ns(s->s_user_ns);
282 	kfree(s->s_subtype);
283 	for (int i = 0; i < SB_FREEZE_LEVELS; i++)
284 		percpu_free_rwsem(&s->s_writers.rw_sem[i]);
285 	kfree(s);
286 }
287 
288 static void destroy_super_rcu(struct rcu_head *head)
289 {
290 	struct super_block *s = container_of(head, struct super_block, rcu);
291 	INIT_WORK(&s->destroy_work, destroy_super_work);
292 	schedule_work(&s->destroy_work);
293 }
294 
295 /* Free a superblock that has never been seen by anyone */
296 static void destroy_unused_super(struct super_block *s)
297 {
298 	if (!s)
299 		return;
300 	super_unlock_excl(s);
301 	list_lru_destroy(&s->s_dentry_lru);
302 	list_lru_destroy(&s->s_inode_lru);
303 	shrinker_free(s->s_shrink);
304 	/* no delays needed */
305 	destroy_super_work(&s->destroy_work);
306 }
307 
308 /**
309  *	alloc_super	-	create new superblock
310  *	@type:	filesystem type superblock should belong to
311  *	@flags: the mount flags
312  *	@user_ns: User namespace for the super_block
313  *
314  *	Allocates and initializes a new &struct super_block.  alloc_super()
315  *	returns a pointer new superblock or %NULL if allocation had failed.
316  */
317 static struct super_block *alloc_super(struct file_system_type *type, int flags,
318 				       struct user_namespace *user_ns)
319 {
320 	struct super_block *s = kzalloc_obj(struct super_block);
321 	static const struct super_operations default_op;
322 	int i;
323 
324 	if (!s)
325 		return NULL;
326 
327 	s->s_user_ns = get_user_ns(user_ns);
328 	init_rwsem(&s->s_umount);
329 	lockdep_set_class(&s->s_umount, &type->s_umount_key);
330 	/*
331 	 * sget_fc() can have s_umount recursion.
332 	 *
333 	 * When it cannot find a suitable sb, it allocates a new
334 	 * one (this one), and tries again to find a suitable old
335 	 * one.
336 	 *
337 	 * In case that succeeds, it will acquire the s_umount
338 	 * lock of the old one. Since these are clearly distrinct
339 	 * locks, and this object isn't exposed yet, there's no
340 	 * risk of deadlocks.
341 	 *
342 	 * Annotate this by putting this lock in a different
343 	 * subclass.
344 	 */
345 	down_write_nested(&s->s_umount, SINGLE_DEPTH_NESTING);
346 
347 	if (security_sb_alloc(s))
348 		goto fail;
349 
350 	for (i = 0; i < SB_FREEZE_LEVELS; i++) {
351 		if (__percpu_init_rwsem(&s->s_writers.rw_sem[i],
352 					sb_writers_name[i],
353 					&type->s_writers_key[i]))
354 			goto fail;
355 	}
356 	s->s_bdi = &noop_backing_dev_info;
357 	s->s_flags = flags;
358 	if (s->s_user_ns != &init_user_ns)
359 		s->s_iflags |= SB_I_NODEV;
360 	INIT_HLIST_NODE(&s->s_instances);
361 	INIT_HLIST_BL_HEAD(&s->s_roots);
362 	spin_lock_init(&s->s_roots_lock);
363 	mutex_init(&s->s_sync_lock);
364 	INIT_LIST_HEAD(&s->s_inodes);
365 	spin_lock_init(&s->s_inode_list_lock);
366 	INIT_LIST_HEAD(&s->s_inodes_wb);
367 	spin_lock_init(&s->s_inode_wblist_lock);
368 	fserror_mount(s);
369 
370 	s->s_count = 1;
371 	atomic_set(&s->s_active, 1);
372 	mutex_init(&s->s_vfs_rename_mutex);
373 	lockdep_set_class(&s->s_vfs_rename_mutex, &type->s_vfs_rename_key);
374 	init_rwsem(&s->s_dquot.dqio_sem);
375 	s->s_maxbytes = MAX_NON_LFS;
376 	s->s_op = &default_op;
377 	s->s_time_gran = 1000000000;
378 	s->s_time_min = TIME64_MIN;
379 	s->s_time_max = TIME64_MAX;
380 
381 	s->s_shrink = shrinker_alloc(SHRINKER_NUMA_AWARE | SHRINKER_MEMCG_AWARE,
382 				     "sb-%s", type->name);
383 	if (!s->s_shrink)
384 		goto fail;
385 
386 	s->s_shrink->scan_objects = super_cache_scan;
387 	s->s_shrink->count_objects = super_cache_count;
388 	s->s_shrink->batch = 1024;
389 	s->s_shrink->private_data = s;
390 
391 	if (list_lru_init_memcg(&s->s_dentry_lru, s->s_shrink))
392 		goto fail;
393 	if (list_lru_init_memcg(&s->s_inode_lru, s->s_shrink))
394 		goto fail;
395 	s->s_min_writeback_pages = MIN_WRITEBACK_PAGES;
396 	return s;
397 
398 fail:
399 	destroy_unused_super(s);
400 	return NULL;
401 }
402 
403 /* Superblock refcounting  */
404 
405 /*
406  * Drop a superblock's refcount.  The caller must hold sb_lock.
407  */
408 static void __put_super(struct super_block *s)
409 {
410 	if (!--s->s_count) {
411 		list_del_init(&s->s_list);
412 		WARN_ON(s->s_dentry_lru.node);
413 		WARN_ON(s->s_inode_lru.node);
414 		WARN_ON(s->s_mounts);
415 		call_rcu(&s->rcu, destroy_super_rcu);
416 	}
417 }
418 
419 /**
420  *	put_super	-	drop a temporary reference to superblock
421  *	@sb: superblock in question
422  *
423  *	Drops a temporary reference, frees superblock if there's no
424  *	references left.
425  */
426 void put_super(struct super_block *sb)
427 {
428 	spin_lock(&sb_lock);
429 	__put_super(sb);
430 	spin_unlock(&sb_lock);
431 }
432 
433 static void kill_super_notify(struct super_block *sb)
434 {
435 	lockdep_assert_not_held(&sb->s_umount);
436 
437 	/* already notified earlier */
438 	if (sb->s_flags & SB_DEAD)
439 		return;
440 
441 	/*
442 	 * Remove it from @fs_supers so it isn't found by new
443 	 * sget_fc() walkers anymore. Any concurrent mounter still
444 	 * managing to grab a temporary reference is guaranteed to
445 	 * already see SB_DYING and will wait until we notify them about
446 	 * SB_DEAD.
447 	 */
448 	spin_lock(&sb_lock);
449 	hlist_del_init(&sb->s_instances);
450 	spin_unlock(&sb_lock);
451 
452 	/*
453 	 * Let concurrent mounts know that this thing is really dead.
454 	 * We don't need @sb->s_umount here as every concurrent caller
455 	 * will see SB_DYING and either discard the superblock or wait
456 	 * for SB_DEAD.
457 	 */
458 	super_wake(sb, SB_DEAD);
459 }
460 
461 /**
462  *	deactivate_locked_super	-	drop an active reference to superblock
463  *	@s: superblock to deactivate
464  *
465  *	Drops an active reference to superblock, converting it into a temporary
466  *	one if there is no other active references left.  In that case we
467  *	tell fs driver to shut it down and drop the temporary reference we
468  *	had just acquired.
469  *
470  *	Caller holds exclusive lock on superblock; that lock is released.
471  */
472 void deactivate_locked_super(struct super_block *s)
473 {
474 	struct file_system_type *fs = s->s_type;
475 	if (atomic_dec_and_test(&s->s_active)) {
476 		shrinker_free(s->s_shrink);
477 		fs->kill_sb(s);
478 
479 		kill_super_notify(s);
480 
481 		/*
482 		 * Since list_lru_destroy() may sleep, we cannot call it from
483 		 * put_super(), where we hold the sb_lock. Therefore we destroy
484 		 * the lru lists right now.
485 		 */
486 		list_lru_destroy(&s->s_dentry_lru);
487 		list_lru_destroy(&s->s_inode_lru);
488 
489 		put_filesystem(fs);
490 		put_super(s);
491 	} else {
492 		super_unlock_excl(s);
493 	}
494 }
495 
496 EXPORT_SYMBOL(deactivate_locked_super);
497 
498 /**
499  *	deactivate_super	-	drop an active reference to superblock
500  *	@s: superblock to deactivate
501  *
502  *	Variant of deactivate_locked_super(), except that superblock is *not*
503  *	locked by caller.  If we are going to drop the final active reference,
504  *	lock will be acquired prior to that.
505  */
506 void deactivate_super(struct super_block *s)
507 {
508 	if (!atomic_add_unless(&s->s_active, -1, 1)) {
509 		__super_lock_excl(s);
510 		deactivate_locked_super(s);
511 	}
512 }
513 
514 EXPORT_SYMBOL(deactivate_super);
515 
516 /**
517  * grab_super - acquire an active reference to a superblock
518  * @sb: superblock to acquire
519  *
520  * Acquire a temporary reference on a superblock and try to trade it for
521  * an active reference. This is used in sget_fc() to wait for a
522  * superblock to either become SB_BORN or for it to pass through
523  * sb->kill() and be marked as SB_DEAD.
524  *
525  * Return: This returns true if an active reference could be acquired,
526  *         false if not.
527  */
528 static bool grab_super(struct super_block *sb)
529 {
530 	bool locked;
531 
532 	sb->s_count++;
533 	spin_unlock(&sb_lock);
534 	locked = super_lock_excl(sb);
535 	if (locked) {
536 		if (atomic_inc_not_zero(&sb->s_active)) {
537 			put_super(sb);
538 			return true;
539 		}
540 		super_unlock_excl(sb);
541 	}
542 	wait_var_event(&sb->s_flags, super_flags(sb, SB_DEAD));
543 	put_super(sb);
544 	return false;
545 }
546 
547 /*
548  *	super_trylock_shared - try to grab ->s_umount shared
549  *	@sb: reference we are trying to grab
550  *
551  *	Try to prevent fs shutdown.  This is used in places where we
552  *	cannot take an active reference but we need to ensure that the
553  *	filesystem is not shut down while we are working on it. It returns
554  *	false if we cannot acquire s_umount or if we lose the race and
555  *	filesystem already got into shutdown, and returns true with the s_umount
556  *	lock held in read mode in case of success. On successful return,
557  *	the caller must drop the s_umount lock when done.
558  *
559  *	Note that unlike get_super() et.al. this one does *not* bump ->s_count.
560  *	The reason why it's safe is that we are OK with doing trylock instead
561  *	of down_read().  There's a couple of places that are OK with that, but
562  *	it's very much not a general-purpose interface.
563  */
564 bool super_trylock_shared(struct super_block *sb)
565 {
566 	if (down_read_trylock(&sb->s_umount)) {
567 		if (!(sb->s_flags & SB_DYING) && sb->s_root &&
568 		    (sb->s_flags & SB_BORN))
569 			return true;
570 		super_unlock_shared(sb);
571 	}
572 
573 	return false;
574 }
575 
576 /**
577  *	retire_super	-	prevents superblock from being reused
578  *	@sb: superblock to retire
579  *
580  *	The function marks superblock to be ignored in superblock test, which
581  *	prevents it from being reused for any new mounts.  If the superblock has
582  *	a private bdi, it also unregisters it, but doesn't reduce the refcount
583  *	of the superblock to prevent potential races.  The refcount is reduced
584  *	by generic_shutdown_super().  The function can not be called
585  *	concurrently with generic_shutdown_super().  It is safe to call the
586  *	function multiple times, subsequent calls have no effect.
587  *
588  *	The marker will affect the re-use only for block-device-based
589  *	superblocks.  Other superblocks will still get marked if this function
590  *	is used, but that will not affect their reusability.
591  */
592 void retire_super(struct super_block *sb)
593 {
594 	WARN_ON(!sb->s_bdev);
595 	__super_lock_excl(sb);
596 	if (sb->s_iflags & SB_I_PERSB_BDI) {
597 		bdi_unregister(sb->s_bdi);
598 		sb->s_iflags &= ~SB_I_PERSB_BDI;
599 	}
600 	sb->s_iflags |= SB_I_RETIRED;
601 	super_unlock_excl(sb);
602 }
603 EXPORT_SYMBOL(retire_super);
604 
605 /**
606  *	generic_shutdown_super	-	common helper for ->kill_sb()
607  *	@sb: superblock to kill
608  *
609  *	generic_shutdown_super() does all fs-independent work on superblock
610  *	shutdown.  Typical ->kill_sb() should pick all fs-specific objects
611  *	that need destruction out of superblock, call generic_shutdown_super()
612  *	and release aforementioned objects.  Note: dentries and inodes _are_
613  *	taken care of and do not need specific handling.
614  *
615  *	Upon calling this function, the filesystem may no longer alter or
616  *	rearrange the set of dentries belonging to this super_block, nor may it
617  *	change the attachments of dentries to inodes.
618  */
619 void generic_shutdown_super(struct super_block *sb)
620 {
621 	const struct super_operations *sop = sb->s_op;
622 
623 	if (sb->s_root) {
624 		fsnotify_sb_delete(sb);
625 		shrink_dcache_for_umount(sb);
626 		sync_filesystem(sb);
627 		sb->s_flags &= ~SB_ACTIVE;
628 
629 		fserror_unmount(sb);
630 		cgroup_writeback_umount(sb);
631 
632 		/* Evict all inodes with zero refcount. */
633 		evict_inodes(sb);
634 
635 		/*
636 		 * Clean up and evict any inodes that still have references due
637 		 * to the security policy.
638 		 */
639 		security_sb_delete(sb);
640 
641 		if (sb->s_dio_done_wq) {
642 			destroy_workqueue(sb->s_dio_done_wq);
643 			sb->s_dio_done_wq = NULL;
644 		}
645 
646 		if (sop->put_super)
647 			sop->put_super(sb);
648 
649 		/*
650 		 * Now that all potentially-encrypted inodes have been evicted,
651 		 * the fscrypt keyring can be destroyed.
652 		 */
653 		fscrypt_destroy_keyring(sb);
654 
655 		if (CHECK_DATA_CORRUPTION(!list_empty(&sb->s_inodes), NULL,
656 				"VFS: Busy inodes after unmount of %s (%s)",
657 				sb->s_id, sb->s_type->name)) {
658 			/*
659 			 * Adding a proper bailout path here would be hard, but
660 			 * we can at least make it more likely that a later
661 			 * iput_final() or such crashes cleanly.
662 			 */
663 			struct inode *inode;
664 
665 			spin_lock(&sb->s_inode_list_lock);
666 			list_for_each_entry(inode, &sb->s_inodes, i_sb_list) {
667 				inode->i_op = VFS_PTR_POISON;
668 				inode->i_sb = VFS_PTR_POISON;
669 				inode->i_mapping = VFS_PTR_POISON;
670 			}
671 			spin_unlock(&sb->s_inode_list_lock);
672 		}
673 	}
674 	/*
675 	 * Broadcast to everyone that grabbed a temporary reference to this
676 	 * superblock before we removed it from @fs_supers that the superblock
677 	 * is dying. Every walker of @fs_supers outside of sget_fc() will now
678 	 * discard this superblock and treat it as dead.
679 	 *
680 	 * We leave the superblock on @fs_supers so it can be found by
681 	 * sget_fc() until we passed sb->kill_sb().
682 	 */
683 	super_wake(sb, SB_DYING);
684 	super_unlock_excl(sb);
685 	if (sb->s_bdi != &noop_backing_dev_info) {
686 		if (sb->s_iflags & SB_I_PERSB_BDI)
687 			bdi_unregister(sb->s_bdi);
688 		bdi_put(sb->s_bdi);
689 		sb->s_bdi = &noop_backing_dev_info;
690 	}
691 }
692 
693 EXPORT_SYMBOL(generic_shutdown_super);
694 
695 bool mount_capable(struct fs_context *fc)
696 {
697 	if (!(fc->fs_type->fs_flags & FS_USERNS_MOUNT))
698 		return capable(CAP_SYS_ADMIN);
699 	else
700 		return ns_capable(fc->user_ns, CAP_SYS_ADMIN);
701 }
702 
703 /**
704  * sget_fc - Find or create a superblock
705  * @fc:	Filesystem context.
706  * @test: Comparison callback
707  * @set: Setup callback
708  *
709  * Create a new superblock or find an existing one.
710  *
711  * The @test callback is used to find a matching existing superblock.
712  * Whether or not the requested parameters in @fc are taken into account
713  * is specific to the @test callback that is used. They may even be
714  * completely ignored.
715  *
716  * If an extant superblock is matched, it will be returned unless:
717  *
718  * (1) the namespace the filesystem context @fc and the extant
719  *     superblock's namespace differ
720  *
721  * (2) the filesystem context @fc has requested that reusing an extant
722  *     superblock is not allowed
723  *
724  * In both cases EBUSY will be returned.
725  *
726  * If no match is made, a new superblock will be allocated and basic
727  * initialisation will be performed (s_type, s_fs_info and s_id will be
728  * set and the @set callback will be invoked), the superblock will be
729  * published and it will be returned in a partially constructed state
730  * with SB_BORN and SB_ACTIVE as yet unset.
731  *
732  * Return: On success, an extant or newly created superblock is
733  *         returned. On failure an error pointer is returned.
734  */
735 struct super_block *sget_fc(struct fs_context *fc,
736 			    int (*test)(struct super_block *, struct fs_context *),
737 			    int (*set)(struct super_block *, struct fs_context *))
738 {
739 	struct super_block *s = NULL;
740 	struct super_block *old;
741 	struct user_namespace *user_ns = fc->global ? &init_user_ns : fc->user_ns;
742 	int err;
743 
744 	/*
745 	 * Never allow s_user_ns != &init_user_ns when FS_USERNS_MOUNT or
746 	 * FS_USERNS_DELEGATABLE is not set, as the filesystem is likely
747 	 * unprepared to handle it. This can happen when fsconfig() is called
748 	 * from init_user_ns with an fs_fd opened in another user namespace.
749 	 */
750 	if (user_ns != &init_user_ns &&
751 	    !(fc->fs_type->fs_flags & (FS_USERNS_MOUNT | FS_USERNS_DELEGATABLE))) {
752 		errorfc(fc, "VFS: Mounting from non-initial user namespace is not allowed");
753 		return ERR_PTR(-EPERM);
754 	}
755 
756 retry:
757 	spin_lock(&sb_lock);
758 	if (test) {
759 		hlist_for_each_entry(old, &fc->fs_type->fs_supers, s_instances) {
760 			if (test(old, fc))
761 				goto share_extant_sb;
762 		}
763 	}
764 	if (!s) {
765 		spin_unlock(&sb_lock);
766 		s = alloc_super(fc->fs_type, fc->sb_flags, user_ns);
767 		if (!s)
768 			return ERR_PTR(-ENOMEM);
769 		goto retry;
770 	}
771 
772 	s->s_fs_info = fc->s_fs_info;
773 	err = set(s, fc);
774 	if (err) {
775 		s->s_fs_info = NULL;
776 		spin_unlock(&sb_lock);
777 		destroy_unused_super(s);
778 		return ERR_PTR(err);
779 	}
780 	fc->s_fs_info = NULL;
781 	s->s_type = fc->fs_type;
782 	s->s_iflags |= fc->s_iflags;
783 	strscpy(s->s_id, s->s_type->name, sizeof(s->s_id));
784 	/*
785 	 * Make the superblock visible on @super_blocks and @fs_supers.
786 	 * It's in a nascent state and users should wait on SB_BORN or
787 	 * SB_DYING to be set.
788 	 */
789 	list_add_tail(&s->s_list, &super_blocks);
790 	hlist_add_head(&s->s_instances, &s->s_type->fs_supers);
791 	spin_unlock(&sb_lock);
792 	get_filesystem(s->s_type);
793 	shrinker_register(s->s_shrink);
794 	return s;
795 
796 share_extant_sb:
797 	if (user_ns != old->s_user_ns || fc->exclusive) {
798 		spin_unlock(&sb_lock);
799 		destroy_unused_super(s);
800 		if (fc->exclusive)
801 			warnfc(fc, "reusing existing filesystem not allowed");
802 		else
803 			warnfc(fc, "reusing existing filesystem in another namespace not allowed");
804 		return ERR_PTR(-EBUSY);
805 	}
806 	if (!grab_super(old))
807 		goto retry;
808 	destroy_unused_super(s);
809 	return old;
810 }
811 EXPORT_SYMBOL(sget_fc);
812 
813 void drop_super(struct super_block *sb)
814 {
815 	super_unlock_shared(sb);
816 	put_super(sb);
817 }
818 
819 EXPORT_SYMBOL(drop_super);
820 
821 void drop_super_exclusive(struct super_block *sb)
822 {
823 	super_unlock_excl(sb);
824 	put_super(sb);
825 }
826 
827 enum super_iter_flags_t {
828 	SUPER_ITER_EXCL		= (1U << 0),
829 	SUPER_ITER_UNLOCKED	= (1U << 1),
830 	SUPER_ITER_REVERSE	= (1U << 2),
831 };
832 
833 static inline struct super_block *first_super(enum super_iter_flags_t flags)
834 {
835 	if (flags & SUPER_ITER_REVERSE)
836 		return list_last_entry(&super_blocks, struct super_block, s_list);
837 	return list_first_entry(&super_blocks, struct super_block, s_list);
838 }
839 
840 static inline struct super_block *next_super(struct super_block *sb,
841 					     enum super_iter_flags_t flags)
842 {
843 	if (flags & SUPER_ITER_REVERSE)
844 		return list_prev_entry(sb, s_list);
845 	return list_next_entry(sb, s_list);
846 }
847 
848 static void __iterate_supers(void (*f)(struct super_block *, void *), void *arg,
849 			     enum super_iter_flags_t flags)
850 {
851 	struct super_block *sb, *p = NULL;
852 	bool excl = flags & SUPER_ITER_EXCL;
853 
854 	guard(spinlock)(&sb_lock);
855 
856 	for (sb = first_super(flags);
857 	     !list_entry_is_head(sb, &super_blocks, s_list);
858 	     sb = next_super(sb, flags)) {
859 		if (super_flags(sb, SB_DYING))
860 			continue;
861 		sb->s_count++;
862 		spin_unlock(&sb_lock);
863 
864 		if (flags & SUPER_ITER_UNLOCKED) {
865 			f(sb, arg);
866 		} else if (super_lock(sb, excl)) {
867 			f(sb, arg);
868 			super_unlock(sb, excl);
869 		}
870 
871 		spin_lock(&sb_lock);
872 		if (p)
873 			__put_super(p);
874 		p = sb;
875 	}
876 	if (p)
877 		__put_super(p);
878 }
879 
880 void iterate_supers(void (*f)(struct super_block *, void *), void *arg)
881 {
882 	__iterate_supers(f, arg, 0);
883 }
884 
885 /**
886  *	iterate_supers_type - call function for superblocks of given type
887  *	@type: fs type
888  *	@f: function to call
889  *	@arg: argument to pass to it
890  *
891  *	Scans the superblock list and calls given function, passing it
892  *	locked superblock and given argument.
893  */
894 void iterate_supers_type(struct file_system_type *type,
895 	void (*f)(struct super_block *, void *), void *arg)
896 {
897 	struct super_block *sb, *p = NULL;
898 
899 	spin_lock(&sb_lock);
900 	hlist_for_each_entry(sb, &type->fs_supers, s_instances) {
901 		bool locked;
902 
903 		if (super_flags(sb, SB_DYING))
904 			continue;
905 
906 		sb->s_count++;
907 		spin_unlock(&sb_lock);
908 
909 		locked = super_lock_shared(sb);
910 		if (locked) {
911 			f(sb, arg);
912 			super_unlock_shared(sb);
913 		}
914 
915 		spin_lock(&sb_lock);
916 		if (p)
917 			__put_super(p);
918 		p = sb;
919 	}
920 	if (p)
921 		__put_super(p);
922 	spin_unlock(&sb_lock);
923 }
924 
925 EXPORT_SYMBOL(iterate_supers_type);
926 
927 struct super_block *user_get_super(dev_t dev, bool excl)
928 {
929 	struct super_block *sb;
930 
931 	spin_lock(&sb_lock);
932 	list_for_each_entry(sb, &super_blocks, s_list) {
933 		bool locked;
934 
935 		if (sb->s_dev != dev)
936 			continue;
937 
938 		sb->s_count++;
939 		spin_unlock(&sb_lock);
940 
941 		locked = super_lock(sb, excl);
942 		if (locked)
943 			return sb;
944 
945 		spin_lock(&sb_lock);
946 		__put_super(sb);
947 		break;
948 	}
949 	spin_unlock(&sb_lock);
950 	return NULL;
951 }
952 
953 /**
954  * reconfigure_super - asks filesystem to change superblock parameters
955  * @fc: The superblock and configuration
956  *
957  * Alters the configuration parameters of a live superblock.
958  */
959 int reconfigure_super(struct fs_context *fc)
960 {
961 	struct super_block *sb = fc->root->d_sb;
962 	int retval;
963 	bool remount_ro = false;
964 	bool remount_rw = false;
965 	bool force = fc->sb_flags & SB_FORCE;
966 
967 	if (fc->sb_flags_mask & ~MS_RMT_MASK)
968 		return -EINVAL;
969 	if (sb->s_writers.frozen != SB_UNFROZEN)
970 		return -EBUSY;
971 
972 	retval = security_sb_remount(sb, fc->security);
973 	if (retval)
974 		return retval;
975 
976 	if (fc->sb_flags_mask & SB_RDONLY) {
977 #ifdef CONFIG_BLOCK
978 		if (!(fc->sb_flags & SB_RDONLY) && sb->s_bdev &&
979 		    bdev_read_only(sb->s_bdev))
980 			return -EACCES;
981 #endif
982 		remount_rw = !(fc->sb_flags & SB_RDONLY) && sb_rdonly(sb);
983 		remount_ro = (fc->sb_flags & SB_RDONLY) && !sb_rdonly(sb);
984 	}
985 
986 	if (remount_ro) {
987 		if (!hlist_empty(&sb->s_pins)) {
988 			super_unlock_excl(sb);
989 			group_pin_kill(&sb->s_pins);
990 			__super_lock_excl(sb);
991 			if (!sb->s_root)
992 				return 0;
993 			if (sb->s_writers.frozen != SB_UNFROZEN)
994 				return -EBUSY;
995 			remount_ro = !sb_rdonly(sb);
996 		}
997 	}
998 	shrink_dcache_sb(sb);
999 
1000 	/* If we are reconfiguring to RDONLY and current sb is read/write,
1001 	 * make sure there are no files open for writing.
1002 	 */
1003 	if (remount_ro) {
1004 		if (force) {
1005 			sb_start_ro_state_change(sb);
1006 		} else {
1007 			retval = sb_prepare_remount_readonly(sb);
1008 			if (retval)
1009 				return retval;
1010 		}
1011 	} else if (remount_rw) {
1012 		/*
1013 		 * Protect filesystem's reconfigure code from writes from
1014 		 * userspace until reconfigure finishes.
1015 		 */
1016 		sb_start_ro_state_change(sb);
1017 	}
1018 
1019 	if (fc->ops->reconfigure) {
1020 		retval = fc->ops->reconfigure(fc);
1021 		if (retval) {
1022 			if (!force)
1023 				goto cancel_readonly;
1024 			/* If forced remount, go ahead despite any errors */
1025 			WARN(1, "forced remount of a %s fs returned %i\n",
1026 			     sb->s_type->name, retval);
1027 		}
1028 	}
1029 
1030 	WRITE_ONCE(sb->s_flags, ((sb->s_flags & ~fc->sb_flags_mask) |
1031 				 (fc->sb_flags & fc->sb_flags_mask)));
1032 	sb_end_ro_state_change(sb);
1033 
1034 	/*
1035 	 * Some filesystems modify their metadata via some other path than the
1036 	 * bdev buffer cache (eg. use a private mapping, or directories in
1037 	 * pagecache, etc). Also file data modifications go via their own
1038 	 * mappings. So If we try to mount readonly then copy the filesystem
1039 	 * from bdev, we could get stale data, so invalidate it to give a best
1040 	 * effort at coherency.
1041 	 */
1042 	if (remount_ro && sb->s_bdev)
1043 		invalidate_bdev(sb->s_bdev);
1044 	return 0;
1045 
1046 cancel_readonly:
1047 	sb_end_ro_state_change(sb);
1048 	return retval;
1049 }
1050 
1051 static void do_emergency_remount_callback(struct super_block *sb, void *unused)
1052 {
1053 	if (sb->s_bdev && !sb_rdonly(sb)) {
1054 		struct fs_context *fc;
1055 
1056 		fc = fs_context_for_reconfigure(sb->s_root,
1057 					SB_RDONLY | SB_FORCE, SB_RDONLY);
1058 		if (!IS_ERR(fc)) {
1059 			if (parse_monolithic_mount_data(fc, NULL) == 0)
1060 				(void)reconfigure_super(fc);
1061 			put_fs_context(fc);
1062 		}
1063 	}
1064 }
1065 
1066 static void do_emergency_remount(struct work_struct *work)
1067 {
1068 	__iterate_supers(do_emergency_remount_callback, NULL,
1069 			 SUPER_ITER_EXCL | SUPER_ITER_REVERSE);
1070 	kfree(work);
1071 	printk("Emergency Remount complete\n");
1072 }
1073 
1074 void emergency_remount(void)
1075 {
1076 	struct work_struct *work;
1077 
1078 	work = kmalloc_obj(*work, GFP_ATOMIC);
1079 	if (work) {
1080 		INIT_WORK(work, do_emergency_remount);
1081 		schedule_work(work);
1082 	}
1083 }
1084 
1085 static inline bool get_active_super(struct super_block *sb)
1086 {
1087 	bool active = false;
1088 
1089 	if (super_lock_excl(sb)) {
1090 		active = atomic_inc_not_zero(&sb->s_active);
1091 		super_unlock_excl(sb);
1092 	}
1093 	return active;
1094 }
1095 
1096 static void do_thaw_all_callback(struct super_block *sb, void *unused)
1097 {
1098 	if (!get_active_super(sb))
1099 		return;
1100 
1101 	/* fs_bdev_thaw() acquires s_umount so it must not be held here */
1102 	if (IS_ENABLED(CONFIG_BLOCK))
1103 		while (sb->s_bdev && !bdev_thaw(sb->s_bdev))
1104 			pr_warn("Emergency Thaw on %pg\n", sb->s_bdev);
1105 
1106 	if (super_lock_excl(sb))
1107 		thaw_super_locked(sb, FREEZE_HOLDER_USERSPACE, NULL);
1108 	deactivate_super(sb);
1109 }
1110 
1111 static void do_thaw_all(struct work_struct *work)
1112 {
1113 	__iterate_supers(do_thaw_all_callback, NULL, SUPER_ITER_UNLOCKED);
1114 	kfree(work);
1115 	printk(KERN_WARNING "Emergency Thaw complete\n");
1116 }
1117 
1118 /**
1119  * emergency_thaw_all -- forcibly thaw every frozen filesystem
1120  *
1121  * Used for emergency unfreeze of all filesystems via SysRq
1122  */
1123 void emergency_thaw_all(void)
1124 {
1125 	struct work_struct *work;
1126 
1127 	work = kmalloc_obj(*work, GFP_ATOMIC);
1128 	if (work) {
1129 		INIT_WORK(work, do_thaw_all);
1130 		schedule_work(work);
1131 	}
1132 }
1133 
1134 static const char *filesystems_freeze_ptr = "filesystems_freeze";
1135 
1136 static void filesystems_freeze_callback(struct super_block *sb, void *freeze_all_ptr)
1137 {
1138 	if (!sb->s_op->freeze_fs && !sb->s_op->freeze_super)
1139 		return;
1140 
1141 	if (!freeze_all_ptr && !(sb->s_type->fs_flags & FS_POWER_FREEZE))
1142 		return;
1143 
1144 	if (!get_active_super(sb))
1145 		return;
1146 
1147 	if (sb->s_op->freeze_super)
1148 		sb->s_op->freeze_super(sb, FREEZE_EXCL | FREEZE_HOLDER_KERNEL,
1149 				       filesystems_freeze_ptr);
1150 	else
1151 		freeze_super(sb, FREEZE_EXCL | FREEZE_HOLDER_KERNEL,
1152 			     filesystems_freeze_ptr);
1153 
1154 	deactivate_super(sb);
1155 }
1156 
1157 void filesystems_freeze(bool freeze_all)
1158 {
1159 	void *freeze_all_ptr = NULL;
1160 
1161 	if (freeze_all)
1162 		freeze_all_ptr = &freeze_all;
1163 	__iterate_supers(filesystems_freeze_callback, freeze_all_ptr,
1164 			 SUPER_ITER_UNLOCKED | SUPER_ITER_REVERSE);
1165 }
1166 
1167 static void filesystems_thaw_callback(struct super_block *sb, void *unused)
1168 {
1169 	if (!sb->s_op->freeze_fs && !sb->s_op->freeze_super)
1170 		return;
1171 
1172 	if (!get_active_super(sb))
1173 		return;
1174 
1175 	if (sb->s_op->thaw_super)
1176 		sb->s_op->thaw_super(sb, FREEZE_EXCL | FREEZE_HOLDER_KERNEL,
1177 				     filesystems_freeze_ptr);
1178 	else
1179 		thaw_super(sb, FREEZE_EXCL | FREEZE_HOLDER_KERNEL,
1180 			   filesystems_freeze_ptr);
1181 
1182 	deactivate_super(sb);
1183 }
1184 
1185 void filesystems_thaw(void)
1186 {
1187 	__iterate_supers(filesystems_thaw_callback, NULL, SUPER_ITER_UNLOCKED);
1188 }
1189 
1190 static DEFINE_IDA(unnamed_dev_ida);
1191 
1192 /**
1193  * get_anon_bdev - Allocate a block device for filesystems which don't have one.
1194  * @p: Pointer to a dev_t.
1195  *
1196  * Filesystems which don't use real block devices can call this function
1197  * to allocate a virtual block device.
1198  *
1199  * Context: Any context.  Frequently called while holding sb_lock.
1200  * Return: 0 on success, -EMFILE if there are no anonymous bdevs left
1201  * or -ENOMEM if memory allocation failed.
1202  */
1203 int get_anon_bdev(dev_t *p)
1204 {
1205 	int dev;
1206 
1207 	/*
1208 	 * Many userspace utilities consider an FSID of 0 invalid.
1209 	 * Always return at least 1 from get_anon_bdev.
1210 	 */
1211 	dev = ida_alloc_range(&unnamed_dev_ida, 1, (1 << MINORBITS) - 1,
1212 			GFP_ATOMIC);
1213 	if (dev == -ENOSPC)
1214 		dev = -EMFILE;
1215 	if (dev < 0)
1216 		return dev;
1217 
1218 	*p = MKDEV(0, dev);
1219 	return 0;
1220 }
1221 EXPORT_SYMBOL(get_anon_bdev);
1222 
1223 void free_anon_bdev(dev_t dev)
1224 {
1225 	ida_free(&unnamed_dev_ida, MINOR(dev));
1226 }
1227 EXPORT_SYMBOL(free_anon_bdev);
1228 
1229 int set_anon_super(struct super_block *s, void *data)
1230 {
1231 	return get_anon_bdev(&s->s_dev);
1232 }
1233 EXPORT_SYMBOL(set_anon_super);
1234 
1235 void kill_anon_super(struct super_block *sb)
1236 {
1237 	dev_t dev = sb->s_dev;
1238 	generic_shutdown_super(sb);
1239 	kill_super_notify(sb);
1240 	free_anon_bdev(dev);
1241 }
1242 EXPORT_SYMBOL(kill_anon_super);
1243 
1244 int set_anon_super_fc(struct super_block *sb, struct fs_context *fc)
1245 {
1246 	return set_anon_super(sb, NULL);
1247 }
1248 EXPORT_SYMBOL(set_anon_super_fc);
1249 
1250 static int test_keyed_super(struct super_block *sb, struct fs_context *fc)
1251 {
1252 	return sb->s_fs_info == fc->s_fs_info;
1253 }
1254 
1255 static int test_single_super(struct super_block *s, struct fs_context *fc)
1256 {
1257 	return 1;
1258 }
1259 
1260 static int vfs_get_super(struct fs_context *fc,
1261 		int (*test)(struct super_block *, struct fs_context *),
1262 		int (*fill_super)(struct super_block *sb,
1263 				  struct fs_context *fc))
1264 {
1265 	struct super_block *sb;
1266 	int err;
1267 
1268 	sb = sget_fc(fc, test, set_anon_super_fc);
1269 	if (IS_ERR(sb))
1270 		return PTR_ERR(sb);
1271 
1272 	if (!sb->s_root) {
1273 		err = fill_super(sb, fc);
1274 		if (err)
1275 			goto error;
1276 
1277 		sb->s_flags |= SB_ACTIVE;
1278 	}
1279 
1280 	fc->root = dget(sb->s_root);
1281 	return 0;
1282 
1283 error:
1284 	deactivate_locked_super(sb);
1285 	return err;
1286 }
1287 
1288 int get_tree_nodev(struct fs_context *fc,
1289 		  int (*fill_super)(struct super_block *sb,
1290 				    struct fs_context *fc))
1291 {
1292 	return vfs_get_super(fc, NULL, fill_super);
1293 }
1294 EXPORT_SYMBOL(get_tree_nodev);
1295 
1296 int get_tree_single(struct fs_context *fc,
1297 		  int (*fill_super)(struct super_block *sb,
1298 				    struct fs_context *fc))
1299 {
1300 	return vfs_get_super(fc, test_single_super, fill_super);
1301 }
1302 EXPORT_SYMBOL(get_tree_single);
1303 
1304 int get_tree_keyed(struct fs_context *fc,
1305 		  int (*fill_super)(struct super_block *sb,
1306 				    struct fs_context *fc),
1307 		void *key)
1308 {
1309 	fc->s_fs_info = key;
1310 	return vfs_get_super(fc, test_keyed_super, fill_super);
1311 }
1312 EXPORT_SYMBOL(get_tree_keyed);
1313 
1314 static int set_bdev_super(struct super_block *s, void *data)
1315 {
1316 	s->s_dev = *(dev_t *)data;
1317 	return 0;
1318 }
1319 
1320 static int super_s_dev_set(struct super_block *s, struct fs_context *fc)
1321 {
1322 	return set_bdev_super(s, fc->sget_key);
1323 }
1324 
1325 static int super_s_dev_test(struct super_block *s, struct fs_context *fc)
1326 {
1327 	return !(s->s_iflags & SB_I_RETIRED) &&
1328 		s->s_dev == *(dev_t *)fc->sget_key;
1329 }
1330 
1331 /**
1332  * sget_dev - Find or create a superblock by device number
1333  * @fc: Filesystem context.
1334  * @dev: device number
1335  *
1336  * Find or create a superblock using the provided device number that
1337  * will be stored in fc->sget_key.
1338  *
1339  * If an extant superblock is matched, then that will be returned with
1340  * an elevated reference count that the caller must transfer or discard.
1341  *
1342  * If no match is made, a new superblock will be allocated and basic
1343  * initialisation will be performed (s_type, s_fs_info, s_id, s_dev will
1344  * be set). The superblock will be published and it will be returned in
1345  * a partially constructed state with SB_BORN and SB_ACTIVE as yet
1346  * unset.
1347  *
1348  * Return: an existing or newly created superblock on success, an error
1349  *         pointer on failure.
1350  */
1351 struct super_block *sget_dev(struct fs_context *fc, dev_t dev)
1352 {
1353 	fc->sget_key = &dev;
1354 	return sget_fc(fc, super_s_dev_test, super_s_dev_set);
1355 }
1356 EXPORT_SYMBOL(sget_dev);
1357 
1358 #ifdef CONFIG_BLOCK
1359 /*
1360  * Lock the superblock that is holder of the bdev. Returns the superblock
1361  * pointer if we successfully locked the superblock and it is alive. Otherwise
1362  * we return NULL and just unlock bdev->bd_holder_lock.
1363  *
1364  * The function must be called with bdev->bd_holder_lock and releases it.
1365  */
1366 static struct super_block *bdev_super_lock(struct block_device *bdev, bool excl)
1367 	__releases(&bdev->bd_holder_lock)
1368 {
1369 	struct super_block *sb = bdev->bd_holder;
1370 	bool locked;
1371 
1372 	lockdep_assert_held(&bdev->bd_holder_lock);
1373 	lockdep_assert_not_held(&sb->s_umount);
1374 	lockdep_assert_not_held(&bdev->bd_disk->open_mutex);
1375 
1376 	/* Make sure sb doesn't go away from under us */
1377 	spin_lock(&sb_lock);
1378 	sb->s_count++;
1379 	spin_unlock(&sb_lock);
1380 
1381 	mutex_unlock(&bdev->bd_holder_lock);
1382 
1383 	locked = super_lock(sb, excl);
1384 
1385 	/*
1386 	 * If the superblock wasn't already SB_DYING then we hold
1387 	 * s_umount and can safely drop our temporary reference.
1388          */
1389 	put_super(sb);
1390 
1391 	if (!locked)
1392 		return NULL;
1393 
1394 	if (!sb->s_root || !(sb->s_flags & SB_ACTIVE)) {
1395 		super_unlock(sb, excl);
1396 		return NULL;
1397 	}
1398 
1399 	return sb;
1400 }
1401 
1402 static void fs_bdev_mark_dead(struct block_device *bdev, bool surprise)
1403 {
1404 	struct super_block *sb;
1405 
1406 	sb = bdev_super_lock(bdev, false);
1407 	if (!sb)
1408 		return;
1409 
1410 	if (sb->s_op->remove_bdev) {
1411 		int ret;
1412 
1413 		ret = sb->s_op->remove_bdev(sb, bdev);
1414 		if (!ret) {
1415 			super_unlock_shared(sb);
1416 			return;
1417 		}
1418 		/* Fallback to shutdown. */
1419 	}
1420 
1421 	if (!surprise)
1422 		sync_filesystem(sb);
1423 	shrink_dcache_sb(sb);
1424 	evict_inodes(sb);
1425 	if (sb->s_op->shutdown)
1426 		sb->s_op->shutdown(sb);
1427 
1428 	super_unlock_shared(sb);
1429 }
1430 
1431 static void fs_bdev_sync(struct block_device *bdev)
1432 {
1433 	struct super_block *sb;
1434 
1435 	sb = bdev_super_lock(bdev, false);
1436 	if (!sb)
1437 		return;
1438 
1439 	sync_filesystem(sb);
1440 	super_unlock_shared(sb);
1441 }
1442 
1443 static struct super_block *get_bdev_super(struct block_device *bdev)
1444 {
1445 	bool active = false;
1446 	struct super_block *sb;
1447 
1448 	sb = bdev_super_lock(bdev, true);
1449 	if (sb) {
1450 		active = atomic_inc_not_zero(&sb->s_active);
1451 		super_unlock_excl(sb);
1452 	}
1453 	if (!active)
1454 		return NULL;
1455 	return sb;
1456 }
1457 
1458 /**
1459  * fs_bdev_freeze - freeze owning filesystem of block device
1460  * @bdev: block device
1461  *
1462  * Freeze the filesystem that owns this block device if it is still
1463  * active.
1464  *
1465  * A filesystem that owns multiple block devices may be frozen from each
1466  * block device and won't be unfrozen until all block devices are
1467  * unfrozen. Each block device can only freeze the filesystem once as we
1468  * nest freezes for block devices in the block layer.
1469  *
1470  * Return: If the freeze was successful zero is returned. If the freeze
1471  *         failed a negative error code is returned.
1472  */
1473 static int fs_bdev_freeze(struct block_device *bdev)
1474 {
1475 	struct super_block *sb;
1476 	int error = 0;
1477 
1478 	lockdep_assert_held(&bdev->bd_fsfreeze_mutex);
1479 
1480 	sb = get_bdev_super(bdev);
1481 	if (!sb)
1482 		return -EINVAL;
1483 
1484 	if (sb->s_op->freeze_super)
1485 		error = sb->s_op->freeze_super(sb,
1486 				FREEZE_MAY_NEST | FREEZE_HOLDER_USERSPACE, NULL);
1487 	else
1488 		error = freeze_super(sb,
1489 				FREEZE_MAY_NEST | FREEZE_HOLDER_USERSPACE, NULL);
1490 	if (!error)
1491 		error = sync_blockdev(bdev);
1492 	deactivate_super(sb);
1493 	return error;
1494 }
1495 
1496 /**
1497  * fs_bdev_thaw - thaw owning filesystem of block device
1498  * @bdev: block device
1499  *
1500  * Thaw the filesystem that owns this block device.
1501  *
1502  * A filesystem that owns multiple block devices may be frozen from each
1503  * block device and won't be unfrozen until all block devices are
1504  * unfrozen. Each block device can only freeze the filesystem once as we
1505  * nest freezes for block devices in the block layer.
1506  *
1507  * Return: If the thaw was successful zero is returned. If the thaw
1508  *         failed a negative error code is returned. If this function
1509  *         returns zero it doesn't mean that the filesystem is unfrozen
1510  *         as it may have been frozen multiple times (kernel may hold a
1511  *         freeze or might be frozen from other block devices).
1512  */
1513 static int fs_bdev_thaw(struct block_device *bdev)
1514 {
1515 	struct super_block *sb;
1516 	int error;
1517 
1518 	lockdep_assert_held(&bdev->bd_fsfreeze_mutex);
1519 
1520 	/*
1521 	 * The block device may have been frozen before it was claimed by a
1522 	 * filesystem. Concurrently another process might try to mount that
1523 	 * frozen block device and has temporarily claimed the block device for
1524 	 * that purpose causing a concurrent fs_bdev_thaw() to end up here. The
1525 	 * mounter is already about to abort mounting because they still saw an
1526 	 * elevanted bdev->bd_fsfreeze_count so get_bdev_super() will return
1527 	 * NULL in that case.
1528 	 */
1529 	sb = get_bdev_super(bdev);
1530 	if (!sb)
1531 		return -EINVAL;
1532 
1533 	if (sb->s_op->thaw_super)
1534 		error = sb->s_op->thaw_super(sb,
1535 				FREEZE_MAY_NEST | FREEZE_HOLDER_USERSPACE, NULL);
1536 	else
1537 		error = thaw_super(sb,
1538 				FREEZE_MAY_NEST | FREEZE_HOLDER_USERSPACE, NULL);
1539 	deactivate_super(sb);
1540 	return error;
1541 }
1542 
1543 const struct blk_holder_ops fs_holder_ops = {
1544 	.mark_dead		= fs_bdev_mark_dead,
1545 	.sync			= fs_bdev_sync,
1546 	.freeze			= fs_bdev_freeze,
1547 	.thaw			= fs_bdev_thaw,
1548 };
1549 EXPORT_SYMBOL_GPL(fs_holder_ops);
1550 
1551 int setup_bdev_super(struct super_block *sb, int sb_flags,
1552 		struct fs_context *fc)
1553 {
1554 	blk_mode_t mode = sb_open_mode(sb_flags);
1555 	struct file *bdev_file;
1556 	struct block_device *bdev;
1557 
1558 	bdev_file = bdev_file_open_by_dev(sb->s_dev, mode, sb, &fs_holder_ops);
1559 	if (IS_ERR(bdev_file)) {
1560 		if (fc)
1561 			errorf(fc, "%s: Can't open blockdev", fc->source);
1562 		return PTR_ERR(bdev_file);
1563 	}
1564 	bdev = file_bdev(bdev_file);
1565 
1566 	/*
1567 	 * This really should be in blkdev_get_by_dev, but right now can't due
1568 	 * to legacy issues that require us to allow opening a block device node
1569 	 * writable from userspace even for a read-only block device.
1570 	 */
1571 	if ((mode & BLK_OPEN_WRITE) && bdev_read_only(bdev)) {
1572 		bdev_fput(bdev_file);
1573 		return -EACCES;
1574 	}
1575 
1576 	/*
1577 	 * It is enough to check bdev was not frozen before we set
1578 	 * s_bdev as freezing will wait until SB_BORN is set.
1579 	 */
1580 	if (atomic_read(&bdev->bd_fsfreeze_count) > 0) {
1581 		if (fc)
1582 			warnf(fc, "%pg: Can't mount, blockdev is frozen", bdev);
1583 		bdev_fput(bdev_file);
1584 		return -EBUSY;
1585 	}
1586 	spin_lock(&sb_lock);
1587 	sb->s_bdev_file = bdev_file;
1588 	sb->s_bdev = bdev;
1589 	sb->s_bdi = bdi_get(bdev->bd_disk->bdi);
1590 	if (bdev_stable_writes(bdev))
1591 		sb->s_iflags |= SB_I_STABLE_WRITES;
1592 	spin_unlock(&sb_lock);
1593 
1594 	snprintf(sb->s_id, sizeof(sb->s_id), "%pg", bdev);
1595 	shrinker_debugfs_rename(sb->s_shrink, "sb-%s:%s", sb->s_type->name,
1596 				sb->s_id);
1597 	sb_set_blocksize(sb, block_size(bdev));
1598 	return 0;
1599 }
1600 EXPORT_SYMBOL_GPL(setup_bdev_super);
1601 
1602 /**
1603  * get_tree_bdev_flags - Get a superblock based on a single block device
1604  * @fc: The filesystem context holding the parameters
1605  * @fill_super: Helper to initialise a new superblock
1606  * @flags: GET_TREE_BDEV_* flags
1607  */
1608 int get_tree_bdev_flags(struct fs_context *fc,
1609 		int (*fill_super)(struct super_block *sb,
1610 				  struct fs_context *fc), unsigned int flags)
1611 {
1612 	struct super_block *s;
1613 	int error = 0;
1614 	dev_t dev;
1615 
1616 	if (!fc->source)
1617 		return invalf(fc, "No source specified");
1618 
1619 	error = lookup_bdev(fc->source, &dev);
1620 	if (error) {
1621 		if (!(flags & GET_TREE_BDEV_QUIET_LOOKUP))
1622 			errorf(fc, "%s: Can't lookup blockdev", fc->source);
1623 		return error;
1624 	}
1625 	fc->sb_flags |= SB_NOSEC;
1626 	s = sget_dev(fc, dev);
1627 	if (IS_ERR(s))
1628 		return PTR_ERR(s);
1629 
1630 	if (s->s_root) {
1631 		/* Don't summarily change the RO/RW state. */
1632 		if ((fc->sb_flags ^ s->s_flags) & SB_RDONLY) {
1633 			warnf(fc, "%pg: Can't mount, would change RO state", s->s_bdev);
1634 			deactivate_locked_super(s);
1635 			return -EBUSY;
1636 		}
1637 	} else {
1638 		error = setup_bdev_super(s, fc->sb_flags, fc);
1639 		if (!error)
1640 			error = fill_super(s, fc);
1641 		if (error) {
1642 			deactivate_locked_super(s);
1643 			return error;
1644 		}
1645 		s->s_flags |= SB_ACTIVE;
1646 	}
1647 
1648 	BUG_ON(fc->root);
1649 	fc->root = dget(s->s_root);
1650 	return 0;
1651 }
1652 EXPORT_SYMBOL_GPL(get_tree_bdev_flags);
1653 
1654 /**
1655  * get_tree_bdev - Get a superblock based on a single block device
1656  * @fc: The filesystem context holding the parameters
1657  * @fill_super: Helper to initialise a new superblock
1658  */
1659 int get_tree_bdev(struct fs_context *fc,
1660 		int (*fill_super)(struct super_block *,
1661 				  struct fs_context *))
1662 {
1663 	return get_tree_bdev_flags(fc, fill_super, 0);
1664 }
1665 EXPORT_SYMBOL(get_tree_bdev);
1666 
1667 void kill_block_super(struct super_block *sb)
1668 {
1669 	struct block_device *bdev = sb->s_bdev;
1670 
1671 	generic_shutdown_super(sb);
1672 	if (bdev) {
1673 		sync_blockdev(bdev);
1674 		bdev_fput(sb->s_bdev_file);
1675 	}
1676 }
1677 
1678 EXPORT_SYMBOL(kill_block_super);
1679 #endif
1680 
1681 /**
1682  * vfs_get_tree - Get the mountable root
1683  * @fc: The superblock configuration context.
1684  *
1685  * The filesystem is invoked to get or create a superblock which can then later
1686  * be used for mounting.  The filesystem places a pointer to the root to be
1687  * used for mounting in @fc->root.
1688  */
1689 int vfs_get_tree(struct fs_context *fc)
1690 {
1691 	struct super_block *sb;
1692 	int error;
1693 
1694 	if (fc->root)
1695 		return -EBUSY;
1696 
1697 	/* Get the mountable root in fc->root, with a ref on the root and a ref
1698 	 * on the superblock.
1699 	 */
1700 	error = fc->ops->get_tree(fc);
1701 	if (error < 0)
1702 		return error;
1703 
1704 	if (!fc->root) {
1705 		pr_err("Filesystem %s get_tree() didn't set fc->root, returned %i\n",
1706 		       fc->fs_type->name, error);
1707 		/* We don't know what the locking state of the superblock is -
1708 		 * if there is a superblock.
1709 		 */
1710 		BUG();
1711 	}
1712 
1713 	sb = fc->root->d_sb;
1714 	WARN_ON(!sb->s_bdi);
1715 
1716 	/*
1717 	 * super_wake() contains a memory barrier which also care of
1718 	 * ordering for super_cache_count(). We place it before setting
1719 	 * SB_BORN as the data dependency between the two functions is
1720 	 * the superblock structure contents that we just set up, not
1721 	 * the SB_BORN flag.
1722 	 */
1723 	super_wake(sb, SB_BORN);
1724 
1725 	error = security_sb_set_mnt_opts(sb, fc->security, 0, NULL);
1726 	if (unlikely(error)) {
1727 		fc_drop_locked(fc);
1728 		return error;
1729 	}
1730 
1731 	/*
1732 	 * filesystems should never set s_maxbytes larger than MAX_LFS_FILESIZE
1733 	 * but s_maxbytes was an unsigned long long for many releases. Throw
1734 	 * this warning for a little while to try and catch filesystems that
1735 	 * violate this rule.
1736 	 */
1737 	WARN((sb->s_maxbytes < 0), "%s set sb->s_maxbytes to "
1738 		"negative value (%lld)\n", fc->fs_type->name, sb->s_maxbytes);
1739 
1740 	return 0;
1741 }
1742 EXPORT_SYMBOL(vfs_get_tree);
1743 
1744 /*
1745  * Setup private BDI for given superblock. It gets automatically cleaned up
1746  * in generic_shutdown_super().
1747  */
1748 int super_setup_bdi_name(struct super_block *sb, char *fmt, ...)
1749 {
1750 	struct backing_dev_info *bdi;
1751 	int err;
1752 	va_list args;
1753 
1754 	bdi = bdi_alloc(NUMA_NO_NODE);
1755 	if (!bdi)
1756 		return -ENOMEM;
1757 
1758 	va_start(args, fmt);
1759 	err = bdi_register_va(bdi, fmt, args);
1760 	va_end(args);
1761 	if (err) {
1762 		bdi_put(bdi);
1763 		return err;
1764 	}
1765 	WARN_ON(sb->s_bdi != &noop_backing_dev_info);
1766 	sb->s_bdi = bdi;
1767 	sb->s_iflags |= SB_I_PERSB_BDI;
1768 
1769 	return 0;
1770 }
1771 EXPORT_SYMBOL(super_setup_bdi_name);
1772 
1773 /*
1774  * Setup private BDI for given superblock. I gets automatically cleaned up
1775  * in generic_shutdown_super().
1776  */
1777 int super_setup_bdi(struct super_block *sb)
1778 {
1779 	static atomic_long_t bdi_seq = ATOMIC_LONG_INIT(0);
1780 
1781 	return super_setup_bdi_name(sb, "%.28s-%ld", sb->s_type->name,
1782 				    atomic_long_inc_return(&bdi_seq));
1783 }
1784 EXPORT_SYMBOL(super_setup_bdi);
1785 
1786 /**
1787  * sb_wait_write - wait until all writers to given file system finish
1788  * @sb: the super for which we wait
1789  * @level: type of writers we wait for (normal vs page fault)
1790  *
1791  * This function waits until there are no writers of given type to given file
1792  * system.
1793  */
1794 static void sb_wait_write(struct super_block *sb, int level)
1795 {
1796 	percpu_down_write(sb->s_writers.rw_sem + level-1);
1797 }
1798 
1799 /*
1800  * We are going to return to userspace and forget about these locks, the
1801  * ownership goes to the caller of thaw_super() which does unlock().
1802  */
1803 static void lockdep_sb_freeze_release(struct super_block *sb)
1804 {
1805 	int level;
1806 
1807 	for (level = SB_FREEZE_LEVELS - 1; level >= 0; level--)
1808 		percpu_rwsem_release(sb->s_writers.rw_sem + level, _THIS_IP_);
1809 }
1810 
1811 /*
1812  * Tell lockdep we are holding these locks before we call ->unfreeze_fs(sb).
1813  */
1814 static void lockdep_sb_freeze_acquire(struct super_block *sb)
1815 {
1816 	int level;
1817 
1818 	for (level = 0; level < SB_FREEZE_LEVELS; ++level)
1819 		percpu_rwsem_acquire(sb->s_writers.rw_sem + level, 0, _THIS_IP_);
1820 }
1821 
1822 static void sb_freeze_unlock(struct super_block *sb, int level)
1823 {
1824 	for (level--; level >= 0; level--)
1825 		percpu_up_write(sb->s_writers.rw_sem + level);
1826 }
1827 
1828 static int wait_for_partially_frozen(struct super_block *sb)
1829 {
1830 	int ret = 0;
1831 
1832 	do {
1833 		unsigned short old = sb->s_writers.frozen;
1834 
1835 		up_write(&sb->s_umount);
1836 		ret = wait_var_event_killable(&sb->s_writers.frozen,
1837 					       sb->s_writers.frozen != old);
1838 		down_write(&sb->s_umount);
1839 	} while (ret == 0 &&
1840 		 sb->s_writers.frozen != SB_UNFROZEN &&
1841 		 sb->s_writers.frozen != SB_FREEZE_COMPLETE);
1842 
1843 	return ret;
1844 }
1845 
1846 #define FREEZE_HOLDERS (FREEZE_HOLDER_KERNEL | FREEZE_HOLDER_USERSPACE)
1847 #define FREEZE_FLAGS (FREEZE_HOLDERS | FREEZE_MAY_NEST | FREEZE_EXCL)
1848 
1849 static inline int freeze_inc(struct super_block *sb, enum freeze_holder who)
1850 {
1851 	WARN_ON_ONCE((who & ~FREEZE_FLAGS));
1852 	WARN_ON_ONCE(hweight32(who & FREEZE_HOLDERS) > 1);
1853 
1854 	if (who & FREEZE_HOLDER_KERNEL)
1855 		++sb->s_writers.freeze_kcount;
1856 	if (who & FREEZE_HOLDER_USERSPACE)
1857 		++sb->s_writers.freeze_ucount;
1858 	return sb->s_writers.freeze_kcount + sb->s_writers.freeze_ucount;
1859 }
1860 
1861 static inline int freeze_dec(struct super_block *sb, enum freeze_holder who)
1862 {
1863 	WARN_ON_ONCE((who & ~FREEZE_FLAGS));
1864 	WARN_ON_ONCE(hweight32(who & FREEZE_HOLDERS) > 1);
1865 
1866 	if ((who & FREEZE_HOLDER_KERNEL) && sb->s_writers.freeze_kcount)
1867 		--sb->s_writers.freeze_kcount;
1868 	if ((who & FREEZE_HOLDER_USERSPACE) && sb->s_writers.freeze_ucount)
1869 		--sb->s_writers.freeze_ucount;
1870 	return sb->s_writers.freeze_kcount + sb->s_writers.freeze_ucount;
1871 }
1872 
1873 static inline bool may_freeze(struct super_block *sb, enum freeze_holder who,
1874 			      const void *freeze_owner)
1875 {
1876 	lockdep_assert_held(&sb->s_umount);
1877 
1878 	WARN_ON_ONCE((who & ~FREEZE_FLAGS));
1879 	WARN_ON_ONCE(hweight32(who & FREEZE_HOLDERS) > 1);
1880 
1881 	if (who & FREEZE_EXCL) {
1882 		if (WARN_ON_ONCE(!(who & FREEZE_HOLDER_KERNEL)))
1883 			return false;
1884 		if (WARN_ON_ONCE(who & ~(FREEZE_EXCL | FREEZE_HOLDER_KERNEL)))
1885 			return false;
1886 		if (WARN_ON_ONCE(!freeze_owner))
1887 			return false;
1888 		/* This freeze already has a specific owner. */
1889 		if (sb->s_writers.freeze_owner)
1890 			return false;
1891 		/*
1892 		 * This is already frozen multiple times so we're just
1893 		 * going to take a reference count and mark the freeze as
1894 		 * being owned by the caller.
1895 		 */
1896 		if (sb->s_writers.freeze_kcount + sb->s_writers.freeze_ucount)
1897 			sb->s_writers.freeze_owner = freeze_owner;
1898 		return true;
1899 	}
1900 
1901 	if (who & FREEZE_HOLDER_KERNEL)
1902 		return (who & FREEZE_MAY_NEST) ||
1903 		       sb->s_writers.freeze_kcount == 0;
1904 	if (who & FREEZE_HOLDER_USERSPACE)
1905 		return (who & FREEZE_MAY_NEST) ||
1906 		       sb->s_writers.freeze_ucount == 0;
1907 	return false;
1908 }
1909 
1910 static inline bool may_unfreeze(struct super_block *sb, enum freeze_holder who,
1911 				const void *freeze_owner)
1912 {
1913 	lockdep_assert_held(&sb->s_umount);
1914 
1915 	WARN_ON_ONCE((who & ~FREEZE_FLAGS));
1916 	WARN_ON_ONCE(hweight32(who & FREEZE_HOLDERS) > 1);
1917 
1918 	if (who & FREEZE_EXCL) {
1919 		if (WARN_ON_ONCE(!(who & FREEZE_HOLDER_KERNEL)))
1920 			return false;
1921 		if (WARN_ON_ONCE(who & ~(FREEZE_EXCL | FREEZE_HOLDER_KERNEL)))
1922 			return false;
1923 		if (WARN_ON_ONCE(!freeze_owner))
1924 			return false;
1925 		if (WARN_ON_ONCE(sb->s_writers.freeze_kcount == 0))
1926 			return false;
1927 		/* This isn't exclusively frozen. */
1928 		if (!sb->s_writers.freeze_owner)
1929 			return false;
1930 		/* This isn't exclusively frozen by us. */
1931 		if (sb->s_writers.freeze_owner != freeze_owner)
1932 			return false;
1933 		/*
1934 		 * This is still frozen multiple times so we're just
1935 		 * going to drop our reference count and undo our
1936 		 * exclusive freeze.
1937 		 */
1938 		if ((sb->s_writers.freeze_kcount + sb->s_writers.freeze_ucount) > 1)
1939 			sb->s_writers.freeze_owner = NULL;
1940 		return true;
1941 	}
1942 
1943 	if (who & FREEZE_HOLDER_KERNEL) {
1944 		/*
1945 		 * Someone's trying to steal the reference belonging to
1946 		 * @sb->s_writers.freeze_owner.
1947 		 */
1948 		if (sb->s_writers.freeze_kcount == 1 &&
1949 		    sb->s_writers.freeze_owner)
1950 			return false;
1951 		return sb->s_writers.freeze_kcount > 0;
1952 	}
1953 
1954 	if (who & FREEZE_HOLDER_USERSPACE)
1955 		return sb->s_writers.freeze_ucount > 0;
1956 
1957 	return false;
1958 }
1959 
1960 /**
1961  * freeze_super - lock the filesystem and force it into a consistent state
1962  * @sb: the super to lock
1963  * @who: context that wants to freeze
1964  * @freeze_owner: owner of the freeze
1965  *
1966  * Syncs the super to make sure the filesystem is consistent and calls the fs's
1967  * freeze_fs.  Subsequent calls to this without first thawing the fs may return
1968  * -EBUSY.
1969  *
1970  * @who should be:
1971  * * %FREEZE_HOLDER_USERSPACE if userspace wants to freeze the fs;
1972  * * %FREEZE_HOLDER_KERNEL if the kernel wants to freeze the fs.
1973  * * %FREEZE_MAY_NEST whether nesting freeze and thaw requests is allowed.
1974  *
1975  * The @who argument distinguishes between the kernel and userspace trying to
1976  * freeze the filesystem.  Although there cannot be multiple kernel freezes or
1977  * multiple userspace freezes in effect at any given time, the kernel and
1978  * userspace can both hold a filesystem frozen.  The filesystem remains frozen
1979  * until there are no kernel or userspace freezes in effect.
1980  *
1981  * A filesystem may hold multiple devices and thus a filesystems may be
1982  * frozen through the block layer via multiple block devices. In this
1983  * case the request is marked as being allowed to nest by passing
1984  * FREEZE_MAY_NEST. The filesystem remains frozen until all block
1985  * devices are unfrozen. If multiple freezes are attempted without
1986  * FREEZE_MAY_NEST -EBUSY will be returned.
1987  *
1988  * During this function, sb->s_writers.frozen goes through these values:
1989  *
1990  * SB_UNFROZEN: File system is normal, all writes progress as usual.
1991  *
1992  * SB_FREEZE_WRITE: The file system is in the process of being frozen.  New
1993  * writes should be blocked, though page faults are still allowed. We wait for
1994  * all writes to complete and then proceed to the next stage.
1995  *
1996  * SB_FREEZE_PAGEFAULT: Freezing continues. Now also page faults are blocked
1997  * but internal fs threads can still modify the filesystem (although they
1998  * should not dirty new pages or inodes), writeback can run etc. After waiting
1999  * for all running page faults we sync the filesystem which will clean all
2000  * dirty pages and inodes (no new dirty pages or inodes can be created when
2001  * sync is running).
2002  *
2003  * SB_FREEZE_FS: The file system is frozen. Now all internal sources of fs
2004  * modification are blocked (e.g. XFS preallocation truncation on inode
2005  * reclaim). This is usually implemented by blocking new transactions for
2006  * filesystems that have them and need this additional guard. After all
2007  * internal writers are finished we call ->freeze_fs() to finish filesystem
2008  * freezing. Then we transition to SB_FREEZE_COMPLETE state. This state is
2009  * mostly auxiliary for filesystems to verify they do not modify frozen fs.
2010  *
2011  * sb->s_writers.frozen is protected by sb->s_umount.
2012  *
2013  * Return: If the freeze was successful zero is returned. If the freeze
2014  *         failed a negative error code is returned.
2015  */
2016 int freeze_super(struct super_block *sb, enum freeze_holder who, const void *freeze_owner)
2017 {
2018 	int ret;
2019 
2020 	if (!super_lock_excl(sb)) {
2021 		WARN_ON_ONCE("Dying superblock while freezing!");
2022 		return -EINVAL;
2023 	}
2024 	atomic_inc(&sb->s_active);
2025 
2026 retry:
2027 	if (sb->s_writers.frozen == SB_FREEZE_COMPLETE) {
2028 		if (may_freeze(sb, who, freeze_owner))
2029 			ret = !!WARN_ON_ONCE(freeze_inc(sb, who) == 1);
2030 		else
2031 			ret = -EBUSY;
2032 		/* All freezers share a single active reference. */
2033 		deactivate_locked_super(sb);
2034 		return ret;
2035 	}
2036 
2037 	if (sb->s_writers.frozen != SB_UNFROZEN) {
2038 		ret = wait_for_partially_frozen(sb);
2039 		if (ret) {
2040 			deactivate_locked_super(sb);
2041 			return ret;
2042 		}
2043 
2044 		goto retry;
2045 	}
2046 
2047 	if (sb_rdonly(sb)) {
2048 		/* Nothing to do really... */
2049 		WARN_ON_ONCE(freeze_inc(sb, who) > 1);
2050 		sb->s_writers.freeze_owner = freeze_owner;
2051 		sb->s_writers.frozen = SB_FREEZE_COMPLETE;
2052 		wake_up_var(&sb->s_writers.frozen);
2053 		super_unlock_excl(sb);
2054 		return 0;
2055 	}
2056 
2057 	sb->s_writers.frozen = SB_FREEZE_WRITE;
2058 	/* Release s_umount to preserve sb_start_write -> s_umount ordering */
2059 	super_unlock_excl(sb);
2060 	sb_wait_write(sb, SB_FREEZE_WRITE);
2061 	__super_lock_excl(sb);
2062 
2063 	/* Now we go and block page faults... */
2064 	sb->s_writers.frozen = SB_FREEZE_PAGEFAULT;
2065 	sb_wait_write(sb, SB_FREEZE_PAGEFAULT);
2066 
2067 	/* All writers are done so after syncing there won't be dirty data */
2068 	ret = sync_filesystem(sb);
2069 	if (ret) {
2070 		sb->s_writers.frozen = SB_UNFROZEN;
2071 		sb_freeze_unlock(sb, SB_FREEZE_PAGEFAULT);
2072 		wake_up_var(&sb->s_writers.frozen);
2073 		deactivate_locked_super(sb);
2074 		return ret;
2075 	}
2076 
2077 	/* Now wait for internal filesystem counter */
2078 	sb->s_writers.frozen = SB_FREEZE_FS;
2079 	sb_wait_write(sb, SB_FREEZE_FS);
2080 
2081 	if (sb->s_op->freeze_fs) {
2082 		ret = sb->s_op->freeze_fs(sb);
2083 		if (ret) {
2084 			printk(KERN_ERR
2085 				"VFS:Filesystem freeze failed\n");
2086 			sb->s_writers.frozen = SB_UNFROZEN;
2087 			sb_freeze_unlock(sb, SB_FREEZE_FS);
2088 			wake_up_var(&sb->s_writers.frozen);
2089 			deactivate_locked_super(sb);
2090 			return ret;
2091 		}
2092 	}
2093 	/*
2094 	 * For debugging purposes so that fs can warn if it sees write activity
2095 	 * when frozen is set to SB_FREEZE_COMPLETE, and for thaw_super().
2096 	 */
2097 	WARN_ON_ONCE(freeze_inc(sb, who) > 1);
2098 	sb->s_writers.freeze_owner = freeze_owner;
2099 	sb->s_writers.frozen = SB_FREEZE_COMPLETE;
2100 	wake_up_var(&sb->s_writers.frozen);
2101 	lockdep_sb_freeze_release(sb);
2102 	super_unlock_excl(sb);
2103 	return 0;
2104 }
2105 EXPORT_SYMBOL(freeze_super);
2106 
2107 /*
2108  * Undoes the effect of a freeze_super_locked call.  If the filesystem is
2109  * frozen both by userspace and the kernel, a thaw call from either source
2110  * removes that state without releasing the other state or unlocking the
2111  * filesystem.
2112  */
2113 static int thaw_super_locked(struct super_block *sb, enum freeze_holder who,
2114 			     const void *freeze_owner)
2115 {
2116 	int error = -EINVAL;
2117 
2118 	if (sb->s_writers.frozen != SB_FREEZE_COMPLETE)
2119 		goto out_unlock;
2120 
2121 	if (!may_unfreeze(sb, who, freeze_owner))
2122 		goto out_unlock;
2123 
2124 	/*
2125 	 * All freezers share a single active reference.
2126 	 * So just unlock in case there are any left.
2127 	 */
2128 	if (freeze_dec(sb, who))
2129 		goto out_unlock;
2130 
2131 	if (sb_rdonly(sb)) {
2132 		sb->s_writers.frozen = SB_UNFROZEN;
2133 		sb->s_writers.freeze_owner = NULL;
2134 		wake_up_var(&sb->s_writers.frozen);
2135 		goto out_deactivate;
2136 	}
2137 
2138 	lockdep_sb_freeze_acquire(sb);
2139 
2140 	if (sb->s_op->unfreeze_fs) {
2141 		error = sb->s_op->unfreeze_fs(sb);
2142 		if (error) {
2143 			pr_err("VFS: Filesystem thaw failed\n");
2144 			freeze_inc(sb, who);
2145 			lockdep_sb_freeze_release(sb);
2146 			goto out_unlock;
2147 		}
2148 	}
2149 
2150 	sb->s_writers.frozen = SB_UNFROZEN;
2151 	sb->s_writers.freeze_owner = NULL;
2152 	wake_up_var(&sb->s_writers.frozen);
2153 	sb_freeze_unlock(sb, SB_FREEZE_FS);
2154 out_deactivate:
2155 	deactivate_locked_super(sb);
2156 	return 0;
2157 
2158 out_unlock:
2159 	super_unlock_excl(sb);
2160 	return error;
2161 }
2162 
2163 /**
2164  * thaw_super -- unlock filesystem
2165  * @sb: the super to thaw
2166  * @who: context that wants to freeze
2167  * @freeze_owner: owner of the freeze
2168  *
2169  * Unlocks the filesystem and marks it writeable again after freeze_super()
2170  * if there are no remaining freezes on the filesystem.
2171  *
2172  * @who should be:
2173  * * %FREEZE_HOLDER_USERSPACE if userspace wants to thaw the fs;
2174  * * %FREEZE_HOLDER_KERNEL if the kernel wants to thaw the fs.
2175  * * %FREEZE_MAY_NEST whether nesting freeze and thaw requests is allowed
2176  *
2177  * A filesystem may hold multiple devices and thus a filesystems may
2178  * have been frozen through the block layer via multiple block devices.
2179  * The filesystem remains frozen until all block devices are unfrozen.
2180  */
2181 int thaw_super(struct super_block *sb, enum freeze_holder who,
2182 	       const void *freeze_owner)
2183 {
2184 	if (!super_lock_excl(sb)) {
2185 		WARN_ON_ONCE("Dying superblock while thawing!");
2186 		return -EINVAL;
2187 	}
2188 	return thaw_super_locked(sb, who, freeze_owner);
2189 }
2190 EXPORT_SYMBOL(thaw_super);
2191 
2192 /*
2193  * Create workqueue for deferred direct IO completions. We allocate the
2194  * workqueue when it's first needed. This avoids creating workqueue for
2195  * filesystems that don't need it and also allows us to create the workqueue
2196  * late enough so the we can include s_id in the name of the workqueue.
2197  */
2198 int sb_init_dio_done_wq(struct super_block *sb)
2199 {
2200 	struct workqueue_struct *old;
2201 	struct workqueue_struct *wq = alloc_workqueue("dio/%s",
2202 						      WQ_MEM_RECLAIM | WQ_PERCPU,
2203 						      0,
2204 						      sb->s_id);
2205 	if (!wq)
2206 		return -ENOMEM;
2207 
2208 	old = NULL;
2209 	/*
2210 	 * This has to be atomic as more DIOs can race to create the workqueue
2211 	 */
2212 	if (!try_cmpxchg(&sb->s_dio_done_wq, &old, wq)) {
2213 		/* Someone created workqueue before us? Free ours... */
2214 		destroy_workqueue(wq);
2215 	}
2216 	return 0;
2217 }
2218 EXPORT_SYMBOL_GPL(sb_init_dio_done_wq);
2219