xref: /linux-6.15/block/bdev.c (revision df65f166)
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_inode = inode;
427 	bdev->bd_mapping = &inode->i_data;
428 	bdev->bd_queue = disk->queue;
429 	if (partno)
430 		bdev->bd_has_submit_bio = disk->part0->bd_has_submit_bio;
431 	else
432 		bdev->bd_has_submit_bio = false;
433 	bdev->bd_stats = alloc_percpu(struct disk_stats);
434 	if (!bdev->bd_stats) {
435 		iput(inode);
436 		return NULL;
437 	}
438 	bdev->bd_disk = disk;
439 	return bdev;
440 }
441 
442 void bdev_set_nr_sectors(struct block_device *bdev, sector_t sectors)
443 {
444 	spin_lock(&bdev->bd_size_lock);
445 	i_size_write(BD_INODE(bdev), (loff_t)sectors << SECTOR_SHIFT);
446 	bdev->bd_nr_sectors = sectors;
447 	spin_unlock(&bdev->bd_size_lock);
448 }
449 
450 void bdev_add(struct block_device *bdev, dev_t dev)
451 {
452 	struct inode *inode = BD_INODE(bdev);
453 	if (bdev_stable_writes(bdev))
454 		mapping_set_stable_writes(bdev->bd_mapping);
455 	bdev->bd_dev = dev;
456 	inode->i_rdev = dev;
457 	inode->i_ino = dev;
458 	insert_inode_hash(inode);
459 }
460 
461 void bdev_unhash(struct block_device *bdev)
462 {
463 	remove_inode_hash(BD_INODE(bdev));
464 }
465 
466 void bdev_drop(struct block_device *bdev)
467 {
468 	iput(BD_INODE(bdev));
469 }
470 
471 long nr_blockdev_pages(void)
472 {
473 	struct inode *inode;
474 	long ret = 0;
475 
476 	spin_lock(&blockdev_superblock->s_inode_list_lock);
477 	list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list)
478 		ret += inode->i_mapping->nrpages;
479 	spin_unlock(&blockdev_superblock->s_inode_list_lock);
480 
481 	return ret;
482 }
483 
484 /**
485  * bd_may_claim - test whether a block device can be claimed
486  * @bdev: block device of interest
487  * @holder: holder trying to claim @bdev
488  * @hops: holder ops
489  *
490  * Test whether @bdev can be claimed by @holder.
491  *
492  * RETURNS:
493  * %true if @bdev can be claimed, %false otherwise.
494  */
495 static bool bd_may_claim(struct block_device *bdev, void *holder,
496 		const struct blk_holder_ops *hops)
497 {
498 	struct block_device *whole = bdev_whole(bdev);
499 
500 	lockdep_assert_held(&bdev_lock);
501 
502 	if (bdev->bd_holder) {
503 		/*
504 		 * The same holder can always re-claim.
505 		 */
506 		if (bdev->bd_holder == holder) {
507 			if (WARN_ON_ONCE(bdev->bd_holder_ops != hops))
508 				return false;
509 			return true;
510 		}
511 		return false;
512 	}
513 
514 	/*
515 	 * If the whole devices holder is set to bd_may_claim, a partition on
516 	 * the device is claimed, but not the whole device.
517 	 */
518 	if (whole != bdev &&
519 	    whole->bd_holder && whole->bd_holder != bd_may_claim)
520 		return false;
521 	return true;
522 }
523 
524 /**
525  * bd_prepare_to_claim - claim a block device
526  * @bdev: block device of interest
527  * @holder: holder trying to claim @bdev
528  * @hops: holder ops.
529  *
530  * Claim @bdev.  This function fails if @bdev is already claimed by another
531  * holder and waits if another claiming is in progress. return, the caller
532  * has ownership of bd_claiming and bd_holder[s].
533  *
534  * RETURNS:
535  * 0 if @bdev can be claimed, -EBUSY otherwise.
536  */
537 int bd_prepare_to_claim(struct block_device *bdev, void *holder,
538 		const struct blk_holder_ops *hops)
539 {
540 	struct block_device *whole = bdev_whole(bdev);
541 
542 	if (WARN_ON_ONCE(!holder))
543 		return -EINVAL;
544 retry:
545 	mutex_lock(&bdev_lock);
546 	/* if someone else claimed, fail */
547 	if (!bd_may_claim(bdev, holder, hops)) {
548 		mutex_unlock(&bdev_lock);
549 		return -EBUSY;
550 	}
551 
552 	/* if claiming is already in progress, wait for it to finish */
553 	if (whole->bd_claiming) {
554 		wait_queue_head_t *wq = bit_waitqueue(&whole->bd_claiming, 0);
555 		DEFINE_WAIT(wait);
556 
557 		prepare_to_wait(wq, &wait, TASK_UNINTERRUPTIBLE);
558 		mutex_unlock(&bdev_lock);
559 		schedule();
560 		finish_wait(wq, &wait);
561 		goto retry;
562 	}
563 
564 	/* yay, all mine */
565 	whole->bd_claiming = holder;
566 	mutex_unlock(&bdev_lock);
567 	return 0;
568 }
569 EXPORT_SYMBOL_GPL(bd_prepare_to_claim); /* only for the loop driver */
570 
571 static void bd_clear_claiming(struct block_device *whole, void *holder)
572 {
573 	lockdep_assert_held(&bdev_lock);
574 	/* tell others that we're done */
575 	BUG_ON(whole->bd_claiming != holder);
576 	whole->bd_claiming = NULL;
577 	wake_up_bit(&whole->bd_claiming, 0);
578 }
579 
580 /**
581  * bd_finish_claiming - finish claiming of a block device
582  * @bdev: block device of interest
583  * @holder: holder that has claimed @bdev
584  * @hops: block device holder operations
585  *
586  * Finish exclusive open of a block device. Mark the device as exlusively
587  * open by the holder and wake up all waiters for exclusive open to finish.
588  */
589 static void bd_finish_claiming(struct block_device *bdev, void *holder,
590 		const struct blk_holder_ops *hops)
591 {
592 	struct block_device *whole = bdev_whole(bdev);
593 
594 	mutex_lock(&bdev_lock);
595 	BUG_ON(!bd_may_claim(bdev, holder, hops));
596 	/*
597 	 * Note that for a whole device bd_holders will be incremented twice,
598 	 * and bd_holder will be set to bd_may_claim before being set to holder
599 	 */
600 	whole->bd_holders++;
601 	whole->bd_holder = bd_may_claim;
602 	bdev->bd_holders++;
603 	mutex_lock(&bdev->bd_holder_lock);
604 	bdev->bd_holder = holder;
605 	bdev->bd_holder_ops = hops;
606 	mutex_unlock(&bdev->bd_holder_lock);
607 	bd_clear_claiming(whole, holder);
608 	mutex_unlock(&bdev_lock);
609 }
610 
611 /**
612  * bd_abort_claiming - abort claiming of a block device
613  * @bdev: block device of interest
614  * @holder: holder that has claimed @bdev
615  *
616  * Abort claiming of a block device when the exclusive open failed. This can be
617  * also used when exclusive open is not actually desired and we just needed
618  * to block other exclusive openers for a while.
619  */
620 void bd_abort_claiming(struct block_device *bdev, void *holder)
621 {
622 	mutex_lock(&bdev_lock);
623 	bd_clear_claiming(bdev_whole(bdev), holder);
624 	mutex_unlock(&bdev_lock);
625 }
626 EXPORT_SYMBOL(bd_abort_claiming);
627 
628 static void bd_end_claim(struct block_device *bdev, void *holder)
629 {
630 	struct block_device *whole = bdev_whole(bdev);
631 	bool unblock = false;
632 
633 	/*
634 	 * Release a claim on the device.  The holder fields are protected with
635 	 * bdev_lock.  open_mutex is used to synchronize disk_holder unlinking.
636 	 */
637 	mutex_lock(&bdev_lock);
638 	WARN_ON_ONCE(bdev->bd_holder != holder);
639 	WARN_ON_ONCE(--bdev->bd_holders < 0);
640 	WARN_ON_ONCE(--whole->bd_holders < 0);
641 	if (!bdev->bd_holders) {
642 		mutex_lock(&bdev->bd_holder_lock);
643 		bdev->bd_holder = NULL;
644 		bdev->bd_holder_ops = NULL;
645 		mutex_unlock(&bdev->bd_holder_lock);
646 		if (bdev->bd_write_holder)
647 			unblock = true;
648 	}
649 	if (!whole->bd_holders)
650 		whole->bd_holder = NULL;
651 	mutex_unlock(&bdev_lock);
652 
653 	/*
654 	 * If this was the last claim, remove holder link and unblock evpoll if
655 	 * it was a write holder.
656 	 */
657 	if (unblock) {
658 		disk_unblock_events(bdev->bd_disk);
659 		bdev->bd_write_holder = false;
660 	}
661 }
662 
663 static void blkdev_flush_mapping(struct block_device *bdev)
664 {
665 	WARN_ON_ONCE(bdev->bd_holders);
666 	sync_blockdev(bdev);
667 	kill_bdev(bdev);
668 	bdev_write_inode(bdev);
669 }
670 
671 static int blkdev_get_whole(struct block_device *bdev, blk_mode_t mode)
672 {
673 	struct gendisk *disk = bdev->bd_disk;
674 	int ret;
675 
676 	if (disk->fops->open) {
677 		ret = disk->fops->open(disk, mode);
678 		if (ret) {
679 			/* avoid ghost partitions on a removed medium */
680 			if (ret == -ENOMEDIUM &&
681 			     test_bit(GD_NEED_PART_SCAN, &disk->state))
682 				bdev_disk_changed(disk, true);
683 			return ret;
684 		}
685 	}
686 
687 	if (!atomic_read(&bdev->bd_openers))
688 		set_init_blocksize(bdev);
689 	if (test_bit(GD_NEED_PART_SCAN, &disk->state))
690 		bdev_disk_changed(disk, false);
691 	atomic_inc(&bdev->bd_openers);
692 	return 0;
693 }
694 
695 static void blkdev_put_whole(struct block_device *bdev)
696 {
697 	if (atomic_dec_and_test(&bdev->bd_openers))
698 		blkdev_flush_mapping(bdev);
699 	if (bdev->bd_disk->fops->release)
700 		bdev->bd_disk->fops->release(bdev->bd_disk);
701 }
702 
703 static int blkdev_get_part(struct block_device *part, blk_mode_t mode)
704 {
705 	struct gendisk *disk = part->bd_disk;
706 	int ret;
707 
708 	ret = blkdev_get_whole(bdev_whole(part), mode);
709 	if (ret)
710 		return ret;
711 
712 	ret = -ENXIO;
713 	if (!bdev_nr_sectors(part))
714 		goto out_blkdev_put;
715 
716 	if (!atomic_read(&part->bd_openers)) {
717 		disk->open_partitions++;
718 		set_init_blocksize(part);
719 	}
720 	atomic_inc(&part->bd_openers);
721 	return 0;
722 
723 out_blkdev_put:
724 	blkdev_put_whole(bdev_whole(part));
725 	return ret;
726 }
727 
728 int bdev_permission(dev_t dev, blk_mode_t mode, void *holder)
729 {
730 	int ret;
731 
732 	ret = devcgroup_check_permission(DEVCG_DEV_BLOCK,
733 			MAJOR(dev), MINOR(dev),
734 			((mode & BLK_OPEN_READ) ? DEVCG_ACC_READ : 0) |
735 			((mode & BLK_OPEN_WRITE) ? DEVCG_ACC_WRITE : 0));
736 	if (ret)
737 		return ret;
738 
739 	/* Blocking writes requires exclusive opener */
740 	if (mode & BLK_OPEN_RESTRICT_WRITES && !holder)
741 		return -EINVAL;
742 
743 	/*
744 	 * We're using error pointers to indicate to ->release() when we
745 	 * failed to open that block device. Also this doesn't make sense.
746 	 */
747 	if (WARN_ON_ONCE(IS_ERR(holder)))
748 		return -EINVAL;
749 
750 	return 0;
751 }
752 
753 static void blkdev_put_part(struct block_device *part)
754 {
755 	struct block_device *whole = bdev_whole(part);
756 
757 	if (atomic_dec_and_test(&part->bd_openers)) {
758 		blkdev_flush_mapping(part);
759 		whole->bd_disk->open_partitions--;
760 	}
761 	blkdev_put_whole(whole);
762 }
763 
764 struct block_device *blkdev_get_no_open(dev_t dev)
765 {
766 	struct block_device *bdev;
767 	struct inode *inode;
768 
769 	inode = ilookup(blockdev_superblock, dev);
770 	if (!inode && IS_ENABLED(CONFIG_BLOCK_LEGACY_AUTOLOAD)) {
771 		blk_request_module(dev);
772 		inode = ilookup(blockdev_superblock, dev);
773 		if (inode)
774 			pr_warn_ratelimited(
775 "block device autoloading is deprecated and will be removed.\n");
776 	}
777 	if (!inode)
778 		return NULL;
779 
780 	/* switch from the inode reference to a device mode one: */
781 	bdev = &BDEV_I(inode)->bdev;
782 	if (!kobject_get_unless_zero(&bdev->bd_device.kobj))
783 		bdev = NULL;
784 	iput(inode);
785 	return bdev;
786 }
787 
788 void blkdev_put_no_open(struct block_device *bdev)
789 {
790 	put_device(&bdev->bd_device);
791 }
792 
793 static bool bdev_writes_blocked(struct block_device *bdev)
794 {
795 	return bdev->bd_writers < 0;
796 }
797 
798 static void bdev_block_writes(struct block_device *bdev)
799 {
800 	bdev->bd_writers--;
801 }
802 
803 static void bdev_unblock_writes(struct block_device *bdev)
804 {
805 	bdev->bd_writers++;
806 }
807 
808 static bool bdev_may_open(struct block_device *bdev, blk_mode_t mode)
809 {
810 	if (bdev_allow_write_mounted)
811 		return true;
812 	/* Writes blocked? */
813 	if (mode & BLK_OPEN_WRITE && bdev_writes_blocked(bdev))
814 		return false;
815 	if (mode & BLK_OPEN_RESTRICT_WRITES && bdev->bd_writers > 0)
816 		return false;
817 	return true;
818 }
819 
820 static void bdev_claim_write_access(struct block_device *bdev, blk_mode_t mode)
821 {
822 	if (bdev_allow_write_mounted)
823 		return;
824 
825 	/* Claim exclusive or shared write access. */
826 	if (mode & BLK_OPEN_RESTRICT_WRITES)
827 		bdev_block_writes(bdev);
828 	else if (mode & BLK_OPEN_WRITE)
829 		bdev->bd_writers++;
830 }
831 
832 static inline bool bdev_unclaimed(const struct file *bdev_file)
833 {
834 	return bdev_file->private_data == BDEV_I(bdev_file->f_mapping->host);
835 }
836 
837 static void bdev_yield_write_access(struct file *bdev_file)
838 {
839 	struct block_device *bdev;
840 
841 	if (bdev_allow_write_mounted)
842 		return;
843 
844 	if (bdev_unclaimed(bdev_file))
845 		return;
846 
847 	bdev = file_bdev(bdev_file);
848 
849 	if (bdev_file->f_mode & FMODE_WRITE_RESTRICTED)
850 		bdev_unblock_writes(bdev);
851 	else if (bdev_file->f_mode & FMODE_WRITE)
852 		bdev->bd_writers--;
853 }
854 
855 /**
856  * bdev_open - open a block device
857  * @bdev: block device to open
858  * @mode: open mode (BLK_OPEN_*)
859  * @holder: exclusive holder identifier
860  * @hops: holder operations
861  * @bdev_file: file for the block device
862  *
863  * Open the block device. If @holder is not %NULL, the block device is opened
864  * with exclusive access.  Exclusive opens may nest for the same @holder.
865  *
866  * CONTEXT:
867  * Might sleep.
868  *
869  * RETURNS:
870  * zero on success, -errno on failure.
871  */
872 int bdev_open(struct block_device *bdev, blk_mode_t mode, void *holder,
873 	      const struct blk_holder_ops *hops, struct file *bdev_file)
874 {
875 	bool unblock_events = true;
876 	struct gendisk *disk = bdev->bd_disk;
877 	int ret;
878 
879 	if (holder) {
880 		mode |= BLK_OPEN_EXCL;
881 		ret = bd_prepare_to_claim(bdev, holder, hops);
882 		if (ret)
883 			return ret;
884 	} else {
885 		if (WARN_ON_ONCE(mode & BLK_OPEN_EXCL))
886 			return -EIO;
887 	}
888 
889 	disk_block_events(disk);
890 
891 	mutex_lock(&disk->open_mutex);
892 	ret = -ENXIO;
893 	if (!disk_live(disk))
894 		goto abort_claiming;
895 	if (!try_module_get(disk->fops->owner))
896 		goto abort_claiming;
897 	ret = -EBUSY;
898 	if (!bdev_may_open(bdev, mode))
899 		goto abort_claiming;
900 	if (bdev_is_partition(bdev))
901 		ret = blkdev_get_part(bdev, mode);
902 	else
903 		ret = blkdev_get_whole(bdev, mode);
904 	if (ret)
905 		goto put_module;
906 	bdev_claim_write_access(bdev, mode);
907 	if (holder) {
908 		bd_finish_claiming(bdev, holder, hops);
909 
910 		/*
911 		 * Block event polling for write claims if requested.  Any write
912 		 * holder makes the write_holder state stick until all are
913 		 * released.  This is good enough and tracking individual
914 		 * writeable reference is too fragile given the way @mode is
915 		 * used in blkdev_get/put().
916 		 */
917 		if ((mode & BLK_OPEN_WRITE) && !bdev->bd_write_holder &&
918 		    (disk->event_flags & DISK_EVENT_FLAG_BLOCK_ON_EXCL_WRITE)) {
919 			bdev->bd_write_holder = true;
920 			unblock_events = false;
921 		}
922 	}
923 	mutex_unlock(&disk->open_mutex);
924 
925 	if (unblock_events)
926 		disk_unblock_events(disk);
927 
928 	bdev_file->f_flags |= O_LARGEFILE;
929 	bdev_file->f_mode |= FMODE_BUF_RASYNC | FMODE_CAN_ODIRECT;
930 	if (bdev_nowait(bdev))
931 		bdev_file->f_mode |= FMODE_NOWAIT;
932 	if (mode & BLK_OPEN_RESTRICT_WRITES)
933 		bdev_file->f_mode |= FMODE_WRITE_RESTRICTED;
934 	bdev_file->f_mapping = bdev->bd_mapping;
935 	bdev_file->f_wb_err = filemap_sample_wb_err(bdev_file->f_mapping);
936 	bdev_file->private_data = holder;
937 
938 	return 0;
939 put_module:
940 	module_put(disk->fops->owner);
941 abort_claiming:
942 	if (holder)
943 		bd_abort_claiming(bdev, holder);
944 	mutex_unlock(&disk->open_mutex);
945 	disk_unblock_events(disk);
946 	return ret;
947 }
948 
949 /*
950  * If BLK_OPEN_WRITE_IOCTL is set then this is a historical quirk
951  * associated with the floppy driver where it has allowed ioctls if the
952  * file was opened for writing, but does not allow reads or writes.
953  * Make sure that this quirk is reflected in @f_flags.
954  *
955  * It can also happen if a block device is opened as O_RDWR | O_WRONLY.
956  */
957 static unsigned blk_to_file_flags(blk_mode_t mode)
958 {
959 	unsigned int flags = 0;
960 
961 	if ((mode & (BLK_OPEN_READ | BLK_OPEN_WRITE)) ==
962 	    (BLK_OPEN_READ | BLK_OPEN_WRITE))
963 		flags |= O_RDWR;
964 	else if (mode & BLK_OPEN_WRITE_IOCTL)
965 		flags |= O_RDWR | O_WRONLY;
966 	else if (mode & BLK_OPEN_WRITE)
967 		flags |= O_WRONLY;
968 	else if (mode & BLK_OPEN_READ)
969 		flags |= O_RDONLY; /* homeopathic, because O_RDONLY is 0 */
970 	else
971 		WARN_ON_ONCE(true);
972 
973 	if (mode & BLK_OPEN_NDELAY)
974 		flags |= O_NDELAY;
975 
976 	return flags;
977 }
978 
979 struct file *bdev_file_open_by_dev(dev_t dev, blk_mode_t mode, void *holder,
980 				   const struct blk_holder_ops *hops)
981 {
982 	struct file *bdev_file;
983 	struct block_device *bdev;
984 	unsigned int flags;
985 	int ret;
986 
987 	ret = bdev_permission(dev, mode, holder);
988 	if (ret)
989 		return ERR_PTR(ret);
990 
991 	bdev = blkdev_get_no_open(dev);
992 	if (!bdev)
993 		return ERR_PTR(-ENXIO);
994 
995 	flags = blk_to_file_flags(mode);
996 	bdev_file = alloc_file_pseudo_noaccount(BD_INODE(bdev),
997 			blockdev_mnt, "", flags | O_LARGEFILE, &def_blk_fops);
998 	if (IS_ERR(bdev_file)) {
999 		blkdev_put_no_open(bdev);
1000 		return bdev_file;
1001 	}
1002 	ihold(BD_INODE(bdev));
1003 
1004 	ret = bdev_open(bdev, mode, holder, hops, bdev_file);
1005 	if (ret) {
1006 		/* We failed to open the block device. Let ->release() know. */
1007 		bdev_file->private_data = ERR_PTR(ret);
1008 		fput(bdev_file);
1009 		return ERR_PTR(ret);
1010 	}
1011 	return bdev_file;
1012 }
1013 EXPORT_SYMBOL(bdev_file_open_by_dev);
1014 
1015 struct file *bdev_file_open_by_path(const char *path, blk_mode_t mode,
1016 				    void *holder,
1017 				    const struct blk_holder_ops *hops)
1018 {
1019 	struct file *file;
1020 	dev_t dev;
1021 	int error;
1022 
1023 	error = lookup_bdev(path, &dev);
1024 	if (error)
1025 		return ERR_PTR(error);
1026 
1027 	file = bdev_file_open_by_dev(dev, mode, holder, hops);
1028 	if (!IS_ERR(file) && (mode & BLK_OPEN_WRITE)) {
1029 		if (bdev_read_only(file_bdev(file))) {
1030 			fput(file);
1031 			file = ERR_PTR(-EACCES);
1032 		}
1033 	}
1034 
1035 	return file;
1036 }
1037 EXPORT_SYMBOL(bdev_file_open_by_path);
1038 
1039 static inline void bd_yield_claim(struct file *bdev_file)
1040 {
1041 	struct block_device *bdev = file_bdev(bdev_file);
1042 	void *holder = bdev_file->private_data;
1043 
1044 	lockdep_assert_held(&bdev->bd_disk->open_mutex);
1045 
1046 	if (WARN_ON_ONCE(IS_ERR_OR_NULL(holder)))
1047 		return;
1048 
1049 	if (!bdev_unclaimed(bdev_file))
1050 		bd_end_claim(bdev, holder);
1051 }
1052 
1053 void bdev_release(struct file *bdev_file)
1054 {
1055 	struct block_device *bdev = file_bdev(bdev_file);
1056 	void *holder = bdev_file->private_data;
1057 	struct gendisk *disk = bdev->bd_disk;
1058 
1059 	/* We failed to open that block device. */
1060 	if (IS_ERR(holder))
1061 		goto put_no_open;
1062 
1063 	/*
1064 	 * Sync early if it looks like we're the last one.  If someone else
1065 	 * opens the block device between now and the decrement of bd_openers
1066 	 * then we did a sync that we didn't need to, but that's not the end
1067 	 * of the world and we want to avoid long (could be several minute)
1068 	 * syncs while holding the mutex.
1069 	 */
1070 	if (atomic_read(&bdev->bd_openers) == 1)
1071 		sync_blockdev(bdev);
1072 
1073 	mutex_lock(&disk->open_mutex);
1074 	bdev_yield_write_access(bdev_file);
1075 
1076 	if (holder)
1077 		bd_yield_claim(bdev_file);
1078 
1079 	/*
1080 	 * Trigger event checking and tell drivers to flush MEDIA_CHANGE
1081 	 * event.  This is to ensure detection of media removal commanded
1082 	 * from userland - e.g. eject(1).
1083 	 */
1084 	disk_flush_events(disk, DISK_EVENT_MEDIA_CHANGE);
1085 
1086 	if (bdev_is_partition(bdev))
1087 		blkdev_put_part(bdev);
1088 	else
1089 		blkdev_put_whole(bdev);
1090 	mutex_unlock(&disk->open_mutex);
1091 
1092 	module_put(disk->fops->owner);
1093 put_no_open:
1094 	blkdev_put_no_open(bdev);
1095 }
1096 
1097 /**
1098  * bdev_fput - yield claim to the block device and put the file
1099  * @bdev_file: open block device
1100  *
1101  * Yield claim on the block device and put the file. Ensure that the
1102  * block device can be reclaimed before the file is closed which is a
1103  * deferred operation.
1104  */
1105 void bdev_fput(struct file *bdev_file)
1106 {
1107 	if (WARN_ON_ONCE(bdev_file->f_op != &def_blk_fops))
1108 		return;
1109 
1110 	if (bdev_file->private_data) {
1111 		struct block_device *bdev = file_bdev(bdev_file);
1112 		struct gendisk *disk = bdev->bd_disk;
1113 
1114 		mutex_lock(&disk->open_mutex);
1115 		bdev_yield_write_access(bdev_file);
1116 		bd_yield_claim(bdev_file);
1117 		/*
1118 		 * Tell release we already gave up our hold on the
1119 		 * device and if write restrictions are available that
1120 		 * we already gave up write access to the device.
1121 		 */
1122 		bdev_file->private_data = BDEV_I(bdev_file->f_mapping->host);
1123 		mutex_unlock(&disk->open_mutex);
1124 	}
1125 
1126 	fput(bdev_file);
1127 }
1128 EXPORT_SYMBOL(bdev_fput);
1129 
1130 /**
1131  * lookup_bdev() - Look up a struct block_device by name.
1132  * @pathname: Name of the block device in the filesystem.
1133  * @dev: Pointer to the block device's dev_t, if found.
1134  *
1135  * Lookup the block device's dev_t at @pathname in the current
1136  * namespace if possible and return it in @dev.
1137  *
1138  * Context: May sleep.
1139  * Return: 0 if succeeded, negative errno otherwise.
1140  */
1141 int lookup_bdev(const char *pathname, dev_t *dev)
1142 {
1143 	struct inode *inode;
1144 	struct path path;
1145 	int error;
1146 
1147 	if (!pathname || !*pathname)
1148 		return -EINVAL;
1149 
1150 	error = kern_path(pathname, LOOKUP_FOLLOW, &path);
1151 	if (error)
1152 		return error;
1153 
1154 	inode = d_backing_inode(path.dentry);
1155 	error = -ENOTBLK;
1156 	if (!S_ISBLK(inode->i_mode))
1157 		goto out_path_put;
1158 	error = -EACCES;
1159 	if (!may_open_dev(&path))
1160 		goto out_path_put;
1161 
1162 	*dev = inode->i_rdev;
1163 	error = 0;
1164 out_path_put:
1165 	path_put(&path);
1166 	return error;
1167 }
1168 EXPORT_SYMBOL(lookup_bdev);
1169 
1170 /**
1171  * bdev_mark_dead - mark a block device as dead
1172  * @bdev: block device to operate on
1173  * @surprise: indicate a surprise removal
1174  *
1175  * Tell the file system that this devices or media is dead.  If @surprise is set
1176  * to %true the device or media is already gone, if not we are preparing for an
1177  * orderly removal.
1178  *
1179  * This calls into the file system, which then typicall syncs out all dirty data
1180  * and writes back inodes and then invalidates any cached data in the inodes on
1181  * the file system.  In addition we also invalidate the block device mapping.
1182  */
1183 void bdev_mark_dead(struct block_device *bdev, bool surprise)
1184 {
1185 	mutex_lock(&bdev->bd_holder_lock);
1186 	if (bdev->bd_holder_ops && bdev->bd_holder_ops->mark_dead)
1187 		bdev->bd_holder_ops->mark_dead(bdev, surprise);
1188 	else {
1189 		mutex_unlock(&bdev->bd_holder_lock);
1190 		sync_blockdev(bdev);
1191 	}
1192 
1193 	invalidate_bdev(bdev);
1194 }
1195 /*
1196  * New drivers should not use this directly.  There are some drivers however
1197  * that needs this for historical reasons. For example, the DASD driver has
1198  * historically had a shutdown to offline mode that doesn't actually remove the
1199  * gendisk that otherwise looks a lot like a safe device removal.
1200  */
1201 EXPORT_SYMBOL_GPL(bdev_mark_dead);
1202 
1203 void sync_bdevs(bool wait)
1204 {
1205 	struct inode *inode, *old_inode = NULL;
1206 
1207 	spin_lock(&blockdev_superblock->s_inode_list_lock);
1208 	list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list) {
1209 		struct address_space *mapping = inode->i_mapping;
1210 		struct block_device *bdev;
1211 
1212 		spin_lock(&inode->i_lock);
1213 		if (inode->i_state & (I_FREEING|I_WILL_FREE|I_NEW) ||
1214 		    mapping->nrpages == 0) {
1215 			spin_unlock(&inode->i_lock);
1216 			continue;
1217 		}
1218 		__iget(inode);
1219 		spin_unlock(&inode->i_lock);
1220 		spin_unlock(&blockdev_superblock->s_inode_list_lock);
1221 		/*
1222 		 * We hold a reference to 'inode' so it couldn't have been
1223 		 * removed from s_inodes list while we dropped the
1224 		 * s_inode_list_lock  We cannot iput the inode now as we can
1225 		 * be holding the last reference and we cannot iput it under
1226 		 * s_inode_list_lock. So we keep the reference and iput it
1227 		 * later.
1228 		 */
1229 		iput(old_inode);
1230 		old_inode = inode;
1231 		bdev = I_BDEV(inode);
1232 
1233 		mutex_lock(&bdev->bd_disk->open_mutex);
1234 		if (!atomic_read(&bdev->bd_openers)) {
1235 			; /* skip */
1236 		} else if (wait) {
1237 			/*
1238 			 * We keep the error status of individual mapping so
1239 			 * that applications can catch the writeback error using
1240 			 * fsync(2). See filemap_fdatawait_keep_errors() for
1241 			 * details.
1242 			 */
1243 			filemap_fdatawait_keep_errors(inode->i_mapping);
1244 		} else {
1245 			filemap_fdatawrite(inode->i_mapping);
1246 		}
1247 		mutex_unlock(&bdev->bd_disk->open_mutex);
1248 
1249 		spin_lock(&blockdev_superblock->s_inode_list_lock);
1250 	}
1251 	spin_unlock(&blockdev_superblock->s_inode_list_lock);
1252 	iput(old_inode);
1253 }
1254 
1255 /*
1256  * Handle STATX_DIOALIGN for block devices.
1257  *
1258  * Note that the inode passed to this is the inode of a block device node file,
1259  * not the block device's internal inode.  Therefore it is *not* valid to use
1260  * I_BDEV() here; the block device has to be looked up by i_rdev instead.
1261  */
1262 void bdev_statx_dioalign(struct inode *inode, struct kstat *stat)
1263 {
1264 	struct block_device *bdev;
1265 
1266 	bdev = blkdev_get_no_open(inode->i_rdev);
1267 	if (!bdev)
1268 		return;
1269 
1270 	stat->dio_mem_align = bdev_dma_alignment(bdev) + 1;
1271 	stat->dio_offset_align = bdev_logical_block_size(bdev);
1272 	stat->result_mask |= STATX_DIOALIGN;
1273 
1274 	blkdev_put_no_open(bdev);
1275 }
1276 
1277 bool disk_live(struct gendisk *disk)
1278 {
1279 	return !inode_unhashed(BD_INODE(disk->part0));
1280 }
1281 EXPORT_SYMBOL_GPL(disk_live);
1282 
1283 unsigned int block_size(struct block_device *bdev)
1284 {
1285 	return 1 << BD_INODE(bdev)->i_blkbits;
1286 }
1287 EXPORT_SYMBOL_GPL(block_size);
1288 
1289 static int __init setup_bdev_allow_write_mounted(char *str)
1290 {
1291 	if (kstrtobool(str, &bdev_allow_write_mounted))
1292 		pr_warn("Invalid option string for bdev_allow_write_mounted:"
1293 			" '%s'\n", str);
1294 	return 1;
1295 }
1296 __setup("bdev_allow_write_mounted=", setup_bdev_allow_write_mounted);
1297