1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 1991, 1992 Linus Torvalds
4 * Copyright (C) 2001 Andrea Arcangeli <andrea@suse.de> SuSE
5 * Copyright (C) 2016 - 2020 Christoph Hellwig
8 #include <linux/init.h>
10 #include <linux/fcntl.h>
11 #include <linux/slab.h>
12 #include <linux/kmod.h>
13 #include <linux/major.h>
14 #include <linux/device_cgroup.h>
15 #include <linux/highmem.h>
16 #include <linux/blkdev.h>
17 #include <linux/backing-dev.h>
18 #include <linux/module.h>
19 #include <linux/blkpg.h>
20 #include <linux/magic.h>
21 #include <linux/buffer_head.h>
22 #include <linux/swap.h>
23 #include <linux/pagevec.h>
24 #include <linux/writeback.h>
25 #include <linux/mpage.h>
26 #include <linux/mount.h>
27 #include <linux/pseudo_fs.h>
28 #include <linux/uio.h>
29 #include <linux/namei.h>
30 #include <linux/log2.h>
31 #include <linux/cleancache.h>
32 #include <linux/task_io_accounting_ops.h>
33 #include <linux/falloc.h>
34 #include <linux/part_stat.h>
35 #include <linux/uaccess.h>
36 #include <linux/suspend.h>
38 #include "../block/blk.h"
41 struct block_device bdev;
42 struct inode vfs_inode;
45 static const struct address_space_operations def_blk_aops;
47 static inline struct bdev_inode *BDEV_I(struct inode *inode)
49 return container_of(inode, struct bdev_inode, vfs_inode);
52 struct block_device *I_BDEV(struct inode *inode)
54 return &BDEV_I(inode)->bdev;
56 EXPORT_SYMBOL(I_BDEV);
58 static void bdev_write_inode(struct block_device *bdev)
60 struct inode *inode = bdev->bd_inode;
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);
68 char name[BDEVNAME_SIZE];
69 pr_warn_ratelimited("VFS: Dirty inode writeback failed "
70 "for block device %s (err=%d).\n",
71 bdevname(bdev, name), ret);
73 spin_lock(&inode->i_lock);
75 spin_unlock(&inode->i_lock);
78 /* Kill _all_ buffers and pagecache , dirty or not.. */
79 static void kill_bdev(struct block_device *bdev)
81 struct address_space *mapping = bdev->bd_inode->i_mapping;
83 if (mapping_empty(mapping))
87 truncate_inode_pages(mapping, 0);
90 /* Invalidate clean unused buffers and pagecache. */
91 void invalidate_bdev(struct block_device *bdev)
93 struct address_space *mapping = bdev->bd_inode->i_mapping;
95 if (mapping->nrpages) {
97 lru_add_drain_all(); /* make sure all lru add caches are flushed */
98 invalidate_mapping_pages(mapping, 0, -1);
100 /* 99% of the time, we don't need to flush the cleancache on the bdev.
101 * But, for the strange corners, lets be cautious
103 cleancache_invalidate_inode(mapping);
105 EXPORT_SYMBOL(invalidate_bdev);
108 * Drop all buffers & page cache for given bdev range. This function bails
109 * with error if bdev has other exclusive owner (such as filesystem).
111 int truncate_bdev_range(struct block_device *bdev, fmode_t mode,
112 loff_t lstart, loff_t lend)
115 * If we don't hold exclusive handle for the device, upgrade to it
116 * while we discard the buffer cache to avoid discarding buffers
117 * under live filesystem.
119 if (!(mode & FMODE_EXCL)) {
120 int err = bd_prepare_to_claim(bdev, truncate_bdev_range);
125 truncate_inode_pages_range(bdev->bd_inode->i_mapping, lstart, lend);
126 if (!(mode & FMODE_EXCL))
127 bd_abort_claiming(bdev, truncate_bdev_range);
132 * Someone else has handle exclusively open. Try invalidating instead.
133 * The 'end' argument is inclusive so the rounding is safe.
135 return invalidate_inode_pages2_range(bdev->bd_inode->i_mapping,
136 lstart >> PAGE_SHIFT,
140 static void set_init_blocksize(struct block_device *bdev)
142 unsigned int bsize = bdev_logical_block_size(bdev);
143 loff_t size = i_size_read(bdev->bd_inode);
145 while (bsize < PAGE_SIZE) {
150 bdev->bd_inode->i_blkbits = blksize_bits(bsize);
153 int set_blocksize(struct block_device *bdev, int size)
155 /* Size must be a power of two, and between 512 and PAGE_SIZE */
156 if (size > PAGE_SIZE || size < 512 || !is_power_of_2(size))
159 /* Size cannot be smaller than the size supported by the device */
160 if (size < bdev_logical_block_size(bdev))
163 /* Don't change the size if it is same as current */
164 if (bdev->bd_inode->i_blkbits != blksize_bits(size)) {
166 bdev->bd_inode->i_blkbits = blksize_bits(size);
172 EXPORT_SYMBOL(set_blocksize);
174 int sb_set_blocksize(struct super_block *sb, int size)
176 if (set_blocksize(sb->s_bdev, size))
178 /* If we get here, we know size is power of two
179 * and it's value is between 512 and PAGE_SIZE */
180 sb->s_blocksize = size;
181 sb->s_blocksize_bits = blksize_bits(size);
182 return sb->s_blocksize;
185 EXPORT_SYMBOL(sb_set_blocksize);
187 int sb_min_blocksize(struct super_block *sb, int size)
189 int minsize = bdev_logical_block_size(sb->s_bdev);
192 return sb_set_blocksize(sb, size);
195 EXPORT_SYMBOL(sb_min_blocksize);
198 blkdev_get_block(struct inode *inode, sector_t iblock,
199 struct buffer_head *bh, int create)
201 bh->b_bdev = I_BDEV(inode);
202 bh->b_blocknr = iblock;
203 set_buffer_mapped(bh);
207 static struct inode *bdev_file_inode(struct file *file)
209 return file->f_mapping->host;
212 static unsigned int dio_bio_write_op(struct kiocb *iocb)
214 unsigned int op = REQ_OP_WRITE | REQ_SYNC | REQ_IDLE;
216 /* avoid the need for a I/O completion work item */
217 if (iocb->ki_flags & IOCB_DSYNC)
222 #define DIO_INLINE_BIO_VECS 4
224 static void blkdev_bio_end_io_simple(struct bio *bio)
226 struct task_struct *waiter = bio->bi_private;
228 WRITE_ONCE(bio->bi_private, NULL);
229 blk_wake_io_task(waiter);
233 __blkdev_direct_IO_simple(struct kiocb *iocb, struct iov_iter *iter,
234 unsigned int nr_pages)
236 struct file *file = iocb->ki_filp;
237 struct block_device *bdev = I_BDEV(bdev_file_inode(file));
238 struct bio_vec inline_vecs[DIO_INLINE_BIO_VECS], *vecs;
239 loff_t pos = iocb->ki_pos;
240 bool should_dirty = false;
245 if ((pos | iov_iter_alignment(iter)) &
246 (bdev_logical_block_size(bdev) - 1))
249 if (nr_pages <= DIO_INLINE_BIO_VECS)
252 vecs = kmalloc_array(nr_pages, sizeof(struct bio_vec),
258 bio_init(&bio, vecs, nr_pages);
259 bio_set_dev(&bio, bdev);
260 bio.bi_iter.bi_sector = pos >> 9;
261 bio.bi_write_hint = iocb->ki_hint;
262 bio.bi_private = current;
263 bio.bi_end_io = blkdev_bio_end_io_simple;
264 bio.bi_ioprio = iocb->ki_ioprio;
266 ret = bio_iov_iter_get_pages(&bio, iter);
269 ret = bio.bi_iter.bi_size;
271 if (iov_iter_rw(iter) == READ) {
272 bio.bi_opf = REQ_OP_READ;
273 if (iter_is_iovec(iter))
276 bio.bi_opf = dio_bio_write_op(iocb);
277 task_io_account_write(ret);
279 if (iocb->ki_flags & IOCB_NOWAIT)
280 bio.bi_opf |= REQ_NOWAIT;
281 if (iocb->ki_flags & IOCB_HIPRI)
282 bio_set_polled(&bio, iocb);
284 qc = submit_bio(&bio);
286 set_current_state(TASK_UNINTERRUPTIBLE);
287 if (!READ_ONCE(bio.bi_private))
289 if (!(iocb->ki_flags & IOCB_HIPRI) ||
290 !blk_poll(bdev_get_queue(bdev), qc, true))
293 __set_current_state(TASK_RUNNING);
295 bio_release_pages(&bio, should_dirty);
296 if (unlikely(bio.bi_status))
297 ret = blk_status_to_errno(bio.bi_status);
300 if (vecs != inline_vecs)
311 struct task_struct *waiter;
316 bool should_dirty : 1;
321 static struct bio_set blkdev_dio_pool;
323 static int blkdev_iopoll(struct kiocb *kiocb, bool wait)
325 struct block_device *bdev = I_BDEV(kiocb->ki_filp->f_mapping->host);
326 struct request_queue *q = bdev_get_queue(bdev);
328 return blk_poll(q, READ_ONCE(kiocb->ki_cookie), wait);
331 static void blkdev_bio_end_io(struct bio *bio)
333 struct blkdev_dio *dio = bio->bi_private;
334 bool should_dirty = dio->should_dirty;
336 if (bio->bi_status && !dio->bio.bi_status)
337 dio->bio.bi_status = bio->bi_status;
339 if (!dio->multi_bio || atomic_dec_and_test(&dio->ref)) {
341 struct kiocb *iocb = dio->iocb;
344 if (likely(!dio->bio.bi_status)) {
348 ret = blk_status_to_errno(dio->bio.bi_status);
351 dio->iocb->ki_complete(iocb, ret, 0);
355 struct task_struct *waiter = dio->waiter;
357 WRITE_ONCE(dio->waiter, NULL);
358 blk_wake_io_task(waiter);
363 bio_check_pages_dirty(bio);
365 bio_release_pages(bio, false);
370 static ssize_t __blkdev_direct_IO(struct kiocb *iocb, struct iov_iter *iter,
371 unsigned int nr_pages)
373 struct file *file = iocb->ki_filp;
374 struct inode *inode = bdev_file_inode(file);
375 struct block_device *bdev = I_BDEV(inode);
376 struct blk_plug plug;
377 struct blkdev_dio *dio;
379 bool is_poll = (iocb->ki_flags & IOCB_HIPRI) != 0;
380 bool is_read = (iov_iter_rw(iter) == READ), is_sync;
381 loff_t pos = iocb->ki_pos;
382 blk_qc_t qc = BLK_QC_T_NONE;
385 if ((pos | iov_iter_alignment(iter)) &
386 (bdev_logical_block_size(bdev) - 1))
389 bio = bio_alloc_bioset(GFP_KERNEL, nr_pages, &blkdev_dio_pool);
391 dio = container_of(bio, struct blkdev_dio, bio);
392 dio->is_sync = is_sync = is_sync_kiocb(iocb);
394 dio->waiter = current;
401 dio->multi_bio = false;
402 dio->should_dirty = is_read && iter_is_iovec(iter);
405 * Don't plug for HIPRI/polled IO, as those should go straight
409 blk_start_plug(&plug);
412 bio_set_dev(bio, bdev);
413 bio->bi_iter.bi_sector = pos >> 9;
414 bio->bi_write_hint = iocb->ki_hint;
415 bio->bi_private = dio;
416 bio->bi_end_io = blkdev_bio_end_io;
417 bio->bi_ioprio = iocb->ki_ioprio;
419 ret = bio_iov_iter_get_pages(bio, iter);
421 bio->bi_status = BLK_STS_IOERR;
427 bio->bi_opf = REQ_OP_READ;
428 if (dio->should_dirty)
429 bio_set_pages_dirty(bio);
431 bio->bi_opf = dio_bio_write_op(iocb);
432 task_io_account_write(bio->bi_iter.bi_size);
434 if (iocb->ki_flags & IOCB_NOWAIT)
435 bio->bi_opf |= REQ_NOWAIT;
437 dio->size += bio->bi_iter.bi_size;
438 pos += bio->bi_iter.bi_size;
440 nr_pages = bio_iov_vecs_to_alloc(iter, BIO_MAX_VECS);
444 if (iocb->ki_flags & IOCB_HIPRI) {
445 bio_set_polled(bio, iocb);
449 qc = submit_bio(bio);
452 WRITE_ONCE(iocb->ki_cookie, qc);
456 if (!dio->multi_bio) {
458 * AIO needs an extra reference to ensure the dio
459 * structure which is embedded into the first bio
464 dio->multi_bio = true;
465 atomic_set(&dio->ref, 2);
467 atomic_inc(&dio->ref);
471 bio = bio_alloc(GFP_KERNEL, nr_pages);
475 blk_finish_plug(&plug);
481 set_current_state(TASK_UNINTERRUPTIBLE);
482 if (!READ_ONCE(dio->waiter))
485 if (!(iocb->ki_flags & IOCB_HIPRI) ||
486 !blk_poll(bdev_get_queue(bdev), qc, true))
489 __set_current_state(TASK_RUNNING);
492 ret = blk_status_to_errno(dio->bio.bi_status);
501 blkdev_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
503 unsigned int nr_pages;
505 if (!iov_iter_count(iter))
508 nr_pages = bio_iov_vecs_to_alloc(iter, BIO_MAX_VECS + 1);
509 if (is_sync_kiocb(iocb) && nr_pages <= BIO_MAX_VECS)
510 return __blkdev_direct_IO_simple(iocb, iter, nr_pages);
512 return __blkdev_direct_IO(iocb, iter, bio_max_segs(nr_pages));
515 static __init int blkdev_init(void)
517 return bioset_init(&blkdev_dio_pool, 4, offsetof(struct blkdev_dio, bio), BIOSET_NEED_BVECS);
519 module_init(blkdev_init);
521 int __sync_blockdev(struct block_device *bdev, int wait)
526 return filemap_flush(bdev->bd_inode->i_mapping);
527 return filemap_write_and_wait(bdev->bd_inode->i_mapping);
531 * Write out and wait upon all the dirty data associated with a block
532 * device via its mapping. Does not take the superblock lock.
534 int sync_blockdev(struct block_device *bdev)
536 return __sync_blockdev(bdev, 1);
538 EXPORT_SYMBOL(sync_blockdev);
541 * Write out and wait upon all dirty data associated with this
542 * device. Filesystem data as well as the underlying block
543 * device. Takes the superblock lock.
545 int fsync_bdev(struct block_device *bdev)
547 struct super_block *sb = get_super(bdev);
549 int res = sync_filesystem(sb);
553 return sync_blockdev(bdev);
555 EXPORT_SYMBOL(fsync_bdev);
558 * freeze_bdev -- lock a filesystem and force it into a consistent state
559 * @bdev: blockdevice to lock
561 * If a superblock is found on this device, we take the s_umount semaphore
562 * on it to make sure nobody unmounts until the snapshot creation is done.
563 * The reference counter (bd_fsfreeze_count) guarantees that only the last
564 * unfreeze process can unfreeze the frozen filesystem actually when multiple
565 * freeze requests arrive simultaneously. It counts up in freeze_bdev() and
566 * count down in thaw_bdev(). When it becomes 0, thaw_bdev() will unfreeze
569 int freeze_bdev(struct block_device *bdev)
571 struct super_block *sb;
574 mutex_lock(&bdev->bd_fsfreeze_mutex);
575 if (++bdev->bd_fsfreeze_count > 1)
578 sb = get_active_super(bdev);
581 if (sb->s_op->freeze_super)
582 error = sb->s_op->freeze_super(sb);
584 error = freeze_super(sb);
585 deactivate_super(sb);
588 bdev->bd_fsfreeze_count--;
591 bdev->bd_fsfreeze_sb = sb;
596 mutex_unlock(&bdev->bd_fsfreeze_mutex);
599 EXPORT_SYMBOL(freeze_bdev);
602 * thaw_bdev -- unlock filesystem
603 * @bdev: blockdevice to unlock
605 * Unlocks the filesystem and marks it writeable again after freeze_bdev().
607 int thaw_bdev(struct block_device *bdev)
609 struct super_block *sb;
612 mutex_lock(&bdev->bd_fsfreeze_mutex);
613 if (!bdev->bd_fsfreeze_count)
617 if (--bdev->bd_fsfreeze_count > 0)
620 sb = bdev->bd_fsfreeze_sb;
624 if (sb->s_op->thaw_super)
625 error = sb->s_op->thaw_super(sb);
627 error = thaw_super(sb);
629 bdev->bd_fsfreeze_count++;
631 bdev->bd_fsfreeze_sb = NULL;
633 mutex_unlock(&bdev->bd_fsfreeze_mutex);
636 EXPORT_SYMBOL(thaw_bdev);
638 static int blkdev_writepage(struct page *page, struct writeback_control *wbc)
640 return block_write_full_page(page, blkdev_get_block, wbc);
643 static int blkdev_readpage(struct file * file, struct page * page)
645 return block_read_full_page(page, blkdev_get_block);
648 static void blkdev_readahead(struct readahead_control *rac)
650 mpage_readahead(rac, blkdev_get_block);
653 static int blkdev_write_begin(struct file *file, struct address_space *mapping,
654 loff_t pos, unsigned len, unsigned flags,
655 struct page **pagep, void **fsdata)
657 return block_write_begin(mapping, pos, len, flags, pagep,
661 static int blkdev_write_end(struct file *file, struct address_space *mapping,
662 loff_t pos, unsigned len, unsigned copied,
663 struct page *page, void *fsdata)
666 ret = block_write_end(file, mapping, pos, len, copied, page, fsdata);
676 * for a block special file file_inode(file)->i_size is zero
677 * so we compute the size by hand (just as in block_read/write above)
679 static loff_t block_llseek(struct file *file, loff_t offset, int whence)
681 struct inode *bd_inode = bdev_file_inode(file);
684 inode_lock(bd_inode);
685 retval = fixed_size_llseek(file, offset, whence, i_size_read(bd_inode));
686 inode_unlock(bd_inode);
690 static int blkdev_fsync(struct file *filp, loff_t start, loff_t end,
693 struct inode *bd_inode = bdev_file_inode(filp);
694 struct block_device *bdev = I_BDEV(bd_inode);
697 error = file_write_and_wait_range(filp, start, end);
702 * There is no need to serialise calls to blkdev_issue_flush with
703 * i_mutex and doing so causes performance issues with concurrent
704 * O_SYNC writers to a block device.
706 error = blkdev_issue_flush(bdev);
707 if (error == -EOPNOTSUPP)
714 * bdev_read_page() - Start reading a page from a block device
715 * @bdev: The device to read the page from
716 * @sector: The offset on the device to read the page to (need not be aligned)
717 * @page: The page to read
719 * On entry, the page should be locked. It will be unlocked when the page
720 * has been read. If the block driver implements rw_page synchronously,
721 * that will be true on exit from this function, but it need not be.
723 * Errors returned by this function are usually "soft", eg out of memory, or
724 * queue full; callers should try a different route to read this page rather
725 * than propagate an error back up the stack.
727 * Return: negative errno if an error occurs, 0 if submission was successful.
729 int bdev_read_page(struct block_device *bdev, sector_t sector,
732 const struct block_device_operations *ops = bdev->bd_disk->fops;
733 int result = -EOPNOTSUPP;
735 if (!ops->rw_page || bdev_get_integrity(bdev))
738 result = blk_queue_enter(bdev->bd_disk->queue, 0);
741 result = ops->rw_page(bdev, sector + get_start_sect(bdev), page,
743 blk_queue_exit(bdev->bd_disk->queue);
748 * bdev_write_page() - Start writing a page to a block device
749 * @bdev: The device to write the page to
750 * @sector: The offset on the device to write the page to (need not be aligned)
751 * @page: The page to write
752 * @wbc: The writeback_control for the write
754 * On entry, the page should be locked and not currently under writeback.
755 * On exit, if the write started successfully, the page will be unlocked and
756 * under writeback. If the write failed already (eg the driver failed to
757 * queue the page to the device), the page will still be locked. If the
758 * caller is a ->writepage implementation, it will need to unlock the page.
760 * Errors returned by this function are usually "soft", eg out of memory, or
761 * queue full; callers should try a different route to write this page rather
762 * than propagate an error back up the stack.
764 * Return: negative errno if an error occurs, 0 if submission was successful.
766 int bdev_write_page(struct block_device *bdev, sector_t sector,
767 struct page *page, struct writeback_control *wbc)
770 const struct block_device_operations *ops = bdev->bd_disk->fops;
772 if (!ops->rw_page || bdev_get_integrity(bdev))
774 result = blk_queue_enter(bdev->bd_disk->queue, 0);
778 set_page_writeback(page);
779 result = ops->rw_page(bdev, sector + get_start_sect(bdev), page,
782 end_page_writeback(page);
784 clean_page_buffers(page);
787 blk_queue_exit(bdev->bd_disk->queue);
795 static __cacheline_aligned_in_smp DEFINE_SPINLOCK(bdev_lock);
796 static struct kmem_cache * bdev_cachep __read_mostly;
798 static struct inode *bdev_alloc_inode(struct super_block *sb)
800 struct bdev_inode *ei = kmem_cache_alloc(bdev_cachep, GFP_KERNEL);
804 memset(&ei->bdev, 0, sizeof(ei->bdev));
805 return &ei->vfs_inode;
808 static void bdev_free_inode(struct inode *inode)
810 struct block_device *bdev = I_BDEV(inode);
812 free_percpu(bdev->bd_stats);
813 kfree(bdev->bd_meta_info);
815 if (!bdev_is_partition(bdev)) {
816 if (bdev->bd_disk && bdev->bd_disk->bdi)
817 bdi_put(bdev->bd_disk->bdi);
818 kfree(bdev->bd_disk);
821 if (MAJOR(bdev->bd_dev) == BLOCK_EXT_MAJOR)
822 blk_free_ext_minor(MINOR(bdev->bd_dev));
824 kmem_cache_free(bdev_cachep, BDEV_I(inode));
827 static void init_once(void *data)
829 struct bdev_inode *ei = data;
831 inode_init_once(&ei->vfs_inode);
834 static void bdev_evict_inode(struct inode *inode)
836 truncate_inode_pages_final(&inode->i_data);
837 invalidate_inode_buffers(inode); /* is it needed here? */
841 static const struct super_operations bdev_sops = {
842 .statfs = simple_statfs,
843 .alloc_inode = bdev_alloc_inode,
844 .free_inode = bdev_free_inode,
845 .drop_inode = generic_delete_inode,
846 .evict_inode = bdev_evict_inode,
849 static int bd_init_fs_context(struct fs_context *fc)
851 struct pseudo_fs_context *ctx = init_pseudo(fc, BDEVFS_MAGIC);
854 fc->s_iflags |= SB_I_CGROUPWB;
855 ctx->ops = &bdev_sops;
859 static struct file_system_type bd_type = {
861 .init_fs_context = bd_init_fs_context,
862 .kill_sb = kill_anon_super,
865 struct super_block *blockdev_superblock __read_mostly;
866 EXPORT_SYMBOL_GPL(blockdev_superblock);
868 void __init bdev_cache_init(void)
871 static struct vfsmount *bd_mnt;
873 bdev_cachep = kmem_cache_create("bdev_cache", sizeof(struct bdev_inode),
874 0, (SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT|
875 SLAB_MEM_SPREAD|SLAB_ACCOUNT|SLAB_PANIC),
877 err = register_filesystem(&bd_type);
879 panic("Cannot register bdev pseudo-fs");
880 bd_mnt = kern_mount(&bd_type);
882 panic("Cannot create bdev pseudo-fs");
883 blockdev_superblock = bd_mnt->mnt_sb; /* For writeback */
886 struct block_device *bdev_alloc(struct gendisk *disk, u8 partno)
888 struct block_device *bdev;
891 inode = new_inode(blockdev_superblock);
894 inode->i_mode = S_IFBLK;
896 inode->i_data.a_ops = &def_blk_aops;
897 mapping_set_gfp_mask(&inode->i_data, GFP_USER);
899 bdev = I_BDEV(inode);
900 mutex_init(&bdev->bd_fsfreeze_mutex);
901 spin_lock_init(&bdev->bd_size_lock);
902 bdev->bd_disk = disk;
903 bdev->bd_partno = partno;
904 bdev->bd_inode = inode;
905 bdev->bd_stats = alloc_percpu(struct disk_stats);
906 if (!bdev->bd_stats) {
913 void bdev_add(struct block_device *bdev, dev_t dev)
916 bdev->bd_inode->i_rdev = dev;
917 bdev->bd_inode->i_ino = dev;
918 insert_inode_hash(bdev->bd_inode);
921 long nr_blockdev_pages(void)
926 spin_lock(&blockdev_superblock->s_inode_list_lock);
927 list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list)
928 ret += inode->i_mapping->nrpages;
929 spin_unlock(&blockdev_superblock->s_inode_list_lock);
935 * bd_may_claim - test whether a block device can be claimed
936 * @bdev: block device of interest
937 * @whole: whole block device containing @bdev, may equal @bdev
938 * @holder: holder trying to claim @bdev
940 * Test whether @bdev can be claimed by @holder.
943 * spin_lock(&bdev_lock).
946 * %true if @bdev can be claimed, %false otherwise.
948 static bool bd_may_claim(struct block_device *bdev, struct block_device *whole,
951 if (bdev->bd_holder == holder)
952 return true; /* already a holder */
953 else if (bdev->bd_holder != NULL)
954 return false; /* held by someone else */
955 else if (whole == bdev)
956 return true; /* is a whole device which isn't held */
958 else if (whole->bd_holder == bd_may_claim)
959 return true; /* is a partition of a device that is being partitioned */
960 else if (whole->bd_holder != NULL)
961 return false; /* is a partition of a held device */
963 return true; /* is a partition of an un-held device */
967 * bd_prepare_to_claim - claim a block device
968 * @bdev: block device of interest
969 * @holder: holder trying to claim @bdev
971 * Claim @bdev. This function fails if @bdev is already claimed by another
972 * holder and waits if another claiming is in progress. return, the caller
973 * has ownership of bd_claiming and bd_holder[s].
976 * 0 if @bdev can be claimed, -EBUSY otherwise.
978 int bd_prepare_to_claim(struct block_device *bdev, void *holder)
980 struct block_device *whole = bdev_whole(bdev);
982 if (WARN_ON_ONCE(!holder))
985 spin_lock(&bdev_lock);
986 /* if someone else claimed, fail */
987 if (!bd_may_claim(bdev, whole, holder)) {
988 spin_unlock(&bdev_lock);
992 /* if claiming is already in progress, wait for it to finish */
993 if (whole->bd_claiming) {
994 wait_queue_head_t *wq = bit_waitqueue(&whole->bd_claiming, 0);
997 prepare_to_wait(wq, &wait, TASK_UNINTERRUPTIBLE);
998 spin_unlock(&bdev_lock);
1000 finish_wait(wq, &wait);
1005 whole->bd_claiming = holder;
1006 spin_unlock(&bdev_lock);
1009 EXPORT_SYMBOL_GPL(bd_prepare_to_claim); /* only for the loop driver */
1011 static void bd_clear_claiming(struct block_device *whole, void *holder)
1013 lockdep_assert_held(&bdev_lock);
1014 /* tell others that we're done */
1015 BUG_ON(whole->bd_claiming != holder);
1016 whole->bd_claiming = NULL;
1017 wake_up_bit(&whole->bd_claiming, 0);
1021 * bd_finish_claiming - finish claiming of a block device
1022 * @bdev: block device of interest
1023 * @holder: holder that has claimed @bdev
1025 * Finish exclusive open of a block device. Mark the device as exlusively
1026 * open by the holder and wake up all waiters for exclusive open to finish.
1028 static void bd_finish_claiming(struct block_device *bdev, void *holder)
1030 struct block_device *whole = bdev_whole(bdev);
1032 spin_lock(&bdev_lock);
1033 BUG_ON(!bd_may_claim(bdev, whole, holder));
1035 * Note that for a whole device bd_holders will be incremented twice,
1036 * and bd_holder will be set to bd_may_claim before being set to holder
1038 whole->bd_holders++;
1039 whole->bd_holder = bd_may_claim;
1041 bdev->bd_holder = holder;
1042 bd_clear_claiming(whole, holder);
1043 spin_unlock(&bdev_lock);
1047 * bd_abort_claiming - abort claiming of a block device
1048 * @bdev: block device of interest
1049 * @holder: holder that has claimed @bdev
1051 * Abort claiming of a block device when the exclusive open failed. This can be
1052 * also used when exclusive open is not actually desired and we just needed
1053 * to block other exclusive openers for a while.
1055 void bd_abort_claiming(struct block_device *bdev, void *holder)
1057 spin_lock(&bdev_lock);
1058 bd_clear_claiming(bdev_whole(bdev), holder);
1059 spin_unlock(&bdev_lock);
1061 EXPORT_SYMBOL(bd_abort_claiming);
1063 static void blkdev_flush_mapping(struct block_device *bdev)
1065 WARN_ON_ONCE(bdev->bd_holders);
1066 sync_blockdev(bdev);
1068 bdev_write_inode(bdev);
1071 static int blkdev_get_whole(struct block_device *bdev, fmode_t mode)
1073 struct gendisk *disk = bdev->bd_disk;
1076 if (disk->fops->open) {
1077 ret = disk->fops->open(bdev, mode);
1079 /* avoid ghost partitions on a removed medium */
1080 if (ret == -ENOMEDIUM &&
1081 test_bit(GD_NEED_PART_SCAN, &disk->state))
1082 bdev_disk_changed(disk, true);
1087 if (!bdev->bd_openers)
1088 set_init_blocksize(bdev);
1089 if (test_bit(GD_NEED_PART_SCAN, &disk->state))
1090 bdev_disk_changed(disk, false);
1095 static void blkdev_put_whole(struct block_device *bdev, fmode_t mode)
1097 if (!--bdev->bd_openers)
1098 blkdev_flush_mapping(bdev);
1099 if (bdev->bd_disk->fops->release)
1100 bdev->bd_disk->fops->release(bdev->bd_disk, mode);
1103 static int blkdev_get_part(struct block_device *part, fmode_t mode)
1105 struct gendisk *disk = part->bd_disk;
1108 if (part->bd_openers)
1111 ret = blkdev_get_whole(bdev_whole(part), mode);
1116 if (!bdev_nr_sectors(part))
1117 goto out_blkdev_put;
1119 disk->open_partitions++;
1120 set_init_blocksize(part);
1126 blkdev_put_whole(bdev_whole(part), mode);
1130 static void blkdev_put_part(struct block_device *part, fmode_t mode)
1132 struct block_device *whole = bdev_whole(part);
1134 if (--part->bd_openers)
1136 blkdev_flush_mapping(part);
1137 whole->bd_disk->open_partitions--;
1138 blkdev_put_whole(whole, mode);
1141 struct block_device *blkdev_get_no_open(dev_t dev)
1143 struct block_device *bdev;
1144 struct inode *inode;
1146 inode = ilookup(blockdev_superblock, dev);
1148 blk_request_module(dev);
1149 inode = ilookup(blockdev_superblock, dev);
1154 /* switch from the inode reference to a device mode one: */
1155 bdev = &BDEV_I(inode)->bdev;
1156 if (!kobject_get_unless_zero(&bdev->bd_device.kobj))
1162 if ((bdev->bd_disk->flags & GENHD_FL_HIDDEN) ||
1163 !try_module_get(bdev->bd_disk->fops->owner)) {
1164 put_device(&bdev->bd_device);
1171 void blkdev_put_no_open(struct block_device *bdev)
1173 module_put(bdev->bd_disk->fops->owner);
1174 put_device(&bdev->bd_device);
1178 * blkdev_get_by_dev - open a block device by device number
1179 * @dev: device number of block device to open
1180 * @mode: FMODE_* mask
1181 * @holder: exclusive holder identifier
1183 * Open the block device described by device number @dev. If @mode includes
1184 * %FMODE_EXCL, the block device is opened with exclusive access. Specifying
1185 * %FMODE_EXCL with a %NULL @holder is invalid. Exclusive opens may nest for
1188 * Use this interface ONLY if you really do not have anything better - i.e. when
1189 * you are behind a truly sucky interface and all you are given is a device
1190 * number. Everything else should use blkdev_get_by_path().
1196 * Reference to the block_device on success, ERR_PTR(-errno) on failure.
1198 struct block_device *blkdev_get_by_dev(dev_t dev, fmode_t mode, void *holder)
1200 bool unblock_events = true;
1201 struct block_device *bdev;
1202 struct gendisk *disk;
1205 ret = devcgroup_check_permission(DEVCG_DEV_BLOCK,
1206 MAJOR(dev), MINOR(dev),
1207 ((mode & FMODE_READ) ? DEVCG_ACC_READ : 0) |
1208 ((mode & FMODE_WRITE) ? DEVCG_ACC_WRITE : 0));
1210 return ERR_PTR(ret);
1212 bdev = blkdev_get_no_open(dev);
1214 return ERR_PTR(-ENXIO);
1215 disk = bdev->bd_disk;
1217 if (mode & FMODE_EXCL) {
1218 ret = bd_prepare_to_claim(bdev, holder);
1223 disk_block_events(disk);
1225 mutex_lock(&disk->open_mutex);
1227 if (!disk_live(disk))
1228 goto abort_claiming;
1229 if (bdev_is_partition(bdev))
1230 ret = blkdev_get_part(bdev, mode);
1232 ret = blkdev_get_whole(bdev, mode);
1234 goto abort_claiming;
1235 if (mode & FMODE_EXCL) {
1236 bd_finish_claiming(bdev, holder);
1239 * Block event polling for write claims if requested. Any write
1240 * holder makes the write_holder state stick until all are
1241 * released. This is good enough and tracking individual
1242 * writeable reference is too fragile given the way @mode is
1243 * used in blkdev_get/put().
1245 if ((mode & FMODE_WRITE) && !bdev->bd_write_holder &&
1246 (disk->flags & GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE)) {
1247 bdev->bd_write_holder = true;
1248 unblock_events = false;
1251 mutex_unlock(&disk->open_mutex);
1254 disk_unblock_events(disk);
1258 if (mode & FMODE_EXCL)
1259 bd_abort_claiming(bdev, holder);
1260 mutex_unlock(&disk->open_mutex);
1261 disk_unblock_events(disk);
1263 blkdev_put_no_open(bdev);
1264 return ERR_PTR(ret);
1266 EXPORT_SYMBOL(blkdev_get_by_dev);
1269 * blkdev_get_by_path - open a block device by name
1270 * @path: path to the block device to open
1271 * @mode: FMODE_* mask
1272 * @holder: exclusive holder identifier
1274 * Open the block device described by the device file at @path. If @mode
1275 * includes %FMODE_EXCL, the block device is opened with exclusive access.
1276 * Specifying %FMODE_EXCL with a %NULL @holder is invalid. Exclusive opens may
1277 * nest for the same @holder.
1283 * Reference to the block_device on success, ERR_PTR(-errno) on failure.
1285 struct block_device *blkdev_get_by_path(const char *path, fmode_t mode,
1288 struct block_device *bdev;
1292 error = lookup_bdev(path, &dev);
1294 return ERR_PTR(error);
1296 bdev = blkdev_get_by_dev(dev, mode, holder);
1297 if (!IS_ERR(bdev) && (mode & FMODE_WRITE) && bdev_read_only(bdev)) {
1298 blkdev_put(bdev, mode);
1299 return ERR_PTR(-EACCES);
1304 EXPORT_SYMBOL(blkdev_get_by_path);
1306 static int blkdev_open(struct inode * inode, struct file * filp)
1308 struct block_device *bdev;
1311 * Preserve backwards compatibility and allow large file access
1312 * even if userspace doesn't ask for it explicitly. Some mkfs
1313 * binary needs it. We might want to drop this workaround
1314 * during an unstable branch.
1316 filp->f_flags |= O_LARGEFILE;
1318 filp->f_mode |= FMODE_NOWAIT | FMODE_BUF_RASYNC;
1320 if (filp->f_flags & O_NDELAY)
1321 filp->f_mode |= FMODE_NDELAY;
1322 if (filp->f_flags & O_EXCL)
1323 filp->f_mode |= FMODE_EXCL;
1324 if ((filp->f_flags & O_ACCMODE) == 3)
1325 filp->f_mode |= FMODE_WRITE_IOCTL;
1327 bdev = blkdev_get_by_dev(inode->i_rdev, filp->f_mode, filp);
1329 return PTR_ERR(bdev);
1330 filp->f_mapping = bdev->bd_inode->i_mapping;
1331 filp->f_wb_err = filemap_sample_wb_err(filp->f_mapping);
1335 void blkdev_put(struct block_device *bdev, fmode_t mode)
1337 struct gendisk *disk = bdev->bd_disk;
1340 * Sync early if it looks like we're the last one. If someone else
1341 * opens the block device between now and the decrement of bd_openers
1342 * then we did a sync that we didn't need to, but that's not the end
1343 * of the world and we want to avoid long (could be several minute)
1344 * syncs while holding the mutex.
1346 if (bdev->bd_openers == 1)
1347 sync_blockdev(bdev);
1349 mutex_lock(&disk->open_mutex);
1350 if (mode & FMODE_EXCL) {
1351 struct block_device *whole = bdev_whole(bdev);
1355 * Release a claim on the device. The holder fields
1356 * are protected with bdev_lock. open_mutex is to
1357 * synchronize disk_holder unlinking.
1359 spin_lock(&bdev_lock);
1361 WARN_ON_ONCE(--bdev->bd_holders < 0);
1362 WARN_ON_ONCE(--whole->bd_holders < 0);
1364 if ((bdev_free = !bdev->bd_holders))
1365 bdev->bd_holder = NULL;
1366 if (!whole->bd_holders)
1367 whole->bd_holder = NULL;
1369 spin_unlock(&bdev_lock);
1372 * If this was the last claim, remove holder link and
1373 * unblock evpoll if it was a write holder.
1375 if (bdev_free && bdev->bd_write_holder) {
1376 disk_unblock_events(disk);
1377 bdev->bd_write_holder = false;
1382 * Trigger event checking and tell drivers to flush MEDIA_CHANGE
1383 * event. This is to ensure detection of media removal commanded
1384 * from userland - e.g. eject(1).
1386 disk_flush_events(disk, DISK_EVENT_MEDIA_CHANGE);
1388 if (bdev_is_partition(bdev))
1389 blkdev_put_part(bdev, mode);
1391 blkdev_put_whole(bdev, mode);
1392 mutex_unlock(&disk->open_mutex);
1394 blkdev_put_no_open(bdev);
1396 EXPORT_SYMBOL(blkdev_put);
1398 static int blkdev_close(struct inode * inode, struct file * filp)
1400 struct block_device *bdev = I_BDEV(bdev_file_inode(filp));
1401 blkdev_put(bdev, filp->f_mode);
1405 static long block_ioctl(struct file *file, unsigned cmd, unsigned long arg)
1407 struct block_device *bdev = I_BDEV(bdev_file_inode(file));
1408 fmode_t mode = file->f_mode;
1411 * O_NDELAY can be altered using fcntl(.., F_SETFL, ..), so we have
1412 * to updated it before every ioctl.
1414 if (file->f_flags & O_NDELAY)
1415 mode |= FMODE_NDELAY;
1417 mode &= ~FMODE_NDELAY;
1419 return blkdev_ioctl(bdev, mode, cmd, arg);
1423 * Write data to the block device. Only intended for the block device itself
1424 * and the raw driver which basically is a fake block device.
1426 * Does not take i_mutex for the write and thus is not for general purpose
1429 static ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)
1431 struct file *file = iocb->ki_filp;
1432 struct inode *bd_inode = bdev_file_inode(file);
1433 loff_t size = i_size_read(bd_inode);
1434 struct blk_plug plug;
1438 if (bdev_read_only(I_BDEV(bd_inode)))
1441 if (IS_SWAPFILE(bd_inode) && !is_hibernate_resume_dev(bd_inode->i_rdev))
1444 if (!iov_iter_count(from))
1447 if (iocb->ki_pos >= size)
1450 if ((iocb->ki_flags & (IOCB_NOWAIT | IOCB_DIRECT)) == IOCB_NOWAIT)
1453 size -= iocb->ki_pos;
1454 if (iov_iter_count(from) > size) {
1455 shorted = iov_iter_count(from) - size;
1456 iov_iter_truncate(from, size);
1459 blk_start_plug(&plug);
1460 ret = __generic_file_write_iter(iocb, from);
1462 ret = generic_write_sync(iocb, ret);
1463 iov_iter_reexpand(from, iov_iter_count(from) + shorted);
1464 blk_finish_plug(&plug);
1468 static ssize_t blkdev_read_iter(struct kiocb *iocb, struct iov_iter *to)
1470 struct file *file = iocb->ki_filp;
1471 struct inode *bd_inode = bdev_file_inode(file);
1472 loff_t size = i_size_read(bd_inode);
1473 loff_t pos = iocb->ki_pos;
1481 if (iov_iter_count(to) > size) {
1482 shorted = iov_iter_count(to) - size;
1483 iov_iter_truncate(to, size);
1486 ret = generic_file_read_iter(iocb, to);
1487 iov_iter_reexpand(to, iov_iter_count(to) + shorted);
1491 static int blkdev_writepages(struct address_space *mapping,
1492 struct writeback_control *wbc)
1494 return generic_writepages(mapping, wbc);
1497 static const struct address_space_operations def_blk_aops = {
1498 .set_page_dirty = __set_page_dirty_buffers,
1499 .readpage = blkdev_readpage,
1500 .readahead = blkdev_readahead,
1501 .writepage = blkdev_writepage,
1502 .write_begin = blkdev_write_begin,
1503 .write_end = blkdev_write_end,
1504 .writepages = blkdev_writepages,
1505 .direct_IO = blkdev_direct_IO,
1506 .migratepage = buffer_migrate_page_norefs,
1507 .is_dirty_writeback = buffer_check_dirty_writeback,
1510 #define BLKDEV_FALLOC_FL_SUPPORTED \
1511 (FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE | \
1512 FALLOC_FL_ZERO_RANGE | FALLOC_FL_NO_HIDE_STALE)
1514 static long blkdev_fallocate(struct file *file, int mode, loff_t start,
1517 struct block_device *bdev = I_BDEV(bdev_file_inode(file));
1518 loff_t end = start + len - 1;
1522 /* Fail if we don't recognize the flags. */
1523 if (mode & ~BLKDEV_FALLOC_FL_SUPPORTED)
1526 /* Don't go off the end of the device. */
1527 isize = i_size_read(bdev->bd_inode);
1531 if (mode & FALLOC_FL_KEEP_SIZE) {
1532 len = isize - start;
1533 end = start + len - 1;
1539 * Don't allow IO that isn't aligned to logical block size.
1541 if ((start | len) & (bdev_logical_block_size(bdev) - 1))
1544 /* Invalidate the page cache, including dirty pages. */
1545 error = truncate_bdev_range(bdev, file->f_mode, start, end);
1550 case FALLOC_FL_ZERO_RANGE:
1551 case FALLOC_FL_ZERO_RANGE | FALLOC_FL_KEEP_SIZE:
1552 error = blkdev_issue_zeroout(bdev, start >> 9, len >> 9,
1553 GFP_KERNEL, BLKDEV_ZERO_NOUNMAP);
1555 case FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE:
1556 error = blkdev_issue_zeroout(bdev, start >> 9, len >> 9,
1557 GFP_KERNEL, BLKDEV_ZERO_NOFALLBACK);
1559 case FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE | FALLOC_FL_NO_HIDE_STALE:
1560 error = blkdev_issue_discard(bdev, start >> 9, len >> 9,
1570 * Invalidate the page cache again; if someone wandered in and dirtied
1571 * a page, we just discard it - userspace has no way of knowing whether
1572 * the write happened before or after discard completing...
1574 return truncate_bdev_range(bdev, file->f_mode, start, end);
1577 const struct file_operations def_blk_fops = {
1578 .open = blkdev_open,
1579 .release = blkdev_close,
1580 .llseek = block_llseek,
1581 .read_iter = blkdev_read_iter,
1582 .write_iter = blkdev_write_iter,
1583 .iopoll = blkdev_iopoll,
1584 .mmap = generic_file_mmap,
1585 .fsync = blkdev_fsync,
1586 .unlocked_ioctl = block_ioctl,
1587 #ifdef CONFIG_COMPAT
1588 .compat_ioctl = compat_blkdev_ioctl,
1590 .splice_read = generic_file_splice_read,
1591 .splice_write = iter_file_splice_write,
1592 .fallocate = blkdev_fallocate,
1596 * lookup_bdev - lookup a struct block_device by name
1597 * @pathname: special file representing the block device
1598 * @dev: return value of the block device's dev_t
1600 * Get a reference to the blockdevice at @pathname in the current
1601 * namespace if possible and return it. Return ERR_PTR(error)
1604 int lookup_bdev(const char *pathname, dev_t *dev)
1606 struct inode *inode;
1610 if (!pathname || !*pathname)
1613 error = kern_path(pathname, LOOKUP_FOLLOW, &path);
1617 inode = d_backing_inode(path.dentry);
1619 if (!S_ISBLK(inode->i_mode))
1622 if (!may_open_dev(&path))
1625 *dev = inode->i_rdev;
1631 EXPORT_SYMBOL(lookup_bdev);
1633 int __invalidate_device(struct block_device *bdev, bool kill_dirty)
1635 struct super_block *sb = get_super(bdev);
1640 * no need to lock the super, get_super holds the
1641 * read mutex so the filesystem cannot go away
1642 * under us (->put_super runs with the write lock
1645 shrink_dcache_sb(sb);
1646 res = invalidate_inodes(sb, kill_dirty);
1649 invalidate_bdev(bdev);
1652 EXPORT_SYMBOL(__invalidate_device);
1654 void iterate_bdevs(void (*func)(struct block_device *, void *), void *arg)
1656 struct inode *inode, *old_inode = NULL;
1658 spin_lock(&blockdev_superblock->s_inode_list_lock);
1659 list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list) {
1660 struct address_space *mapping = inode->i_mapping;
1661 struct block_device *bdev;
1663 spin_lock(&inode->i_lock);
1664 if (inode->i_state & (I_FREEING|I_WILL_FREE|I_NEW) ||
1665 mapping->nrpages == 0) {
1666 spin_unlock(&inode->i_lock);
1670 spin_unlock(&inode->i_lock);
1671 spin_unlock(&blockdev_superblock->s_inode_list_lock);
1673 * We hold a reference to 'inode' so it couldn't have been
1674 * removed from s_inodes list while we dropped the
1675 * s_inode_list_lock We cannot iput the inode now as we can
1676 * be holding the last reference and we cannot iput it under
1677 * s_inode_list_lock. So we keep the reference and iput it
1682 bdev = I_BDEV(inode);
1684 mutex_lock(&bdev->bd_disk->open_mutex);
1685 if (bdev->bd_openers)
1687 mutex_unlock(&bdev->bd_disk->open_mutex);
1689 spin_lock(&blockdev_superblock->s_inode_list_lock);
1691 spin_unlock(&blockdev_superblock->s_inode_list_lock);