1 // SPDX-License-Identifier: GPL-2.0-only
5 * Copyright (C) 1991, 1992 Linus Torvalds
6 * Copyright (C) 2001 Andrea Arcangeli <andrea@suse.de> SuSE
9 #include <linux/init.h>
11 #include <linux/fcntl.h>
12 #include <linux/slab.h>
13 #include <linux/kmod.h>
14 #include <linux/major.h>
15 #include <linux/device_cgroup.h>
16 #include <linux/highmem.h>
17 #include <linux/blkdev.h>
18 #include <linux/backing-dev.h>
19 #include <linux/module.h>
20 #include <linux/blkpg.h>
21 #include <linux/magic.h>
22 #include <linux/buffer_head.h>
23 #include <linux/swap.h>
24 #include <linux/pagevec.h>
25 #include <linux/writeback.h>
26 #include <linux/mpage.h>
27 #include <linux/mount.h>
28 #include <linux/pseudo_fs.h>
29 #include <linux/uio.h>
30 #include <linux/namei.h>
31 #include <linux/log2.h>
32 #include <linux/cleancache.h>
33 #include <linux/task_io_accounting_ops.h>
34 #include <linux/falloc.h>
35 #include <linux/uaccess.h>
36 #include <linux/suspend.h>
40 struct block_device bdev;
41 struct inode vfs_inode;
44 static const struct address_space_operations def_blk_aops;
46 static inline struct bdev_inode *BDEV_I(struct inode *inode)
48 return container_of(inode, struct bdev_inode, vfs_inode);
51 struct block_device *I_BDEV(struct inode *inode)
53 return &BDEV_I(inode)->bdev;
55 EXPORT_SYMBOL(I_BDEV);
57 static void bdev_write_inode(struct block_device *bdev)
59 struct inode *inode = bdev->bd_inode;
62 spin_lock(&inode->i_lock);
63 while (inode->i_state & I_DIRTY) {
64 spin_unlock(&inode->i_lock);
65 ret = write_inode_now(inode, true);
67 char name[BDEVNAME_SIZE];
68 pr_warn_ratelimited("VFS: Dirty inode writeback failed "
69 "for block device %s (err=%d).\n",
70 bdevname(bdev, name), ret);
72 spin_lock(&inode->i_lock);
74 spin_unlock(&inode->i_lock);
77 /* Kill _all_ buffers and pagecache , dirty or not.. */
78 void kill_bdev(struct block_device *bdev)
80 struct address_space *mapping = bdev->bd_inode->i_mapping;
82 if (mapping->nrpages == 0 && mapping->nrexceptional == 0)
86 truncate_inode_pages(mapping, 0);
88 EXPORT_SYMBOL(kill_bdev);
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)
114 struct block_device *claimed_bdev = NULL;
118 * If we don't hold exclusive handle for the device, upgrade to it
119 * while we discard the buffer cache to avoid discarding buffers
120 * under live filesystem.
122 if (!(mode & FMODE_EXCL)) {
123 claimed_bdev = bdev->bd_contains;
124 err = bd_prepare_to_claim(bdev, claimed_bdev,
125 truncate_bdev_range);
129 truncate_inode_pages_range(bdev->bd_inode->i_mapping, lstart, lend);
131 bd_abort_claiming(bdev, claimed_bdev, truncate_bdev_range);
136 * Someone else has handle exclusively open. Try invalidating instead.
137 * The 'end' argument is inclusive so the rounding is safe.
139 return invalidate_inode_pages2_range(bdev->bd_inode->i_mapping,
140 lstart >> PAGE_SHIFT,
143 EXPORT_SYMBOL(truncate_bdev_range);
145 static void set_init_blocksize(struct block_device *bdev)
147 unsigned int bsize = bdev_logical_block_size(bdev);
148 loff_t size = i_size_read(bdev->bd_inode);
150 while (bsize < PAGE_SIZE) {
155 bdev->bd_inode->i_blkbits = blksize_bits(bsize);
158 int set_blocksize(struct block_device *bdev, int size)
160 /* Size must be a power of two, and between 512 and PAGE_SIZE */
161 if (size > PAGE_SIZE || size < 512 || !is_power_of_2(size))
164 /* Size cannot be smaller than the size supported by the device */
165 if (size < bdev_logical_block_size(bdev))
168 /* Don't change the size if it is same as current */
169 if (bdev->bd_inode->i_blkbits != blksize_bits(size)) {
171 bdev->bd_inode->i_blkbits = blksize_bits(size);
177 EXPORT_SYMBOL(set_blocksize);
179 int sb_set_blocksize(struct super_block *sb, int size)
181 if (set_blocksize(sb->s_bdev, size))
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;
190 EXPORT_SYMBOL(sb_set_blocksize);
192 int sb_min_blocksize(struct super_block *sb, int size)
194 int minsize = bdev_logical_block_size(sb->s_bdev);
197 return sb_set_blocksize(sb, size);
200 EXPORT_SYMBOL(sb_min_blocksize);
203 blkdev_get_block(struct inode *inode, sector_t iblock,
204 struct buffer_head *bh, int create)
206 bh->b_bdev = I_BDEV(inode);
207 bh->b_blocknr = iblock;
208 set_buffer_mapped(bh);
212 static struct inode *bdev_file_inode(struct file *file)
214 return file->f_mapping->host;
217 static unsigned int dio_bio_write_op(struct kiocb *iocb)
219 unsigned int op = REQ_OP_WRITE | REQ_SYNC | REQ_IDLE;
221 /* avoid the need for a I/O completion work item */
222 if (iocb->ki_flags & IOCB_DSYNC)
227 #define DIO_INLINE_BIO_VECS 4
229 static void blkdev_bio_end_io_simple(struct bio *bio)
231 struct task_struct *waiter = bio->bi_private;
233 WRITE_ONCE(bio->bi_private, NULL);
234 blk_wake_io_task(waiter);
238 __blkdev_direct_IO_simple(struct kiocb *iocb, struct iov_iter *iter,
241 struct file *file = iocb->ki_filp;
242 struct block_device *bdev = I_BDEV(bdev_file_inode(file));
243 struct bio_vec inline_vecs[DIO_INLINE_BIO_VECS], *vecs;
244 loff_t pos = iocb->ki_pos;
245 bool should_dirty = false;
250 if ((pos | iov_iter_alignment(iter)) &
251 (bdev_logical_block_size(bdev) - 1))
254 if (nr_pages <= DIO_INLINE_BIO_VECS)
257 vecs = kmalloc_array(nr_pages, sizeof(struct bio_vec),
263 bio_init(&bio, vecs, nr_pages);
264 bio_set_dev(&bio, bdev);
265 bio.bi_iter.bi_sector = pos >> 9;
266 bio.bi_write_hint = iocb->ki_hint;
267 bio.bi_private = current;
268 bio.bi_end_io = blkdev_bio_end_io_simple;
269 bio.bi_ioprio = iocb->ki_ioprio;
271 ret = bio_iov_iter_get_pages(&bio, iter);
274 ret = bio.bi_iter.bi_size;
276 if (iov_iter_rw(iter) == READ) {
277 bio.bi_opf = REQ_OP_READ;
278 if (iter_is_iovec(iter))
281 bio.bi_opf = dio_bio_write_op(iocb);
282 task_io_account_write(ret);
284 if (iocb->ki_flags & IOCB_HIPRI)
285 bio_set_polled(&bio, iocb);
287 qc = submit_bio(&bio);
289 set_current_state(TASK_UNINTERRUPTIBLE);
290 if (!READ_ONCE(bio.bi_private))
292 if (!(iocb->ki_flags & IOCB_HIPRI) ||
293 !blk_poll(bdev_get_queue(bdev), qc, true))
296 __set_current_state(TASK_RUNNING);
298 bio_release_pages(&bio, should_dirty);
299 if (unlikely(bio.bi_status))
300 ret = blk_status_to_errno(bio.bi_status);
303 if (vecs != inline_vecs)
314 struct task_struct *waiter;
319 bool should_dirty : 1;
324 static struct bio_set blkdev_dio_pool;
326 static int blkdev_iopoll(struct kiocb *kiocb, bool wait)
328 struct block_device *bdev = I_BDEV(kiocb->ki_filp->f_mapping->host);
329 struct request_queue *q = bdev_get_queue(bdev);
331 return blk_poll(q, READ_ONCE(kiocb->ki_cookie), wait);
334 static void blkdev_bio_end_io(struct bio *bio)
336 struct blkdev_dio *dio = bio->bi_private;
337 bool should_dirty = dio->should_dirty;
339 if (bio->bi_status && !dio->bio.bi_status)
340 dio->bio.bi_status = bio->bi_status;
342 if (!dio->multi_bio || atomic_dec_and_test(&dio->ref)) {
344 struct kiocb *iocb = dio->iocb;
347 if (likely(!dio->bio.bi_status)) {
351 ret = blk_status_to_errno(dio->bio.bi_status);
354 dio->iocb->ki_complete(iocb, ret, 0);
358 struct task_struct *waiter = dio->waiter;
360 WRITE_ONCE(dio->waiter, NULL);
361 blk_wake_io_task(waiter);
366 bio_check_pages_dirty(bio);
368 bio_release_pages(bio, false);
374 __blkdev_direct_IO(struct kiocb *iocb, struct iov_iter *iter, int nr_pages)
376 struct file *file = iocb->ki_filp;
377 struct inode *inode = bdev_file_inode(file);
378 struct block_device *bdev = I_BDEV(inode);
379 struct blk_plug plug;
380 struct blkdev_dio *dio;
382 bool is_poll = (iocb->ki_flags & IOCB_HIPRI) != 0;
383 bool is_read = (iov_iter_rw(iter) == READ), is_sync;
384 loff_t pos = iocb->ki_pos;
385 blk_qc_t qc = BLK_QC_T_NONE;
388 if ((pos | iov_iter_alignment(iter)) &
389 (bdev_logical_block_size(bdev) - 1))
392 bio = bio_alloc_bioset(GFP_KERNEL, nr_pages, &blkdev_dio_pool);
394 dio = container_of(bio, struct blkdev_dio, bio);
395 dio->is_sync = is_sync = is_sync_kiocb(iocb);
397 dio->waiter = current;
404 dio->multi_bio = false;
405 dio->should_dirty = is_read && iter_is_iovec(iter);
408 * Don't plug for HIPRI/polled IO, as those should go straight
412 blk_start_plug(&plug);
415 bio_set_dev(bio, bdev);
416 bio->bi_iter.bi_sector = pos >> 9;
417 bio->bi_write_hint = iocb->ki_hint;
418 bio->bi_private = dio;
419 bio->bi_end_io = blkdev_bio_end_io;
420 bio->bi_ioprio = iocb->ki_ioprio;
422 ret = bio_iov_iter_get_pages(bio, iter);
424 bio->bi_status = BLK_STS_IOERR;
430 bio->bi_opf = REQ_OP_READ;
431 if (dio->should_dirty)
432 bio_set_pages_dirty(bio);
434 bio->bi_opf = dio_bio_write_op(iocb);
435 task_io_account_write(bio->bi_iter.bi_size);
438 dio->size += bio->bi_iter.bi_size;
439 pos += bio->bi_iter.bi_size;
441 nr_pages = iov_iter_npages(iter, BIO_MAX_PAGES);
445 if (iocb->ki_flags & IOCB_HIPRI) {
446 bio_set_polled(bio, iocb);
450 qc = submit_bio(bio);
453 WRITE_ONCE(iocb->ki_cookie, qc);
457 if (!dio->multi_bio) {
459 * AIO needs an extra reference to ensure the dio
460 * structure which is embedded into the first bio
465 dio->multi_bio = true;
466 atomic_set(&dio->ref, 2);
468 atomic_inc(&dio->ref);
472 bio = bio_alloc(GFP_KERNEL, nr_pages);
476 blk_finish_plug(&plug);
482 set_current_state(TASK_UNINTERRUPTIBLE);
483 if (!READ_ONCE(dio->waiter))
486 if (!(iocb->ki_flags & IOCB_HIPRI) ||
487 !blk_poll(bdev_get_queue(bdev), qc, true))
490 __set_current_state(TASK_RUNNING);
493 ret = blk_status_to_errno(dio->bio.bi_status);
502 blkdev_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
506 nr_pages = iov_iter_npages(iter, BIO_MAX_PAGES + 1);
509 if (is_sync_kiocb(iocb) && nr_pages <= BIO_MAX_PAGES)
510 return __blkdev_direct_IO_simple(iocb, iter, nr_pages);
512 return __blkdev_direct_IO(iocb, iter, min(nr_pages, BIO_MAX_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 struct super_block *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) {
577 * We don't even need to grab a reference - the first call
578 * to freeze_bdev grab an active reference and only the last
579 * thaw_bdev drops it.
581 sb = get_super(bdev);
584 mutex_unlock(&bdev->bd_fsfreeze_mutex);
588 sb = get_active_super(bdev);
591 if (sb->s_op->freeze_super)
592 error = sb->s_op->freeze_super(sb);
594 error = freeze_super(sb);
596 deactivate_super(sb);
597 bdev->bd_fsfreeze_count--;
598 mutex_unlock(&bdev->bd_fsfreeze_mutex);
599 return ERR_PTR(error);
601 deactivate_super(sb);
604 mutex_unlock(&bdev->bd_fsfreeze_mutex);
605 return sb; /* thaw_bdev releases s->s_umount */
607 EXPORT_SYMBOL(freeze_bdev);
610 * thaw_bdev -- unlock filesystem
611 * @bdev: blockdevice to unlock
612 * @sb: associated superblock
614 * Unlocks the filesystem and marks it writeable again after freeze_bdev().
616 int thaw_bdev(struct block_device *bdev, struct super_block *sb)
620 mutex_lock(&bdev->bd_fsfreeze_mutex);
621 if (!bdev->bd_fsfreeze_count)
625 if (--bdev->bd_fsfreeze_count > 0)
631 if (sb->s_op->thaw_super)
632 error = sb->s_op->thaw_super(sb);
634 error = thaw_super(sb);
636 bdev->bd_fsfreeze_count++;
638 mutex_unlock(&bdev->bd_fsfreeze_mutex);
641 EXPORT_SYMBOL(thaw_bdev);
643 static int blkdev_writepage(struct page *page, struct writeback_control *wbc)
645 return block_write_full_page(page, blkdev_get_block, wbc);
648 static int blkdev_readpage(struct file * file, struct page * page)
650 return block_read_full_page(page, blkdev_get_block);
653 static void blkdev_readahead(struct readahead_control *rac)
655 mpage_readahead(rac, blkdev_get_block);
658 static int blkdev_write_begin(struct file *file, struct address_space *mapping,
659 loff_t pos, unsigned len, unsigned flags,
660 struct page **pagep, void **fsdata)
662 return block_write_begin(mapping, pos, len, flags, pagep,
666 static int blkdev_write_end(struct file *file, struct address_space *mapping,
667 loff_t pos, unsigned len, unsigned copied,
668 struct page *page, void *fsdata)
671 ret = block_write_end(file, mapping, pos, len, copied, page, fsdata);
681 * for a block special file file_inode(file)->i_size is zero
682 * so we compute the size by hand (just as in block_read/write above)
684 static loff_t block_llseek(struct file *file, loff_t offset, int whence)
686 struct inode *bd_inode = bdev_file_inode(file);
689 inode_lock(bd_inode);
690 retval = fixed_size_llseek(file, offset, whence, i_size_read(bd_inode));
691 inode_unlock(bd_inode);
695 int blkdev_fsync(struct file *filp, loff_t start, loff_t end, int datasync)
697 struct inode *bd_inode = bdev_file_inode(filp);
698 struct block_device *bdev = I_BDEV(bd_inode);
701 error = file_write_and_wait_range(filp, start, end);
706 * There is no need to serialise calls to blkdev_issue_flush with
707 * i_mutex and doing so causes performance issues with concurrent
708 * O_SYNC writers to a block device.
710 error = blkdev_issue_flush(bdev, GFP_KERNEL);
711 if (error == -EOPNOTSUPP)
716 EXPORT_SYMBOL(blkdev_fsync);
719 * bdev_read_page() - Start reading a page from a block device
720 * @bdev: The device to read the page from
721 * @sector: The offset on the device to read the page to (need not be aligned)
722 * @page: The page to read
724 * On entry, the page should be locked. It will be unlocked when the page
725 * has been read. If the block driver implements rw_page synchronously,
726 * that will be true on exit from this function, but it need not be.
728 * Errors returned by this function are usually "soft", eg out of memory, or
729 * queue full; callers should try a different route to read this page rather
730 * than propagate an error back up the stack.
732 * Return: negative errno if an error occurs, 0 if submission was successful.
734 int bdev_read_page(struct block_device *bdev, sector_t sector,
737 const struct block_device_operations *ops = bdev->bd_disk->fops;
738 int result = -EOPNOTSUPP;
740 if (!ops->rw_page || bdev_get_integrity(bdev))
743 result = blk_queue_enter(bdev->bd_disk->queue, 0);
746 result = ops->rw_page(bdev, sector + get_start_sect(bdev), page,
748 blk_queue_exit(bdev->bd_disk->queue);
753 * bdev_write_page() - Start writing a page to a block device
754 * @bdev: The device to write the page to
755 * @sector: The offset on the device to write the page to (need not be aligned)
756 * @page: The page to write
757 * @wbc: The writeback_control for the write
759 * On entry, the page should be locked and not currently under writeback.
760 * On exit, if the write started successfully, the page will be unlocked and
761 * under writeback. If the write failed already (eg the driver failed to
762 * queue the page to the device), the page will still be locked. If the
763 * caller is a ->writepage implementation, it will need to unlock the page.
765 * Errors returned by this function are usually "soft", eg out of memory, or
766 * queue full; callers should try a different route to write this page rather
767 * than propagate an error back up the stack.
769 * Return: negative errno if an error occurs, 0 if submission was successful.
771 int bdev_write_page(struct block_device *bdev, sector_t sector,
772 struct page *page, struct writeback_control *wbc)
775 const struct block_device_operations *ops = bdev->bd_disk->fops;
777 if (!ops->rw_page || bdev_get_integrity(bdev))
779 result = blk_queue_enter(bdev->bd_disk->queue, 0);
783 set_page_writeback(page);
784 result = ops->rw_page(bdev, sector + get_start_sect(bdev), page,
787 end_page_writeback(page);
789 clean_page_buffers(page);
792 blk_queue_exit(bdev->bd_disk->queue);
800 static __cacheline_aligned_in_smp DEFINE_SPINLOCK(bdev_lock);
801 static struct kmem_cache * bdev_cachep __read_mostly;
803 static struct inode *bdev_alloc_inode(struct super_block *sb)
805 struct bdev_inode *ei = kmem_cache_alloc(bdev_cachep, GFP_KERNEL);
808 return &ei->vfs_inode;
811 static void bdev_free_inode(struct inode *inode)
813 kmem_cache_free(bdev_cachep, BDEV_I(inode));
816 static void init_once(void *foo)
818 struct bdev_inode *ei = (struct bdev_inode *) foo;
819 struct block_device *bdev = &ei->bdev;
821 memset(bdev, 0, sizeof(*bdev));
822 mutex_init(&bdev->bd_mutex);
824 INIT_LIST_HEAD(&bdev->bd_holder_disks);
826 bdev->bd_bdi = &noop_backing_dev_info;
827 inode_init_once(&ei->vfs_inode);
828 /* Initialize mutex for freeze. */
829 mutex_init(&bdev->bd_fsfreeze_mutex);
832 static void bdev_evict_inode(struct inode *inode)
834 struct block_device *bdev = &BDEV_I(inode)->bdev;
835 truncate_inode_pages_final(&inode->i_data);
836 invalidate_inode_buffers(inode); /* is it needed here? */
838 /* Detach inode from wb early as bdi_put() may free bdi->wb */
839 inode_detach_wb(inode);
840 if (bdev->bd_bdi != &noop_backing_dev_info) {
841 bdi_put(bdev->bd_bdi);
842 bdev->bd_bdi = &noop_backing_dev_info;
846 static const struct super_operations bdev_sops = {
847 .statfs = simple_statfs,
848 .alloc_inode = bdev_alloc_inode,
849 .free_inode = bdev_free_inode,
850 .drop_inode = generic_delete_inode,
851 .evict_inode = bdev_evict_inode,
854 static int bd_init_fs_context(struct fs_context *fc)
856 struct pseudo_fs_context *ctx = init_pseudo(fc, BDEVFS_MAGIC);
859 fc->s_iflags |= SB_I_CGROUPWB;
860 ctx->ops = &bdev_sops;
864 static struct file_system_type bd_type = {
866 .init_fs_context = bd_init_fs_context,
867 .kill_sb = kill_anon_super,
870 struct super_block *blockdev_superblock __read_mostly;
871 EXPORT_SYMBOL_GPL(blockdev_superblock);
873 void __init bdev_cache_init(void)
876 static struct vfsmount *bd_mnt;
878 bdev_cachep = kmem_cache_create("bdev_cache", sizeof(struct bdev_inode),
879 0, (SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT|
880 SLAB_MEM_SPREAD|SLAB_ACCOUNT|SLAB_PANIC),
882 err = register_filesystem(&bd_type);
884 panic("Cannot register bdev pseudo-fs");
885 bd_mnt = kern_mount(&bd_type);
887 panic("Cannot create bdev pseudo-fs");
888 blockdev_superblock = bd_mnt->mnt_sb; /* For writeback */
892 * Most likely _very_ bad one - but then it's hardly critical for small
893 * /dev and can be fixed when somebody will need really large one.
894 * Keep in mind that it will be fed through icache hash function too.
896 static inline unsigned long hash(dev_t dev)
898 return MAJOR(dev)+MINOR(dev);
901 static int bdev_test(struct inode *inode, void *data)
903 return BDEV_I(inode)->bdev.bd_dev == *(dev_t *)data;
906 static int bdev_set(struct inode *inode, void *data)
908 BDEV_I(inode)->bdev.bd_dev = *(dev_t *)data;
912 static struct block_device *bdget(dev_t dev)
914 struct block_device *bdev;
917 inode = iget5_locked(blockdev_superblock, hash(dev),
918 bdev_test, bdev_set, &dev);
923 bdev = &BDEV_I(inode)->bdev;
925 if (inode->i_state & I_NEW) {
926 spin_lock_init(&bdev->bd_size_lock);
927 bdev->bd_contains = NULL;
928 bdev->bd_super = NULL;
929 bdev->bd_inode = inode;
930 bdev->bd_part_count = 0;
931 inode->i_mode = S_IFBLK;
933 inode->i_bdev = bdev;
934 inode->i_data.a_ops = &def_blk_aops;
935 mapping_set_gfp_mask(&inode->i_data, GFP_USER);
936 unlock_new_inode(inode);
942 * bdgrab -- Grab a reference to an already referenced block device
943 * @bdev: Block device to grab a reference to.
945 struct block_device *bdgrab(struct block_device *bdev)
947 ihold(bdev->bd_inode);
950 EXPORT_SYMBOL(bdgrab);
952 struct block_device *bdget_part(struct hd_struct *part)
954 return bdget(part_devt(part));
957 long nr_blockdev_pages(void)
962 spin_lock(&blockdev_superblock->s_inode_list_lock);
963 list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list)
964 ret += inode->i_mapping->nrpages;
965 spin_unlock(&blockdev_superblock->s_inode_list_lock);
970 void bdput(struct block_device *bdev)
972 iput(bdev->bd_inode);
975 EXPORT_SYMBOL(bdput);
977 static struct block_device *bd_acquire(struct inode *inode)
979 struct block_device *bdev;
981 spin_lock(&bdev_lock);
982 bdev = inode->i_bdev;
983 if (bdev && !inode_unhashed(bdev->bd_inode)) {
985 spin_unlock(&bdev_lock);
988 spin_unlock(&bdev_lock);
991 * i_bdev references block device inode that was already shut down
992 * (corresponding device got removed). Remove the reference and look
993 * up block device inode again just in case new device got
994 * reestablished under the same device number.
999 bdev = bdget(inode->i_rdev);
1001 spin_lock(&bdev_lock);
1002 if (!inode->i_bdev) {
1004 * We take an additional reference to bd_inode,
1005 * and it's released in clear_inode() of inode.
1006 * So, we can access it via ->i_mapping always
1010 inode->i_bdev = bdev;
1011 inode->i_mapping = bdev->bd_inode->i_mapping;
1013 spin_unlock(&bdev_lock);
1018 /* Call when you free inode */
1020 void bd_forget(struct inode *inode)
1022 struct block_device *bdev = NULL;
1024 spin_lock(&bdev_lock);
1025 if (!sb_is_blkdev_sb(inode->i_sb))
1026 bdev = inode->i_bdev;
1027 inode->i_bdev = NULL;
1028 inode->i_mapping = &inode->i_data;
1029 spin_unlock(&bdev_lock);
1036 * bd_may_claim - test whether a block device can be claimed
1037 * @bdev: block device of interest
1038 * @whole: whole block device containing @bdev, may equal @bdev
1039 * @holder: holder trying to claim @bdev
1041 * Test whether @bdev can be claimed by @holder.
1044 * spin_lock(&bdev_lock).
1047 * %true if @bdev can be claimed, %false otherwise.
1049 static bool bd_may_claim(struct block_device *bdev, struct block_device *whole,
1052 if (bdev->bd_holder == holder)
1053 return true; /* already a holder */
1054 else if (bdev->bd_holder != NULL)
1055 return false; /* held by someone else */
1056 else if (whole == bdev)
1057 return true; /* is a whole device which isn't held */
1059 else if (whole->bd_holder == bd_may_claim)
1060 return true; /* is a partition of a device that is being partitioned */
1061 else if (whole->bd_holder != NULL)
1062 return false; /* is a partition of a held device */
1064 return true; /* is a partition of an un-held device */
1068 * bd_prepare_to_claim - claim a block device
1069 * @bdev: block device of interest
1070 * @whole: the whole device containing @bdev, may equal @bdev
1071 * @holder: holder trying to claim @bdev
1073 * Claim @bdev. This function fails if @bdev is already claimed by another
1074 * holder and waits if another claiming is in progress. return, the caller
1075 * has ownership of bd_claiming and bd_holder[s].
1078 * 0 if @bdev can be claimed, -EBUSY otherwise.
1080 int bd_prepare_to_claim(struct block_device *bdev, struct block_device *whole,
1084 spin_lock(&bdev_lock);
1085 /* if someone else claimed, fail */
1086 if (!bd_may_claim(bdev, whole, holder)) {
1087 spin_unlock(&bdev_lock);
1091 /* if claiming is already in progress, wait for it to finish */
1092 if (whole->bd_claiming) {
1093 wait_queue_head_t *wq = bit_waitqueue(&whole->bd_claiming, 0);
1096 prepare_to_wait(wq, &wait, TASK_UNINTERRUPTIBLE);
1097 spin_unlock(&bdev_lock);
1099 finish_wait(wq, &wait);
1104 whole->bd_claiming = holder;
1105 spin_unlock(&bdev_lock);
1108 EXPORT_SYMBOL_GPL(bd_prepare_to_claim); /* only for the loop driver */
1110 static struct gendisk *bdev_get_gendisk(struct block_device *bdev, int *partno)
1112 struct gendisk *disk = get_gendisk(bdev->bd_dev, partno);
1117 * Now that we hold gendisk reference we make sure bdev we looked up is
1118 * not stale. If it is, it means device got removed and created before
1119 * we looked up gendisk and we fail open in such case. Associating
1120 * unhashed bdev with newly created gendisk could lead to two bdevs
1121 * (and thus two independent caches) being associated with one device
1124 if (inode_unhashed(bdev->bd_inode)) {
1125 put_disk_and_module(disk);
1131 static void bd_clear_claiming(struct block_device *whole, void *holder)
1133 lockdep_assert_held(&bdev_lock);
1134 /* tell others that we're done */
1135 BUG_ON(whole->bd_claiming != holder);
1136 whole->bd_claiming = NULL;
1137 wake_up_bit(&whole->bd_claiming, 0);
1141 * bd_finish_claiming - finish claiming of a block device
1142 * @bdev: block device of interest
1143 * @whole: whole block device
1144 * @holder: holder that has claimed @bdev
1146 * Finish exclusive open of a block device. Mark the device as exlusively
1147 * open by the holder and wake up all waiters for exclusive open to finish.
1149 static void bd_finish_claiming(struct block_device *bdev,
1150 struct block_device *whole, void *holder)
1152 spin_lock(&bdev_lock);
1153 BUG_ON(!bd_may_claim(bdev, whole, holder));
1155 * Note that for a whole device bd_holders will be incremented twice,
1156 * and bd_holder will be set to bd_may_claim before being set to holder
1158 whole->bd_holders++;
1159 whole->bd_holder = bd_may_claim;
1161 bdev->bd_holder = holder;
1162 bd_clear_claiming(whole, holder);
1163 spin_unlock(&bdev_lock);
1167 * bd_abort_claiming - abort claiming of a block device
1168 * @bdev: block device of interest
1169 * @whole: whole block device
1170 * @holder: holder that has claimed @bdev
1172 * Abort claiming of a block device when the exclusive open failed. This can be
1173 * also used when exclusive open is not actually desired and we just needed
1174 * to block other exclusive openers for a while.
1176 void bd_abort_claiming(struct block_device *bdev, struct block_device *whole,
1179 spin_lock(&bdev_lock);
1180 bd_clear_claiming(whole, holder);
1181 spin_unlock(&bdev_lock);
1183 EXPORT_SYMBOL(bd_abort_claiming);
1186 struct bd_holder_disk {
1187 struct list_head list;
1188 struct gendisk *disk;
1192 static struct bd_holder_disk *bd_find_holder_disk(struct block_device *bdev,
1193 struct gendisk *disk)
1195 struct bd_holder_disk *holder;
1197 list_for_each_entry(holder, &bdev->bd_holder_disks, list)
1198 if (holder->disk == disk)
1203 static int add_symlink(struct kobject *from, struct kobject *to)
1205 return sysfs_create_link(from, to, kobject_name(to));
1208 static void del_symlink(struct kobject *from, struct kobject *to)
1210 sysfs_remove_link(from, kobject_name(to));
1214 * bd_link_disk_holder - create symlinks between holding disk and slave bdev
1215 * @bdev: the claimed slave bdev
1216 * @disk: the holding disk
1218 * DON'T USE THIS UNLESS YOU'RE ALREADY USING IT.
1220 * This functions creates the following sysfs symlinks.
1222 * - from "slaves" directory of the holder @disk to the claimed @bdev
1223 * - from "holders" directory of the @bdev to the holder @disk
1225 * For example, if /dev/dm-0 maps to /dev/sda and disk for dm-0 is
1226 * passed to bd_link_disk_holder(), then:
1228 * /sys/block/dm-0/slaves/sda --> /sys/block/sda
1229 * /sys/block/sda/holders/dm-0 --> /sys/block/dm-0
1231 * The caller must have claimed @bdev before calling this function and
1232 * ensure that both @bdev and @disk are valid during the creation and
1233 * lifetime of these symlinks.
1239 * 0 on success, -errno on failure.
1241 int bd_link_disk_holder(struct block_device *bdev, struct gendisk *disk)
1243 struct bd_holder_disk *holder;
1246 mutex_lock(&bdev->bd_mutex);
1248 WARN_ON_ONCE(!bdev->bd_holder);
1250 /* FIXME: remove the following once add_disk() handles errors */
1251 if (WARN_ON(!disk->slave_dir || !bdev->bd_part->holder_dir))
1254 holder = bd_find_holder_disk(bdev, disk);
1260 holder = kzalloc(sizeof(*holder), GFP_KERNEL);
1266 INIT_LIST_HEAD(&holder->list);
1267 holder->disk = disk;
1270 ret = add_symlink(disk->slave_dir, &part_to_dev(bdev->bd_part)->kobj);
1274 ret = add_symlink(bdev->bd_part->holder_dir, &disk_to_dev(disk)->kobj);
1278 * bdev could be deleted beneath us which would implicitly destroy
1279 * the holder directory. Hold on to it.
1281 kobject_get(bdev->bd_part->holder_dir);
1283 list_add(&holder->list, &bdev->bd_holder_disks);
1287 del_symlink(disk->slave_dir, &part_to_dev(bdev->bd_part)->kobj);
1291 mutex_unlock(&bdev->bd_mutex);
1294 EXPORT_SYMBOL_GPL(bd_link_disk_holder);
1297 * bd_unlink_disk_holder - destroy symlinks created by bd_link_disk_holder()
1298 * @bdev: the calimed slave bdev
1299 * @disk: the holding disk
1301 * DON'T USE THIS UNLESS YOU'RE ALREADY USING IT.
1306 void bd_unlink_disk_holder(struct block_device *bdev, struct gendisk *disk)
1308 struct bd_holder_disk *holder;
1310 mutex_lock(&bdev->bd_mutex);
1312 holder = bd_find_holder_disk(bdev, disk);
1314 if (!WARN_ON_ONCE(holder == NULL) && !--holder->refcnt) {
1315 del_symlink(disk->slave_dir, &part_to_dev(bdev->bd_part)->kobj);
1316 del_symlink(bdev->bd_part->holder_dir,
1317 &disk_to_dev(disk)->kobj);
1318 kobject_put(bdev->bd_part->holder_dir);
1319 list_del_init(&holder->list);
1323 mutex_unlock(&bdev->bd_mutex);
1325 EXPORT_SYMBOL_GPL(bd_unlink_disk_holder);
1329 * check_disk_size_change - checks for disk size change and adjusts bdev size.
1330 * @disk: struct gendisk to check
1331 * @bdev: struct bdev to adjust.
1332 * @verbose: if %true log a message about a size change if there is any
1334 * This routine checks to see if the bdev size does not match the disk size
1335 * and adjusts it if it differs. When shrinking the bdev size, its all caches
1338 static void check_disk_size_change(struct gendisk *disk,
1339 struct block_device *bdev, bool verbose)
1341 loff_t disk_size, bdev_size;
1343 spin_lock(&bdev->bd_size_lock);
1344 disk_size = (loff_t)get_capacity(disk) << 9;
1345 bdev_size = i_size_read(bdev->bd_inode);
1346 if (disk_size != bdev_size) {
1349 "%s: detected capacity change from %lld to %lld\n",
1350 disk->disk_name, bdev_size, disk_size);
1352 i_size_write(bdev->bd_inode, disk_size);
1354 spin_unlock(&bdev->bd_size_lock);
1356 if (bdev_size > disk_size) {
1357 if (__invalidate_device(bdev, false))
1358 pr_warn("VFS: busy inodes on resized disk %s\n",
1364 * revalidate_disk_size - checks for disk size change and adjusts bdev size.
1365 * @disk: struct gendisk to check
1366 * @verbose: if %true log a message about a size change if there is any
1368 * This routine checks to see if the bdev size does not match the disk size
1369 * and adjusts it if it differs. When shrinking the bdev size, its all caches
1372 void revalidate_disk_size(struct gendisk *disk, bool verbose)
1374 struct block_device *bdev;
1377 * Hidden disks don't have associated bdev so there's no point in
1378 * revalidating them.
1380 if (disk->flags & GENHD_FL_HIDDEN)
1383 bdev = bdget_disk(disk, 0);
1385 check_disk_size_change(disk, bdev, verbose);
1389 EXPORT_SYMBOL(revalidate_disk_size);
1391 void bd_set_nr_sectors(struct block_device *bdev, sector_t sectors)
1393 spin_lock(&bdev->bd_size_lock);
1394 i_size_write(bdev->bd_inode, (loff_t)sectors << SECTOR_SHIFT);
1395 spin_unlock(&bdev->bd_size_lock);
1397 EXPORT_SYMBOL(bd_set_nr_sectors);
1399 static void __blkdev_put(struct block_device *bdev, fmode_t mode, int for_part);
1401 int bdev_disk_changed(struct block_device *bdev, bool invalidate)
1403 struct gendisk *disk = bdev->bd_disk;
1406 lockdep_assert_held(&bdev->bd_mutex);
1408 clear_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1411 ret = blk_drop_partitions(bdev);
1416 * Historically we only set the capacity to zero for devices that
1417 * support partitions (independ of actually having partitions created).
1418 * Doing that is rather inconsistent, but changing it broke legacy
1419 * udisks polling for legacy ide-cdrom devices. Use the crude check
1420 * below to get the sane behavior for most device while not breaking
1421 * userspace for this particular setup.
1424 if (disk_part_scan_enabled(disk) ||
1425 !(disk->flags & GENHD_FL_REMOVABLE))
1426 set_capacity(disk, 0);
1428 if (disk->fops->revalidate_disk)
1429 disk->fops->revalidate_disk(disk);
1432 check_disk_size_change(disk, bdev, !invalidate);
1434 if (get_capacity(disk)) {
1435 ret = blk_add_partitions(disk, bdev);
1438 } else if (invalidate) {
1440 * Tell userspace that the media / partition table may have
1443 kobject_uevent(&disk_to_dev(disk)->kobj, KOBJ_CHANGE);
1449 * Only exported for for loop and dasd for historic reasons. Don't use in new
1452 EXPORT_SYMBOL_GPL(bdev_disk_changed);
1457 * mutex_lock(part->bd_mutex)
1458 * mutex_lock_nested(whole->bd_mutex, 1)
1461 static int __blkdev_get(struct block_device *bdev, fmode_t mode, void *holder,
1464 struct block_device *whole = NULL, *claiming = NULL;
1465 struct gendisk *disk;
1468 bool first_open = false, unblock_events = true, need_restart;
1471 need_restart = false;
1473 disk = bdev_get_gendisk(bdev, &partno);
1478 whole = bdget_disk(disk, 0);
1485 if (!for_part && (mode & FMODE_EXCL)) {
1486 WARN_ON_ONCE(!holder);
1491 ret = bd_prepare_to_claim(bdev, claiming, holder);
1496 disk_block_events(disk);
1497 mutex_lock_nested(&bdev->bd_mutex, for_part);
1498 if (!bdev->bd_openers) {
1500 bdev->bd_disk = disk;
1501 bdev->bd_contains = bdev;
1502 bdev->bd_partno = partno;
1506 bdev->bd_part = disk_get_part(disk, partno);
1511 if (disk->fops->open) {
1512 ret = disk->fops->open(bdev, mode);
1514 * If we lost a race with 'disk' being deleted,
1515 * try again. See md.c
1517 if (ret == -ERESTARTSYS)
1518 need_restart = true;
1522 bd_set_nr_sectors(bdev, get_capacity(disk));
1523 set_init_blocksize(bdev);
1527 * If the device is invalidated, rescan partition
1528 * if open succeeded or failed with -ENOMEDIUM.
1529 * The latter is necessary to prevent ghost
1530 * partitions on a removed medium.
1532 if (test_bit(GD_NEED_PART_SCAN, &disk->state) &&
1533 (!ret || ret == -ENOMEDIUM))
1534 bdev_disk_changed(bdev, ret == -ENOMEDIUM);
1540 ret = __blkdev_get(whole, mode, NULL, 1);
1543 bdev->bd_contains = bdgrab(whole);
1544 bdev->bd_part = disk_get_part(disk, partno);
1545 if (!(disk->flags & GENHD_FL_UP) ||
1546 !bdev->bd_part || !bdev->bd_part->nr_sects) {
1550 bd_set_nr_sectors(bdev, bdev->bd_part->nr_sects);
1551 set_init_blocksize(bdev);
1554 if (bdev->bd_bdi == &noop_backing_dev_info)
1555 bdev->bd_bdi = bdi_get(disk->queue->backing_dev_info);
1557 if (bdev->bd_contains == bdev) {
1559 if (bdev->bd_disk->fops->open)
1560 ret = bdev->bd_disk->fops->open(bdev, mode);
1561 /* the same as first opener case, read comment there */
1562 if (test_bit(GD_NEED_PART_SCAN, &disk->state) &&
1563 (!ret || ret == -ENOMEDIUM))
1564 bdev_disk_changed(bdev, ret == -ENOMEDIUM);
1566 goto out_unlock_bdev;
1571 bdev->bd_part_count++;
1573 bd_finish_claiming(bdev, claiming, holder);
1576 * Block event polling for write claims if requested. Any write holder
1577 * makes the write_holder state stick until all are released. This is
1578 * good enough and tracking individual writeable reference is too
1579 * fragile given the way @mode is used in blkdev_get/put().
1581 if (claiming && (mode & FMODE_WRITE) && !bdev->bd_write_holder &&
1582 (disk->flags & GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE)) {
1583 bdev->bd_write_holder = true;
1584 unblock_events = false;
1586 mutex_unlock(&bdev->bd_mutex);
1589 disk_unblock_events(disk);
1591 /* only one opener holds refs to the module and disk */
1593 put_disk_and_module(disk);
1599 disk_put_part(bdev->bd_part);
1600 bdev->bd_disk = NULL;
1601 bdev->bd_part = NULL;
1602 if (bdev != bdev->bd_contains)
1603 __blkdev_put(bdev->bd_contains, mode, 1);
1604 bdev->bd_contains = NULL;
1607 bd_abort_claiming(bdev, claiming, holder);
1608 mutex_unlock(&bdev->bd_mutex);
1609 disk_unblock_events(disk);
1614 put_disk_and_module(disk);
1622 * blkdev_get - open a block device
1623 * @bdev: block_device to open
1624 * @mode: FMODE_* mask
1625 * @holder: exclusive holder identifier
1627 * Open @bdev with @mode. If @mode includes %FMODE_EXCL, @bdev is
1628 * open with exclusive access. Specifying %FMODE_EXCL with %NULL
1629 * @holder is invalid. Exclusive opens may nest for the same @holder.
1631 * On success, the reference count of @bdev is unchanged. On failure,
1638 * 0 on success, -errno on failure.
1640 static int blkdev_get(struct block_device *bdev, fmode_t mode, void *holder)
1644 if (mode & FMODE_READ)
1646 if (mode & FMODE_WRITE)
1648 ret = devcgroup_inode_permission(bdev->bd_inode, perm);
1652 ret =__blkdev_get(bdev, mode, holder, 0);
1663 * blkdev_get_by_path - open a block device by name
1664 * @path: path to the block device to open
1665 * @mode: FMODE_* mask
1666 * @holder: exclusive holder identifier
1668 * Open the blockdevice described by the device file at @path. @mode
1669 * and @holder are identical to blkdev_get().
1671 * On success, the returned block_device has reference count of one.
1677 * Pointer to block_device on success, ERR_PTR(-errno) on failure.
1679 struct block_device *blkdev_get_by_path(const char *path, fmode_t mode,
1682 struct block_device *bdev;
1685 bdev = lookup_bdev(path);
1689 err = blkdev_get(bdev, mode, holder);
1691 return ERR_PTR(err);
1693 if ((mode & FMODE_WRITE) && bdev_read_only(bdev)) {
1694 blkdev_put(bdev, mode);
1695 return ERR_PTR(-EACCES);
1700 EXPORT_SYMBOL(blkdev_get_by_path);
1703 * blkdev_get_by_dev - open a block device by device number
1704 * @dev: device number of block device to open
1705 * @mode: FMODE_* mask
1706 * @holder: exclusive holder identifier
1708 * Open the blockdevice described by device number @dev. @mode and
1709 * @holder are identical to blkdev_get().
1711 * Use it ONLY if you really do not have anything better - i.e. when
1712 * you are behind a truly sucky interface and all you are given is a
1713 * device number. _Never_ to be used for internal purposes. If you
1714 * ever need it - reconsider your API.
1716 * On success, the returned block_device has reference count of one.
1722 * Pointer to block_device on success, ERR_PTR(-errno) on failure.
1724 struct block_device *blkdev_get_by_dev(dev_t dev, fmode_t mode, void *holder)
1726 struct block_device *bdev;
1731 return ERR_PTR(-ENOMEM);
1733 err = blkdev_get(bdev, mode, holder);
1735 return ERR_PTR(err);
1739 EXPORT_SYMBOL(blkdev_get_by_dev);
1741 static int blkdev_open(struct inode * inode, struct file * filp)
1743 struct block_device *bdev;
1746 * Preserve backwards compatibility and allow large file access
1747 * even if userspace doesn't ask for it explicitly. Some mkfs
1748 * binary needs it. We might want to drop this workaround
1749 * during an unstable branch.
1751 filp->f_flags |= O_LARGEFILE;
1753 filp->f_mode |= FMODE_NOWAIT | FMODE_BUF_RASYNC;
1755 if (filp->f_flags & O_NDELAY)
1756 filp->f_mode |= FMODE_NDELAY;
1757 if (filp->f_flags & O_EXCL)
1758 filp->f_mode |= FMODE_EXCL;
1759 if ((filp->f_flags & O_ACCMODE) == 3)
1760 filp->f_mode |= FMODE_WRITE_IOCTL;
1762 bdev = bd_acquire(inode);
1766 filp->f_mapping = bdev->bd_inode->i_mapping;
1767 filp->f_wb_err = filemap_sample_wb_err(filp->f_mapping);
1769 return blkdev_get(bdev, filp->f_mode, filp);
1772 static void __blkdev_put(struct block_device *bdev, fmode_t mode, int for_part)
1774 struct gendisk *disk = bdev->bd_disk;
1775 struct block_device *victim = NULL;
1778 * Sync early if it looks like we're the last one. If someone else
1779 * opens the block device between now and the decrement of bd_openers
1780 * then we did a sync that we didn't need to, but that's not the end
1781 * of the world and we want to avoid long (could be several minute)
1782 * syncs while holding the mutex.
1784 if (bdev->bd_openers == 1)
1785 sync_blockdev(bdev);
1787 mutex_lock_nested(&bdev->bd_mutex, for_part);
1789 bdev->bd_part_count--;
1791 if (!--bdev->bd_openers) {
1792 WARN_ON_ONCE(bdev->bd_holders);
1793 sync_blockdev(bdev);
1796 bdev_write_inode(bdev);
1798 if (bdev->bd_contains == bdev) {
1799 if (disk->fops->release)
1800 disk->fops->release(disk, mode);
1802 if (!bdev->bd_openers) {
1803 disk_put_part(bdev->bd_part);
1804 bdev->bd_part = NULL;
1805 bdev->bd_disk = NULL;
1806 if (bdev != bdev->bd_contains)
1807 victim = bdev->bd_contains;
1808 bdev->bd_contains = NULL;
1810 put_disk_and_module(disk);
1812 mutex_unlock(&bdev->bd_mutex);
1815 __blkdev_put(victim, mode, 1);
1818 void blkdev_put(struct block_device *bdev, fmode_t mode)
1820 mutex_lock(&bdev->bd_mutex);
1822 if (mode & FMODE_EXCL) {
1826 * Release a claim on the device. The holder fields
1827 * are protected with bdev_lock. bd_mutex is to
1828 * synchronize disk_holder unlinking.
1830 spin_lock(&bdev_lock);
1832 WARN_ON_ONCE(--bdev->bd_holders < 0);
1833 WARN_ON_ONCE(--bdev->bd_contains->bd_holders < 0);
1835 /* bd_contains might point to self, check in a separate step */
1836 if ((bdev_free = !bdev->bd_holders))
1837 bdev->bd_holder = NULL;
1838 if (!bdev->bd_contains->bd_holders)
1839 bdev->bd_contains->bd_holder = NULL;
1841 spin_unlock(&bdev_lock);
1844 * If this was the last claim, remove holder link and
1845 * unblock evpoll if it was a write holder.
1847 if (bdev_free && bdev->bd_write_holder) {
1848 disk_unblock_events(bdev->bd_disk);
1849 bdev->bd_write_holder = false;
1854 * Trigger event checking and tell drivers to flush MEDIA_CHANGE
1855 * event. This is to ensure detection of media removal commanded
1856 * from userland - e.g. eject(1).
1858 disk_flush_events(bdev->bd_disk, DISK_EVENT_MEDIA_CHANGE);
1860 mutex_unlock(&bdev->bd_mutex);
1862 __blkdev_put(bdev, mode, 0);
1864 EXPORT_SYMBOL(blkdev_put);
1866 static int blkdev_close(struct inode * inode, struct file * filp)
1868 struct block_device *bdev = I_BDEV(bdev_file_inode(filp));
1869 blkdev_put(bdev, filp->f_mode);
1873 static long block_ioctl(struct file *file, unsigned cmd, unsigned long arg)
1875 struct block_device *bdev = I_BDEV(bdev_file_inode(file));
1876 fmode_t mode = file->f_mode;
1879 * O_NDELAY can be altered using fcntl(.., F_SETFL, ..), so we have
1880 * to updated it before every ioctl.
1882 if (file->f_flags & O_NDELAY)
1883 mode |= FMODE_NDELAY;
1885 mode &= ~FMODE_NDELAY;
1887 return blkdev_ioctl(bdev, mode, cmd, arg);
1891 * Write data to the block device. Only intended for the block device itself
1892 * and the raw driver which basically is a fake block device.
1894 * Does not take i_mutex for the write and thus is not for general purpose
1897 ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)
1899 struct file *file = iocb->ki_filp;
1900 struct inode *bd_inode = bdev_file_inode(file);
1901 loff_t size = i_size_read(bd_inode);
1902 struct blk_plug plug;
1905 if (bdev_read_only(I_BDEV(bd_inode)))
1908 if (IS_SWAPFILE(bd_inode) && !is_hibernate_resume_dev(bd_inode->i_rdev))
1911 if (!iov_iter_count(from))
1914 if (iocb->ki_pos >= size)
1917 if ((iocb->ki_flags & (IOCB_NOWAIT | IOCB_DIRECT)) == IOCB_NOWAIT)
1920 iov_iter_truncate(from, size - iocb->ki_pos);
1922 blk_start_plug(&plug);
1923 ret = __generic_file_write_iter(iocb, from);
1925 ret = generic_write_sync(iocb, ret);
1926 blk_finish_plug(&plug);
1929 EXPORT_SYMBOL_GPL(blkdev_write_iter);
1931 ssize_t blkdev_read_iter(struct kiocb *iocb, struct iov_iter *to)
1933 struct file *file = iocb->ki_filp;
1934 struct inode *bd_inode = bdev_file_inode(file);
1935 loff_t size = i_size_read(bd_inode);
1936 loff_t pos = iocb->ki_pos;
1942 iov_iter_truncate(to, size);
1943 return generic_file_read_iter(iocb, to);
1945 EXPORT_SYMBOL_GPL(blkdev_read_iter);
1948 * Try to release a page associated with block device when the system
1949 * is under memory pressure.
1951 static int blkdev_releasepage(struct page *page, gfp_t wait)
1953 struct super_block *super = BDEV_I(page->mapping->host)->bdev.bd_super;
1955 if (super && super->s_op->bdev_try_to_free_page)
1956 return super->s_op->bdev_try_to_free_page(super, page, wait);
1958 return try_to_free_buffers(page);
1961 static int blkdev_writepages(struct address_space *mapping,
1962 struct writeback_control *wbc)
1964 return generic_writepages(mapping, wbc);
1967 static const struct address_space_operations def_blk_aops = {
1968 .readpage = blkdev_readpage,
1969 .readahead = blkdev_readahead,
1970 .writepage = blkdev_writepage,
1971 .write_begin = blkdev_write_begin,
1972 .write_end = blkdev_write_end,
1973 .writepages = blkdev_writepages,
1974 .releasepage = blkdev_releasepage,
1975 .direct_IO = blkdev_direct_IO,
1976 .migratepage = buffer_migrate_page_norefs,
1977 .is_dirty_writeback = buffer_check_dirty_writeback,
1980 #define BLKDEV_FALLOC_FL_SUPPORTED \
1981 (FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE | \
1982 FALLOC_FL_ZERO_RANGE | FALLOC_FL_NO_HIDE_STALE)
1984 static long blkdev_fallocate(struct file *file, int mode, loff_t start,
1987 struct block_device *bdev = I_BDEV(bdev_file_inode(file));
1988 loff_t end = start + len - 1;
1992 /* Fail if we don't recognize the flags. */
1993 if (mode & ~BLKDEV_FALLOC_FL_SUPPORTED)
1996 /* Don't go off the end of the device. */
1997 isize = i_size_read(bdev->bd_inode);
2001 if (mode & FALLOC_FL_KEEP_SIZE) {
2002 len = isize - start;
2003 end = start + len - 1;
2009 * Don't allow IO that isn't aligned to logical block size.
2011 if ((start | len) & (bdev_logical_block_size(bdev) - 1))
2014 /* Invalidate the page cache, including dirty pages. */
2015 error = truncate_bdev_range(bdev, file->f_mode, start, end);
2020 case FALLOC_FL_ZERO_RANGE:
2021 case FALLOC_FL_ZERO_RANGE | FALLOC_FL_KEEP_SIZE:
2022 error = blkdev_issue_zeroout(bdev, start >> 9, len >> 9,
2023 GFP_KERNEL, BLKDEV_ZERO_NOUNMAP);
2025 case FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE:
2026 error = blkdev_issue_zeroout(bdev, start >> 9, len >> 9,
2027 GFP_KERNEL, BLKDEV_ZERO_NOFALLBACK);
2029 case FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE | FALLOC_FL_NO_HIDE_STALE:
2030 error = blkdev_issue_discard(bdev, start >> 9, len >> 9,
2040 * Invalidate again; if someone wandered in and dirtied a page,
2041 * the caller will be given -EBUSY. The third argument is
2042 * inclusive, so the rounding here is safe.
2044 return invalidate_inode_pages2_range(bdev->bd_inode->i_mapping,
2045 start >> PAGE_SHIFT,
2049 const struct file_operations def_blk_fops = {
2050 .open = blkdev_open,
2051 .release = blkdev_close,
2052 .llseek = block_llseek,
2053 .read_iter = blkdev_read_iter,
2054 .write_iter = blkdev_write_iter,
2055 .iopoll = blkdev_iopoll,
2056 .mmap = generic_file_mmap,
2057 .fsync = blkdev_fsync,
2058 .unlocked_ioctl = block_ioctl,
2059 #ifdef CONFIG_COMPAT
2060 .compat_ioctl = compat_blkdev_ioctl,
2062 .splice_read = generic_file_splice_read,
2063 .splice_write = iter_file_splice_write,
2064 .fallocate = blkdev_fallocate,
2068 * lookup_bdev - lookup a struct block_device by name
2069 * @pathname: special file representing the block device
2071 * Get a reference to the blockdevice at @pathname in the current
2072 * namespace if possible and return it. Return ERR_PTR(error)
2075 struct block_device *lookup_bdev(const char *pathname)
2077 struct block_device *bdev;
2078 struct inode *inode;
2082 if (!pathname || !*pathname)
2083 return ERR_PTR(-EINVAL);
2085 error = kern_path(pathname, LOOKUP_FOLLOW, &path);
2087 return ERR_PTR(error);
2089 inode = d_backing_inode(path.dentry);
2091 if (!S_ISBLK(inode->i_mode))
2094 if (!may_open_dev(&path))
2097 bdev = bd_acquire(inode);
2104 bdev = ERR_PTR(error);
2107 EXPORT_SYMBOL(lookup_bdev);
2109 int __invalidate_device(struct block_device *bdev, bool kill_dirty)
2111 struct super_block *sb = get_super(bdev);
2116 * no need to lock the super, get_super holds the
2117 * read mutex so the filesystem cannot go away
2118 * under us (->put_super runs with the write lock
2121 shrink_dcache_sb(sb);
2122 res = invalidate_inodes(sb, kill_dirty);
2125 invalidate_bdev(bdev);
2128 EXPORT_SYMBOL(__invalidate_device);
2130 void iterate_bdevs(void (*func)(struct block_device *, void *), void *arg)
2132 struct inode *inode, *old_inode = NULL;
2134 spin_lock(&blockdev_superblock->s_inode_list_lock);
2135 list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list) {
2136 struct address_space *mapping = inode->i_mapping;
2137 struct block_device *bdev;
2139 spin_lock(&inode->i_lock);
2140 if (inode->i_state & (I_FREEING|I_WILL_FREE|I_NEW) ||
2141 mapping->nrpages == 0) {
2142 spin_unlock(&inode->i_lock);
2146 spin_unlock(&inode->i_lock);
2147 spin_unlock(&blockdev_superblock->s_inode_list_lock);
2149 * We hold a reference to 'inode' so it couldn't have been
2150 * removed from s_inodes list while we dropped the
2151 * s_inode_list_lock We cannot iput the inode now as we can
2152 * be holding the last reference and we cannot iput it under
2153 * s_inode_list_lock. So we keep the reference and iput it
2158 bdev = I_BDEV(inode);
2160 mutex_lock(&bdev->bd_mutex);
2161 if (bdev->bd_openers)
2163 mutex_unlock(&bdev->bd_mutex);
2165 spin_lock(&blockdev_superblock->s_inode_list_lock);
2167 spin_unlock(&blockdev_superblock->s_inode_list_lock);