xref: /linux/fs/super.c (revision e8a56d6fc828bb569fa2dd33c3e6eb16a165b097)
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 void do_thaw_all_callback(struct super_block *sb, void *unused)
1086 {
1087 	if (IS_ENABLED(CONFIG_BLOCK))
1088 		while (sb->s_bdev && !bdev_thaw(sb->s_bdev))
1089 			pr_warn("Emergency Thaw on %pg\n", sb->s_bdev);
1090 	thaw_super_locked(sb, FREEZE_HOLDER_USERSPACE, NULL);
1091 	return;
1092 }
1093 
1094 static void do_thaw_all(struct work_struct *work)
1095 {
1096 	__iterate_supers(do_thaw_all_callback, NULL, SUPER_ITER_EXCL);
1097 	kfree(work);
1098 	printk(KERN_WARNING "Emergency Thaw complete\n");
1099 }
1100 
1101 /**
1102  * emergency_thaw_all -- forcibly thaw every frozen filesystem
1103  *
1104  * Used for emergency unfreeze of all filesystems via SysRq
1105  */
1106 void emergency_thaw_all(void)
1107 {
1108 	struct work_struct *work;
1109 
1110 	work = kmalloc_obj(*work, GFP_ATOMIC);
1111 	if (work) {
1112 		INIT_WORK(work, do_thaw_all);
1113 		schedule_work(work);
1114 	}
1115 }
1116 
1117 static inline bool get_active_super(struct super_block *sb)
1118 {
1119 	bool active = false;
1120 
1121 	if (super_lock_excl(sb)) {
1122 		active = atomic_inc_not_zero(&sb->s_active);
1123 		super_unlock_excl(sb);
1124 	}
1125 	return active;
1126 }
1127 
1128 static const char *filesystems_freeze_ptr = "filesystems_freeze";
1129 
1130 static void filesystems_freeze_callback(struct super_block *sb, void *freeze_all_ptr)
1131 {
1132 	if (!sb->s_op->freeze_fs && !sb->s_op->freeze_super)
1133 		return;
1134 
1135 	if (!freeze_all_ptr && !(sb->s_type->fs_flags & FS_POWER_FREEZE))
1136 		return;
1137 
1138 	if (!get_active_super(sb))
1139 		return;
1140 
1141 	if (sb->s_op->freeze_super)
1142 		sb->s_op->freeze_super(sb, FREEZE_EXCL | FREEZE_HOLDER_KERNEL,
1143 				       filesystems_freeze_ptr);
1144 	else
1145 		freeze_super(sb, FREEZE_EXCL | FREEZE_HOLDER_KERNEL,
1146 			     filesystems_freeze_ptr);
1147 
1148 	deactivate_super(sb);
1149 }
1150 
1151 void filesystems_freeze(bool freeze_all)
1152 {
1153 	void *freeze_all_ptr = NULL;
1154 
1155 	if (freeze_all)
1156 		freeze_all_ptr = &freeze_all;
1157 	__iterate_supers(filesystems_freeze_callback, freeze_all_ptr,
1158 			 SUPER_ITER_UNLOCKED | SUPER_ITER_REVERSE);
1159 }
1160 
1161 static void filesystems_thaw_callback(struct super_block *sb, void *unused)
1162 {
1163 	if (!sb->s_op->freeze_fs && !sb->s_op->freeze_super)
1164 		return;
1165 
1166 	if (!get_active_super(sb))
1167 		return;
1168 
1169 	if (sb->s_op->thaw_super)
1170 		sb->s_op->thaw_super(sb, FREEZE_EXCL | FREEZE_HOLDER_KERNEL,
1171 				     filesystems_freeze_ptr);
1172 	else
1173 		thaw_super(sb, FREEZE_EXCL | FREEZE_HOLDER_KERNEL,
1174 			   filesystems_freeze_ptr);
1175 
1176 	deactivate_super(sb);
1177 }
1178 
1179 void filesystems_thaw(void)
1180 {
1181 	__iterate_supers(filesystems_thaw_callback, NULL, SUPER_ITER_UNLOCKED);
1182 }
1183 
1184 static DEFINE_IDA(unnamed_dev_ida);
1185 
1186 /**
1187  * get_anon_bdev - Allocate a block device for filesystems which don't have one.
1188  * @p: Pointer to a dev_t.
1189  *
1190  * Filesystems which don't use real block devices can call this function
1191  * to allocate a virtual block device.
1192  *
1193  * Context: Any context.  Frequently called while holding sb_lock.
1194  * Return: 0 on success, -EMFILE if there are no anonymous bdevs left
1195  * or -ENOMEM if memory allocation failed.
1196  */
1197 int get_anon_bdev(dev_t *p)
1198 {
1199 	int dev;
1200 
1201 	/*
1202 	 * Many userspace utilities consider an FSID of 0 invalid.
1203 	 * Always return at least 1 from get_anon_bdev.
1204 	 */
1205 	dev = ida_alloc_range(&unnamed_dev_ida, 1, (1 << MINORBITS) - 1,
1206 			GFP_ATOMIC);
1207 	if (dev == -ENOSPC)
1208 		dev = -EMFILE;
1209 	if (dev < 0)
1210 		return dev;
1211 
1212 	*p = MKDEV(0, dev);
1213 	return 0;
1214 }
1215 EXPORT_SYMBOL(get_anon_bdev);
1216 
1217 void free_anon_bdev(dev_t dev)
1218 {
1219 	ida_free(&unnamed_dev_ida, MINOR(dev));
1220 }
1221 EXPORT_SYMBOL(free_anon_bdev);
1222 
1223 int set_anon_super(struct super_block *s, void *data)
1224 {
1225 	return get_anon_bdev(&s->s_dev);
1226 }
1227 EXPORT_SYMBOL(set_anon_super);
1228 
1229 void kill_anon_super(struct super_block *sb)
1230 {
1231 	dev_t dev = sb->s_dev;
1232 	generic_shutdown_super(sb);
1233 	kill_super_notify(sb);
1234 	free_anon_bdev(dev);
1235 }
1236 EXPORT_SYMBOL(kill_anon_super);
1237 
1238 int set_anon_super_fc(struct super_block *sb, struct fs_context *fc)
1239 {
1240 	return set_anon_super(sb, NULL);
1241 }
1242 EXPORT_SYMBOL(set_anon_super_fc);
1243 
1244 static int test_keyed_super(struct super_block *sb, struct fs_context *fc)
1245 {
1246 	return sb->s_fs_info == fc->s_fs_info;
1247 }
1248 
1249 static int test_single_super(struct super_block *s, struct fs_context *fc)
1250 {
1251 	return 1;
1252 }
1253 
1254 static int vfs_get_super(struct fs_context *fc,
1255 		int (*test)(struct super_block *, struct fs_context *),
1256 		int (*fill_super)(struct super_block *sb,
1257 				  struct fs_context *fc))
1258 {
1259 	struct super_block *sb;
1260 	int err;
1261 
1262 	sb = sget_fc(fc, test, set_anon_super_fc);
1263 	if (IS_ERR(sb))
1264 		return PTR_ERR(sb);
1265 
1266 	if (!sb->s_root) {
1267 		err = fill_super(sb, fc);
1268 		if (err)
1269 			goto error;
1270 
1271 		sb->s_flags |= SB_ACTIVE;
1272 	}
1273 
1274 	fc->root = dget(sb->s_root);
1275 	return 0;
1276 
1277 error:
1278 	deactivate_locked_super(sb);
1279 	return err;
1280 }
1281 
1282 int get_tree_nodev(struct fs_context *fc,
1283 		  int (*fill_super)(struct super_block *sb,
1284 				    struct fs_context *fc))
1285 {
1286 	return vfs_get_super(fc, NULL, fill_super);
1287 }
1288 EXPORT_SYMBOL(get_tree_nodev);
1289 
1290 int get_tree_single(struct fs_context *fc,
1291 		  int (*fill_super)(struct super_block *sb,
1292 				    struct fs_context *fc))
1293 {
1294 	return vfs_get_super(fc, test_single_super, fill_super);
1295 }
1296 EXPORT_SYMBOL(get_tree_single);
1297 
1298 int get_tree_keyed(struct fs_context *fc,
1299 		  int (*fill_super)(struct super_block *sb,
1300 				    struct fs_context *fc),
1301 		void *key)
1302 {
1303 	fc->s_fs_info = key;
1304 	return vfs_get_super(fc, test_keyed_super, fill_super);
1305 }
1306 EXPORT_SYMBOL(get_tree_keyed);
1307 
1308 static int set_bdev_super(struct super_block *s, void *data)
1309 {
1310 	s->s_dev = *(dev_t *)data;
1311 	return 0;
1312 }
1313 
1314 static int super_s_dev_set(struct super_block *s, struct fs_context *fc)
1315 {
1316 	return set_bdev_super(s, fc->sget_key);
1317 }
1318 
1319 static int super_s_dev_test(struct super_block *s, struct fs_context *fc)
1320 {
1321 	return !(s->s_iflags & SB_I_RETIRED) &&
1322 		s->s_dev == *(dev_t *)fc->sget_key;
1323 }
1324 
1325 /**
1326  * sget_dev - Find or create a superblock by device number
1327  * @fc: Filesystem context.
1328  * @dev: device number
1329  *
1330  * Find or create a superblock using the provided device number that
1331  * will be stored in fc->sget_key.
1332  *
1333  * If an extant superblock is matched, then that will be returned with
1334  * an elevated reference count that the caller must transfer or discard.
1335  *
1336  * If no match is made, a new superblock will be allocated and basic
1337  * initialisation will be performed (s_type, s_fs_info, s_id, s_dev will
1338  * be set). The superblock will be published and it will be returned in
1339  * a partially constructed state with SB_BORN and SB_ACTIVE as yet
1340  * unset.
1341  *
1342  * Return: an existing or newly created superblock on success, an error
1343  *         pointer on failure.
1344  */
1345 struct super_block *sget_dev(struct fs_context *fc, dev_t dev)
1346 {
1347 	fc->sget_key = &dev;
1348 	return sget_fc(fc, super_s_dev_test, super_s_dev_set);
1349 }
1350 EXPORT_SYMBOL(sget_dev);
1351 
1352 #ifdef CONFIG_BLOCK
1353 /*
1354  * Lock the superblock that is holder of the bdev. Returns the superblock
1355  * pointer if we successfully locked the superblock and it is alive. Otherwise
1356  * we return NULL and just unlock bdev->bd_holder_lock.
1357  *
1358  * The function must be called with bdev->bd_holder_lock and releases it.
1359  */
1360 static struct super_block *bdev_super_lock(struct block_device *bdev, bool excl)
1361 	__releases(&bdev->bd_holder_lock)
1362 {
1363 	struct super_block *sb = bdev->bd_holder;
1364 	bool locked;
1365 
1366 	lockdep_assert_held(&bdev->bd_holder_lock);
1367 	lockdep_assert_not_held(&sb->s_umount);
1368 	lockdep_assert_not_held(&bdev->bd_disk->open_mutex);
1369 
1370 	/* Make sure sb doesn't go away from under us */
1371 	spin_lock(&sb_lock);
1372 	sb->s_count++;
1373 	spin_unlock(&sb_lock);
1374 
1375 	mutex_unlock(&bdev->bd_holder_lock);
1376 
1377 	locked = super_lock(sb, excl);
1378 
1379 	/*
1380 	 * If the superblock wasn't already SB_DYING then we hold
1381 	 * s_umount and can safely drop our temporary reference.
1382          */
1383 	put_super(sb);
1384 
1385 	if (!locked)
1386 		return NULL;
1387 
1388 	if (!sb->s_root || !(sb->s_flags & SB_ACTIVE)) {
1389 		super_unlock(sb, excl);
1390 		return NULL;
1391 	}
1392 
1393 	return sb;
1394 }
1395 
1396 static void fs_bdev_mark_dead(struct block_device *bdev, bool surprise)
1397 {
1398 	struct super_block *sb;
1399 
1400 	sb = bdev_super_lock(bdev, false);
1401 	if (!sb)
1402 		return;
1403 
1404 	if (sb->s_op->remove_bdev) {
1405 		int ret;
1406 
1407 		ret = sb->s_op->remove_bdev(sb, bdev);
1408 		if (!ret) {
1409 			super_unlock_shared(sb);
1410 			return;
1411 		}
1412 		/* Fallback to shutdown. */
1413 	}
1414 
1415 	if (!surprise)
1416 		sync_filesystem(sb);
1417 	shrink_dcache_sb(sb);
1418 	evict_inodes(sb);
1419 	if (sb->s_op->shutdown)
1420 		sb->s_op->shutdown(sb);
1421 
1422 	super_unlock_shared(sb);
1423 }
1424 
1425 static void fs_bdev_sync(struct block_device *bdev)
1426 {
1427 	struct super_block *sb;
1428 
1429 	sb = bdev_super_lock(bdev, false);
1430 	if (!sb)
1431 		return;
1432 
1433 	sync_filesystem(sb);
1434 	super_unlock_shared(sb);
1435 }
1436 
1437 static struct super_block *get_bdev_super(struct block_device *bdev)
1438 {
1439 	bool active = false;
1440 	struct super_block *sb;
1441 
1442 	sb = bdev_super_lock(bdev, true);
1443 	if (sb) {
1444 		active = atomic_inc_not_zero(&sb->s_active);
1445 		super_unlock_excl(sb);
1446 	}
1447 	if (!active)
1448 		return NULL;
1449 	return sb;
1450 }
1451 
1452 /**
1453  * fs_bdev_freeze - freeze owning filesystem of block device
1454  * @bdev: block device
1455  *
1456  * Freeze the filesystem that owns this block device if it is still
1457  * active.
1458  *
1459  * A filesystem that owns multiple block devices may be frozen from each
1460  * block device and won't be unfrozen until all block devices are
1461  * unfrozen. Each block device can only freeze the filesystem once as we
1462  * nest freezes for block devices in the block layer.
1463  *
1464  * Return: If the freeze was successful zero is returned. If the freeze
1465  *         failed a negative error code is returned.
1466  */
1467 static int fs_bdev_freeze(struct block_device *bdev)
1468 {
1469 	struct super_block *sb;
1470 	int error = 0;
1471 
1472 	lockdep_assert_held(&bdev->bd_fsfreeze_mutex);
1473 
1474 	sb = get_bdev_super(bdev);
1475 	if (!sb)
1476 		return -EINVAL;
1477 
1478 	if (sb->s_op->freeze_super)
1479 		error = sb->s_op->freeze_super(sb,
1480 				FREEZE_MAY_NEST | FREEZE_HOLDER_USERSPACE, NULL);
1481 	else
1482 		error = freeze_super(sb,
1483 				FREEZE_MAY_NEST | FREEZE_HOLDER_USERSPACE, NULL);
1484 	if (!error)
1485 		error = sync_blockdev(bdev);
1486 	deactivate_super(sb);
1487 	return error;
1488 }
1489 
1490 /**
1491  * fs_bdev_thaw - thaw owning filesystem of block device
1492  * @bdev: block device
1493  *
1494  * Thaw the filesystem that owns this block device.
1495  *
1496  * A filesystem that owns multiple block devices may be frozen from each
1497  * block device and won't be unfrozen until all block devices are
1498  * unfrozen. Each block device can only freeze the filesystem once as we
1499  * nest freezes for block devices in the block layer.
1500  *
1501  * Return: If the thaw was successful zero is returned. If the thaw
1502  *         failed a negative error code is returned. If this function
1503  *         returns zero it doesn't mean that the filesystem is unfrozen
1504  *         as it may have been frozen multiple times (kernel may hold a
1505  *         freeze or might be frozen from other block devices).
1506  */
1507 static int fs_bdev_thaw(struct block_device *bdev)
1508 {
1509 	struct super_block *sb;
1510 	int error;
1511 
1512 	lockdep_assert_held(&bdev->bd_fsfreeze_mutex);
1513 
1514 	/*
1515 	 * The block device may have been frozen before it was claimed by a
1516 	 * filesystem. Concurrently another process might try to mount that
1517 	 * frozen block device and has temporarily claimed the block device for
1518 	 * that purpose causing a concurrent fs_bdev_thaw() to end up here. The
1519 	 * mounter is already about to abort mounting because they still saw an
1520 	 * elevanted bdev->bd_fsfreeze_count so get_bdev_super() will return
1521 	 * NULL in that case.
1522 	 */
1523 	sb = get_bdev_super(bdev);
1524 	if (!sb)
1525 		return -EINVAL;
1526 
1527 	if (sb->s_op->thaw_super)
1528 		error = sb->s_op->thaw_super(sb,
1529 				FREEZE_MAY_NEST | FREEZE_HOLDER_USERSPACE, NULL);
1530 	else
1531 		error = thaw_super(sb,
1532 				FREEZE_MAY_NEST | FREEZE_HOLDER_USERSPACE, NULL);
1533 	deactivate_super(sb);
1534 	return error;
1535 }
1536 
1537 const struct blk_holder_ops fs_holder_ops = {
1538 	.mark_dead		= fs_bdev_mark_dead,
1539 	.sync			= fs_bdev_sync,
1540 	.freeze			= fs_bdev_freeze,
1541 	.thaw			= fs_bdev_thaw,
1542 };
1543 EXPORT_SYMBOL_GPL(fs_holder_ops);
1544 
1545 int setup_bdev_super(struct super_block *sb, int sb_flags,
1546 		struct fs_context *fc)
1547 {
1548 	blk_mode_t mode = sb_open_mode(sb_flags);
1549 	struct file *bdev_file;
1550 	struct block_device *bdev;
1551 
1552 	bdev_file = bdev_file_open_by_dev(sb->s_dev, mode, sb, &fs_holder_ops);
1553 	if (IS_ERR(bdev_file)) {
1554 		if (fc)
1555 			errorf(fc, "%s: Can't open blockdev", fc->source);
1556 		return PTR_ERR(bdev_file);
1557 	}
1558 	bdev = file_bdev(bdev_file);
1559 
1560 	/*
1561 	 * This really should be in blkdev_get_by_dev, but right now can't due
1562 	 * to legacy issues that require us to allow opening a block device node
1563 	 * writable from userspace even for a read-only block device.
1564 	 */
1565 	if ((mode & BLK_OPEN_WRITE) && bdev_read_only(bdev)) {
1566 		bdev_fput(bdev_file);
1567 		return -EACCES;
1568 	}
1569 
1570 	/*
1571 	 * It is enough to check bdev was not frozen before we set
1572 	 * s_bdev as freezing will wait until SB_BORN is set.
1573 	 */
1574 	if (atomic_read(&bdev->bd_fsfreeze_count) > 0) {
1575 		if (fc)
1576 			warnf(fc, "%pg: Can't mount, blockdev is frozen", bdev);
1577 		bdev_fput(bdev_file);
1578 		return -EBUSY;
1579 	}
1580 	spin_lock(&sb_lock);
1581 	sb->s_bdev_file = bdev_file;
1582 	sb->s_bdev = bdev;
1583 	sb->s_bdi = bdi_get(bdev->bd_disk->bdi);
1584 	if (bdev_stable_writes(bdev))
1585 		sb->s_iflags |= SB_I_STABLE_WRITES;
1586 	spin_unlock(&sb_lock);
1587 
1588 	snprintf(sb->s_id, sizeof(sb->s_id), "%pg", bdev);
1589 	shrinker_debugfs_rename(sb->s_shrink, "sb-%s:%s", sb->s_type->name,
1590 				sb->s_id);
1591 	sb_set_blocksize(sb, block_size(bdev));
1592 	return 0;
1593 }
1594 EXPORT_SYMBOL_GPL(setup_bdev_super);
1595 
1596 /**
1597  * get_tree_bdev_flags - Get a superblock based on a single block device
1598  * @fc: The filesystem context holding the parameters
1599  * @fill_super: Helper to initialise a new superblock
1600  * @flags: GET_TREE_BDEV_* flags
1601  */
1602 int get_tree_bdev_flags(struct fs_context *fc,
1603 		int (*fill_super)(struct super_block *sb,
1604 				  struct fs_context *fc), unsigned int flags)
1605 {
1606 	struct super_block *s;
1607 	int error = 0;
1608 	dev_t dev;
1609 
1610 	if (!fc->source)
1611 		return invalf(fc, "No source specified");
1612 
1613 	error = lookup_bdev(fc->source, &dev);
1614 	if (error) {
1615 		if (!(flags & GET_TREE_BDEV_QUIET_LOOKUP))
1616 			errorf(fc, "%s: Can't lookup blockdev", fc->source);
1617 		return error;
1618 	}
1619 	fc->sb_flags |= SB_NOSEC;
1620 	s = sget_dev(fc, dev);
1621 	if (IS_ERR(s))
1622 		return PTR_ERR(s);
1623 
1624 	if (s->s_root) {
1625 		/* Don't summarily change the RO/RW state. */
1626 		if ((fc->sb_flags ^ s->s_flags) & SB_RDONLY) {
1627 			warnf(fc, "%pg: Can't mount, would change RO state", s->s_bdev);
1628 			deactivate_locked_super(s);
1629 			return -EBUSY;
1630 		}
1631 	} else {
1632 		error = setup_bdev_super(s, fc->sb_flags, fc);
1633 		if (!error)
1634 			error = fill_super(s, fc);
1635 		if (error) {
1636 			deactivate_locked_super(s);
1637 			return error;
1638 		}
1639 		s->s_flags |= SB_ACTIVE;
1640 	}
1641 
1642 	BUG_ON(fc->root);
1643 	fc->root = dget(s->s_root);
1644 	return 0;
1645 }
1646 EXPORT_SYMBOL_GPL(get_tree_bdev_flags);
1647 
1648 /**
1649  * get_tree_bdev - Get a superblock based on a single block device
1650  * @fc: The filesystem context holding the parameters
1651  * @fill_super: Helper to initialise a new superblock
1652  */
1653 int get_tree_bdev(struct fs_context *fc,
1654 		int (*fill_super)(struct super_block *,
1655 				  struct fs_context *))
1656 {
1657 	return get_tree_bdev_flags(fc, fill_super, 0);
1658 }
1659 EXPORT_SYMBOL(get_tree_bdev);
1660 
1661 void kill_block_super(struct super_block *sb)
1662 {
1663 	struct block_device *bdev = sb->s_bdev;
1664 
1665 	generic_shutdown_super(sb);
1666 	if (bdev) {
1667 		sync_blockdev(bdev);
1668 		bdev_fput(sb->s_bdev_file);
1669 	}
1670 }
1671 
1672 EXPORT_SYMBOL(kill_block_super);
1673 #endif
1674 
1675 /**
1676  * vfs_get_tree - Get the mountable root
1677  * @fc: The superblock configuration context.
1678  *
1679  * The filesystem is invoked to get or create a superblock which can then later
1680  * be used for mounting.  The filesystem places a pointer to the root to be
1681  * used for mounting in @fc->root.
1682  */
1683 int vfs_get_tree(struct fs_context *fc)
1684 {
1685 	struct super_block *sb;
1686 	int error;
1687 
1688 	if (fc->root)
1689 		return -EBUSY;
1690 
1691 	/* Get the mountable root in fc->root, with a ref on the root and a ref
1692 	 * on the superblock.
1693 	 */
1694 	error = fc->ops->get_tree(fc);
1695 	if (error < 0)
1696 		return error;
1697 
1698 	if (!fc->root) {
1699 		pr_err("Filesystem %s get_tree() didn't set fc->root, returned %i\n",
1700 		       fc->fs_type->name, error);
1701 		/* We don't know what the locking state of the superblock is -
1702 		 * if there is a superblock.
1703 		 */
1704 		BUG();
1705 	}
1706 
1707 	sb = fc->root->d_sb;
1708 	WARN_ON(!sb->s_bdi);
1709 
1710 	/*
1711 	 * super_wake() contains a memory barrier which also care of
1712 	 * ordering for super_cache_count(). We place it before setting
1713 	 * SB_BORN as the data dependency between the two functions is
1714 	 * the superblock structure contents that we just set up, not
1715 	 * the SB_BORN flag.
1716 	 */
1717 	super_wake(sb, SB_BORN);
1718 
1719 	error = security_sb_set_mnt_opts(sb, fc->security, 0, NULL);
1720 	if (unlikely(error)) {
1721 		fc_drop_locked(fc);
1722 		return error;
1723 	}
1724 
1725 	/*
1726 	 * filesystems should never set s_maxbytes larger than MAX_LFS_FILESIZE
1727 	 * but s_maxbytes was an unsigned long long for many releases. Throw
1728 	 * this warning for a little while to try and catch filesystems that
1729 	 * violate this rule.
1730 	 */
1731 	WARN((sb->s_maxbytes < 0), "%s set sb->s_maxbytes to "
1732 		"negative value (%lld)\n", fc->fs_type->name, sb->s_maxbytes);
1733 
1734 	return 0;
1735 }
1736 EXPORT_SYMBOL(vfs_get_tree);
1737 
1738 /*
1739  * Setup private BDI for given superblock. It gets automatically cleaned up
1740  * in generic_shutdown_super().
1741  */
1742 int super_setup_bdi_name(struct super_block *sb, char *fmt, ...)
1743 {
1744 	struct backing_dev_info *bdi;
1745 	int err;
1746 	va_list args;
1747 
1748 	bdi = bdi_alloc(NUMA_NO_NODE);
1749 	if (!bdi)
1750 		return -ENOMEM;
1751 
1752 	va_start(args, fmt);
1753 	err = bdi_register_va(bdi, fmt, args);
1754 	va_end(args);
1755 	if (err) {
1756 		bdi_put(bdi);
1757 		return err;
1758 	}
1759 	WARN_ON(sb->s_bdi != &noop_backing_dev_info);
1760 	sb->s_bdi = bdi;
1761 	sb->s_iflags |= SB_I_PERSB_BDI;
1762 
1763 	return 0;
1764 }
1765 EXPORT_SYMBOL(super_setup_bdi_name);
1766 
1767 /*
1768  * Setup private BDI for given superblock. I gets automatically cleaned up
1769  * in generic_shutdown_super().
1770  */
1771 int super_setup_bdi(struct super_block *sb)
1772 {
1773 	static atomic_long_t bdi_seq = ATOMIC_LONG_INIT(0);
1774 
1775 	return super_setup_bdi_name(sb, "%.28s-%ld", sb->s_type->name,
1776 				    atomic_long_inc_return(&bdi_seq));
1777 }
1778 EXPORT_SYMBOL(super_setup_bdi);
1779 
1780 /**
1781  * sb_wait_write - wait until all writers to given file system finish
1782  * @sb: the super for which we wait
1783  * @level: type of writers we wait for (normal vs page fault)
1784  *
1785  * This function waits until there are no writers of given type to given file
1786  * system.
1787  */
1788 static void sb_wait_write(struct super_block *sb, int level)
1789 {
1790 	percpu_down_write(sb->s_writers.rw_sem + level-1);
1791 }
1792 
1793 /*
1794  * We are going to return to userspace and forget about these locks, the
1795  * ownership goes to the caller of thaw_super() which does unlock().
1796  */
1797 static void lockdep_sb_freeze_release(struct super_block *sb)
1798 {
1799 	int level;
1800 
1801 	for (level = SB_FREEZE_LEVELS - 1; level >= 0; level--)
1802 		percpu_rwsem_release(sb->s_writers.rw_sem + level, _THIS_IP_);
1803 }
1804 
1805 /*
1806  * Tell lockdep we are holding these locks before we call ->unfreeze_fs(sb).
1807  */
1808 static void lockdep_sb_freeze_acquire(struct super_block *sb)
1809 {
1810 	int level;
1811 
1812 	for (level = 0; level < SB_FREEZE_LEVELS; ++level)
1813 		percpu_rwsem_acquire(sb->s_writers.rw_sem + level, 0, _THIS_IP_);
1814 }
1815 
1816 static void sb_freeze_unlock(struct super_block *sb, int level)
1817 {
1818 	for (level--; level >= 0; level--)
1819 		percpu_up_write(sb->s_writers.rw_sem + level);
1820 }
1821 
1822 static int wait_for_partially_frozen(struct super_block *sb)
1823 {
1824 	int ret = 0;
1825 
1826 	do {
1827 		unsigned short old = sb->s_writers.frozen;
1828 
1829 		up_write(&sb->s_umount);
1830 		ret = wait_var_event_killable(&sb->s_writers.frozen,
1831 					       sb->s_writers.frozen != old);
1832 		down_write(&sb->s_umount);
1833 	} while (ret == 0 &&
1834 		 sb->s_writers.frozen != SB_UNFROZEN &&
1835 		 sb->s_writers.frozen != SB_FREEZE_COMPLETE);
1836 
1837 	return ret;
1838 }
1839 
1840 #define FREEZE_HOLDERS (FREEZE_HOLDER_KERNEL | FREEZE_HOLDER_USERSPACE)
1841 #define FREEZE_FLAGS (FREEZE_HOLDERS | FREEZE_MAY_NEST | FREEZE_EXCL)
1842 
1843 static inline int freeze_inc(struct super_block *sb, enum freeze_holder who)
1844 {
1845 	WARN_ON_ONCE((who & ~FREEZE_FLAGS));
1846 	WARN_ON_ONCE(hweight32(who & FREEZE_HOLDERS) > 1);
1847 
1848 	if (who & FREEZE_HOLDER_KERNEL)
1849 		++sb->s_writers.freeze_kcount;
1850 	if (who & FREEZE_HOLDER_USERSPACE)
1851 		++sb->s_writers.freeze_ucount;
1852 	return sb->s_writers.freeze_kcount + sb->s_writers.freeze_ucount;
1853 }
1854 
1855 static inline int freeze_dec(struct super_block *sb, enum freeze_holder who)
1856 {
1857 	WARN_ON_ONCE((who & ~FREEZE_FLAGS));
1858 	WARN_ON_ONCE(hweight32(who & FREEZE_HOLDERS) > 1);
1859 
1860 	if ((who & FREEZE_HOLDER_KERNEL) && sb->s_writers.freeze_kcount)
1861 		--sb->s_writers.freeze_kcount;
1862 	if ((who & FREEZE_HOLDER_USERSPACE) && sb->s_writers.freeze_ucount)
1863 		--sb->s_writers.freeze_ucount;
1864 	return sb->s_writers.freeze_kcount + sb->s_writers.freeze_ucount;
1865 }
1866 
1867 static inline bool may_freeze(struct super_block *sb, enum freeze_holder who,
1868 			      const void *freeze_owner)
1869 {
1870 	lockdep_assert_held(&sb->s_umount);
1871 
1872 	WARN_ON_ONCE((who & ~FREEZE_FLAGS));
1873 	WARN_ON_ONCE(hweight32(who & FREEZE_HOLDERS) > 1);
1874 
1875 	if (who & FREEZE_EXCL) {
1876 		if (WARN_ON_ONCE(!(who & FREEZE_HOLDER_KERNEL)))
1877 			return false;
1878 		if (WARN_ON_ONCE(who & ~(FREEZE_EXCL | FREEZE_HOLDER_KERNEL)))
1879 			return false;
1880 		if (WARN_ON_ONCE(!freeze_owner))
1881 			return false;
1882 		/* This freeze already has a specific owner. */
1883 		if (sb->s_writers.freeze_owner)
1884 			return false;
1885 		/*
1886 		 * This is already frozen multiple times so we're just
1887 		 * going to take a reference count and mark the freeze as
1888 		 * being owned by the caller.
1889 		 */
1890 		if (sb->s_writers.freeze_kcount + sb->s_writers.freeze_ucount)
1891 			sb->s_writers.freeze_owner = freeze_owner;
1892 		return true;
1893 	}
1894 
1895 	if (who & FREEZE_HOLDER_KERNEL)
1896 		return (who & FREEZE_MAY_NEST) ||
1897 		       sb->s_writers.freeze_kcount == 0;
1898 	if (who & FREEZE_HOLDER_USERSPACE)
1899 		return (who & FREEZE_MAY_NEST) ||
1900 		       sb->s_writers.freeze_ucount == 0;
1901 	return false;
1902 }
1903 
1904 static inline bool may_unfreeze(struct super_block *sb, enum freeze_holder who,
1905 				const void *freeze_owner)
1906 {
1907 	lockdep_assert_held(&sb->s_umount);
1908 
1909 	WARN_ON_ONCE((who & ~FREEZE_FLAGS));
1910 	WARN_ON_ONCE(hweight32(who & FREEZE_HOLDERS) > 1);
1911 
1912 	if (who & FREEZE_EXCL) {
1913 		if (WARN_ON_ONCE(!(who & FREEZE_HOLDER_KERNEL)))
1914 			return false;
1915 		if (WARN_ON_ONCE(who & ~(FREEZE_EXCL | FREEZE_HOLDER_KERNEL)))
1916 			return false;
1917 		if (WARN_ON_ONCE(!freeze_owner))
1918 			return false;
1919 		if (WARN_ON_ONCE(sb->s_writers.freeze_kcount == 0))
1920 			return false;
1921 		/* This isn't exclusively frozen. */
1922 		if (!sb->s_writers.freeze_owner)
1923 			return false;
1924 		/* This isn't exclusively frozen by us. */
1925 		if (sb->s_writers.freeze_owner != freeze_owner)
1926 			return false;
1927 		/*
1928 		 * This is still frozen multiple times so we're just
1929 		 * going to drop our reference count and undo our
1930 		 * exclusive freeze.
1931 		 */
1932 		if ((sb->s_writers.freeze_kcount + sb->s_writers.freeze_ucount) > 1)
1933 			sb->s_writers.freeze_owner = NULL;
1934 		return true;
1935 	}
1936 
1937 	if (who & FREEZE_HOLDER_KERNEL) {
1938 		/*
1939 		 * Someone's trying to steal the reference belonging to
1940 		 * @sb->s_writers.freeze_owner.
1941 		 */
1942 		if (sb->s_writers.freeze_kcount == 1 &&
1943 		    sb->s_writers.freeze_owner)
1944 			return false;
1945 		return sb->s_writers.freeze_kcount > 0;
1946 	}
1947 
1948 	if (who & FREEZE_HOLDER_USERSPACE)
1949 		return sb->s_writers.freeze_ucount > 0;
1950 
1951 	return false;
1952 }
1953 
1954 /**
1955  * freeze_super - lock the filesystem and force it into a consistent state
1956  * @sb: the super to lock
1957  * @who: context that wants to freeze
1958  * @freeze_owner: owner of the freeze
1959  *
1960  * Syncs the super to make sure the filesystem is consistent and calls the fs's
1961  * freeze_fs.  Subsequent calls to this without first thawing the fs may return
1962  * -EBUSY.
1963  *
1964  * @who should be:
1965  * * %FREEZE_HOLDER_USERSPACE if userspace wants to freeze the fs;
1966  * * %FREEZE_HOLDER_KERNEL if the kernel wants to freeze the fs.
1967  * * %FREEZE_MAY_NEST whether nesting freeze and thaw requests is allowed.
1968  *
1969  * The @who argument distinguishes between the kernel and userspace trying to
1970  * freeze the filesystem.  Although there cannot be multiple kernel freezes or
1971  * multiple userspace freezes in effect at any given time, the kernel and
1972  * userspace can both hold a filesystem frozen.  The filesystem remains frozen
1973  * until there are no kernel or userspace freezes in effect.
1974  *
1975  * A filesystem may hold multiple devices and thus a filesystems may be
1976  * frozen through the block layer via multiple block devices. In this
1977  * case the request is marked as being allowed to nest by passing
1978  * FREEZE_MAY_NEST. The filesystem remains frozen until all block
1979  * devices are unfrozen. If multiple freezes are attempted without
1980  * FREEZE_MAY_NEST -EBUSY will be returned.
1981  *
1982  * During this function, sb->s_writers.frozen goes through these values:
1983  *
1984  * SB_UNFROZEN: File system is normal, all writes progress as usual.
1985  *
1986  * SB_FREEZE_WRITE: The file system is in the process of being frozen.  New
1987  * writes should be blocked, though page faults are still allowed. We wait for
1988  * all writes to complete and then proceed to the next stage.
1989  *
1990  * SB_FREEZE_PAGEFAULT: Freezing continues. Now also page faults are blocked
1991  * but internal fs threads can still modify the filesystem (although they
1992  * should not dirty new pages or inodes), writeback can run etc. After waiting
1993  * for all running page faults we sync the filesystem which will clean all
1994  * dirty pages and inodes (no new dirty pages or inodes can be created when
1995  * sync is running).
1996  *
1997  * SB_FREEZE_FS: The file system is frozen. Now all internal sources of fs
1998  * modification are blocked (e.g. XFS preallocation truncation on inode
1999  * reclaim). This is usually implemented by blocking new transactions for
2000  * filesystems that have them and need this additional guard. After all
2001  * internal writers are finished we call ->freeze_fs() to finish filesystem
2002  * freezing. Then we transition to SB_FREEZE_COMPLETE state. This state is
2003  * mostly auxiliary for filesystems to verify they do not modify frozen fs.
2004  *
2005  * sb->s_writers.frozen is protected by sb->s_umount.
2006  *
2007  * Return: If the freeze was successful zero is returned. If the freeze
2008  *         failed a negative error code is returned.
2009  */
2010 int freeze_super(struct super_block *sb, enum freeze_holder who, const void *freeze_owner)
2011 {
2012 	int ret;
2013 
2014 	if (!super_lock_excl(sb)) {
2015 		WARN_ON_ONCE("Dying superblock while freezing!");
2016 		return -EINVAL;
2017 	}
2018 	atomic_inc(&sb->s_active);
2019 
2020 retry:
2021 	if (sb->s_writers.frozen == SB_FREEZE_COMPLETE) {
2022 		if (may_freeze(sb, who, freeze_owner))
2023 			ret = !!WARN_ON_ONCE(freeze_inc(sb, who) == 1);
2024 		else
2025 			ret = -EBUSY;
2026 		/* All freezers share a single active reference. */
2027 		deactivate_locked_super(sb);
2028 		return ret;
2029 	}
2030 
2031 	if (sb->s_writers.frozen != SB_UNFROZEN) {
2032 		ret = wait_for_partially_frozen(sb);
2033 		if (ret) {
2034 			deactivate_locked_super(sb);
2035 			return ret;
2036 		}
2037 
2038 		goto retry;
2039 	}
2040 
2041 	if (sb_rdonly(sb)) {
2042 		/* Nothing to do really... */
2043 		WARN_ON_ONCE(freeze_inc(sb, who) > 1);
2044 		sb->s_writers.freeze_owner = freeze_owner;
2045 		sb->s_writers.frozen = SB_FREEZE_COMPLETE;
2046 		wake_up_var(&sb->s_writers.frozen);
2047 		super_unlock_excl(sb);
2048 		return 0;
2049 	}
2050 
2051 	sb->s_writers.frozen = SB_FREEZE_WRITE;
2052 	/* Release s_umount to preserve sb_start_write -> s_umount ordering */
2053 	super_unlock_excl(sb);
2054 	sb_wait_write(sb, SB_FREEZE_WRITE);
2055 	__super_lock_excl(sb);
2056 
2057 	/* Now we go and block page faults... */
2058 	sb->s_writers.frozen = SB_FREEZE_PAGEFAULT;
2059 	sb_wait_write(sb, SB_FREEZE_PAGEFAULT);
2060 
2061 	/* All writers are done so after syncing there won't be dirty data */
2062 	ret = sync_filesystem(sb);
2063 	if (ret) {
2064 		sb->s_writers.frozen = SB_UNFROZEN;
2065 		sb_freeze_unlock(sb, SB_FREEZE_PAGEFAULT);
2066 		wake_up_var(&sb->s_writers.frozen);
2067 		deactivate_locked_super(sb);
2068 		return ret;
2069 	}
2070 
2071 	/* Now wait for internal filesystem counter */
2072 	sb->s_writers.frozen = SB_FREEZE_FS;
2073 	sb_wait_write(sb, SB_FREEZE_FS);
2074 
2075 	if (sb->s_op->freeze_fs) {
2076 		ret = sb->s_op->freeze_fs(sb);
2077 		if (ret) {
2078 			printk(KERN_ERR
2079 				"VFS:Filesystem freeze failed\n");
2080 			sb->s_writers.frozen = SB_UNFROZEN;
2081 			sb_freeze_unlock(sb, SB_FREEZE_FS);
2082 			wake_up_var(&sb->s_writers.frozen);
2083 			deactivate_locked_super(sb);
2084 			return ret;
2085 		}
2086 	}
2087 	/*
2088 	 * For debugging purposes so that fs can warn if it sees write activity
2089 	 * when frozen is set to SB_FREEZE_COMPLETE, and for thaw_super().
2090 	 */
2091 	WARN_ON_ONCE(freeze_inc(sb, who) > 1);
2092 	sb->s_writers.freeze_owner = freeze_owner;
2093 	sb->s_writers.frozen = SB_FREEZE_COMPLETE;
2094 	wake_up_var(&sb->s_writers.frozen);
2095 	lockdep_sb_freeze_release(sb);
2096 	super_unlock_excl(sb);
2097 	return 0;
2098 }
2099 EXPORT_SYMBOL(freeze_super);
2100 
2101 /*
2102  * Undoes the effect of a freeze_super_locked call.  If the filesystem is
2103  * frozen both by userspace and the kernel, a thaw call from either source
2104  * removes that state without releasing the other state or unlocking the
2105  * filesystem.
2106  */
2107 static int thaw_super_locked(struct super_block *sb, enum freeze_holder who,
2108 			     const void *freeze_owner)
2109 {
2110 	int error = -EINVAL;
2111 
2112 	if (sb->s_writers.frozen != SB_FREEZE_COMPLETE)
2113 		goto out_unlock;
2114 
2115 	if (!may_unfreeze(sb, who, freeze_owner))
2116 		goto out_unlock;
2117 
2118 	/*
2119 	 * All freezers share a single active reference.
2120 	 * So just unlock in case there are any left.
2121 	 */
2122 	if (freeze_dec(sb, who))
2123 		goto out_unlock;
2124 
2125 	if (sb_rdonly(sb)) {
2126 		sb->s_writers.frozen = SB_UNFROZEN;
2127 		sb->s_writers.freeze_owner = NULL;
2128 		wake_up_var(&sb->s_writers.frozen);
2129 		goto out_deactivate;
2130 	}
2131 
2132 	lockdep_sb_freeze_acquire(sb);
2133 
2134 	if (sb->s_op->unfreeze_fs) {
2135 		error = sb->s_op->unfreeze_fs(sb);
2136 		if (error) {
2137 			pr_err("VFS: Filesystem thaw failed\n");
2138 			freeze_inc(sb, who);
2139 			lockdep_sb_freeze_release(sb);
2140 			goto out_unlock;
2141 		}
2142 	}
2143 
2144 	sb->s_writers.frozen = SB_UNFROZEN;
2145 	sb->s_writers.freeze_owner = NULL;
2146 	wake_up_var(&sb->s_writers.frozen);
2147 	sb_freeze_unlock(sb, SB_FREEZE_FS);
2148 out_deactivate:
2149 	deactivate_locked_super(sb);
2150 	return 0;
2151 
2152 out_unlock:
2153 	super_unlock_excl(sb);
2154 	return error;
2155 }
2156 
2157 /**
2158  * thaw_super -- unlock filesystem
2159  * @sb: the super to thaw
2160  * @who: context that wants to freeze
2161  * @freeze_owner: owner of the freeze
2162  *
2163  * Unlocks the filesystem and marks it writeable again after freeze_super()
2164  * if there are no remaining freezes on the filesystem.
2165  *
2166  * @who should be:
2167  * * %FREEZE_HOLDER_USERSPACE if userspace wants to thaw the fs;
2168  * * %FREEZE_HOLDER_KERNEL if the kernel wants to thaw the fs.
2169  * * %FREEZE_MAY_NEST whether nesting freeze and thaw requests is allowed
2170  *
2171  * A filesystem may hold multiple devices and thus a filesystems may
2172  * have been frozen through the block layer via multiple block devices.
2173  * The filesystem remains frozen until all block devices are unfrozen.
2174  */
2175 int thaw_super(struct super_block *sb, enum freeze_holder who,
2176 	       const void *freeze_owner)
2177 {
2178 	if (!super_lock_excl(sb)) {
2179 		WARN_ON_ONCE("Dying superblock while thawing!");
2180 		return -EINVAL;
2181 	}
2182 	return thaw_super_locked(sb, who, freeze_owner);
2183 }
2184 EXPORT_SYMBOL(thaw_super);
2185 
2186 /*
2187  * Create workqueue for deferred direct IO completions. We allocate the
2188  * workqueue when it's first needed. This avoids creating workqueue for
2189  * filesystems that don't need it and also allows us to create the workqueue
2190  * late enough so the we can include s_id in the name of the workqueue.
2191  */
2192 int sb_init_dio_done_wq(struct super_block *sb)
2193 {
2194 	struct workqueue_struct *old;
2195 	struct workqueue_struct *wq = alloc_workqueue("dio/%s",
2196 						      WQ_MEM_RECLAIM | WQ_PERCPU,
2197 						      0,
2198 						      sb->s_id);
2199 	if (!wq)
2200 		return -ENOMEM;
2201 
2202 	old = NULL;
2203 	/*
2204 	 * This has to be atomic as more DIOs can race to create the workqueue
2205 	 */
2206 	if (!try_cmpxchg(&sb->s_dio_done_wq, &old, wq)) {
2207 		/* Someone created workqueue before us? Free ours... */
2208 		destroy_workqueue(wq);
2209 	}
2210 	return 0;
2211 }
2212 EXPORT_SYMBOL_GPL(sb_init_dio_done_wq);
2213