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