4 * Copyright (C) 1991, 1992 Linus Torvalds
5 * Copyright (C) 2001 Andrea Arcangeli <andrea@suse.de> SuSE
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/dax.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/uio.h>
29 #include <linux/namei.h>
30 #include <linux/log2.h>
31 #include <linux/cleancache.h>
32 #include <linux/dax.h>
33 #include <linux/badblocks.h>
34 #include <linux/task_io_accounting_ops.h>
35 #include <linux/falloc.h>
36 #include <linux/uaccess.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);
107 int set_blocksize(struct block_device *bdev, int size)
109 /* Size must be a power of two, and between 512 and PAGE_SIZE */
110 if (size > PAGE_SIZE || size < 512 || !is_power_of_2(size))
113 /* Size cannot be smaller than the size supported by the device */
114 if (size < bdev_logical_block_size(bdev))
117 /* Don't change the size if it is same as current */
118 if (bdev->bd_block_size != size) {
120 bdev->bd_block_size = size;
121 bdev->bd_inode->i_blkbits = blksize_bits(size);
127 EXPORT_SYMBOL(set_blocksize);
129 int sb_set_blocksize(struct super_block *sb, int size)
131 if (set_blocksize(sb->s_bdev, size))
133 /* If we get here, we know size is power of two
134 * and it's value is between 512 and PAGE_SIZE */
135 sb->s_blocksize = size;
136 sb->s_blocksize_bits = blksize_bits(size);
137 return sb->s_blocksize;
140 EXPORT_SYMBOL(sb_set_blocksize);
142 int sb_min_blocksize(struct super_block *sb, int size)
144 int minsize = bdev_logical_block_size(sb->s_bdev);
147 return sb_set_blocksize(sb, size);
150 EXPORT_SYMBOL(sb_min_blocksize);
153 blkdev_get_block(struct inode *inode, sector_t iblock,
154 struct buffer_head *bh, int create)
156 bh->b_bdev = I_BDEV(inode);
157 bh->b_blocknr = iblock;
158 set_buffer_mapped(bh);
162 static struct inode *bdev_file_inode(struct file *file)
164 return file->f_mapping->host;
167 static unsigned int dio_bio_write_op(struct kiocb *iocb)
169 unsigned int op = REQ_OP_WRITE | REQ_SYNC | REQ_IDLE;
171 /* avoid the need for a I/O completion work item */
172 if (iocb->ki_flags & IOCB_DSYNC)
177 #define DIO_INLINE_BIO_VECS 4
179 static void blkdev_bio_end_io_simple(struct bio *bio)
181 struct task_struct *waiter = bio->bi_private;
183 WRITE_ONCE(bio->bi_private, NULL);
184 wake_up_process(waiter);
188 __blkdev_direct_IO_simple(struct kiocb *iocb, struct iov_iter *iter,
191 struct file *file = iocb->ki_filp;
192 struct block_device *bdev = I_BDEV(bdev_file_inode(file));
193 struct bio_vec inline_vecs[DIO_INLINE_BIO_VECS], *vecs, *bvec;
194 loff_t pos = iocb->ki_pos;
195 bool should_dirty = false;
201 if ((pos | iov_iter_alignment(iter)) &
202 (bdev_logical_block_size(bdev) - 1))
205 if (nr_pages <= DIO_INLINE_BIO_VECS)
208 vecs = kmalloc_array(nr_pages, sizeof(struct bio_vec),
214 bio_init(&bio, vecs, nr_pages);
215 bio_set_dev(&bio, bdev);
216 bio.bi_iter.bi_sector = pos >> 9;
217 bio.bi_write_hint = iocb->ki_hint;
218 bio.bi_private = current;
219 bio.bi_end_io = blkdev_bio_end_io_simple;
220 bio.bi_ioprio = iocb->ki_ioprio;
222 ret = bio_iov_iter_get_pages(&bio, iter);
225 ret = bio.bi_iter.bi_size;
227 if (iov_iter_rw(iter) == READ) {
228 bio.bi_opf = REQ_OP_READ;
229 if (iter_is_iovec(iter))
232 bio.bi_opf = dio_bio_write_op(iocb);
233 task_io_account_write(ret);
236 qc = submit_bio(&bio);
238 set_current_state(TASK_UNINTERRUPTIBLE);
239 if (!READ_ONCE(bio.bi_private))
241 if (!(iocb->ki_flags & IOCB_HIPRI) ||
242 !blk_poll(bdev_get_queue(bdev), qc))
245 __set_current_state(TASK_RUNNING);
247 bio_for_each_segment_all(bvec, &bio, i) {
248 if (should_dirty && !PageCompound(bvec->bv_page))
249 set_page_dirty_lock(bvec->bv_page);
250 put_page(bvec->bv_page);
253 if (unlikely(bio.bi_status))
254 ret = blk_status_to_errno(bio.bi_status);
257 if (vecs != inline_vecs)
268 struct task_struct *waiter;
273 bool should_dirty : 1;
278 static struct bio_set blkdev_dio_pool;
280 static void blkdev_bio_end_io(struct bio *bio)
282 struct blkdev_dio *dio = bio->bi_private;
283 bool should_dirty = dio->should_dirty;
285 if (dio->multi_bio && !atomic_dec_and_test(&dio->ref)) {
286 if (bio->bi_status && !dio->bio.bi_status)
287 dio->bio.bi_status = bio->bi_status;
290 struct kiocb *iocb = dio->iocb;
293 if (likely(!dio->bio.bi_status)) {
297 ret = blk_status_to_errno(dio->bio.bi_status);
300 dio->iocb->ki_complete(iocb, ret, 0);
303 struct task_struct *waiter = dio->waiter;
305 WRITE_ONCE(dio->waiter, NULL);
306 wake_up_process(waiter);
311 bio_check_pages_dirty(bio);
313 struct bio_vec *bvec;
316 bio_for_each_segment_all(bvec, bio, i)
317 put_page(bvec->bv_page);
323 __blkdev_direct_IO(struct kiocb *iocb, struct iov_iter *iter, int nr_pages)
325 struct file *file = iocb->ki_filp;
326 struct inode *inode = bdev_file_inode(file);
327 struct block_device *bdev = I_BDEV(inode);
328 struct blk_plug plug;
329 struct blkdev_dio *dio;
331 bool is_read = (iov_iter_rw(iter) == READ), is_sync;
332 loff_t pos = iocb->ki_pos;
333 blk_qc_t qc = BLK_QC_T_NONE;
336 if ((pos | iov_iter_alignment(iter)) &
337 (bdev_logical_block_size(bdev) - 1))
340 bio = bio_alloc_bioset(GFP_KERNEL, nr_pages, &blkdev_dio_pool);
341 bio_get(bio); /* extra ref for the completion handler */
343 dio = container_of(bio, struct blkdev_dio, bio);
344 dio->is_sync = is_sync = is_sync_kiocb(iocb);
346 dio->waiter = current;
351 dio->multi_bio = false;
352 dio->should_dirty = is_read && (iter->type == ITER_IOVEC);
354 blk_start_plug(&plug);
356 bio_set_dev(bio, bdev);
357 bio->bi_iter.bi_sector = pos >> 9;
358 bio->bi_write_hint = iocb->ki_hint;
359 bio->bi_private = dio;
360 bio->bi_end_io = blkdev_bio_end_io;
361 bio->bi_ioprio = iocb->ki_ioprio;
363 ret = bio_iov_iter_get_pages(bio, iter);
365 bio->bi_status = BLK_STS_IOERR;
371 bio->bi_opf = REQ_OP_READ;
372 if (dio->should_dirty)
373 bio_set_pages_dirty(bio);
375 bio->bi_opf = dio_bio_write_op(iocb);
376 task_io_account_write(bio->bi_iter.bi_size);
379 dio->size += bio->bi_iter.bi_size;
380 pos += bio->bi_iter.bi_size;
382 nr_pages = iov_iter_npages(iter, BIO_MAX_PAGES);
384 qc = submit_bio(bio);
388 if (!dio->multi_bio) {
389 dio->multi_bio = true;
390 atomic_set(&dio->ref, 2);
392 atomic_inc(&dio->ref);
396 bio = bio_alloc(GFP_KERNEL, nr_pages);
398 blk_finish_plug(&plug);
404 set_current_state(TASK_UNINTERRUPTIBLE);
405 if (!READ_ONCE(dio->waiter))
408 if (!(iocb->ki_flags & IOCB_HIPRI) ||
409 !blk_poll(bdev_get_queue(bdev), qc))
412 __set_current_state(TASK_RUNNING);
415 ret = blk_status_to_errno(dio->bio.bi_status);
424 blkdev_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
428 nr_pages = iov_iter_npages(iter, BIO_MAX_PAGES + 1);
431 if (is_sync_kiocb(iocb) && nr_pages <= BIO_MAX_PAGES)
432 return __blkdev_direct_IO_simple(iocb, iter, nr_pages);
434 return __blkdev_direct_IO(iocb, iter, min(nr_pages, BIO_MAX_PAGES));
437 static __init int blkdev_init(void)
439 return bioset_init(&blkdev_dio_pool, 4, offsetof(struct blkdev_dio, bio), BIOSET_NEED_BVECS);
441 module_init(blkdev_init);
443 int __sync_blockdev(struct block_device *bdev, int wait)
448 return filemap_flush(bdev->bd_inode->i_mapping);
449 return filemap_write_and_wait(bdev->bd_inode->i_mapping);
453 * Write out and wait upon all the dirty data associated with a block
454 * device via its mapping. Does not take the superblock lock.
456 int sync_blockdev(struct block_device *bdev)
458 return __sync_blockdev(bdev, 1);
460 EXPORT_SYMBOL(sync_blockdev);
463 * Write out and wait upon all dirty data associated with this
464 * device. Filesystem data as well as the underlying block
465 * device. Takes the superblock lock.
467 int fsync_bdev(struct block_device *bdev)
469 struct super_block *sb = get_super(bdev);
471 int res = sync_filesystem(sb);
475 return sync_blockdev(bdev);
477 EXPORT_SYMBOL(fsync_bdev);
480 * freeze_bdev -- lock a filesystem and force it into a consistent state
481 * @bdev: blockdevice to lock
483 * If a superblock is found on this device, we take the s_umount semaphore
484 * on it to make sure nobody unmounts until the snapshot creation is done.
485 * The reference counter (bd_fsfreeze_count) guarantees that only the last
486 * unfreeze process can unfreeze the frozen filesystem actually when multiple
487 * freeze requests arrive simultaneously. It counts up in freeze_bdev() and
488 * count down in thaw_bdev(). When it becomes 0, thaw_bdev() will unfreeze
491 struct super_block *freeze_bdev(struct block_device *bdev)
493 struct super_block *sb;
496 mutex_lock(&bdev->bd_fsfreeze_mutex);
497 if (++bdev->bd_fsfreeze_count > 1) {
499 * We don't even need to grab a reference - the first call
500 * to freeze_bdev grab an active reference and only the last
501 * thaw_bdev drops it.
503 sb = get_super(bdev);
506 mutex_unlock(&bdev->bd_fsfreeze_mutex);
510 sb = get_active_super(bdev);
513 if (sb->s_op->freeze_super)
514 error = sb->s_op->freeze_super(sb);
516 error = freeze_super(sb);
518 deactivate_super(sb);
519 bdev->bd_fsfreeze_count--;
520 mutex_unlock(&bdev->bd_fsfreeze_mutex);
521 return ERR_PTR(error);
523 deactivate_super(sb);
526 mutex_unlock(&bdev->bd_fsfreeze_mutex);
527 return sb; /* thaw_bdev releases s->s_umount */
529 EXPORT_SYMBOL(freeze_bdev);
532 * thaw_bdev -- unlock filesystem
533 * @bdev: blockdevice to unlock
534 * @sb: associated superblock
536 * Unlocks the filesystem and marks it writeable again after freeze_bdev().
538 int thaw_bdev(struct block_device *bdev, struct super_block *sb)
542 mutex_lock(&bdev->bd_fsfreeze_mutex);
543 if (!bdev->bd_fsfreeze_count)
547 if (--bdev->bd_fsfreeze_count > 0)
553 if (sb->s_op->thaw_super)
554 error = sb->s_op->thaw_super(sb);
556 error = thaw_super(sb);
558 bdev->bd_fsfreeze_count++;
560 mutex_unlock(&bdev->bd_fsfreeze_mutex);
563 EXPORT_SYMBOL(thaw_bdev);
565 static int blkdev_writepage(struct page *page, struct writeback_control *wbc)
567 return block_write_full_page(page, blkdev_get_block, wbc);
570 static int blkdev_readpage(struct file * file, struct page * page)
572 return block_read_full_page(page, blkdev_get_block);
575 static int blkdev_readpages(struct file *file, struct address_space *mapping,
576 struct list_head *pages, unsigned nr_pages)
578 return mpage_readpages(mapping, pages, nr_pages, blkdev_get_block);
581 static int blkdev_write_begin(struct file *file, struct address_space *mapping,
582 loff_t pos, unsigned len, unsigned flags,
583 struct page **pagep, void **fsdata)
585 return block_write_begin(mapping, pos, len, flags, pagep,
589 static int blkdev_write_end(struct file *file, struct address_space *mapping,
590 loff_t pos, unsigned len, unsigned copied,
591 struct page *page, void *fsdata)
594 ret = block_write_end(file, mapping, pos, len, copied, page, fsdata);
604 * for a block special file file_inode(file)->i_size is zero
605 * so we compute the size by hand (just as in block_read/write above)
607 static loff_t block_llseek(struct file *file, loff_t offset, int whence)
609 struct inode *bd_inode = bdev_file_inode(file);
612 inode_lock(bd_inode);
613 retval = fixed_size_llseek(file, offset, whence, i_size_read(bd_inode));
614 inode_unlock(bd_inode);
618 int blkdev_fsync(struct file *filp, loff_t start, loff_t end, int datasync)
620 struct inode *bd_inode = bdev_file_inode(filp);
621 struct block_device *bdev = I_BDEV(bd_inode);
624 error = file_write_and_wait_range(filp, start, end);
629 * There is no need to serialise calls to blkdev_issue_flush with
630 * i_mutex and doing so causes performance issues with concurrent
631 * O_SYNC writers to a block device.
633 error = blkdev_issue_flush(bdev, GFP_KERNEL, NULL);
634 if (error == -EOPNOTSUPP)
639 EXPORT_SYMBOL(blkdev_fsync);
642 * bdev_read_page() - Start reading a page from a block device
643 * @bdev: The device to read the page from
644 * @sector: The offset on the device to read the page to (need not be aligned)
645 * @page: The page to read
647 * On entry, the page should be locked. It will be unlocked when the page
648 * has been read. If the block driver implements rw_page synchronously,
649 * that will be true on exit from this function, but it need not be.
651 * Errors returned by this function are usually "soft", eg out of memory, or
652 * queue full; callers should try a different route to read this page rather
653 * than propagate an error back up the stack.
655 * Return: negative errno if an error occurs, 0 if submission was successful.
657 int bdev_read_page(struct block_device *bdev, sector_t sector,
660 const struct block_device_operations *ops = bdev->bd_disk->fops;
661 int result = -EOPNOTSUPP;
663 if (!ops->rw_page || bdev_get_integrity(bdev))
666 result = blk_queue_enter(bdev->bd_queue, 0);
669 result = ops->rw_page(bdev, sector + get_start_sect(bdev), page, false);
670 blk_queue_exit(bdev->bd_queue);
673 EXPORT_SYMBOL_GPL(bdev_read_page);
676 * bdev_write_page() - Start writing a page to a block device
677 * @bdev: The device to write the page to
678 * @sector: The offset on the device to write the page to (need not be aligned)
679 * @page: The page to write
680 * @wbc: The writeback_control for the write
682 * On entry, the page should be locked and not currently under writeback.
683 * On exit, if the write started successfully, the page will be unlocked and
684 * under writeback. If the write failed already (eg the driver failed to
685 * queue the page to the device), the page will still be locked. If the
686 * caller is a ->writepage implementation, it will need to unlock the page.
688 * Errors returned by this function are usually "soft", eg out of memory, or
689 * queue full; callers should try a different route to write this page rather
690 * than propagate an error back up the stack.
692 * Return: negative errno if an error occurs, 0 if submission was successful.
694 int bdev_write_page(struct block_device *bdev, sector_t sector,
695 struct page *page, struct writeback_control *wbc)
698 const struct block_device_operations *ops = bdev->bd_disk->fops;
700 if (!ops->rw_page || bdev_get_integrity(bdev))
702 result = blk_queue_enter(bdev->bd_queue, 0);
706 set_page_writeback(page);
707 result = ops->rw_page(bdev, sector + get_start_sect(bdev), page, true);
709 end_page_writeback(page);
711 clean_page_buffers(page);
714 blk_queue_exit(bdev->bd_queue);
717 EXPORT_SYMBOL_GPL(bdev_write_page);
723 static __cacheline_aligned_in_smp DEFINE_SPINLOCK(bdev_lock);
724 static struct kmem_cache * bdev_cachep __read_mostly;
726 static struct inode *bdev_alloc_inode(struct super_block *sb)
728 struct bdev_inode *ei = kmem_cache_alloc(bdev_cachep, GFP_KERNEL);
731 return &ei->vfs_inode;
734 static void bdev_i_callback(struct rcu_head *head)
736 struct inode *inode = container_of(head, struct inode, i_rcu);
737 struct bdev_inode *bdi = BDEV_I(inode);
739 kmem_cache_free(bdev_cachep, bdi);
742 static void bdev_destroy_inode(struct inode *inode)
744 call_rcu(&inode->i_rcu, bdev_i_callback);
747 static void init_once(void *foo)
749 struct bdev_inode *ei = (struct bdev_inode *) foo;
750 struct block_device *bdev = &ei->bdev;
752 memset(bdev, 0, sizeof(*bdev));
753 mutex_init(&bdev->bd_mutex);
754 INIT_LIST_HEAD(&bdev->bd_list);
756 INIT_LIST_HEAD(&bdev->bd_holder_disks);
758 bdev->bd_bdi = &noop_backing_dev_info;
759 inode_init_once(&ei->vfs_inode);
760 /* Initialize mutex for freeze. */
761 mutex_init(&bdev->bd_fsfreeze_mutex);
764 static void bdev_evict_inode(struct inode *inode)
766 struct block_device *bdev = &BDEV_I(inode)->bdev;
767 truncate_inode_pages_final(&inode->i_data);
768 invalidate_inode_buffers(inode); /* is it needed here? */
770 spin_lock(&bdev_lock);
771 list_del_init(&bdev->bd_list);
772 spin_unlock(&bdev_lock);
773 /* Detach inode from wb early as bdi_put() may free bdi->wb */
774 inode_detach_wb(inode);
775 if (bdev->bd_bdi != &noop_backing_dev_info) {
776 bdi_put(bdev->bd_bdi);
777 bdev->bd_bdi = &noop_backing_dev_info;
781 static const struct super_operations bdev_sops = {
782 .statfs = simple_statfs,
783 .alloc_inode = bdev_alloc_inode,
784 .destroy_inode = bdev_destroy_inode,
785 .drop_inode = generic_delete_inode,
786 .evict_inode = bdev_evict_inode,
789 static struct dentry *bd_mount(struct file_system_type *fs_type,
790 int flags, const char *dev_name, void *data)
793 dent = mount_pseudo(fs_type, "bdev:", &bdev_sops, NULL, BDEVFS_MAGIC);
795 dent->d_sb->s_iflags |= SB_I_CGROUPWB;
799 static struct file_system_type bd_type = {
802 .kill_sb = kill_anon_super,
805 struct super_block *blockdev_superblock __read_mostly;
806 EXPORT_SYMBOL_GPL(blockdev_superblock);
808 void __init bdev_cache_init(void)
811 static struct vfsmount *bd_mnt;
813 bdev_cachep = kmem_cache_create("bdev_cache", sizeof(struct bdev_inode),
814 0, (SLAB_HWCACHE_ALIGN|SLAB_RECLAIM_ACCOUNT|
815 SLAB_MEM_SPREAD|SLAB_ACCOUNT|SLAB_PANIC),
817 err = register_filesystem(&bd_type);
819 panic("Cannot register bdev pseudo-fs");
820 bd_mnt = kern_mount(&bd_type);
822 panic("Cannot create bdev pseudo-fs");
823 blockdev_superblock = bd_mnt->mnt_sb; /* For writeback */
827 * Most likely _very_ bad one - but then it's hardly critical for small
828 * /dev and can be fixed when somebody will need really large one.
829 * Keep in mind that it will be fed through icache hash function too.
831 static inline unsigned long hash(dev_t dev)
833 return MAJOR(dev)+MINOR(dev);
836 static int bdev_test(struct inode *inode, void *data)
838 return BDEV_I(inode)->bdev.bd_dev == *(dev_t *)data;
841 static int bdev_set(struct inode *inode, void *data)
843 BDEV_I(inode)->bdev.bd_dev = *(dev_t *)data;
847 static LIST_HEAD(all_bdevs);
850 * If there is a bdev inode for this device, unhash it so that it gets evicted
851 * as soon as last inode reference is dropped.
853 void bdev_unhash_inode(dev_t dev)
857 inode = ilookup5(blockdev_superblock, hash(dev), bdev_test, &dev);
859 remove_inode_hash(inode);
864 struct block_device *bdget(dev_t dev)
866 struct block_device *bdev;
869 inode = iget5_locked(blockdev_superblock, hash(dev),
870 bdev_test, bdev_set, &dev);
875 bdev = &BDEV_I(inode)->bdev;
877 if (inode->i_state & I_NEW) {
878 bdev->bd_contains = NULL;
879 bdev->bd_super = NULL;
880 bdev->bd_inode = inode;
881 bdev->bd_block_size = i_blocksize(inode);
882 bdev->bd_part_count = 0;
883 bdev->bd_invalidated = 0;
884 inode->i_mode = S_IFBLK;
886 inode->i_bdev = bdev;
887 inode->i_data.a_ops = &def_blk_aops;
888 mapping_set_gfp_mask(&inode->i_data, GFP_USER);
889 spin_lock(&bdev_lock);
890 list_add(&bdev->bd_list, &all_bdevs);
891 spin_unlock(&bdev_lock);
892 unlock_new_inode(inode);
897 EXPORT_SYMBOL(bdget);
900 * bdgrab -- Grab a reference to an already referenced block device
901 * @bdev: Block device to grab a reference to.
903 struct block_device *bdgrab(struct block_device *bdev)
905 ihold(bdev->bd_inode);
908 EXPORT_SYMBOL(bdgrab);
910 long nr_blockdev_pages(void)
912 struct block_device *bdev;
914 spin_lock(&bdev_lock);
915 list_for_each_entry(bdev, &all_bdevs, bd_list) {
916 ret += bdev->bd_inode->i_mapping->nrpages;
918 spin_unlock(&bdev_lock);
922 void bdput(struct block_device *bdev)
924 iput(bdev->bd_inode);
927 EXPORT_SYMBOL(bdput);
929 static struct block_device *bd_acquire(struct inode *inode)
931 struct block_device *bdev;
933 spin_lock(&bdev_lock);
934 bdev = inode->i_bdev;
935 if (bdev && !inode_unhashed(bdev->bd_inode)) {
937 spin_unlock(&bdev_lock);
940 spin_unlock(&bdev_lock);
943 * i_bdev references block device inode that was already shut down
944 * (corresponding device got removed). Remove the reference and look
945 * up block device inode again just in case new device got
946 * reestablished under the same device number.
951 bdev = bdget(inode->i_rdev);
953 spin_lock(&bdev_lock);
954 if (!inode->i_bdev) {
956 * We take an additional reference to bd_inode,
957 * and it's released in clear_inode() of inode.
958 * So, we can access it via ->i_mapping always
962 inode->i_bdev = bdev;
963 inode->i_mapping = bdev->bd_inode->i_mapping;
965 spin_unlock(&bdev_lock);
970 /* Call when you free inode */
972 void bd_forget(struct inode *inode)
974 struct block_device *bdev = NULL;
976 spin_lock(&bdev_lock);
977 if (!sb_is_blkdev_sb(inode->i_sb))
978 bdev = inode->i_bdev;
979 inode->i_bdev = NULL;
980 inode->i_mapping = &inode->i_data;
981 spin_unlock(&bdev_lock);
988 * bd_may_claim - test whether a block device can be claimed
989 * @bdev: block device of interest
990 * @whole: whole block device containing @bdev, may equal @bdev
991 * @holder: holder trying to claim @bdev
993 * Test whether @bdev can be claimed by @holder.
996 * spin_lock(&bdev_lock).
999 * %true if @bdev can be claimed, %false otherwise.
1001 static bool bd_may_claim(struct block_device *bdev, struct block_device *whole,
1004 if (bdev->bd_holder == holder)
1005 return true; /* already a holder */
1006 else if (bdev->bd_holder != NULL)
1007 return false; /* held by someone else */
1008 else if (whole == bdev)
1009 return true; /* is a whole device which isn't held */
1011 else if (whole->bd_holder == bd_may_claim)
1012 return true; /* is a partition of a device that is being partitioned */
1013 else if (whole->bd_holder != NULL)
1014 return false; /* is a partition of a held device */
1016 return true; /* is a partition of an un-held device */
1020 * bd_prepare_to_claim - prepare to claim a block device
1021 * @bdev: block device of interest
1022 * @whole: the whole device containing @bdev, may equal @bdev
1023 * @holder: holder trying to claim @bdev
1025 * Prepare to claim @bdev. This function fails if @bdev is already
1026 * claimed by another holder and waits if another claiming is in
1027 * progress. This function doesn't actually claim. On successful
1028 * return, the caller has ownership of bd_claiming and bd_holder[s].
1031 * spin_lock(&bdev_lock). Might release bdev_lock, sleep and regrab
1032 * it multiple times.
1035 * 0 if @bdev can be claimed, -EBUSY otherwise.
1037 static int bd_prepare_to_claim(struct block_device *bdev,
1038 struct block_device *whole, void *holder)
1041 /* if someone else claimed, fail */
1042 if (!bd_may_claim(bdev, whole, holder))
1045 /* if claiming is already in progress, wait for it to finish */
1046 if (whole->bd_claiming) {
1047 wait_queue_head_t *wq = bit_waitqueue(&whole->bd_claiming, 0);
1050 prepare_to_wait(wq, &wait, TASK_UNINTERRUPTIBLE);
1051 spin_unlock(&bdev_lock);
1053 finish_wait(wq, &wait);
1054 spin_lock(&bdev_lock);
1062 static struct gendisk *bdev_get_gendisk(struct block_device *bdev, int *partno)
1064 struct gendisk *disk = get_gendisk(bdev->bd_dev, partno);
1069 * Now that we hold gendisk reference we make sure bdev we looked up is
1070 * not stale. If it is, it means device got removed and created before
1071 * we looked up gendisk and we fail open in such case. Associating
1072 * unhashed bdev with newly created gendisk could lead to two bdevs
1073 * (and thus two independent caches) being associated with one device
1076 if (inode_unhashed(bdev->bd_inode)) {
1077 put_disk_and_module(disk);
1084 * bd_start_claiming - start claiming a block device
1085 * @bdev: block device of interest
1086 * @holder: holder trying to claim @bdev
1088 * @bdev is about to be opened exclusively. Check @bdev can be opened
1089 * exclusively and mark that an exclusive open is in progress. Each
1090 * successful call to this function must be matched with a call to
1091 * either bd_finish_claiming() or bd_abort_claiming() (which do not
1094 * This function is used to gain exclusive access to the block device
1095 * without actually causing other exclusive open attempts to fail. It
1096 * should be used when the open sequence itself requires exclusive
1097 * access but may subsequently fail.
1103 * Pointer to the block device containing @bdev on success, ERR_PTR()
1106 static struct block_device *bd_start_claiming(struct block_device *bdev,
1109 struct gendisk *disk;
1110 struct block_device *whole;
1116 * @bdev might not have been initialized properly yet, look up
1117 * and grab the outer block device the hard way.
1119 disk = bdev_get_gendisk(bdev, &partno);
1121 return ERR_PTR(-ENXIO);
1124 * Normally, @bdev should equal what's returned from bdget_disk()
1125 * if partno is 0; however, some drivers (floppy) use multiple
1126 * bdev's for the same physical device and @bdev may be one of the
1127 * aliases. Keep @bdev if partno is 0. This means claimer
1128 * tracking is broken for those devices but it has always been that
1132 whole = bdget_disk(disk, 0);
1134 whole = bdgrab(bdev);
1136 put_disk_and_module(disk);
1138 return ERR_PTR(-ENOMEM);
1140 /* prepare to claim, if successful, mark claiming in progress */
1141 spin_lock(&bdev_lock);
1143 err = bd_prepare_to_claim(bdev, whole, holder);
1145 whole->bd_claiming = holder;
1146 spin_unlock(&bdev_lock);
1149 spin_unlock(&bdev_lock);
1151 return ERR_PTR(err);
1156 struct bd_holder_disk {
1157 struct list_head list;
1158 struct gendisk *disk;
1162 static struct bd_holder_disk *bd_find_holder_disk(struct block_device *bdev,
1163 struct gendisk *disk)
1165 struct bd_holder_disk *holder;
1167 list_for_each_entry(holder, &bdev->bd_holder_disks, list)
1168 if (holder->disk == disk)
1173 static int add_symlink(struct kobject *from, struct kobject *to)
1175 return sysfs_create_link(from, to, kobject_name(to));
1178 static void del_symlink(struct kobject *from, struct kobject *to)
1180 sysfs_remove_link(from, kobject_name(to));
1184 * bd_link_disk_holder - create symlinks between holding disk and slave bdev
1185 * @bdev: the claimed slave bdev
1186 * @disk: the holding disk
1188 * DON'T USE THIS UNLESS YOU'RE ALREADY USING IT.
1190 * This functions creates the following sysfs symlinks.
1192 * - from "slaves" directory of the holder @disk to the claimed @bdev
1193 * - from "holders" directory of the @bdev to the holder @disk
1195 * For example, if /dev/dm-0 maps to /dev/sda and disk for dm-0 is
1196 * passed to bd_link_disk_holder(), then:
1198 * /sys/block/dm-0/slaves/sda --> /sys/block/sda
1199 * /sys/block/sda/holders/dm-0 --> /sys/block/dm-0
1201 * The caller must have claimed @bdev before calling this function and
1202 * ensure that both @bdev and @disk are valid during the creation and
1203 * lifetime of these symlinks.
1209 * 0 on success, -errno on failure.
1211 int bd_link_disk_holder(struct block_device *bdev, struct gendisk *disk)
1213 struct bd_holder_disk *holder;
1216 mutex_lock(&bdev->bd_mutex);
1218 WARN_ON_ONCE(!bdev->bd_holder);
1220 /* FIXME: remove the following once add_disk() handles errors */
1221 if (WARN_ON(!disk->slave_dir || !bdev->bd_part->holder_dir))
1224 holder = bd_find_holder_disk(bdev, disk);
1230 holder = kzalloc(sizeof(*holder), GFP_KERNEL);
1236 INIT_LIST_HEAD(&holder->list);
1237 holder->disk = disk;
1240 ret = add_symlink(disk->slave_dir, &part_to_dev(bdev->bd_part)->kobj);
1244 ret = add_symlink(bdev->bd_part->holder_dir, &disk_to_dev(disk)->kobj);
1248 * bdev could be deleted beneath us which would implicitly destroy
1249 * the holder directory. Hold on to it.
1251 kobject_get(bdev->bd_part->holder_dir);
1253 list_add(&holder->list, &bdev->bd_holder_disks);
1257 del_symlink(disk->slave_dir, &part_to_dev(bdev->bd_part)->kobj);
1261 mutex_unlock(&bdev->bd_mutex);
1264 EXPORT_SYMBOL_GPL(bd_link_disk_holder);
1267 * bd_unlink_disk_holder - destroy symlinks created by bd_link_disk_holder()
1268 * @bdev: the calimed slave bdev
1269 * @disk: the holding disk
1271 * DON'T USE THIS UNLESS YOU'RE ALREADY USING IT.
1276 void bd_unlink_disk_holder(struct block_device *bdev, struct gendisk *disk)
1278 struct bd_holder_disk *holder;
1280 mutex_lock(&bdev->bd_mutex);
1282 holder = bd_find_holder_disk(bdev, disk);
1284 if (!WARN_ON_ONCE(holder == NULL) && !--holder->refcnt) {
1285 del_symlink(disk->slave_dir, &part_to_dev(bdev->bd_part)->kobj);
1286 del_symlink(bdev->bd_part->holder_dir,
1287 &disk_to_dev(disk)->kobj);
1288 kobject_put(bdev->bd_part->holder_dir);
1289 list_del_init(&holder->list);
1293 mutex_unlock(&bdev->bd_mutex);
1295 EXPORT_SYMBOL_GPL(bd_unlink_disk_holder);
1299 * flush_disk - invalidates all buffer-cache entries on a disk
1301 * @bdev: struct block device to be flushed
1302 * @kill_dirty: flag to guide handling of dirty inodes
1304 * Invalidates all buffer-cache entries on a disk. It should be called
1305 * when a disk has been changed -- either by a media change or online
1308 static void flush_disk(struct block_device *bdev, bool kill_dirty)
1310 if (__invalidate_device(bdev, kill_dirty)) {
1311 printk(KERN_WARNING "VFS: busy inodes on changed media or "
1312 "resized disk %s\n",
1313 bdev->bd_disk ? bdev->bd_disk->disk_name : "");
1318 if (disk_part_scan_enabled(bdev->bd_disk))
1319 bdev->bd_invalidated = 1;
1323 * check_disk_size_change - checks for disk size change and adjusts bdev size.
1324 * @disk: struct gendisk to check
1325 * @bdev: struct bdev to adjust.
1326 * @verbose: if %true log a message about a size change if there is any
1328 * This routine checks to see if the bdev size does not match the disk size
1329 * and adjusts it if it differs. When shrinking the bdev size, its all caches
1332 void check_disk_size_change(struct gendisk *disk, struct block_device *bdev,
1335 loff_t disk_size, bdev_size;
1337 disk_size = (loff_t)get_capacity(disk) << 9;
1338 bdev_size = i_size_read(bdev->bd_inode);
1339 if (disk_size != bdev_size) {
1342 "%s: detected capacity change from %lld to %lld\n",
1343 disk->disk_name, bdev_size, disk_size);
1345 i_size_write(bdev->bd_inode, disk_size);
1346 if (bdev_size > disk_size)
1347 flush_disk(bdev, false);
1352 * revalidate_disk - wrapper for lower-level driver's revalidate_disk call-back
1353 * @disk: struct gendisk to be revalidated
1355 * This routine is a wrapper for lower-level driver's revalidate_disk
1356 * call-backs. It is used to do common pre and post operations needed
1357 * for all revalidate_disk operations.
1359 int revalidate_disk(struct gendisk *disk)
1361 struct block_device *bdev;
1364 if (disk->fops->revalidate_disk)
1365 ret = disk->fops->revalidate_disk(disk);
1366 bdev = bdget_disk(disk, 0);
1370 mutex_lock(&bdev->bd_mutex);
1371 check_disk_size_change(disk, bdev, ret == 0);
1372 bdev->bd_invalidated = 0;
1373 mutex_unlock(&bdev->bd_mutex);
1377 EXPORT_SYMBOL(revalidate_disk);
1380 * This routine checks whether a removable media has been changed,
1381 * and invalidates all buffer-cache-entries in that case. This
1382 * is a relatively slow routine, so we have to try to minimize using
1383 * it. Thus it is called only upon a 'mount' or 'open'. This
1384 * is the best way of combining speed and utility, I think.
1385 * People changing diskettes in the middle of an operation deserve
1388 int check_disk_change(struct block_device *bdev)
1390 struct gendisk *disk = bdev->bd_disk;
1391 const struct block_device_operations *bdops = disk->fops;
1392 unsigned int events;
1394 events = disk_clear_events(disk, DISK_EVENT_MEDIA_CHANGE |
1395 DISK_EVENT_EJECT_REQUEST);
1396 if (!(events & DISK_EVENT_MEDIA_CHANGE))
1399 flush_disk(bdev, true);
1400 if (bdops->revalidate_disk)
1401 bdops->revalidate_disk(bdev->bd_disk);
1405 EXPORT_SYMBOL(check_disk_change);
1407 void bd_set_size(struct block_device *bdev, loff_t size)
1409 unsigned bsize = bdev_logical_block_size(bdev);
1411 inode_lock(bdev->bd_inode);
1412 i_size_write(bdev->bd_inode, size);
1413 inode_unlock(bdev->bd_inode);
1414 while (bsize < PAGE_SIZE) {
1419 bdev->bd_block_size = bsize;
1420 bdev->bd_inode->i_blkbits = blksize_bits(bsize);
1422 EXPORT_SYMBOL(bd_set_size);
1424 static void __blkdev_put(struct block_device *bdev, fmode_t mode, int for_part);
1429 * mutex_lock(part->bd_mutex)
1430 * mutex_lock_nested(whole->bd_mutex, 1)
1433 static int __blkdev_get(struct block_device *bdev, fmode_t mode, int for_part)
1435 struct gendisk *disk;
1439 bool first_open = false;
1441 if (mode & FMODE_READ)
1443 if (mode & FMODE_WRITE)
1446 * hooks: /n/, see "layering violations".
1449 ret = devcgroup_inode_permission(bdev->bd_inode, perm);
1459 disk = bdev_get_gendisk(bdev, &partno);
1463 disk_block_events(disk);
1464 mutex_lock_nested(&bdev->bd_mutex, for_part);
1465 if (!bdev->bd_openers) {
1467 bdev->bd_disk = disk;
1468 bdev->bd_queue = disk->queue;
1469 bdev->bd_contains = bdev;
1470 bdev->bd_partno = partno;
1474 bdev->bd_part = disk_get_part(disk, partno);
1479 if (disk->fops->open) {
1480 ret = disk->fops->open(bdev, mode);
1481 if (ret == -ERESTARTSYS) {
1482 /* Lost a race with 'disk' being
1483 * deleted, try again.
1486 disk_put_part(bdev->bd_part);
1487 bdev->bd_part = NULL;
1488 bdev->bd_disk = NULL;
1489 bdev->bd_queue = NULL;
1490 mutex_unlock(&bdev->bd_mutex);
1491 disk_unblock_events(disk);
1492 put_disk_and_module(disk);
1498 bd_set_size(bdev,(loff_t)get_capacity(disk)<<9);
1501 * If the device is invalidated, rescan partition
1502 * if open succeeded or failed with -ENOMEDIUM.
1503 * The latter is necessary to prevent ghost
1504 * partitions on a removed medium.
1506 if (bdev->bd_invalidated) {
1508 rescan_partitions(disk, bdev);
1509 else if (ret == -ENOMEDIUM)
1510 invalidate_partitions(disk, bdev);
1516 struct block_device *whole;
1517 whole = bdget_disk(disk, 0);
1522 ret = __blkdev_get(whole, mode, 1);
1525 bdev->bd_contains = whole;
1526 bdev->bd_part = disk_get_part(disk, partno);
1527 if (!(disk->flags & GENHD_FL_UP) ||
1528 !bdev->bd_part || !bdev->bd_part->nr_sects) {
1532 bd_set_size(bdev, (loff_t)bdev->bd_part->nr_sects << 9);
1535 if (bdev->bd_bdi == &noop_backing_dev_info)
1536 bdev->bd_bdi = bdi_get(disk->queue->backing_dev_info);
1538 if (bdev->bd_contains == bdev) {
1540 if (bdev->bd_disk->fops->open)
1541 ret = bdev->bd_disk->fops->open(bdev, mode);
1542 /* the same as first opener case, read comment there */
1543 if (bdev->bd_invalidated) {
1545 rescan_partitions(bdev->bd_disk, bdev);
1546 else if (ret == -ENOMEDIUM)
1547 invalidate_partitions(bdev->bd_disk, bdev);
1550 goto out_unlock_bdev;
1555 bdev->bd_part_count++;
1556 mutex_unlock(&bdev->bd_mutex);
1557 disk_unblock_events(disk);
1558 /* only one opener holds refs to the module and disk */
1560 put_disk_and_module(disk);
1564 disk_put_part(bdev->bd_part);
1565 bdev->bd_disk = NULL;
1566 bdev->bd_part = NULL;
1567 bdev->bd_queue = NULL;
1568 if (bdev != bdev->bd_contains)
1569 __blkdev_put(bdev->bd_contains, mode, 1);
1570 bdev->bd_contains = NULL;
1572 mutex_unlock(&bdev->bd_mutex);
1573 disk_unblock_events(disk);
1574 put_disk_and_module(disk);
1582 * blkdev_get - open a block device
1583 * @bdev: block_device to open
1584 * @mode: FMODE_* mask
1585 * @holder: exclusive holder identifier
1587 * Open @bdev with @mode. If @mode includes %FMODE_EXCL, @bdev is
1588 * open with exclusive access. Specifying %FMODE_EXCL with %NULL
1589 * @holder is invalid. Exclusive opens may nest for the same @holder.
1591 * On success, the reference count of @bdev is unchanged. On failure,
1598 * 0 on success, -errno on failure.
1600 int blkdev_get(struct block_device *bdev, fmode_t mode, void *holder)
1602 struct block_device *whole = NULL;
1605 WARN_ON_ONCE((mode & FMODE_EXCL) && !holder);
1607 if ((mode & FMODE_EXCL) && holder) {
1608 whole = bd_start_claiming(bdev, holder);
1609 if (IS_ERR(whole)) {
1611 return PTR_ERR(whole);
1615 res = __blkdev_get(bdev, mode, 0);
1618 struct gendisk *disk = whole->bd_disk;
1620 /* finish claiming */
1621 mutex_lock(&bdev->bd_mutex);
1622 spin_lock(&bdev_lock);
1625 BUG_ON(!bd_may_claim(bdev, whole, holder));
1627 * Note that for a whole device bd_holders
1628 * will be incremented twice, and bd_holder
1629 * will be set to bd_may_claim before being
1632 whole->bd_holders++;
1633 whole->bd_holder = bd_may_claim;
1635 bdev->bd_holder = holder;
1638 /* tell others that we're done */
1639 BUG_ON(whole->bd_claiming != holder);
1640 whole->bd_claiming = NULL;
1641 wake_up_bit(&whole->bd_claiming, 0);
1643 spin_unlock(&bdev_lock);
1646 * Block event polling for write claims if requested. Any
1647 * write holder makes the write_holder state stick until
1648 * all are released. This is good enough and tracking
1649 * individual writeable reference is too fragile given the
1650 * way @mode is used in blkdev_get/put().
1652 if (!res && (mode & FMODE_WRITE) && !bdev->bd_write_holder &&
1653 (disk->flags & GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE)) {
1654 bdev->bd_write_holder = true;
1655 disk_block_events(disk);
1658 mutex_unlock(&bdev->bd_mutex);
1664 EXPORT_SYMBOL(blkdev_get);
1667 * blkdev_get_by_path - open a block device by name
1668 * @path: path to the block device to open
1669 * @mode: FMODE_* mask
1670 * @holder: exclusive holder identifier
1672 * Open the blockdevice described by the device file at @path. @mode
1673 * and @holder are identical to blkdev_get().
1675 * On success, the returned block_device has reference count of one.
1681 * Pointer to block_device on success, ERR_PTR(-errno) on failure.
1683 struct block_device *blkdev_get_by_path(const char *path, fmode_t mode,
1686 struct block_device *bdev;
1689 bdev = lookup_bdev(path);
1693 err = blkdev_get(bdev, mode, holder);
1695 return ERR_PTR(err);
1697 if ((mode & FMODE_WRITE) && bdev_read_only(bdev)) {
1698 blkdev_put(bdev, mode);
1699 return ERR_PTR(-EACCES);
1704 EXPORT_SYMBOL(blkdev_get_by_path);
1707 * blkdev_get_by_dev - open a block device by device number
1708 * @dev: device number of block device to open
1709 * @mode: FMODE_* mask
1710 * @holder: exclusive holder identifier
1712 * Open the blockdevice described by device number @dev. @mode and
1713 * @holder are identical to blkdev_get().
1715 * Use it ONLY if you really do not have anything better - i.e. when
1716 * you are behind a truly sucky interface and all you are given is a
1717 * device number. _Never_ to be used for internal purposes. If you
1718 * ever need it - reconsider your API.
1720 * On success, the returned block_device has reference count of one.
1726 * Pointer to block_device on success, ERR_PTR(-errno) on failure.
1728 struct block_device *blkdev_get_by_dev(dev_t dev, fmode_t mode, void *holder)
1730 struct block_device *bdev;
1735 return ERR_PTR(-ENOMEM);
1737 err = blkdev_get(bdev, mode, holder);
1739 return ERR_PTR(err);
1743 EXPORT_SYMBOL(blkdev_get_by_dev);
1745 static int blkdev_open(struct inode * inode, struct file * filp)
1747 struct block_device *bdev;
1750 * Preserve backwards compatibility and allow large file access
1751 * even if userspace doesn't ask for it explicitly. Some mkfs
1752 * binary needs it. We might want to drop this workaround
1753 * during an unstable branch.
1755 filp->f_flags |= O_LARGEFILE;
1757 filp->f_mode |= FMODE_NOWAIT;
1759 if (filp->f_flags & O_NDELAY)
1760 filp->f_mode |= FMODE_NDELAY;
1761 if (filp->f_flags & O_EXCL)
1762 filp->f_mode |= FMODE_EXCL;
1763 if ((filp->f_flags & O_ACCMODE) == 3)
1764 filp->f_mode |= FMODE_WRITE_IOCTL;
1766 bdev = bd_acquire(inode);
1770 filp->f_mapping = bdev->bd_inode->i_mapping;
1771 filp->f_wb_err = filemap_sample_wb_err(filp->f_mapping);
1773 return blkdev_get(bdev, filp->f_mode, filp);
1776 static void __blkdev_put(struct block_device *bdev, fmode_t mode, int for_part)
1778 struct gendisk *disk = bdev->bd_disk;
1779 struct block_device *victim = NULL;
1781 mutex_lock_nested(&bdev->bd_mutex, for_part);
1783 bdev->bd_part_count--;
1785 if (!--bdev->bd_openers) {
1786 WARN_ON_ONCE(bdev->bd_holders);
1787 sync_blockdev(bdev);
1790 bdev_write_inode(bdev);
1792 if (bdev->bd_contains == bdev) {
1793 if (disk->fops->release)
1794 disk->fops->release(disk, mode);
1796 if (!bdev->bd_openers) {
1797 disk_put_part(bdev->bd_part);
1798 bdev->bd_part = NULL;
1799 bdev->bd_disk = NULL;
1800 if (bdev != bdev->bd_contains)
1801 victim = bdev->bd_contains;
1802 bdev->bd_contains = NULL;
1804 put_disk_and_module(disk);
1806 mutex_unlock(&bdev->bd_mutex);
1809 __blkdev_put(victim, mode, 1);
1812 void blkdev_put(struct block_device *bdev, fmode_t mode)
1814 mutex_lock(&bdev->bd_mutex);
1816 if (mode & FMODE_EXCL) {
1820 * Release a claim on the device. The holder fields
1821 * are protected with bdev_lock. bd_mutex is to
1822 * synchronize disk_holder unlinking.
1824 spin_lock(&bdev_lock);
1826 WARN_ON_ONCE(--bdev->bd_holders < 0);
1827 WARN_ON_ONCE(--bdev->bd_contains->bd_holders < 0);
1829 /* bd_contains might point to self, check in a separate step */
1830 if ((bdev_free = !bdev->bd_holders))
1831 bdev->bd_holder = NULL;
1832 if (!bdev->bd_contains->bd_holders)
1833 bdev->bd_contains->bd_holder = NULL;
1835 spin_unlock(&bdev_lock);
1838 * If this was the last claim, remove holder link and
1839 * unblock evpoll if it was a write holder.
1841 if (bdev_free && bdev->bd_write_holder) {
1842 disk_unblock_events(bdev->bd_disk);
1843 bdev->bd_write_holder = false;
1848 * Trigger event checking and tell drivers to flush MEDIA_CHANGE
1849 * event. This is to ensure detection of media removal commanded
1850 * from userland - e.g. eject(1).
1852 disk_flush_events(bdev->bd_disk, DISK_EVENT_MEDIA_CHANGE);
1854 mutex_unlock(&bdev->bd_mutex);
1856 __blkdev_put(bdev, mode, 0);
1858 EXPORT_SYMBOL(blkdev_put);
1860 static int blkdev_close(struct inode * inode, struct file * filp)
1862 struct block_device *bdev = I_BDEV(bdev_file_inode(filp));
1863 blkdev_put(bdev, filp->f_mode);
1867 static long block_ioctl(struct file *file, unsigned cmd, unsigned long arg)
1869 struct block_device *bdev = I_BDEV(bdev_file_inode(file));
1870 fmode_t mode = file->f_mode;
1873 * O_NDELAY can be altered using fcntl(.., F_SETFL, ..), so we have
1874 * to updated it before every ioctl.
1876 if (file->f_flags & O_NDELAY)
1877 mode |= FMODE_NDELAY;
1879 mode &= ~FMODE_NDELAY;
1881 return blkdev_ioctl(bdev, mode, cmd, arg);
1885 * Write data to the block device. Only intended for the block device itself
1886 * and the raw driver which basically is a fake block device.
1888 * Does not take i_mutex for the write and thus is not for general purpose
1891 ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from)
1893 struct file *file = iocb->ki_filp;
1894 struct inode *bd_inode = bdev_file_inode(file);
1895 loff_t size = i_size_read(bd_inode);
1896 struct blk_plug plug;
1899 if (bdev_read_only(I_BDEV(bd_inode)))
1902 if (!iov_iter_count(from))
1905 if (iocb->ki_pos >= size)
1908 if ((iocb->ki_flags & (IOCB_NOWAIT | IOCB_DIRECT)) == IOCB_NOWAIT)
1911 iov_iter_truncate(from, size - iocb->ki_pos);
1913 blk_start_plug(&plug);
1914 ret = __generic_file_write_iter(iocb, from);
1916 ret = generic_write_sync(iocb, ret);
1917 blk_finish_plug(&plug);
1920 EXPORT_SYMBOL_GPL(blkdev_write_iter);
1922 ssize_t blkdev_read_iter(struct kiocb *iocb, struct iov_iter *to)
1924 struct file *file = iocb->ki_filp;
1925 struct inode *bd_inode = bdev_file_inode(file);
1926 loff_t size = i_size_read(bd_inode);
1927 loff_t pos = iocb->ki_pos;
1933 iov_iter_truncate(to, size);
1934 return generic_file_read_iter(iocb, to);
1936 EXPORT_SYMBOL_GPL(blkdev_read_iter);
1939 * Try to release a page associated with block device when the system
1940 * is under memory pressure.
1942 static int blkdev_releasepage(struct page *page, gfp_t wait)
1944 struct super_block *super = BDEV_I(page->mapping->host)->bdev.bd_super;
1946 if (super && super->s_op->bdev_try_to_free_page)
1947 return super->s_op->bdev_try_to_free_page(super, page, wait);
1949 return try_to_free_buffers(page);
1952 static int blkdev_writepages(struct address_space *mapping,
1953 struct writeback_control *wbc)
1955 return generic_writepages(mapping, wbc);
1958 static const struct address_space_operations def_blk_aops = {
1959 .readpage = blkdev_readpage,
1960 .readpages = blkdev_readpages,
1961 .writepage = blkdev_writepage,
1962 .write_begin = blkdev_write_begin,
1963 .write_end = blkdev_write_end,
1964 .writepages = blkdev_writepages,
1965 .releasepage = blkdev_releasepage,
1966 .direct_IO = blkdev_direct_IO,
1967 .is_dirty_writeback = buffer_check_dirty_writeback,
1970 #define BLKDEV_FALLOC_FL_SUPPORTED \
1971 (FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE | \
1972 FALLOC_FL_ZERO_RANGE | FALLOC_FL_NO_HIDE_STALE)
1974 static long blkdev_fallocate(struct file *file, int mode, loff_t start,
1977 struct block_device *bdev = I_BDEV(bdev_file_inode(file));
1978 struct address_space *mapping;
1979 loff_t end = start + len - 1;
1983 /* Fail if we don't recognize the flags. */
1984 if (mode & ~BLKDEV_FALLOC_FL_SUPPORTED)
1987 /* Don't go off the end of the device. */
1988 isize = i_size_read(bdev->bd_inode);
1992 if (mode & FALLOC_FL_KEEP_SIZE) {
1993 len = isize - start;
1994 end = start + len - 1;
2000 * Don't allow IO that isn't aligned to logical block size.
2002 if ((start | len) & (bdev_logical_block_size(bdev) - 1))
2005 /* Invalidate the page cache, including dirty pages. */
2006 mapping = bdev->bd_inode->i_mapping;
2007 truncate_inode_pages_range(mapping, start, end);
2010 case FALLOC_FL_ZERO_RANGE:
2011 case FALLOC_FL_ZERO_RANGE | FALLOC_FL_KEEP_SIZE:
2012 error = blkdev_issue_zeroout(bdev, start >> 9, len >> 9,
2013 GFP_KERNEL, BLKDEV_ZERO_NOUNMAP);
2015 case FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE:
2016 error = blkdev_issue_zeroout(bdev, start >> 9, len >> 9,
2017 GFP_KERNEL, BLKDEV_ZERO_NOFALLBACK);
2019 case FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE | FALLOC_FL_NO_HIDE_STALE:
2020 error = blkdev_issue_discard(bdev, start >> 9, len >> 9,
2030 * Invalidate again; if someone wandered in and dirtied a page,
2031 * the caller will be given -EBUSY. The third argument is
2032 * inclusive, so the rounding here is safe.
2034 return invalidate_inode_pages2_range(mapping,
2035 start >> PAGE_SHIFT,
2039 const struct file_operations def_blk_fops = {
2040 .open = blkdev_open,
2041 .release = blkdev_close,
2042 .llseek = block_llseek,
2043 .read_iter = blkdev_read_iter,
2044 .write_iter = blkdev_write_iter,
2045 .mmap = generic_file_mmap,
2046 .fsync = blkdev_fsync,
2047 .unlocked_ioctl = block_ioctl,
2048 #ifdef CONFIG_COMPAT
2049 .compat_ioctl = compat_blkdev_ioctl,
2051 .splice_read = generic_file_splice_read,
2052 .splice_write = iter_file_splice_write,
2053 .fallocate = blkdev_fallocate,
2056 int ioctl_by_bdev(struct block_device *bdev, unsigned cmd, unsigned long arg)
2059 mm_segment_t old_fs = get_fs();
2061 res = blkdev_ioctl(bdev, 0, cmd, arg);
2066 EXPORT_SYMBOL(ioctl_by_bdev);
2069 * lookup_bdev - lookup a struct block_device by name
2070 * @pathname: special file representing the block device
2072 * Get a reference to the blockdevice at @pathname in the current
2073 * namespace if possible and return it. Return ERR_PTR(error)
2076 struct block_device *lookup_bdev(const char *pathname)
2078 struct block_device *bdev;
2079 struct inode *inode;
2083 if (!pathname || !*pathname)
2084 return ERR_PTR(-EINVAL);
2086 error = kern_path(pathname, LOOKUP_FOLLOW, &path);
2088 return ERR_PTR(error);
2090 inode = d_backing_inode(path.dentry);
2092 if (!S_ISBLK(inode->i_mode))
2095 if (!may_open_dev(&path))
2098 bdev = bd_acquire(inode);
2105 bdev = ERR_PTR(error);
2108 EXPORT_SYMBOL(lookup_bdev);
2110 int __invalidate_device(struct block_device *bdev, bool kill_dirty)
2112 struct super_block *sb = get_super(bdev);
2117 * no need to lock the super, get_super holds the
2118 * read mutex so the filesystem cannot go away
2119 * under us (->put_super runs with the write lock
2122 shrink_dcache_sb(sb);
2123 res = invalidate_inodes(sb, kill_dirty);
2126 invalidate_bdev(bdev);
2129 EXPORT_SYMBOL(__invalidate_device);
2131 void iterate_bdevs(void (*func)(struct block_device *, void *), void *arg)
2133 struct inode *inode, *old_inode = NULL;
2135 spin_lock(&blockdev_superblock->s_inode_list_lock);
2136 list_for_each_entry(inode, &blockdev_superblock->s_inodes, i_sb_list) {
2137 struct address_space *mapping = inode->i_mapping;
2138 struct block_device *bdev;
2140 spin_lock(&inode->i_lock);
2141 if (inode->i_state & (I_FREEING|I_WILL_FREE|I_NEW) ||
2142 mapping->nrpages == 0) {
2143 spin_unlock(&inode->i_lock);
2147 spin_unlock(&inode->i_lock);
2148 spin_unlock(&blockdev_superblock->s_inode_list_lock);
2150 * We hold a reference to 'inode' so it couldn't have been
2151 * removed from s_inodes list while we dropped the
2152 * s_inode_list_lock We cannot iput the inode now as we can
2153 * be holding the last reference and we cannot iput it under
2154 * s_inode_list_lock. So we keep the reference and iput it
2159 bdev = I_BDEV(inode);
2161 mutex_lock(&bdev->bd_mutex);
2162 if (bdev->bd_openers)
2164 mutex_unlock(&bdev->bd_mutex);
2166 spin_lock(&blockdev_superblock->s_inode_list_lock);
2168 spin_unlock(&blockdev_superblock->s_inode_list_lock);