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