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