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_kiocb(iocb, 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,
518 offsetof(struct blkdev_dio, bio),
519 BIOSET_NEED_BVECS|BIOSET_PERCPU_CACHE);
521 module_init(blkdev_init);
523 int __sync_blockdev(struct block_device *bdev, int wait)
528 return filemap_flush(bdev->bd_inode->i_mapping);
529 return filemap_write_and_wait(bdev->bd_inode->i_mapping);
533 * Write out and wait upon all the dirty data associated with a block
534 * device via its mapping. Does not take the superblock lock.
536 int sync_blockdev(struct block_device *bdev)
538 return __sync_blockdev(bdev, 1);
540 EXPORT_SYMBOL(sync_blockdev);
543 * Write out and wait upon all dirty data associated with this
544 * device. Filesystem data as well as the underlying block
545 * device. Takes the superblock lock.
547 int fsync_bdev(struct block_device *bdev)
549 struct super_block *sb = get_super(bdev);
551 int res = sync_filesystem(sb);
555 return sync_blockdev(bdev);
557 EXPORT_SYMBOL(fsync_bdev);
560 * freeze_bdev -- lock a filesystem and force it into a consistent state
561 * @bdev: blockdevice to lock
563 * If a superblock is found on this device, we take the s_umount semaphore
564 * on it to make sure nobody unmounts until the snapshot creation is done.
565 * The reference counter (bd_fsfreeze_count) guarantees that only the last
566 * unfreeze process can unfreeze the frozen filesystem actually when multiple
567 * freeze requests arrive simultaneously. It counts up in freeze_bdev() and
568 * count down in thaw_bdev(). When it becomes 0, thaw_bdev() will unfreeze
571 int freeze_bdev(struct block_device *bdev)
573 struct super_block *sb;
576 mutex_lock(&bdev->bd_fsfreeze_mutex);
577 if (++bdev->bd_fsfreeze_count > 1)
580 sb = get_active_super(bdev);
583 if (sb->s_op->freeze_super)
584 error = sb->s_op->freeze_super(sb);
586 error = freeze_super(sb);
587 deactivate_super(sb);
590 bdev->bd_fsfreeze_count--;
593 bdev->bd_fsfreeze_sb = sb;
598 mutex_unlock(&bdev->bd_fsfreeze_mutex);
601 EXPORT_SYMBOL(freeze_bdev);
604 * thaw_bdev -- unlock filesystem
605 * @bdev: blockdevice to unlock
607 * Unlocks the filesystem and marks it writeable again after freeze_bdev().
609 int thaw_bdev(struct block_device *bdev)
611 struct super_block *sb;
614 mutex_lock(&bdev->bd_fsfreeze_mutex);
615 if (!bdev->bd_fsfreeze_count)
619 if (--bdev->bd_fsfreeze_count > 0)
622 sb = bdev->bd_fsfreeze_sb;
626 if (sb->s_op->thaw_super)
627 error = sb->s_op->thaw_super(sb);
629 error = thaw_super(sb);
631 bdev->bd_fsfreeze_count++;
633 bdev->bd_fsfreeze_sb = NULL;
635 mutex_unlock(&bdev->bd_fsfreeze_mutex);
638 EXPORT_SYMBOL(thaw_bdev);
640 static int blkdev_writepage(struct page *page, struct writeback_control *wbc)
642 return block_write_full_page(page, blkdev_get_block, wbc);
645 static int blkdev_readpage(struct file * file, struct page * page)
647 return block_read_full_page(page, blkdev_get_block);
650 static void blkdev_readahead(struct readahead_control *rac)
652 mpage_readahead(rac, blkdev_get_block);
655 static int blkdev_write_begin(struct file *file, struct address_space *mapping,
656 loff_t pos, unsigned len, unsigned flags,
657 struct page **pagep, void **fsdata)
659 return block_write_begin(mapping, pos, len, flags, pagep,
663 static int blkdev_write_end(struct file *file, struct address_space *mapping,
664 loff_t pos, unsigned len, unsigned copied,
665 struct page *page, void *fsdata)
668 ret = block_write_end(file, mapping, pos, len, copied, page, fsdata);
678 * for a block special file file_inode(file)->i_size is zero
679 * so we compute the size by hand (just as in block_read/write above)
681 static loff_t block_llseek(struct file *file, loff_t offset, int whence)
683 struct inode *bd_inode = bdev_file_inode(file);
686 inode_lock(bd_inode);
687 retval = fixed_size_llseek(file, offset, whence, i_size_read(bd_inode));
688 inode_unlock(bd_inode);
692 static int blkdev_fsync(struct file *filp, loff_t start, loff_t end,
695 struct inode *bd_inode = bdev_file_inode(filp);
696 struct block_device *bdev = I_BDEV(bd_inode);
699 error = file_write_and_wait_range(filp, start, end);
704 * There is no need to serialise calls to blkdev_issue_flush with
705 * i_mutex and doing so causes performance issues with concurrent
706 * O_SYNC writers to a block device.
708 error = blkdev_issue_flush(bdev);
709 if (error == -EOPNOTSUPP)
716 * bdev_read_page() - Start reading a page from a block device
717 * @bdev: The device to read the page from
718 * @sector: The offset on the device to read the page to (need not be aligned)
719 * @page: The page to read
721 * On entry, the page should be locked. It will be unlocked when the page
722 * has been read. If the block driver implements rw_page synchronously,
723 * that will be true on exit from this function, but it need not be.
725 * Errors returned by this function are usually "soft", eg out of memory, or
726 * queue full; callers should try a different route to read this page rather
727 * than propagate an error back up the stack.
729 * Return: negative errno if an error occurs, 0 if submission was successful.
731 int bdev_read_page(struct block_device *bdev, sector_t sector,
734 const struct block_device_operations *ops = bdev->bd_disk->fops;
735 int result = -EOPNOTSUPP;
737 if (!ops->rw_page || bdev_get_integrity(bdev))
740 result = blk_queue_enter(bdev->bd_disk->queue, 0);
743 result = ops->rw_page(bdev, sector + get_start_sect(bdev), page,
745 blk_queue_exit(bdev->bd_disk->queue);
750 * bdev_write_page() - Start writing a page to a block device
751 * @bdev: The device to write the page to
752 * @sector: The offset on the device to write the page to (need not be aligned)
753 * @page: The page to write
754 * @wbc: The writeback_control for the write
756 * On entry, the page should be locked and not currently under writeback.
757 * On exit, if the write started successfully, the page will be unlocked and
758 * under writeback. If the write failed already (eg the driver failed to
759 * queue the page to the device), the page will still be locked. If the
760 * caller is a ->writepage implementation, it will need to unlock the page.
762 * Errors returned by this function are usually "soft", eg out of memory, or
763 * queue full; callers should try a different route to write this page rather
764 * than propagate an error back up the stack.
766 * Return: negative errno if an error occurs, 0 if submission was successful.
768 int bdev_write_page(struct block_device *bdev, sector_t sector,
769 struct page *page, struct writeback_control *wbc)
772 const struct block_device_operations *ops = bdev->bd_disk->fops;
774 if (!ops->rw_page || bdev_get_integrity(bdev))
776 result = blk_queue_enter(bdev->bd_disk->queue, 0);
780 set_page_writeback(page);
781 result = ops->rw_page(bdev, sector + get_start_sect(bdev), page,
784 end_page_writeback(page);
786 clean_page_buffers(page);
789 blk_queue_exit(bdev->bd_disk->queue);
797 static __cacheline_aligned_in_smp DEFINE_SPINLOCK(bdev_lock);
798 static struct kmem_cache * bdev_cachep __read_mostly;
800 static struct inode *bdev_alloc_inode(struct super_block *sb)
802 struct bdev_inode *ei = kmem_cache_alloc(bdev_cachep, GFP_KERNEL);
806 memset(&ei->bdev, 0, sizeof(ei->bdev));
807 return &ei->vfs_inode;
810 static void bdev_free_inode(struct inode *inode)
812 struct block_device *bdev = I_BDEV(inode);
814 free_percpu(bdev->bd_stats);
815 kfree(bdev->bd_meta_info);
817 if (!bdev_is_partition(bdev)) {
818 if (bdev->bd_disk && bdev->bd_disk->bdi)
819 bdi_put(bdev->bd_disk->bdi);
820 kfree(bdev->bd_disk);
823 if (MAJOR(bdev->bd_dev) == BLOCK_EXT_MAJOR)
824 blk_free_ext_minor(MINOR(bdev->bd_dev));
826 kmem_cache_free(bdev_cachep, BDEV_I(inode));
829 static void init_once(void *data)
831 struct bdev_inode *ei = data;
833 inode_init_once(&ei->vfs_inode);
836 static void bdev_evict_inode(struct inode *inode)
838 truncate_inode_pages_final(&inode->i_data);
839 invalidate_inode_buffers(inode); /* is it needed here? */
843 static const struct super_operations bdev_sops = {
844 .statfs = simple_statfs,
845 .alloc_inode = bdev_alloc_inode,
846 .free_inode = bdev_free_inode,
847 .drop_inode = generic_delete_inode,
848 .evict_inode = bdev_evict_inode,
851 static int bd_init_fs_context(struct fs_context *fc)
853 struct pseudo_fs_context *ctx = init_pseudo(fc, BDEVFS_MAGIC);
856 fc->s_iflags |= SB_I_CGROUPWB;
857 ctx->ops = &bdev_sops;
861 static struct file_system_type bd_type = {
863 .init_fs_context = bd_init_fs_context,
864 .kill_sb = kill_anon_super,
867 struct super_block *blockdev_superblock __read_mostly;
868 EXPORT_SYMBOL_GPL(blockdev_superblock);
870 void __init bdev_cache_init(void)
873 static struct vfsmount *bd_mnt;
875 bdev_cachep = kmem_cache_create("bdev_cache", sizeof(struct bdev_inode),
876 0, (SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT|
877 SLAB_MEM_SPREAD|SLAB_ACCOUNT|SLAB_PANIC),
879 err = register_filesystem(&bd_type);
881 panic("Cannot register bdev pseudo-fs");
882 bd_mnt = kern_mount(&bd_type);
884 panic("Cannot create bdev pseudo-fs");
885 blockdev_superblock = bd_mnt->mnt_sb; /* For writeback */
888 struct block_device *bdev_alloc(struct gendisk *disk, u8 partno)
890 struct block_device *bdev;
893 inode = new_inode(blockdev_superblock);
896 inode->i_mode = S_IFBLK;
898 inode->i_data.a_ops = &def_blk_aops;
899 mapping_set_gfp_mask(&inode->i_data, GFP_USER);
901 bdev = I_BDEV(inode);
902 mutex_init(&bdev->bd_fsfreeze_mutex);
903 spin_lock_init(&bdev->bd_size_lock);
904 bdev->bd_disk = disk;
905 bdev->bd_partno = partno;
906 bdev->bd_inode = inode;
907 bdev->bd_stats = alloc_percpu(struct disk_stats);
908 if (!bdev->bd_stats) {
915 void bdev_add(struct block_device *bdev, dev_t dev)
918 bdev->bd_inode->i_rdev = dev;
919 bdev->bd_inode->i_ino = dev;
920 insert_inode_hash(bdev->bd_inode);
923 long nr_blockdev_pages(void)
928 spin_lock(&blockdev_superblock->s_inode_list_lock);
929 list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list)
930 ret += inode->i_mapping->nrpages;
931 spin_unlock(&blockdev_superblock->s_inode_list_lock);
937 * bd_may_claim - test whether a block device can be claimed
938 * @bdev: block device of interest
939 * @whole: whole block device containing @bdev, may equal @bdev
940 * @holder: holder trying to claim @bdev
942 * Test whether @bdev can be claimed by @holder.
945 * spin_lock(&bdev_lock).
948 * %true if @bdev can be claimed, %false otherwise.
950 static bool bd_may_claim(struct block_device *bdev, struct block_device *whole,
953 if (bdev->bd_holder == holder)
954 return true; /* already a holder */
955 else if (bdev->bd_holder != NULL)
956 return false; /* held by someone else */
957 else if (whole == bdev)
958 return true; /* is a whole device which isn't held */
960 else if (whole->bd_holder == bd_may_claim)
961 return true; /* is a partition of a device that is being partitioned */
962 else if (whole->bd_holder != NULL)
963 return false; /* is a partition of a held device */
965 return true; /* is a partition of an un-held device */
969 * bd_prepare_to_claim - claim a block device
970 * @bdev: block device of interest
971 * @holder: holder trying to claim @bdev
973 * Claim @bdev. This function fails if @bdev is already claimed by another
974 * holder and waits if another claiming is in progress. return, the caller
975 * has ownership of bd_claiming and bd_holder[s].
978 * 0 if @bdev can be claimed, -EBUSY otherwise.
980 int bd_prepare_to_claim(struct block_device *bdev, void *holder)
982 struct block_device *whole = bdev_whole(bdev);
984 if (WARN_ON_ONCE(!holder))
987 spin_lock(&bdev_lock);
988 /* if someone else claimed, fail */
989 if (!bd_may_claim(bdev, whole, holder)) {
990 spin_unlock(&bdev_lock);
994 /* if claiming is already in progress, wait for it to finish */
995 if (whole->bd_claiming) {
996 wait_queue_head_t *wq = bit_waitqueue(&whole->bd_claiming, 0);
999 prepare_to_wait(wq, &wait, TASK_UNINTERRUPTIBLE);
1000 spin_unlock(&bdev_lock);
1002 finish_wait(wq, &wait);
1007 whole->bd_claiming = holder;
1008 spin_unlock(&bdev_lock);
1011 EXPORT_SYMBOL_GPL(bd_prepare_to_claim); /* only for the loop driver */
1013 static void bd_clear_claiming(struct block_device *whole, void *holder)
1015 lockdep_assert_held(&bdev_lock);
1016 /* tell others that we're done */
1017 BUG_ON(whole->bd_claiming != holder);
1018 whole->bd_claiming = NULL;
1019 wake_up_bit(&whole->bd_claiming, 0);
1023 * bd_finish_claiming - finish claiming of a block device
1024 * @bdev: block device of interest
1025 * @holder: holder that has claimed @bdev
1027 * Finish exclusive open of a block device. Mark the device as exlusively
1028 * open by the holder and wake up all waiters for exclusive open to finish.
1030 static void bd_finish_claiming(struct block_device *bdev, void *holder)
1032 struct block_device *whole = bdev_whole(bdev);
1034 spin_lock(&bdev_lock);
1035 BUG_ON(!bd_may_claim(bdev, whole, holder));
1037 * Note that for a whole device bd_holders will be incremented twice,
1038 * and bd_holder will be set to bd_may_claim before being set to holder
1040 whole->bd_holders++;
1041 whole->bd_holder = bd_may_claim;
1043 bdev->bd_holder = holder;
1044 bd_clear_claiming(whole, holder);
1045 spin_unlock(&bdev_lock);
1049 * bd_abort_claiming - abort claiming of a block device
1050 * @bdev: block device of interest
1051 * @holder: holder that has claimed @bdev
1053 * Abort claiming of a block device when the exclusive open failed. This can be
1054 * also used when exclusive open is not actually desired and we just needed
1055 * to block other exclusive openers for a while.
1057 void bd_abort_claiming(struct block_device *bdev, void *holder)
1059 spin_lock(&bdev_lock);
1060 bd_clear_claiming(bdev_whole(bdev), holder);
1061 spin_unlock(&bdev_lock);
1063 EXPORT_SYMBOL(bd_abort_claiming);
1065 static void blkdev_flush_mapping(struct block_device *bdev)
1067 WARN_ON_ONCE(bdev->bd_holders);
1068 sync_blockdev(bdev);
1070 bdev_write_inode(bdev);
1073 static int blkdev_get_whole(struct block_device *bdev, fmode_t mode)
1075 struct gendisk *disk = bdev->bd_disk;
1078 if (disk->fops->open) {
1079 ret = disk->fops->open(bdev, mode);
1081 /* avoid ghost partitions on a removed medium */
1082 if (ret == -ENOMEDIUM &&
1083 test_bit(GD_NEED_PART_SCAN, &disk->state))
1084 bdev_disk_changed(disk, true);
1089 if (!bdev->bd_openers)
1090 set_init_blocksize(bdev);
1091 if (test_bit(GD_NEED_PART_SCAN, &disk->state))
1092 bdev_disk_changed(disk, false);
1097 static void blkdev_put_whole(struct block_device *bdev, fmode_t mode)
1099 if (!--bdev->bd_openers)
1100 blkdev_flush_mapping(bdev);
1101 if (bdev->bd_disk->fops->release)
1102 bdev->bd_disk->fops->release(bdev->bd_disk, mode);
1105 static int blkdev_get_part(struct block_device *part, fmode_t mode)
1107 struct gendisk *disk = part->bd_disk;
1110 if (part->bd_openers)
1113 ret = blkdev_get_whole(bdev_whole(part), mode);
1118 if (!bdev_nr_sectors(part))
1119 goto out_blkdev_put;
1121 disk->open_partitions++;
1122 set_init_blocksize(part);
1128 blkdev_put_whole(bdev_whole(part), mode);
1132 static void blkdev_put_part(struct block_device *part, fmode_t mode)
1134 struct block_device *whole = bdev_whole(part);
1136 if (--part->bd_openers)
1138 blkdev_flush_mapping(part);
1139 whole->bd_disk->open_partitions--;
1140 blkdev_put_whole(whole, mode);
1143 struct block_device *blkdev_get_no_open(dev_t dev)
1145 struct block_device *bdev;
1146 struct inode *inode;
1148 inode = ilookup(blockdev_superblock, dev);
1150 blk_request_module(dev);
1151 inode = ilookup(blockdev_superblock, dev);
1156 /* switch from the inode reference to a device mode one: */
1157 bdev = &BDEV_I(inode)->bdev;
1158 if (!kobject_get_unless_zero(&bdev->bd_device.kobj))
1164 if ((bdev->bd_disk->flags & GENHD_FL_HIDDEN) ||
1165 !try_module_get(bdev->bd_disk->fops->owner)) {
1166 put_device(&bdev->bd_device);
1173 void blkdev_put_no_open(struct block_device *bdev)
1175 module_put(bdev->bd_disk->fops->owner);
1176 put_device(&bdev->bd_device);
1180 * blkdev_get_by_dev - open a block device by device number
1181 * @dev: device number of block device to open
1182 * @mode: FMODE_* mask
1183 * @holder: exclusive holder identifier
1185 * Open the block device described by device number @dev. If @mode includes
1186 * %FMODE_EXCL, the block device is opened with exclusive access. Specifying
1187 * %FMODE_EXCL with a %NULL @holder is invalid. Exclusive opens may nest for
1190 * Use this interface ONLY if you really do not have anything better - i.e. when
1191 * you are behind a truly sucky interface and all you are given is a device
1192 * number. Everything else should use blkdev_get_by_path().
1198 * Reference to the block_device on success, ERR_PTR(-errno) on failure.
1200 struct block_device *blkdev_get_by_dev(dev_t dev, fmode_t mode, void *holder)
1202 bool unblock_events = true;
1203 struct block_device *bdev;
1204 struct gendisk *disk;
1207 ret = devcgroup_check_permission(DEVCG_DEV_BLOCK,
1208 MAJOR(dev), MINOR(dev),
1209 ((mode & FMODE_READ) ? DEVCG_ACC_READ : 0) |
1210 ((mode & FMODE_WRITE) ? DEVCG_ACC_WRITE : 0));
1212 return ERR_PTR(ret);
1214 bdev = blkdev_get_no_open(dev);
1216 return ERR_PTR(-ENXIO);
1217 disk = bdev->bd_disk;
1219 if (mode & FMODE_EXCL) {
1220 ret = bd_prepare_to_claim(bdev, holder);
1225 disk_block_events(disk);
1227 mutex_lock(&disk->open_mutex);
1229 if (!disk_live(disk))
1230 goto abort_claiming;
1231 if (bdev_is_partition(bdev))
1232 ret = blkdev_get_part(bdev, mode);
1234 ret = blkdev_get_whole(bdev, mode);
1236 goto abort_claiming;
1237 if (mode & FMODE_EXCL) {
1238 bd_finish_claiming(bdev, holder);
1241 * Block event polling for write claims if requested. Any write
1242 * holder makes the write_holder state stick until all are
1243 * released. This is good enough and tracking individual
1244 * writeable reference is too fragile given the way @mode is
1245 * used in blkdev_get/put().
1247 if ((mode & FMODE_WRITE) && !bdev->bd_write_holder &&
1248 (disk->flags & GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE)) {
1249 bdev->bd_write_holder = true;
1250 unblock_events = false;
1253 mutex_unlock(&disk->open_mutex);
1256 disk_unblock_events(disk);
1260 if (mode & FMODE_EXCL)
1261 bd_abort_claiming(bdev, holder);
1262 mutex_unlock(&disk->open_mutex);
1263 disk_unblock_events(disk);
1265 blkdev_put_no_open(bdev);
1266 return ERR_PTR(ret);
1268 EXPORT_SYMBOL(blkdev_get_by_dev);
1271 * blkdev_get_by_path - open a block device by name
1272 * @path: path to the block device to open
1273 * @mode: FMODE_* mask
1274 * @holder: exclusive holder identifier
1276 * Open the block device described by the device file at @path. If @mode
1277 * includes %FMODE_EXCL, the block device is opened with exclusive access.
1278 * Specifying %FMODE_EXCL with a %NULL @holder is invalid. Exclusive opens may
1279 * nest for the same @holder.
1285 * Reference to the block_device on success, ERR_PTR(-errno) on failure.
1287 struct block_device *blkdev_get_by_path(const char *path, fmode_t mode,
1290 struct block_device *bdev;
1294 error = lookup_bdev(path, &dev);
1296 return ERR_PTR(error);
1298 bdev = blkdev_get_by_dev(dev, mode, holder);
1299 if (!IS_ERR(bdev) && (mode & FMODE_WRITE) && bdev_read_only(bdev)) {
1300 blkdev_put(bdev, mode);
1301 return ERR_PTR(-EACCES);
1306 EXPORT_SYMBOL(blkdev_get_by_path);
1308 static int blkdev_open(struct inode * inode, struct file * filp)
1310 struct block_device *bdev;
1313 * Preserve backwards compatibility and allow large file access
1314 * even if userspace doesn't ask for it explicitly. Some mkfs
1315 * binary needs it. We might want to drop this workaround
1316 * during an unstable branch.
1318 filp->f_flags |= O_LARGEFILE;
1320 filp->f_mode |= FMODE_NOWAIT | FMODE_BUF_RASYNC;
1322 if (filp->f_flags & O_NDELAY)
1323 filp->f_mode |= FMODE_NDELAY;
1324 if (filp->f_flags & O_EXCL)
1325 filp->f_mode |= FMODE_EXCL;
1326 if ((filp->f_flags & O_ACCMODE) == 3)
1327 filp->f_mode |= FMODE_WRITE_IOCTL;
1329 bdev = blkdev_get_by_dev(inode->i_rdev, filp->f_mode, filp);
1331 return PTR_ERR(bdev);
1332 filp->f_mapping = bdev->bd_inode->i_mapping;
1333 filp->f_wb_err = filemap_sample_wb_err(filp->f_mapping);
1337 void blkdev_put(struct block_device *bdev, fmode_t mode)
1339 struct gendisk *disk = bdev->bd_disk;
1342 * Sync early if it looks like we're the last one. If someone else
1343 * opens the block device between now and the decrement of bd_openers
1344 * then we did a sync that we didn't need to, but that's not the end
1345 * of the world and we want to avoid long (could be several minute)
1346 * syncs while holding the mutex.
1348 if (bdev->bd_openers == 1)
1349 sync_blockdev(bdev);
1351 mutex_lock(&disk->open_mutex);
1352 if (mode & FMODE_EXCL) {
1353 struct block_device *whole = bdev_whole(bdev);
1357 * Release a claim on the device. The holder fields
1358 * are protected with bdev_lock. open_mutex is to
1359 * synchronize disk_holder unlinking.
1361 spin_lock(&bdev_lock);
1363 WARN_ON_ONCE(--bdev->bd_holders < 0);
1364 WARN_ON_ONCE(--whole->bd_holders < 0);
1366 if ((bdev_free = !bdev->bd_holders))
1367 bdev->bd_holder = NULL;
1368 if (!whole->bd_holders)
1369 whole->bd_holder = NULL;
1371 spin_unlock(&bdev_lock);
1374 * If this was the last claim, remove holder link and
1375 * unblock evpoll if it was a write holder.
1377 if (bdev_free && bdev->bd_write_holder) {
1378 disk_unblock_events(disk);
1379 bdev->bd_write_holder = false;
1384 * Trigger event checking and tell drivers to flush MEDIA_CHANGE
1385 * event. This is to ensure detection of media removal commanded
1386 * from userland - e.g. eject(1).
1388 disk_flush_events(disk, DISK_EVENT_MEDIA_CHANGE);
1390 if (bdev_is_partition(bdev))
1391 blkdev_put_part(bdev, mode);
1393 blkdev_put_whole(bdev, mode);
1394 mutex_unlock(&disk->open_mutex);
1396 blkdev_put_no_open(bdev);
1398 EXPORT_SYMBOL(blkdev_put);
1400 static int blkdev_close(struct inode * inode, struct file * filp)
1402 struct block_device *bdev = I_BDEV(bdev_file_inode(filp));
1403 blkdev_put(bdev, filp->f_mode);
1407 static long block_ioctl(struct file *file, unsigned cmd, unsigned long arg)
1409 struct block_device *bdev = I_BDEV(bdev_file_inode(file));
1410 fmode_t mode = file->f_mode;
1413 * O_NDELAY can be altered using fcntl(.., F_SETFL, ..), so we have
1414 * to updated it before every ioctl.
1416 if (file->f_flags & O_NDELAY)
1417 mode |= FMODE_NDELAY;
1419 mode &= ~FMODE_NDELAY;
1421 return blkdev_ioctl(bdev, mode, cmd, arg);
1425 * Write data to the block device. Only intended for the block device itself
1426 * and the raw driver which basically is a fake block device.
1428 * Does not take i_mutex for the write and thus is not for general purpose
1431 static ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)
1433 struct file *file = iocb->ki_filp;
1434 struct inode *bd_inode = bdev_file_inode(file);
1435 loff_t size = i_size_read(bd_inode);
1436 struct blk_plug plug;
1440 if (bdev_read_only(I_BDEV(bd_inode)))
1443 if (IS_SWAPFILE(bd_inode) && !is_hibernate_resume_dev(bd_inode->i_rdev))
1446 if (!iov_iter_count(from))
1449 if (iocb->ki_pos >= size)
1452 if ((iocb->ki_flags & (IOCB_NOWAIT | IOCB_DIRECT)) == IOCB_NOWAIT)
1455 size -= iocb->ki_pos;
1456 if (iov_iter_count(from) > size) {
1457 shorted = iov_iter_count(from) - size;
1458 iov_iter_truncate(from, size);
1461 blk_start_plug(&plug);
1462 ret = __generic_file_write_iter(iocb, from);
1464 ret = generic_write_sync(iocb, ret);
1465 iov_iter_reexpand(from, iov_iter_count(from) + shorted);
1466 blk_finish_plug(&plug);
1470 static ssize_t blkdev_read_iter(struct kiocb *iocb, struct iov_iter *to)
1472 struct file *file = iocb->ki_filp;
1473 struct inode *bd_inode = bdev_file_inode(file);
1474 loff_t size = i_size_read(bd_inode);
1475 loff_t pos = iocb->ki_pos;
1483 if (iov_iter_count(to) > size) {
1484 shorted = iov_iter_count(to) - size;
1485 iov_iter_truncate(to, size);
1488 ret = generic_file_read_iter(iocb, to);
1489 iov_iter_reexpand(to, iov_iter_count(to) + shorted);
1493 static int blkdev_writepages(struct address_space *mapping,
1494 struct writeback_control *wbc)
1496 return generic_writepages(mapping, wbc);
1499 static const struct address_space_operations def_blk_aops = {
1500 .set_page_dirty = __set_page_dirty_buffers,
1501 .readpage = blkdev_readpage,
1502 .readahead = blkdev_readahead,
1503 .writepage = blkdev_writepage,
1504 .write_begin = blkdev_write_begin,
1505 .write_end = blkdev_write_end,
1506 .writepages = blkdev_writepages,
1507 .direct_IO = blkdev_direct_IO,
1508 .migratepage = buffer_migrate_page_norefs,
1509 .is_dirty_writeback = buffer_check_dirty_writeback,
1512 #define BLKDEV_FALLOC_FL_SUPPORTED \
1513 (FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE | \
1514 FALLOC_FL_ZERO_RANGE | FALLOC_FL_NO_HIDE_STALE)
1516 static long blkdev_fallocate(struct file *file, int mode, loff_t start,
1519 struct block_device *bdev = I_BDEV(bdev_file_inode(file));
1520 loff_t end = start + len - 1;
1524 /* Fail if we don't recognize the flags. */
1525 if (mode & ~BLKDEV_FALLOC_FL_SUPPORTED)
1528 /* Don't go off the end of the device. */
1529 isize = i_size_read(bdev->bd_inode);
1533 if (mode & FALLOC_FL_KEEP_SIZE) {
1534 len = isize - start;
1535 end = start + len - 1;
1541 * Don't allow IO that isn't aligned to logical block size.
1543 if ((start | len) & (bdev_logical_block_size(bdev) - 1))
1546 /* Invalidate the page cache, including dirty pages. */
1547 error = truncate_bdev_range(bdev, file->f_mode, start, end);
1552 case FALLOC_FL_ZERO_RANGE:
1553 case FALLOC_FL_ZERO_RANGE | FALLOC_FL_KEEP_SIZE:
1554 error = blkdev_issue_zeroout(bdev, start >> 9, len >> 9,
1555 GFP_KERNEL, BLKDEV_ZERO_NOUNMAP);
1557 case FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE:
1558 error = blkdev_issue_zeroout(bdev, start >> 9, len >> 9,
1559 GFP_KERNEL, BLKDEV_ZERO_NOFALLBACK);
1561 case FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE | FALLOC_FL_NO_HIDE_STALE:
1562 error = blkdev_issue_discard(bdev, start >> 9, len >> 9,
1572 * Invalidate the page cache again; if someone wandered in and dirtied
1573 * a page, we just discard it - userspace has no way of knowing whether
1574 * the write happened before or after discard completing...
1576 return truncate_bdev_range(bdev, file->f_mode, start, end);
1579 const struct file_operations def_blk_fops = {
1580 .open = blkdev_open,
1581 .release = blkdev_close,
1582 .llseek = block_llseek,
1583 .read_iter = blkdev_read_iter,
1584 .write_iter = blkdev_write_iter,
1585 .iopoll = blkdev_iopoll,
1586 .mmap = generic_file_mmap,
1587 .fsync = blkdev_fsync,
1588 .unlocked_ioctl = block_ioctl,
1589 #ifdef CONFIG_COMPAT
1590 .compat_ioctl = compat_blkdev_ioctl,
1592 .splice_read = generic_file_splice_read,
1593 .splice_write = iter_file_splice_write,
1594 .fallocate = blkdev_fallocate,
1598 * lookup_bdev - lookup a struct block_device by name
1599 * @pathname: special file representing the block device
1600 * @dev: return value of the block device's dev_t
1602 * Get a reference to the blockdevice at @pathname in the current
1603 * namespace if possible and return it. Return ERR_PTR(error)
1606 int lookup_bdev(const char *pathname, dev_t *dev)
1608 struct inode *inode;
1612 if (!pathname || !*pathname)
1615 error = kern_path(pathname, LOOKUP_FOLLOW, &path);
1619 inode = d_backing_inode(path.dentry);
1621 if (!S_ISBLK(inode->i_mode))
1624 if (!may_open_dev(&path))
1627 *dev = inode->i_rdev;
1633 EXPORT_SYMBOL(lookup_bdev);
1635 int __invalidate_device(struct block_device *bdev, bool kill_dirty)
1637 struct super_block *sb = get_super(bdev);
1642 * no need to lock the super, get_super holds the
1643 * read mutex so the filesystem cannot go away
1644 * under us (->put_super runs with the write lock
1647 shrink_dcache_sb(sb);
1648 res = invalidate_inodes(sb, kill_dirty);
1651 invalidate_bdev(bdev);
1654 EXPORT_SYMBOL(__invalidate_device);
1656 void iterate_bdevs(void (*func)(struct block_device *, void *), void *arg)
1658 struct inode *inode, *old_inode = NULL;
1660 spin_lock(&blockdev_superblock->s_inode_list_lock);
1661 list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list) {
1662 struct address_space *mapping = inode->i_mapping;
1663 struct block_device *bdev;
1665 spin_lock(&inode->i_lock);
1666 if (inode->i_state & (I_FREEING|I_WILL_FREE|I_NEW) ||
1667 mapping->nrpages == 0) {
1668 spin_unlock(&inode->i_lock);
1672 spin_unlock(&inode->i_lock);
1673 spin_unlock(&blockdev_superblock->s_inode_list_lock);
1675 * We hold a reference to 'inode' so it couldn't have been
1676 * removed from s_inodes list while we dropped the
1677 * s_inode_list_lock We cannot iput the inode now as we can
1678 * be holding the last reference and we cannot iput it under
1679 * s_inode_list_lock. So we keep the reference and iput it
1684 bdev = I_BDEV(inode);
1686 mutex_lock(&bdev->bd_disk->open_mutex);
1687 if (bdev->bd_openers)
1689 mutex_unlock(&bdev->bd_disk->open_mutex);
1691 spin_lock(&blockdev_superblock->s_inode_list_lock);
1693 spin_unlock(&blockdev_superblock->s_inode_list_lock);