xref: /linux-6.15/block/bdev.c (revision 2638c208)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  Copyright (C) 1991, 1992  Linus Torvalds
4  *  Copyright (C) 2001  Andrea Arcangeli <[email protected]> SuSE
5  *  Copyright (C) 2016 - 2020 Christoph Hellwig
6  */
7 
8 #include <linux/init.h>
9 #include <linux/mm.h>
10 #include <linux/slab.h>
11 #include <linux/kmod.h>
12 #include <linux/major.h>
13 #include <linux/device_cgroup.h>
14 #include <linux/blkdev.h>
15 #include <linux/blk-integrity.h>
16 #include <linux/backing-dev.h>
17 #include <linux/module.h>
18 #include <linux/blkpg.h>
19 #include <linux/magic.h>
20 #include <linux/buffer_head.h>
21 #include <linux/swap.h>
22 #include <linux/writeback.h>
23 #include <linux/mount.h>
24 #include <linux/pseudo_fs.h>
25 #include <linux/uio.h>
26 #include <linux/namei.h>
27 #include <linux/part_stat.h>
28 #include <linux/uaccess.h>
29 #include <linux/stat.h>
30 #include "../fs/internal.h"
31 #include "blk.h"
32 
33 /* Should we allow writing to mounted block devices? */
34 static bool bdev_allow_write_mounted = IS_ENABLED(CONFIG_BLK_DEV_WRITE_MOUNTED);
35 
36 struct bdev_inode {
37 	struct block_device bdev;
38 	struct inode vfs_inode;
39 };
40 
41 static inline struct bdev_inode *BDEV_I(struct inode *inode)
42 {
43 	return container_of(inode, struct bdev_inode, vfs_inode);
44 }
45 
46 struct block_device *I_BDEV(struct inode *inode)
47 {
48 	return &BDEV_I(inode)->bdev;
49 }
50 EXPORT_SYMBOL(I_BDEV);
51 
52 struct block_device *file_bdev(struct file *bdev_file)
53 {
54 	return I_BDEV(bdev_file->f_mapping->host);
55 }
56 EXPORT_SYMBOL(file_bdev);
57 
58 static void bdev_write_inode(struct block_device *bdev)
59 {
60 	struct inode *inode = bdev->bd_inode;
61 	int ret;
62 
63 	spin_lock(&inode->i_lock);
64 	while (inode->i_state & I_DIRTY) {
65 		spin_unlock(&inode->i_lock);
66 		ret = write_inode_now(inode, true);
67 		if (ret)
68 			pr_warn_ratelimited(
69 	"VFS: Dirty inode writeback failed for block device %pg (err=%d).\n",
70 				bdev, ret);
71 		spin_lock(&inode->i_lock);
72 	}
73 	spin_unlock(&inode->i_lock);
74 }
75 
76 /* Kill _all_ buffers and pagecache , dirty or not.. */
77 static void kill_bdev(struct block_device *bdev)
78 {
79 	struct address_space *mapping = bdev->bd_inode->i_mapping;
80 
81 	if (mapping_empty(mapping))
82 		return;
83 
84 	invalidate_bh_lrus();
85 	truncate_inode_pages(mapping, 0);
86 }
87 
88 /* Invalidate clean unused buffers and pagecache. */
89 void invalidate_bdev(struct block_device *bdev)
90 {
91 	struct address_space *mapping = bdev->bd_inode->i_mapping;
92 
93 	if (mapping->nrpages) {
94 		invalidate_bh_lrus();
95 		lru_add_drain_all();	/* make sure all lru add caches are flushed */
96 		invalidate_mapping_pages(mapping, 0, -1);
97 	}
98 }
99 EXPORT_SYMBOL(invalidate_bdev);
100 
101 /*
102  * Drop all buffers & page cache for given bdev range. This function bails
103  * with error if bdev has other exclusive owner (such as filesystem).
104  */
105 int truncate_bdev_range(struct block_device *bdev, blk_mode_t mode,
106 			loff_t lstart, loff_t lend)
107 {
108 	/*
109 	 * If we don't hold exclusive handle for the device, upgrade to it
110 	 * while we discard the buffer cache to avoid discarding buffers
111 	 * under live filesystem.
112 	 */
113 	if (!(mode & BLK_OPEN_EXCL)) {
114 		int err = bd_prepare_to_claim(bdev, truncate_bdev_range, NULL);
115 		if (err)
116 			goto invalidate;
117 	}
118 
119 	truncate_inode_pages_range(bdev->bd_inode->i_mapping, lstart, lend);
120 	if (!(mode & BLK_OPEN_EXCL))
121 		bd_abort_claiming(bdev, truncate_bdev_range);
122 	return 0;
123 
124 invalidate:
125 	/*
126 	 * Someone else has handle exclusively open. Try invalidating instead.
127 	 * The 'end' argument is inclusive so the rounding is safe.
128 	 */
129 	return invalidate_inode_pages2_range(bdev->bd_inode->i_mapping,
130 					     lstart >> PAGE_SHIFT,
131 					     lend >> PAGE_SHIFT);
132 }
133 
134 static void set_init_blocksize(struct block_device *bdev)
135 {
136 	unsigned int bsize = bdev_logical_block_size(bdev);
137 	loff_t size = i_size_read(bdev->bd_inode);
138 
139 	while (bsize < PAGE_SIZE) {
140 		if (size & bsize)
141 			break;
142 		bsize <<= 1;
143 	}
144 	bdev->bd_inode->i_blkbits = blksize_bits(bsize);
145 }
146 
147 int set_blocksize(struct file *file, int size)
148 {
149 	struct inode *inode = file->f_mapping->host;
150 	struct block_device *bdev = I_BDEV(inode);
151 
152 	/* Size must be a power of two, and between 512 and PAGE_SIZE */
153 	if (size > PAGE_SIZE || size < 512 || !is_power_of_2(size))
154 		return -EINVAL;
155 
156 	/* Size cannot be smaller than the size supported by the device */
157 	if (size < bdev_logical_block_size(bdev))
158 		return -EINVAL;
159 
160 	if (!file->private_data)
161 		return -EINVAL;
162 
163 	/* Don't change the size if it is same as current */
164 	if (inode->i_blkbits != blksize_bits(size)) {
165 		sync_blockdev(bdev);
166 		inode->i_blkbits = blksize_bits(size);
167 		kill_bdev(bdev);
168 	}
169 	return 0;
170 }
171 
172 EXPORT_SYMBOL(set_blocksize);
173 
174 int sb_set_blocksize(struct super_block *sb, int size)
175 {
176 	if (set_blocksize(sb->s_bdev_file, size))
177 		return 0;
178 	/* If we get here, we know size is power of two
179 	 * and it's value is between 512 and PAGE_SIZE */
180 	sb->s_blocksize = size;
181 	sb->s_blocksize_bits = blksize_bits(size);
182 	return sb->s_blocksize;
183 }
184 
185 EXPORT_SYMBOL(sb_set_blocksize);
186 
187 int sb_min_blocksize(struct super_block *sb, int size)
188 {
189 	int minsize = bdev_logical_block_size(sb->s_bdev);
190 	if (size < minsize)
191 		size = minsize;
192 	return sb_set_blocksize(sb, size);
193 }
194 
195 EXPORT_SYMBOL(sb_min_blocksize);
196 
197 int sync_blockdev_nowait(struct block_device *bdev)
198 {
199 	if (!bdev)
200 		return 0;
201 	return filemap_flush(bdev->bd_inode->i_mapping);
202 }
203 EXPORT_SYMBOL_GPL(sync_blockdev_nowait);
204 
205 /*
206  * Write out and wait upon all the dirty data associated with a block
207  * device via its mapping.  Does not take the superblock lock.
208  */
209 int sync_blockdev(struct block_device *bdev)
210 {
211 	if (!bdev)
212 		return 0;
213 	return filemap_write_and_wait(bdev->bd_inode->i_mapping);
214 }
215 EXPORT_SYMBOL(sync_blockdev);
216 
217 int sync_blockdev_range(struct block_device *bdev, loff_t lstart, loff_t lend)
218 {
219 	return filemap_write_and_wait_range(bdev->bd_inode->i_mapping,
220 			lstart, lend);
221 }
222 EXPORT_SYMBOL(sync_blockdev_range);
223 
224 /**
225  * bdev_freeze - lock a filesystem and force it into a consistent state
226  * @bdev:	blockdevice to lock
227  *
228  * If a superblock is found on this device, we take the s_umount semaphore
229  * on it to make sure nobody unmounts until the snapshot creation is done.
230  * The reference counter (bd_fsfreeze_count) guarantees that only the last
231  * unfreeze process can unfreeze the frozen filesystem actually when multiple
232  * freeze requests arrive simultaneously. It counts up in bdev_freeze() and
233  * count down in bdev_thaw(). When it becomes 0, thaw_bdev() will unfreeze
234  * actually.
235  *
236  * Return: On success zero is returned, negative error code on failure.
237  */
238 int bdev_freeze(struct block_device *bdev)
239 {
240 	int error = 0;
241 
242 	mutex_lock(&bdev->bd_fsfreeze_mutex);
243 
244 	if (atomic_inc_return(&bdev->bd_fsfreeze_count) > 1) {
245 		mutex_unlock(&bdev->bd_fsfreeze_mutex);
246 		return 0;
247 	}
248 
249 	mutex_lock(&bdev->bd_holder_lock);
250 	if (bdev->bd_holder_ops && bdev->bd_holder_ops->freeze) {
251 		error = bdev->bd_holder_ops->freeze(bdev);
252 		lockdep_assert_not_held(&bdev->bd_holder_lock);
253 	} else {
254 		mutex_unlock(&bdev->bd_holder_lock);
255 		error = sync_blockdev(bdev);
256 	}
257 
258 	if (error)
259 		atomic_dec(&bdev->bd_fsfreeze_count);
260 
261 	mutex_unlock(&bdev->bd_fsfreeze_mutex);
262 	return error;
263 }
264 EXPORT_SYMBOL(bdev_freeze);
265 
266 /**
267  * bdev_thaw - unlock filesystem
268  * @bdev:	blockdevice to unlock
269  *
270  * Unlocks the filesystem and marks it writeable again after bdev_freeze().
271  *
272  * Return: On success zero is returned, negative error code on failure.
273  */
274 int bdev_thaw(struct block_device *bdev)
275 {
276 	int error = -EINVAL, nr_freeze;
277 
278 	mutex_lock(&bdev->bd_fsfreeze_mutex);
279 
280 	/*
281 	 * If this returns < 0 it means that @bd_fsfreeze_count was
282 	 * already 0 and no decrement was performed.
283 	 */
284 	nr_freeze = atomic_dec_if_positive(&bdev->bd_fsfreeze_count);
285 	if (nr_freeze < 0)
286 		goto out;
287 
288 	error = 0;
289 	if (nr_freeze > 0)
290 		goto out;
291 
292 	mutex_lock(&bdev->bd_holder_lock);
293 	if (bdev->bd_holder_ops && bdev->bd_holder_ops->thaw) {
294 		error = bdev->bd_holder_ops->thaw(bdev);
295 		lockdep_assert_not_held(&bdev->bd_holder_lock);
296 	} else {
297 		mutex_unlock(&bdev->bd_holder_lock);
298 	}
299 
300 	if (error)
301 		atomic_inc(&bdev->bd_fsfreeze_count);
302 out:
303 	mutex_unlock(&bdev->bd_fsfreeze_mutex);
304 	return error;
305 }
306 EXPORT_SYMBOL(bdev_thaw);
307 
308 /*
309  * pseudo-fs
310  */
311 
312 static  __cacheline_aligned_in_smp DEFINE_MUTEX(bdev_lock);
313 static struct kmem_cache *bdev_cachep __ro_after_init;
314 
315 static struct inode *bdev_alloc_inode(struct super_block *sb)
316 {
317 	struct bdev_inode *ei = alloc_inode_sb(sb, bdev_cachep, GFP_KERNEL);
318 
319 	if (!ei)
320 		return NULL;
321 	memset(&ei->bdev, 0, sizeof(ei->bdev));
322 	return &ei->vfs_inode;
323 }
324 
325 static void bdev_free_inode(struct inode *inode)
326 {
327 	struct block_device *bdev = I_BDEV(inode);
328 
329 	free_percpu(bdev->bd_stats);
330 	kfree(bdev->bd_meta_info);
331 
332 	if (!bdev_is_partition(bdev)) {
333 		if (bdev->bd_disk && bdev->bd_disk->bdi)
334 			bdi_put(bdev->bd_disk->bdi);
335 		kfree(bdev->bd_disk);
336 	}
337 
338 	if (MAJOR(bdev->bd_dev) == BLOCK_EXT_MAJOR)
339 		blk_free_ext_minor(MINOR(bdev->bd_dev));
340 
341 	kmem_cache_free(bdev_cachep, BDEV_I(inode));
342 }
343 
344 static void init_once(void *data)
345 {
346 	struct bdev_inode *ei = data;
347 
348 	inode_init_once(&ei->vfs_inode);
349 }
350 
351 static void bdev_evict_inode(struct inode *inode)
352 {
353 	truncate_inode_pages_final(&inode->i_data);
354 	invalidate_inode_buffers(inode); /* is it needed here? */
355 	clear_inode(inode);
356 }
357 
358 static const struct super_operations bdev_sops = {
359 	.statfs = simple_statfs,
360 	.alloc_inode = bdev_alloc_inode,
361 	.free_inode = bdev_free_inode,
362 	.drop_inode = generic_delete_inode,
363 	.evict_inode = bdev_evict_inode,
364 };
365 
366 static int bd_init_fs_context(struct fs_context *fc)
367 {
368 	struct pseudo_fs_context *ctx = init_pseudo(fc, BDEVFS_MAGIC);
369 	if (!ctx)
370 		return -ENOMEM;
371 	fc->s_iflags |= SB_I_CGROUPWB;
372 	ctx->ops = &bdev_sops;
373 	return 0;
374 }
375 
376 static struct file_system_type bd_type = {
377 	.name		= "bdev",
378 	.init_fs_context = bd_init_fs_context,
379 	.kill_sb	= kill_anon_super,
380 };
381 
382 struct super_block *blockdev_superblock __ro_after_init;
383 struct vfsmount *blockdev_mnt __ro_after_init;
384 EXPORT_SYMBOL_GPL(blockdev_superblock);
385 
386 void __init bdev_cache_init(void)
387 {
388 	int err;
389 
390 	bdev_cachep = kmem_cache_create("bdev_cache", sizeof(struct bdev_inode),
391 			0, (SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT|
392 				SLAB_ACCOUNT|SLAB_PANIC),
393 			init_once);
394 	err = register_filesystem(&bd_type);
395 	if (err)
396 		panic("Cannot register bdev pseudo-fs");
397 	blockdev_mnt = kern_mount(&bd_type);
398 	if (IS_ERR(blockdev_mnt))
399 		panic("Cannot create bdev pseudo-fs");
400 	blockdev_superblock = blockdev_mnt->mnt_sb;   /* For writeback */
401 }
402 
403 struct block_device *bdev_alloc(struct gendisk *disk, u8 partno)
404 {
405 	struct block_device *bdev;
406 	struct inode *inode;
407 
408 	inode = new_inode(blockdev_superblock);
409 	if (!inode)
410 		return NULL;
411 	inode->i_mode = S_IFBLK;
412 	inode->i_rdev = 0;
413 	inode->i_data.a_ops = &def_blk_aops;
414 	mapping_set_gfp_mask(&inode->i_data, GFP_USER);
415 
416 	bdev = I_BDEV(inode);
417 	mutex_init(&bdev->bd_fsfreeze_mutex);
418 	spin_lock_init(&bdev->bd_size_lock);
419 	mutex_init(&bdev->bd_holder_lock);
420 	bdev->bd_partno = partno;
421 	bdev->bd_inode = inode;
422 	bdev->bd_queue = disk->queue;
423 	if (partno)
424 		bdev->bd_has_submit_bio = disk->part0->bd_has_submit_bio;
425 	else
426 		bdev->bd_has_submit_bio = false;
427 	bdev->bd_stats = alloc_percpu(struct disk_stats);
428 	if (!bdev->bd_stats) {
429 		iput(inode);
430 		return NULL;
431 	}
432 	bdev->bd_disk = disk;
433 	return bdev;
434 }
435 
436 void bdev_set_nr_sectors(struct block_device *bdev, sector_t sectors)
437 {
438 	spin_lock(&bdev->bd_size_lock);
439 	i_size_write(bdev->bd_inode, (loff_t)sectors << SECTOR_SHIFT);
440 	bdev->bd_nr_sectors = sectors;
441 	spin_unlock(&bdev->bd_size_lock);
442 }
443 
444 void bdev_add(struct block_device *bdev, dev_t dev)
445 {
446 	if (bdev_stable_writes(bdev))
447 		mapping_set_stable_writes(bdev->bd_inode->i_mapping);
448 	bdev->bd_dev = dev;
449 	bdev->bd_inode->i_rdev = dev;
450 	bdev->bd_inode->i_ino = dev;
451 	insert_inode_hash(bdev->bd_inode);
452 }
453 
454 void bdev_unhash(struct block_device *bdev)
455 {
456 	remove_inode_hash(bdev->bd_inode);
457 }
458 
459 void bdev_drop(struct block_device *bdev)
460 {
461 	iput(bdev->bd_inode);
462 }
463 
464 long nr_blockdev_pages(void)
465 {
466 	struct inode *inode;
467 	long ret = 0;
468 
469 	spin_lock(&blockdev_superblock->s_inode_list_lock);
470 	list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list)
471 		ret += inode->i_mapping->nrpages;
472 	spin_unlock(&blockdev_superblock->s_inode_list_lock);
473 
474 	return ret;
475 }
476 
477 /**
478  * bd_may_claim - test whether a block device can be claimed
479  * @bdev: block device of interest
480  * @holder: holder trying to claim @bdev
481  * @hops: holder ops
482  *
483  * Test whether @bdev can be claimed by @holder.
484  *
485  * RETURNS:
486  * %true if @bdev can be claimed, %false otherwise.
487  */
488 static bool bd_may_claim(struct block_device *bdev, void *holder,
489 		const struct blk_holder_ops *hops)
490 {
491 	struct block_device *whole = bdev_whole(bdev);
492 
493 	lockdep_assert_held(&bdev_lock);
494 
495 	if (bdev->bd_holder) {
496 		/*
497 		 * The same holder can always re-claim.
498 		 */
499 		if (bdev->bd_holder == holder) {
500 			if (WARN_ON_ONCE(bdev->bd_holder_ops != hops))
501 				return false;
502 			return true;
503 		}
504 		return false;
505 	}
506 
507 	/*
508 	 * If the whole devices holder is set to bd_may_claim, a partition on
509 	 * the device is claimed, but not the whole device.
510 	 */
511 	if (whole != bdev &&
512 	    whole->bd_holder && whole->bd_holder != bd_may_claim)
513 		return false;
514 	return true;
515 }
516 
517 /**
518  * bd_prepare_to_claim - claim a block device
519  * @bdev: block device of interest
520  * @holder: holder trying to claim @bdev
521  * @hops: holder ops.
522  *
523  * Claim @bdev.  This function fails if @bdev is already claimed by another
524  * holder and waits if another claiming is in progress. return, the caller
525  * has ownership of bd_claiming and bd_holder[s].
526  *
527  * RETURNS:
528  * 0 if @bdev can be claimed, -EBUSY otherwise.
529  */
530 int bd_prepare_to_claim(struct block_device *bdev, void *holder,
531 		const struct blk_holder_ops *hops)
532 {
533 	struct block_device *whole = bdev_whole(bdev);
534 
535 	if (WARN_ON_ONCE(!holder))
536 		return -EINVAL;
537 retry:
538 	mutex_lock(&bdev_lock);
539 	/* if someone else claimed, fail */
540 	if (!bd_may_claim(bdev, holder, hops)) {
541 		mutex_unlock(&bdev_lock);
542 		return -EBUSY;
543 	}
544 
545 	/* if claiming is already in progress, wait for it to finish */
546 	if (whole->bd_claiming) {
547 		wait_queue_head_t *wq = bit_waitqueue(&whole->bd_claiming, 0);
548 		DEFINE_WAIT(wait);
549 
550 		prepare_to_wait(wq, &wait, TASK_UNINTERRUPTIBLE);
551 		mutex_unlock(&bdev_lock);
552 		schedule();
553 		finish_wait(wq, &wait);
554 		goto retry;
555 	}
556 
557 	/* yay, all mine */
558 	whole->bd_claiming = holder;
559 	mutex_unlock(&bdev_lock);
560 	return 0;
561 }
562 EXPORT_SYMBOL_GPL(bd_prepare_to_claim); /* only for the loop driver */
563 
564 static void bd_clear_claiming(struct block_device *whole, void *holder)
565 {
566 	lockdep_assert_held(&bdev_lock);
567 	/* tell others that we're done */
568 	BUG_ON(whole->bd_claiming != holder);
569 	whole->bd_claiming = NULL;
570 	wake_up_bit(&whole->bd_claiming, 0);
571 }
572 
573 /**
574  * bd_finish_claiming - finish claiming of a block device
575  * @bdev: block device of interest
576  * @holder: holder that has claimed @bdev
577  * @hops: block device holder operations
578  *
579  * Finish exclusive open of a block device. Mark the device as exlusively
580  * open by the holder and wake up all waiters for exclusive open to finish.
581  */
582 static void bd_finish_claiming(struct block_device *bdev, void *holder,
583 		const struct blk_holder_ops *hops)
584 {
585 	struct block_device *whole = bdev_whole(bdev);
586 
587 	mutex_lock(&bdev_lock);
588 	BUG_ON(!bd_may_claim(bdev, holder, hops));
589 	/*
590 	 * Note that for a whole device bd_holders will be incremented twice,
591 	 * and bd_holder will be set to bd_may_claim before being set to holder
592 	 */
593 	whole->bd_holders++;
594 	whole->bd_holder = bd_may_claim;
595 	bdev->bd_holders++;
596 	mutex_lock(&bdev->bd_holder_lock);
597 	bdev->bd_holder = holder;
598 	bdev->bd_holder_ops = hops;
599 	mutex_unlock(&bdev->bd_holder_lock);
600 	bd_clear_claiming(whole, holder);
601 	mutex_unlock(&bdev_lock);
602 }
603 
604 /**
605  * bd_abort_claiming - abort claiming of a block device
606  * @bdev: block device of interest
607  * @holder: holder that has claimed @bdev
608  *
609  * Abort claiming of a block device when the exclusive open failed. This can be
610  * also used when exclusive open is not actually desired and we just needed
611  * to block other exclusive openers for a while.
612  */
613 void bd_abort_claiming(struct block_device *bdev, void *holder)
614 {
615 	mutex_lock(&bdev_lock);
616 	bd_clear_claiming(bdev_whole(bdev), holder);
617 	mutex_unlock(&bdev_lock);
618 }
619 EXPORT_SYMBOL(bd_abort_claiming);
620 
621 static void bd_end_claim(struct block_device *bdev, void *holder)
622 {
623 	struct block_device *whole = bdev_whole(bdev);
624 	bool unblock = false;
625 
626 	/*
627 	 * Release a claim on the device.  The holder fields are protected with
628 	 * bdev_lock.  open_mutex is used to synchronize disk_holder unlinking.
629 	 */
630 	mutex_lock(&bdev_lock);
631 	WARN_ON_ONCE(bdev->bd_holder != holder);
632 	WARN_ON_ONCE(--bdev->bd_holders < 0);
633 	WARN_ON_ONCE(--whole->bd_holders < 0);
634 	if (!bdev->bd_holders) {
635 		mutex_lock(&bdev->bd_holder_lock);
636 		bdev->bd_holder = NULL;
637 		bdev->bd_holder_ops = NULL;
638 		mutex_unlock(&bdev->bd_holder_lock);
639 		if (bdev->bd_write_holder)
640 			unblock = true;
641 	}
642 	if (!whole->bd_holders)
643 		whole->bd_holder = NULL;
644 	mutex_unlock(&bdev_lock);
645 
646 	/*
647 	 * If this was the last claim, remove holder link and unblock evpoll if
648 	 * it was a write holder.
649 	 */
650 	if (unblock) {
651 		disk_unblock_events(bdev->bd_disk);
652 		bdev->bd_write_holder = false;
653 	}
654 }
655 
656 static void blkdev_flush_mapping(struct block_device *bdev)
657 {
658 	WARN_ON_ONCE(bdev->bd_holders);
659 	sync_blockdev(bdev);
660 	kill_bdev(bdev);
661 	bdev_write_inode(bdev);
662 }
663 
664 static int blkdev_get_whole(struct block_device *bdev, blk_mode_t mode)
665 {
666 	struct gendisk *disk = bdev->bd_disk;
667 	int ret;
668 
669 	if (disk->fops->open) {
670 		ret = disk->fops->open(disk, mode);
671 		if (ret) {
672 			/* avoid ghost partitions on a removed medium */
673 			if (ret == -ENOMEDIUM &&
674 			     test_bit(GD_NEED_PART_SCAN, &disk->state))
675 				bdev_disk_changed(disk, true);
676 			return ret;
677 		}
678 	}
679 
680 	if (!atomic_read(&bdev->bd_openers))
681 		set_init_blocksize(bdev);
682 	if (test_bit(GD_NEED_PART_SCAN, &disk->state))
683 		bdev_disk_changed(disk, false);
684 	atomic_inc(&bdev->bd_openers);
685 	return 0;
686 }
687 
688 static void blkdev_put_whole(struct block_device *bdev)
689 {
690 	if (atomic_dec_and_test(&bdev->bd_openers))
691 		blkdev_flush_mapping(bdev);
692 	if (bdev->bd_disk->fops->release)
693 		bdev->bd_disk->fops->release(bdev->bd_disk);
694 }
695 
696 static int blkdev_get_part(struct block_device *part, blk_mode_t mode)
697 {
698 	struct gendisk *disk = part->bd_disk;
699 	int ret;
700 
701 	ret = blkdev_get_whole(bdev_whole(part), mode);
702 	if (ret)
703 		return ret;
704 
705 	ret = -ENXIO;
706 	if (!bdev_nr_sectors(part))
707 		goto out_blkdev_put;
708 
709 	if (!atomic_read(&part->bd_openers)) {
710 		disk->open_partitions++;
711 		set_init_blocksize(part);
712 	}
713 	atomic_inc(&part->bd_openers);
714 	return 0;
715 
716 out_blkdev_put:
717 	blkdev_put_whole(bdev_whole(part));
718 	return ret;
719 }
720 
721 int bdev_permission(dev_t dev, blk_mode_t mode, void *holder)
722 {
723 	int ret;
724 
725 	ret = devcgroup_check_permission(DEVCG_DEV_BLOCK,
726 			MAJOR(dev), MINOR(dev),
727 			((mode & BLK_OPEN_READ) ? DEVCG_ACC_READ : 0) |
728 			((mode & BLK_OPEN_WRITE) ? DEVCG_ACC_WRITE : 0));
729 	if (ret)
730 		return ret;
731 
732 	/* Blocking writes requires exclusive opener */
733 	if (mode & BLK_OPEN_RESTRICT_WRITES && !holder)
734 		return -EINVAL;
735 
736 	/*
737 	 * We're using error pointers to indicate to ->release() when we
738 	 * failed to open that block device. Also this doesn't make sense.
739 	 */
740 	if (WARN_ON_ONCE(IS_ERR(holder)))
741 		return -EINVAL;
742 
743 	return 0;
744 }
745 
746 static void blkdev_put_part(struct block_device *part)
747 {
748 	struct block_device *whole = bdev_whole(part);
749 
750 	if (atomic_dec_and_test(&part->bd_openers)) {
751 		blkdev_flush_mapping(part);
752 		whole->bd_disk->open_partitions--;
753 	}
754 	blkdev_put_whole(whole);
755 }
756 
757 struct block_device *blkdev_get_no_open(dev_t dev)
758 {
759 	struct block_device *bdev;
760 	struct inode *inode;
761 
762 	inode = ilookup(blockdev_superblock, dev);
763 	if (!inode && IS_ENABLED(CONFIG_BLOCK_LEGACY_AUTOLOAD)) {
764 		blk_request_module(dev);
765 		inode = ilookup(blockdev_superblock, dev);
766 		if (inode)
767 			pr_warn_ratelimited(
768 "block device autoloading is deprecated and will be removed.\n");
769 	}
770 	if (!inode)
771 		return NULL;
772 
773 	/* switch from the inode reference to a device mode one: */
774 	bdev = &BDEV_I(inode)->bdev;
775 	if (!kobject_get_unless_zero(&bdev->bd_device.kobj))
776 		bdev = NULL;
777 	iput(inode);
778 	return bdev;
779 }
780 
781 void blkdev_put_no_open(struct block_device *bdev)
782 {
783 	put_device(&bdev->bd_device);
784 }
785 
786 static bool bdev_writes_blocked(struct block_device *bdev)
787 {
788 	return bdev->bd_writers < 0;
789 }
790 
791 static void bdev_block_writes(struct block_device *bdev)
792 {
793 	bdev->bd_writers--;
794 }
795 
796 static void bdev_unblock_writes(struct block_device *bdev)
797 {
798 	bdev->bd_writers++;
799 }
800 
801 static bool bdev_may_open(struct block_device *bdev, blk_mode_t mode)
802 {
803 	if (bdev_allow_write_mounted)
804 		return true;
805 	/* Writes blocked? */
806 	if (mode & BLK_OPEN_WRITE && bdev_writes_blocked(bdev))
807 		return false;
808 	if (mode & BLK_OPEN_RESTRICT_WRITES && bdev->bd_writers > 0)
809 		return false;
810 	return true;
811 }
812 
813 static void bdev_claim_write_access(struct block_device *bdev, blk_mode_t mode)
814 {
815 	if (bdev_allow_write_mounted)
816 		return;
817 
818 	/* Claim exclusive or shared write access. */
819 	if (mode & BLK_OPEN_RESTRICT_WRITES)
820 		bdev_block_writes(bdev);
821 	else if (mode & BLK_OPEN_WRITE)
822 		bdev->bd_writers++;
823 }
824 
825 static inline bool bdev_unclaimed(const struct file *bdev_file)
826 {
827 	return bdev_file->private_data == BDEV_I(bdev_file->f_mapping->host);
828 }
829 
830 static void bdev_yield_write_access(struct file *bdev_file)
831 {
832 	struct block_device *bdev;
833 
834 	if (bdev_allow_write_mounted)
835 		return;
836 
837 	if (bdev_unclaimed(bdev_file))
838 		return;
839 
840 	bdev = file_bdev(bdev_file);
841 
842 	if (bdev_file->f_mode & FMODE_WRITE_RESTRICTED)
843 		bdev_unblock_writes(bdev);
844 	else if (bdev_file->f_mode & FMODE_WRITE)
845 		bdev->bd_writers--;
846 }
847 
848 /**
849  * bdev_open - open a block device
850  * @bdev: block device to open
851  * @mode: open mode (BLK_OPEN_*)
852  * @holder: exclusive holder identifier
853  * @hops: holder operations
854  * @bdev_file: file for the block device
855  *
856  * Open the block device. If @holder is not %NULL, the block device is opened
857  * with exclusive access.  Exclusive opens may nest for the same @holder.
858  *
859  * CONTEXT:
860  * Might sleep.
861  *
862  * RETURNS:
863  * zero on success, -errno on failure.
864  */
865 int bdev_open(struct block_device *bdev, blk_mode_t mode, void *holder,
866 	      const struct blk_holder_ops *hops, struct file *bdev_file)
867 {
868 	bool unblock_events = true;
869 	struct gendisk *disk = bdev->bd_disk;
870 	int ret;
871 
872 	if (holder) {
873 		mode |= BLK_OPEN_EXCL;
874 		ret = bd_prepare_to_claim(bdev, holder, hops);
875 		if (ret)
876 			return ret;
877 	} else {
878 		if (WARN_ON_ONCE(mode & BLK_OPEN_EXCL))
879 			return -EIO;
880 	}
881 
882 	disk_block_events(disk);
883 
884 	mutex_lock(&disk->open_mutex);
885 	ret = -ENXIO;
886 	if (!disk_live(disk))
887 		goto abort_claiming;
888 	if (!try_module_get(disk->fops->owner))
889 		goto abort_claiming;
890 	ret = -EBUSY;
891 	if (!bdev_may_open(bdev, mode))
892 		goto abort_claiming;
893 	if (bdev_is_partition(bdev))
894 		ret = blkdev_get_part(bdev, mode);
895 	else
896 		ret = blkdev_get_whole(bdev, mode);
897 	if (ret)
898 		goto put_module;
899 	bdev_claim_write_access(bdev, mode);
900 	if (holder) {
901 		bd_finish_claiming(bdev, holder, hops);
902 
903 		/*
904 		 * Block event polling for write claims if requested.  Any write
905 		 * holder makes the write_holder state stick until all are
906 		 * released.  This is good enough and tracking individual
907 		 * writeable reference is too fragile given the way @mode is
908 		 * used in blkdev_get/put().
909 		 */
910 		if ((mode & BLK_OPEN_WRITE) && !bdev->bd_write_holder &&
911 		    (disk->event_flags & DISK_EVENT_FLAG_BLOCK_ON_EXCL_WRITE)) {
912 			bdev->bd_write_holder = true;
913 			unblock_events = false;
914 		}
915 	}
916 	mutex_unlock(&disk->open_mutex);
917 
918 	if (unblock_events)
919 		disk_unblock_events(disk);
920 
921 	bdev_file->f_flags |= O_LARGEFILE;
922 	bdev_file->f_mode |= FMODE_BUF_RASYNC | FMODE_CAN_ODIRECT;
923 	if (bdev_nowait(bdev))
924 		bdev_file->f_mode |= FMODE_NOWAIT;
925 	if (mode & BLK_OPEN_RESTRICT_WRITES)
926 		bdev_file->f_mode |= FMODE_WRITE_RESTRICTED;
927 	bdev_file->f_mapping = bdev->bd_inode->i_mapping;
928 	bdev_file->f_wb_err = filemap_sample_wb_err(bdev_file->f_mapping);
929 	bdev_file->private_data = holder;
930 
931 	return 0;
932 put_module:
933 	module_put(disk->fops->owner);
934 abort_claiming:
935 	if (holder)
936 		bd_abort_claiming(bdev, holder);
937 	mutex_unlock(&disk->open_mutex);
938 	disk_unblock_events(disk);
939 	return ret;
940 }
941 
942 /*
943  * If BLK_OPEN_WRITE_IOCTL is set then this is a historical quirk
944  * associated with the floppy driver where it has allowed ioctls if the
945  * file was opened for writing, but does not allow reads or writes.
946  * Make sure that this quirk is reflected in @f_flags.
947  *
948  * It can also happen if a block device is opened as O_RDWR | O_WRONLY.
949  */
950 static unsigned blk_to_file_flags(blk_mode_t mode)
951 {
952 	unsigned int flags = 0;
953 
954 	if ((mode & (BLK_OPEN_READ | BLK_OPEN_WRITE)) ==
955 	    (BLK_OPEN_READ | BLK_OPEN_WRITE))
956 		flags |= O_RDWR;
957 	else if (mode & BLK_OPEN_WRITE_IOCTL)
958 		flags |= O_RDWR | O_WRONLY;
959 	else if (mode & BLK_OPEN_WRITE)
960 		flags |= O_WRONLY;
961 	else if (mode & BLK_OPEN_READ)
962 		flags |= O_RDONLY; /* homeopathic, because O_RDONLY is 0 */
963 	else
964 		WARN_ON_ONCE(true);
965 
966 	if (mode & BLK_OPEN_NDELAY)
967 		flags |= O_NDELAY;
968 
969 	return flags;
970 }
971 
972 struct file *bdev_file_open_by_dev(dev_t dev, blk_mode_t mode, void *holder,
973 				   const struct blk_holder_ops *hops)
974 {
975 	struct file *bdev_file;
976 	struct block_device *bdev;
977 	unsigned int flags;
978 	int ret;
979 
980 	ret = bdev_permission(dev, mode, holder);
981 	if (ret)
982 		return ERR_PTR(ret);
983 
984 	bdev = blkdev_get_no_open(dev);
985 	if (!bdev)
986 		return ERR_PTR(-ENXIO);
987 
988 	flags = blk_to_file_flags(mode);
989 	bdev_file = alloc_file_pseudo_noaccount(bdev->bd_inode,
990 			blockdev_mnt, "", flags | O_LARGEFILE, &def_blk_fops);
991 	if (IS_ERR(bdev_file)) {
992 		blkdev_put_no_open(bdev);
993 		return bdev_file;
994 	}
995 	ihold(bdev->bd_inode);
996 
997 	ret = bdev_open(bdev, mode, holder, hops, bdev_file);
998 	if (ret) {
999 		/* We failed to open the block device. Let ->release() know. */
1000 		bdev_file->private_data = ERR_PTR(ret);
1001 		fput(bdev_file);
1002 		return ERR_PTR(ret);
1003 	}
1004 	return bdev_file;
1005 }
1006 EXPORT_SYMBOL(bdev_file_open_by_dev);
1007 
1008 struct file *bdev_file_open_by_path(const char *path, blk_mode_t mode,
1009 				    void *holder,
1010 				    const struct blk_holder_ops *hops)
1011 {
1012 	struct file *file;
1013 	dev_t dev;
1014 	int error;
1015 
1016 	error = lookup_bdev(path, &dev);
1017 	if (error)
1018 		return ERR_PTR(error);
1019 
1020 	file = bdev_file_open_by_dev(dev, mode, holder, hops);
1021 	if (!IS_ERR(file) && (mode & BLK_OPEN_WRITE)) {
1022 		if (bdev_read_only(file_bdev(file))) {
1023 			fput(file);
1024 			file = ERR_PTR(-EACCES);
1025 		}
1026 	}
1027 
1028 	return file;
1029 }
1030 EXPORT_SYMBOL(bdev_file_open_by_path);
1031 
1032 static inline void bd_yield_claim(struct file *bdev_file)
1033 {
1034 	struct block_device *bdev = file_bdev(bdev_file);
1035 	void *holder = bdev_file->private_data;
1036 
1037 	lockdep_assert_held(&bdev->bd_disk->open_mutex);
1038 
1039 	if (WARN_ON_ONCE(IS_ERR_OR_NULL(holder)))
1040 		return;
1041 
1042 	if (!bdev_unclaimed(bdev_file))
1043 		bd_end_claim(bdev, holder);
1044 }
1045 
1046 void bdev_release(struct file *bdev_file)
1047 {
1048 	struct block_device *bdev = file_bdev(bdev_file);
1049 	void *holder = bdev_file->private_data;
1050 	struct gendisk *disk = bdev->bd_disk;
1051 
1052 	/* We failed to open that block device. */
1053 	if (IS_ERR(holder))
1054 		goto put_no_open;
1055 
1056 	/*
1057 	 * Sync early if it looks like we're the last one.  If someone else
1058 	 * opens the block device between now and the decrement of bd_openers
1059 	 * then we did a sync that we didn't need to, but that's not the end
1060 	 * of the world and we want to avoid long (could be several minute)
1061 	 * syncs while holding the mutex.
1062 	 */
1063 	if (atomic_read(&bdev->bd_openers) == 1)
1064 		sync_blockdev(bdev);
1065 
1066 	mutex_lock(&disk->open_mutex);
1067 	bdev_yield_write_access(bdev_file);
1068 
1069 	if (holder)
1070 		bd_yield_claim(bdev_file);
1071 
1072 	/*
1073 	 * Trigger event checking and tell drivers to flush MEDIA_CHANGE
1074 	 * event.  This is to ensure detection of media removal commanded
1075 	 * from userland - e.g. eject(1).
1076 	 */
1077 	disk_flush_events(disk, DISK_EVENT_MEDIA_CHANGE);
1078 
1079 	if (bdev_is_partition(bdev))
1080 		blkdev_put_part(bdev);
1081 	else
1082 		blkdev_put_whole(bdev);
1083 	mutex_unlock(&disk->open_mutex);
1084 
1085 	module_put(disk->fops->owner);
1086 put_no_open:
1087 	blkdev_put_no_open(bdev);
1088 }
1089 
1090 /**
1091  * bdev_fput - yield claim to the block device and put the file
1092  * @bdev_file: open block device
1093  *
1094  * Yield claim on the block device and put the file. Ensure that the
1095  * block device can be reclaimed before the file is closed which is a
1096  * deferred operation.
1097  */
1098 void bdev_fput(struct file *bdev_file)
1099 {
1100 	if (WARN_ON_ONCE(bdev_file->f_op != &def_blk_fops))
1101 		return;
1102 
1103 	if (bdev_file->private_data) {
1104 		struct block_device *bdev = file_bdev(bdev_file);
1105 		struct gendisk *disk = bdev->bd_disk;
1106 
1107 		mutex_lock(&disk->open_mutex);
1108 		bdev_yield_write_access(bdev_file);
1109 		bd_yield_claim(bdev_file);
1110 		/*
1111 		 * Tell release we already gave up our hold on the
1112 		 * device and if write restrictions are available that
1113 		 * we already gave up write access to the device.
1114 		 */
1115 		bdev_file->private_data = BDEV_I(bdev_file->f_mapping->host);
1116 		mutex_unlock(&disk->open_mutex);
1117 	}
1118 
1119 	fput(bdev_file);
1120 }
1121 EXPORT_SYMBOL(bdev_fput);
1122 
1123 /**
1124  * lookup_bdev() - Look up a struct block_device by name.
1125  * @pathname: Name of the block device in the filesystem.
1126  * @dev: Pointer to the block device's dev_t, if found.
1127  *
1128  * Lookup the block device's dev_t at @pathname in the current
1129  * namespace if possible and return it in @dev.
1130  *
1131  * Context: May sleep.
1132  * Return: 0 if succeeded, negative errno otherwise.
1133  */
1134 int lookup_bdev(const char *pathname, dev_t *dev)
1135 {
1136 	struct inode *inode;
1137 	struct path path;
1138 	int error;
1139 
1140 	if (!pathname || !*pathname)
1141 		return -EINVAL;
1142 
1143 	error = kern_path(pathname, LOOKUP_FOLLOW, &path);
1144 	if (error)
1145 		return error;
1146 
1147 	inode = d_backing_inode(path.dentry);
1148 	error = -ENOTBLK;
1149 	if (!S_ISBLK(inode->i_mode))
1150 		goto out_path_put;
1151 	error = -EACCES;
1152 	if (!may_open_dev(&path))
1153 		goto out_path_put;
1154 
1155 	*dev = inode->i_rdev;
1156 	error = 0;
1157 out_path_put:
1158 	path_put(&path);
1159 	return error;
1160 }
1161 EXPORT_SYMBOL(lookup_bdev);
1162 
1163 /**
1164  * bdev_mark_dead - mark a block device as dead
1165  * @bdev: block device to operate on
1166  * @surprise: indicate a surprise removal
1167  *
1168  * Tell the file system that this devices or media is dead.  If @surprise is set
1169  * to %true the device or media is already gone, if not we are preparing for an
1170  * orderly removal.
1171  *
1172  * This calls into the file system, which then typicall syncs out all dirty data
1173  * and writes back inodes and then invalidates any cached data in the inodes on
1174  * the file system.  In addition we also invalidate the block device mapping.
1175  */
1176 void bdev_mark_dead(struct block_device *bdev, bool surprise)
1177 {
1178 	mutex_lock(&bdev->bd_holder_lock);
1179 	if (bdev->bd_holder_ops && bdev->bd_holder_ops->mark_dead)
1180 		bdev->bd_holder_ops->mark_dead(bdev, surprise);
1181 	else {
1182 		mutex_unlock(&bdev->bd_holder_lock);
1183 		sync_blockdev(bdev);
1184 	}
1185 
1186 	invalidate_bdev(bdev);
1187 }
1188 /*
1189  * New drivers should not use this directly.  There are some drivers however
1190  * that needs this for historical reasons. For example, the DASD driver has
1191  * historically had a shutdown to offline mode that doesn't actually remove the
1192  * gendisk that otherwise looks a lot like a safe device removal.
1193  */
1194 EXPORT_SYMBOL_GPL(bdev_mark_dead);
1195 
1196 void sync_bdevs(bool wait)
1197 {
1198 	struct inode *inode, *old_inode = NULL;
1199 
1200 	spin_lock(&blockdev_superblock->s_inode_list_lock);
1201 	list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list) {
1202 		struct address_space *mapping = inode->i_mapping;
1203 		struct block_device *bdev;
1204 
1205 		spin_lock(&inode->i_lock);
1206 		if (inode->i_state & (I_FREEING|I_WILL_FREE|I_NEW) ||
1207 		    mapping->nrpages == 0) {
1208 			spin_unlock(&inode->i_lock);
1209 			continue;
1210 		}
1211 		__iget(inode);
1212 		spin_unlock(&inode->i_lock);
1213 		spin_unlock(&blockdev_superblock->s_inode_list_lock);
1214 		/*
1215 		 * We hold a reference to 'inode' so it couldn't have been
1216 		 * removed from s_inodes list while we dropped the
1217 		 * s_inode_list_lock  We cannot iput the inode now as we can
1218 		 * be holding the last reference and we cannot iput it under
1219 		 * s_inode_list_lock. So we keep the reference and iput it
1220 		 * later.
1221 		 */
1222 		iput(old_inode);
1223 		old_inode = inode;
1224 		bdev = I_BDEV(inode);
1225 
1226 		mutex_lock(&bdev->bd_disk->open_mutex);
1227 		if (!atomic_read(&bdev->bd_openers)) {
1228 			; /* skip */
1229 		} else if (wait) {
1230 			/*
1231 			 * We keep the error status of individual mapping so
1232 			 * that applications can catch the writeback error using
1233 			 * fsync(2). See filemap_fdatawait_keep_errors() for
1234 			 * details.
1235 			 */
1236 			filemap_fdatawait_keep_errors(inode->i_mapping);
1237 		} else {
1238 			filemap_fdatawrite(inode->i_mapping);
1239 		}
1240 		mutex_unlock(&bdev->bd_disk->open_mutex);
1241 
1242 		spin_lock(&blockdev_superblock->s_inode_list_lock);
1243 	}
1244 	spin_unlock(&blockdev_superblock->s_inode_list_lock);
1245 	iput(old_inode);
1246 }
1247 
1248 /*
1249  * Handle STATX_DIOALIGN for block devices.
1250  *
1251  * Note that the inode passed to this is the inode of a block device node file,
1252  * not the block device's internal inode.  Therefore it is *not* valid to use
1253  * I_BDEV() here; the block device has to be looked up by i_rdev instead.
1254  */
1255 void bdev_statx_dioalign(struct inode *inode, struct kstat *stat)
1256 {
1257 	struct block_device *bdev;
1258 
1259 	bdev = blkdev_get_no_open(inode->i_rdev);
1260 	if (!bdev)
1261 		return;
1262 
1263 	stat->dio_mem_align = bdev_dma_alignment(bdev) + 1;
1264 	stat->dio_offset_align = bdev_logical_block_size(bdev);
1265 	stat->result_mask |= STATX_DIOALIGN;
1266 
1267 	blkdev_put_no_open(bdev);
1268 }
1269 
1270 bool disk_live(struct gendisk *disk)
1271 {
1272 	return !inode_unhashed(disk->part0->bd_inode);
1273 }
1274 EXPORT_SYMBOL_GPL(disk_live);
1275 
1276 unsigned int block_size(struct block_device *bdev)
1277 {
1278 	return 1 << bdev->bd_inode->i_blkbits;
1279 }
1280 EXPORT_SYMBOL_GPL(block_size);
1281 
1282 static int __init setup_bdev_allow_write_mounted(char *str)
1283 {
1284 	if (kstrtobool(str, &bdev_allow_write_mounted))
1285 		pr_warn("Invalid option string for bdev_allow_write_mounted:"
1286 			" '%s'\n", str);
1287 	return 1;
1288 }
1289 __setup("bdev_allow_write_mounted=", setup_bdev_allow_write_mounted);
1290