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