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